aframe-master.js 2.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201
  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. var str = Object.prototype.toString
  3. module.exports = anArray
  4. function anArray(arr) {
  5. return (
  6. arr.BYTES_PER_ELEMENT
  7. && str.call(arr.buffer) === '[object ArrayBuffer]'
  8. || Array.isArray(arr)
  9. )
  10. }
  11. },{}],2:[function(_dereq_,module,exports){
  12. module.exports = function numtype(num, def) {
  13. return typeof num === 'number'
  14. ? num
  15. : (typeof def === 'number' ? def : 0)
  16. }
  17. },{}],3:[function(_dereq_,module,exports){
  18. 'use strict'
  19. exports.byteLength = byteLength
  20. exports.toByteArray = toByteArray
  21. exports.fromByteArray = fromByteArray
  22. var lookup = []
  23. var revLookup = []
  24. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  25. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  26. for (var i = 0, len = code.length; i < len; ++i) {
  27. lookup[i] = code[i]
  28. revLookup[code.charCodeAt(i)] = i
  29. }
  30. revLookup['-'.charCodeAt(0)] = 62
  31. revLookup['_'.charCodeAt(0)] = 63
  32. function placeHoldersCount (b64) {
  33. var len = b64.length
  34. if (len % 4 > 0) {
  35. throw new Error('Invalid string. Length must be a multiple of 4')
  36. }
  37. // the number of equal signs (place holders)
  38. // if there are two placeholders, than the two characters before it
  39. // represent one byte
  40. // if there is only one, then the three characters before it represent 2 bytes
  41. // this is just a cheap hack to not do indexOf twice
  42. return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
  43. }
  44. function byteLength (b64) {
  45. // base64 is 4/3 + up to two characters of the original data
  46. return b64.length * 3 / 4 - placeHoldersCount(b64)
  47. }
  48. function toByteArray (b64) {
  49. var i, j, l, tmp, placeHolders, arr
  50. var len = b64.length
  51. placeHolders = placeHoldersCount(b64)
  52. arr = new Arr(len * 3 / 4 - placeHolders)
  53. // if there are placeholders, only get up to the last complete 4 chars
  54. l = placeHolders > 0 ? len - 4 : len
  55. var L = 0
  56. for (i = 0, j = 0; i < l; i += 4, j += 3) {
  57. tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
  58. arr[L++] = (tmp >> 16) & 0xFF
  59. arr[L++] = (tmp >> 8) & 0xFF
  60. arr[L++] = tmp & 0xFF
  61. }
  62. if (placeHolders === 2) {
  63. tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
  64. arr[L++] = tmp & 0xFF
  65. } else if (placeHolders === 1) {
  66. tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
  67. arr[L++] = (tmp >> 8) & 0xFF
  68. arr[L++] = tmp & 0xFF
  69. }
  70. return arr
  71. }
  72. function tripletToBase64 (num) {
  73. return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
  74. }
  75. function encodeChunk (uint8, start, end) {
  76. var tmp
  77. var output = []
  78. for (var i = start; i < end; i += 3) {
  79. tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
  80. output.push(tripletToBase64(tmp))
  81. }
  82. return output.join('')
  83. }
  84. function fromByteArray (uint8) {
  85. var tmp
  86. var len = uint8.length
  87. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  88. var output = ''
  89. var parts = []
  90. var maxChunkLength = 16383 // must be multiple of 3
  91. // go through the array every three bytes, we'll deal with trailing stuff later
  92. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  93. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
  94. }
  95. // pad the end with zeros, but make sure to not forget the extra bytes
  96. if (extraBytes === 1) {
  97. tmp = uint8[len - 1]
  98. output += lookup[tmp >> 2]
  99. output += lookup[(tmp << 4) & 0x3F]
  100. output += '=='
  101. } else if (extraBytes === 2) {
  102. tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
  103. output += lookup[tmp >> 10]
  104. output += lookup[(tmp >> 4) & 0x3F]
  105. output += lookup[(tmp << 2) & 0x3F]
  106. output += '='
  107. }
  108. parts.push(output)
  109. return parts.join('')
  110. }
  111. },{}],4:[function(_dereq_,module,exports){
  112. 'use strict';
  113. // For more information about browser field, check out the browser field at https://github.com/substack/browserify-handbook#browser-field.
  114. module.exports = {
  115. // Create a <link> tag with optional data attributes
  116. createLink: function(href, attributes) {
  117. var head = document.head || document.getElementsByTagName('head')[0];
  118. var link = document.createElement('link');
  119. link.href = href;
  120. link.rel = 'stylesheet';
  121. for (var key in attributes) {
  122. if ( ! attributes.hasOwnProperty(key)) {
  123. continue;
  124. }
  125. var value = attributes[key];
  126. link.setAttribute('data-' + key, value);
  127. }
  128. head.appendChild(link);
  129. },
  130. // Create a <style> tag with optional data attributes
  131. createStyle: function(cssText, attributes) {
  132. var head = document.head || document.getElementsByTagName('head')[0],
  133. style = document.createElement('style');
  134. style.type = 'text/css';
  135. for (var key in attributes) {
  136. if ( ! attributes.hasOwnProperty(key)) {
  137. continue;
  138. }
  139. var value = attributes[key];
  140. style.setAttribute('data-' + key, value);
  141. }
  142. if (style.sheet) { // for jsdom and IE9+
  143. style.innerHTML = cssText;
  144. style.sheet.cssText = cssText;
  145. head.appendChild(style);
  146. } else if (style.styleSheet) { // for IE8 and below
  147. head.appendChild(style);
  148. style.styleSheet.cssText = cssText;
  149. } else { // for Chrome, Firefox, and Safari
  150. style.appendChild(document.createTextNode(cssText));
  151. head.appendChild(style);
  152. }
  153. }
  154. };
  155. },{}],5:[function(_dereq_,module,exports){
  156. var Buffer = _dereq_('buffer').Buffer; // for use with browserify
  157. module.exports = function (a, b) {
  158. if (!Buffer.isBuffer(a)) return undefined;
  159. if (!Buffer.isBuffer(b)) return undefined;
  160. if (typeof a.equals === 'function') return a.equals(b);
  161. if (a.length !== b.length) return false;
  162. for (var i = 0; i < a.length; i++) {
  163. if (a[i] !== b[i]) return false;
  164. }
  165. return true;
  166. };
  167. },{"buffer":6}],6:[function(_dereq_,module,exports){
  168. (function (global){
  169. /*!
  170. * The buffer module from node.js, for the browser.
  171. *
  172. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  173. * @license MIT
  174. */
  175. /* eslint-disable no-proto */
  176. 'use strict'
  177. var base64 = _dereq_('base64-js')
  178. var ieee754 = _dereq_('ieee754')
  179. var isArray = _dereq_('isarray')
  180. exports.Buffer = Buffer
  181. exports.SlowBuffer = SlowBuffer
  182. exports.INSPECT_MAX_BYTES = 50
  183. /**
  184. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  185. * === true Use Uint8Array implementation (fastest)
  186. * === false Use Object implementation (most compatible, even IE6)
  187. *
  188. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  189. * Opera 11.6+, iOS 4.2+.
  190. *
  191. * Due to various browser bugs, sometimes the Object implementation will be used even
  192. * when the browser supports typed arrays.
  193. *
  194. * Note:
  195. *
  196. * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
  197. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
  198. *
  199. * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
  200. *
  201. * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
  202. * incorrect length in some situations.
  203. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
  204. * get the Object implementation, which is slower but behaves correctly.
  205. */
  206. Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
  207. ? global.TYPED_ARRAY_SUPPORT
  208. : typedArraySupport()
  209. /*
  210. * Export kMaxLength after typed array support is determined.
  211. */
  212. exports.kMaxLength = kMaxLength()
  213. function typedArraySupport () {
  214. try {
  215. var arr = new Uint8Array(1)
  216. arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
  217. return arr.foo() === 42 && // typed array instances can be augmented
  218. typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
  219. arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
  220. } catch (e) {
  221. return false
  222. }
  223. }
  224. function kMaxLength () {
  225. return Buffer.TYPED_ARRAY_SUPPORT
  226. ? 0x7fffffff
  227. : 0x3fffffff
  228. }
  229. function createBuffer (that, length) {
  230. if (kMaxLength() < length) {
  231. throw new RangeError('Invalid typed array length')
  232. }
  233. if (Buffer.TYPED_ARRAY_SUPPORT) {
  234. // Return an augmented `Uint8Array` instance, for best performance
  235. that = new Uint8Array(length)
  236. that.__proto__ = Buffer.prototype
  237. } else {
  238. // Fallback: Return an object instance of the Buffer class
  239. if (that === null) {
  240. that = new Buffer(length)
  241. }
  242. that.length = length
  243. }
  244. return that
  245. }
  246. /**
  247. * The Buffer constructor returns instances of `Uint8Array` that have their
  248. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  249. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  250. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  251. * returns a single octet.
  252. *
  253. * The `Uint8Array` prototype remains unmodified.
  254. */
  255. function Buffer (arg, encodingOrOffset, length) {
  256. if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
  257. return new Buffer(arg, encodingOrOffset, length)
  258. }
  259. // Common case.
  260. if (typeof arg === 'number') {
  261. if (typeof encodingOrOffset === 'string') {
  262. throw new Error(
  263. 'If encoding is specified then the first argument must be a string'
  264. )
  265. }
  266. return allocUnsafe(this, arg)
  267. }
  268. return from(this, arg, encodingOrOffset, length)
  269. }
  270. Buffer.poolSize = 8192 // not used by this implementation
  271. // TODO: Legacy, not needed anymore. Remove in next major version.
  272. Buffer._augment = function (arr) {
  273. arr.__proto__ = Buffer.prototype
  274. return arr
  275. }
  276. function from (that, value, encodingOrOffset, length) {
  277. if (typeof value === 'number') {
  278. throw new TypeError('"value" argument must not be a number')
  279. }
  280. if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
  281. return fromArrayBuffer(that, value, encodingOrOffset, length)
  282. }
  283. if (typeof value === 'string') {
  284. return fromString(that, value, encodingOrOffset)
  285. }
  286. return fromObject(that, value)
  287. }
  288. /**
  289. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  290. * if value is a number.
  291. * Buffer.from(str[, encoding])
  292. * Buffer.from(array)
  293. * Buffer.from(buffer)
  294. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  295. **/
  296. Buffer.from = function (value, encodingOrOffset, length) {
  297. return from(null, value, encodingOrOffset, length)
  298. }
  299. if (Buffer.TYPED_ARRAY_SUPPORT) {
  300. Buffer.prototype.__proto__ = Uint8Array.prototype
  301. Buffer.__proto__ = Uint8Array
  302. if (typeof Symbol !== 'undefined' && Symbol.species &&
  303. Buffer[Symbol.species] === Buffer) {
  304. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  305. Object.defineProperty(Buffer, Symbol.species, {
  306. value: null,
  307. configurable: true
  308. })
  309. }
  310. }
  311. function assertSize (size) {
  312. if (typeof size !== 'number') {
  313. throw new TypeError('"size" argument must be a number')
  314. } else if (size < 0) {
  315. throw new RangeError('"size" argument must not be negative')
  316. }
  317. }
  318. function alloc (that, size, fill, encoding) {
  319. assertSize(size)
  320. if (size <= 0) {
  321. return createBuffer(that, size)
  322. }
  323. if (fill !== undefined) {
  324. // Only pay attention to encoding if it's a string. This
  325. // prevents accidentally sending in a number that would
  326. // be interpretted as a start offset.
  327. return typeof encoding === 'string'
  328. ? createBuffer(that, size).fill(fill, encoding)
  329. : createBuffer(that, size).fill(fill)
  330. }
  331. return createBuffer(that, size)
  332. }
  333. /**
  334. * Creates a new filled Buffer instance.
  335. * alloc(size[, fill[, encoding]])
  336. **/
  337. Buffer.alloc = function (size, fill, encoding) {
  338. return alloc(null, size, fill, encoding)
  339. }
  340. function allocUnsafe (that, size) {
  341. assertSize(size)
  342. that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
  343. if (!Buffer.TYPED_ARRAY_SUPPORT) {
  344. for (var i = 0; i < size; ++i) {
  345. that[i] = 0
  346. }
  347. }
  348. return that
  349. }
  350. /**
  351. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  352. * */
  353. Buffer.allocUnsafe = function (size) {
  354. return allocUnsafe(null, size)
  355. }
  356. /**
  357. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  358. */
  359. Buffer.allocUnsafeSlow = function (size) {
  360. return allocUnsafe(null, size)
  361. }
  362. function fromString (that, string, encoding) {
  363. if (typeof encoding !== 'string' || encoding === '') {
  364. encoding = 'utf8'
  365. }
  366. if (!Buffer.isEncoding(encoding)) {
  367. throw new TypeError('"encoding" must be a valid string encoding')
  368. }
  369. var length = byteLength(string, encoding) | 0
  370. that = createBuffer(that, length)
  371. var actual = that.write(string, encoding)
  372. if (actual !== length) {
  373. // Writing a hex string, for example, that contains invalid characters will
  374. // cause everything after the first invalid character to be ignored. (e.g.
  375. // 'abxxcd' will be treated as 'ab')
  376. that = that.slice(0, actual)
  377. }
  378. return that
  379. }
  380. function fromArrayLike (that, array) {
  381. var length = array.length < 0 ? 0 : checked(array.length) | 0
  382. that = createBuffer(that, length)
  383. for (var i = 0; i < length; i += 1) {
  384. that[i] = array[i] & 255
  385. }
  386. return that
  387. }
  388. function fromArrayBuffer (that, array, byteOffset, length) {
  389. array.byteLength // this throws if `array` is not a valid ArrayBuffer
  390. if (byteOffset < 0 || array.byteLength < byteOffset) {
  391. throw new RangeError('\'offset\' is out of bounds')
  392. }
  393. if (array.byteLength < byteOffset + (length || 0)) {
  394. throw new RangeError('\'length\' is out of bounds')
  395. }
  396. if (byteOffset === undefined && length === undefined) {
  397. array = new Uint8Array(array)
  398. } else if (length === undefined) {
  399. array = new Uint8Array(array, byteOffset)
  400. } else {
  401. array = new Uint8Array(array, byteOffset, length)
  402. }
  403. if (Buffer.TYPED_ARRAY_SUPPORT) {
  404. // Return an augmented `Uint8Array` instance, for best performance
  405. that = array
  406. that.__proto__ = Buffer.prototype
  407. } else {
  408. // Fallback: Return an object instance of the Buffer class
  409. that = fromArrayLike(that, array)
  410. }
  411. return that
  412. }
  413. function fromObject (that, obj) {
  414. if (Buffer.isBuffer(obj)) {
  415. var len = checked(obj.length) | 0
  416. that = createBuffer(that, len)
  417. if (that.length === 0) {
  418. return that
  419. }
  420. obj.copy(that, 0, 0, len)
  421. return that
  422. }
  423. if (obj) {
  424. if ((typeof ArrayBuffer !== 'undefined' &&
  425. obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
  426. if (typeof obj.length !== 'number' || isnan(obj.length)) {
  427. return createBuffer(that, 0)
  428. }
  429. return fromArrayLike(that, obj)
  430. }
  431. if (obj.type === 'Buffer' && isArray(obj.data)) {
  432. return fromArrayLike(that, obj.data)
  433. }
  434. }
  435. throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  436. }
  437. function checked (length) {
  438. // Note: cannot use `length < kMaxLength()` here because that fails when
  439. // length is NaN (which is otherwise coerced to zero.)
  440. if (length >= kMaxLength()) {
  441. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  442. 'size: 0x' + kMaxLength().toString(16) + ' bytes')
  443. }
  444. return length | 0
  445. }
  446. function SlowBuffer (length) {
  447. if (+length != length) { // eslint-disable-line eqeqeq
  448. length = 0
  449. }
  450. return Buffer.alloc(+length)
  451. }
  452. Buffer.isBuffer = function isBuffer (b) {
  453. return !!(b != null && b._isBuffer)
  454. }
  455. Buffer.compare = function compare (a, b) {
  456. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  457. throw new TypeError('Arguments must be Buffers')
  458. }
  459. if (a === b) return 0
  460. var x = a.length
  461. var y = b.length
  462. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  463. if (a[i] !== b[i]) {
  464. x = a[i]
  465. y = b[i]
  466. break
  467. }
  468. }
  469. if (x < y) return -1
  470. if (y < x) return 1
  471. return 0
  472. }
  473. Buffer.isEncoding = function isEncoding (encoding) {
  474. switch (String(encoding).toLowerCase()) {
  475. case 'hex':
  476. case 'utf8':
  477. case 'utf-8':
  478. case 'ascii':
  479. case 'latin1':
  480. case 'binary':
  481. case 'base64':
  482. case 'ucs2':
  483. case 'ucs-2':
  484. case 'utf16le':
  485. case 'utf-16le':
  486. return true
  487. default:
  488. return false
  489. }
  490. }
  491. Buffer.concat = function concat (list, length) {
  492. if (!isArray(list)) {
  493. throw new TypeError('"list" argument must be an Array of Buffers')
  494. }
  495. if (list.length === 0) {
  496. return Buffer.alloc(0)
  497. }
  498. var i
  499. if (length === undefined) {
  500. length = 0
  501. for (i = 0; i < list.length; ++i) {
  502. length += list[i].length
  503. }
  504. }
  505. var buffer = Buffer.allocUnsafe(length)
  506. var pos = 0
  507. for (i = 0; i < list.length; ++i) {
  508. var buf = list[i]
  509. if (!Buffer.isBuffer(buf)) {
  510. throw new TypeError('"list" argument must be an Array of Buffers')
  511. }
  512. buf.copy(buffer, pos)
  513. pos += buf.length
  514. }
  515. return buffer
  516. }
  517. function byteLength (string, encoding) {
  518. if (Buffer.isBuffer(string)) {
  519. return string.length
  520. }
  521. if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
  522. (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
  523. return string.byteLength
  524. }
  525. if (typeof string !== 'string') {
  526. string = '' + string
  527. }
  528. var len = string.length
  529. if (len === 0) return 0
  530. // Use a for loop to avoid recursion
  531. var loweredCase = false
  532. for (;;) {
  533. switch (encoding) {
  534. case 'ascii':
  535. case 'latin1':
  536. case 'binary':
  537. return len
  538. case 'utf8':
  539. case 'utf-8':
  540. case undefined:
  541. return utf8ToBytes(string).length
  542. case 'ucs2':
  543. case 'ucs-2':
  544. case 'utf16le':
  545. case 'utf-16le':
  546. return len * 2
  547. case 'hex':
  548. return len >>> 1
  549. case 'base64':
  550. return base64ToBytes(string).length
  551. default:
  552. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  553. encoding = ('' + encoding).toLowerCase()
  554. loweredCase = true
  555. }
  556. }
  557. }
  558. Buffer.byteLength = byteLength
  559. function slowToString (encoding, start, end) {
  560. var loweredCase = false
  561. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  562. // property of a typed array.
  563. // This behaves neither like String nor Uint8Array in that we set start/end
  564. // to their upper/lower bounds if the value passed is out of range.
  565. // undefined is handled specially as per ECMA-262 6th Edition,
  566. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  567. if (start === undefined || start < 0) {
  568. start = 0
  569. }
  570. // Return early if start > this.length. Done here to prevent potential uint32
  571. // coercion fail below.
  572. if (start > this.length) {
  573. return ''
  574. }
  575. if (end === undefined || end > this.length) {
  576. end = this.length
  577. }
  578. if (end <= 0) {
  579. return ''
  580. }
  581. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  582. end >>>= 0
  583. start >>>= 0
  584. if (end <= start) {
  585. return ''
  586. }
  587. if (!encoding) encoding = 'utf8'
  588. while (true) {
  589. switch (encoding) {
  590. case 'hex':
  591. return hexSlice(this, start, end)
  592. case 'utf8':
  593. case 'utf-8':
  594. return utf8Slice(this, start, end)
  595. case 'ascii':
  596. return asciiSlice(this, start, end)
  597. case 'latin1':
  598. case 'binary':
  599. return latin1Slice(this, start, end)
  600. case 'base64':
  601. return base64Slice(this, start, end)
  602. case 'ucs2':
  603. case 'ucs-2':
  604. case 'utf16le':
  605. case 'utf-16le':
  606. return utf16leSlice(this, start, end)
  607. default:
  608. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  609. encoding = (encoding + '').toLowerCase()
  610. loweredCase = true
  611. }
  612. }
  613. }
  614. // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
  615. // Buffer instances.
  616. Buffer.prototype._isBuffer = true
  617. function swap (b, n, m) {
  618. var i = b[n]
  619. b[n] = b[m]
  620. b[m] = i
  621. }
  622. Buffer.prototype.swap16 = function swap16 () {
  623. var len = this.length
  624. if (len % 2 !== 0) {
  625. throw new RangeError('Buffer size must be a multiple of 16-bits')
  626. }
  627. for (var i = 0; i < len; i += 2) {
  628. swap(this, i, i + 1)
  629. }
  630. return this
  631. }
  632. Buffer.prototype.swap32 = function swap32 () {
  633. var len = this.length
  634. if (len % 4 !== 0) {
  635. throw new RangeError('Buffer size must be a multiple of 32-bits')
  636. }
  637. for (var i = 0; i < len; i += 4) {
  638. swap(this, i, i + 3)
  639. swap(this, i + 1, i + 2)
  640. }
  641. return this
  642. }
  643. Buffer.prototype.swap64 = function swap64 () {
  644. var len = this.length
  645. if (len % 8 !== 0) {
  646. throw new RangeError('Buffer size must be a multiple of 64-bits')
  647. }
  648. for (var i = 0; i < len; i += 8) {
  649. swap(this, i, i + 7)
  650. swap(this, i + 1, i + 6)
  651. swap(this, i + 2, i + 5)
  652. swap(this, i + 3, i + 4)
  653. }
  654. return this
  655. }
  656. Buffer.prototype.toString = function toString () {
  657. var length = this.length | 0
  658. if (length === 0) return ''
  659. if (arguments.length === 0) return utf8Slice(this, 0, length)
  660. return slowToString.apply(this, arguments)
  661. }
  662. Buffer.prototype.equals = function equals (b) {
  663. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  664. if (this === b) return true
  665. return Buffer.compare(this, b) === 0
  666. }
  667. Buffer.prototype.inspect = function inspect () {
  668. var str = ''
  669. var max = exports.INSPECT_MAX_BYTES
  670. if (this.length > 0) {
  671. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
  672. if (this.length > max) str += ' ... '
  673. }
  674. return '<Buffer ' + str + '>'
  675. }
  676. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  677. if (!Buffer.isBuffer(target)) {
  678. throw new TypeError('Argument must be a Buffer')
  679. }
  680. if (start === undefined) {
  681. start = 0
  682. }
  683. if (end === undefined) {
  684. end = target ? target.length : 0
  685. }
  686. if (thisStart === undefined) {
  687. thisStart = 0
  688. }
  689. if (thisEnd === undefined) {
  690. thisEnd = this.length
  691. }
  692. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  693. throw new RangeError('out of range index')
  694. }
  695. if (thisStart >= thisEnd && start >= end) {
  696. return 0
  697. }
  698. if (thisStart >= thisEnd) {
  699. return -1
  700. }
  701. if (start >= end) {
  702. return 1
  703. }
  704. start >>>= 0
  705. end >>>= 0
  706. thisStart >>>= 0
  707. thisEnd >>>= 0
  708. if (this === target) return 0
  709. var x = thisEnd - thisStart
  710. var y = end - start
  711. var len = Math.min(x, y)
  712. var thisCopy = this.slice(thisStart, thisEnd)
  713. var targetCopy = target.slice(start, end)
  714. for (var i = 0; i < len; ++i) {
  715. if (thisCopy[i] !== targetCopy[i]) {
  716. x = thisCopy[i]
  717. y = targetCopy[i]
  718. break
  719. }
  720. }
  721. if (x < y) return -1
  722. if (y < x) return 1
  723. return 0
  724. }
  725. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  726. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  727. //
  728. // Arguments:
  729. // - buffer - a Buffer to search
  730. // - val - a string, Buffer, or number
  731. // - byteOffset - an index into `buffer`; will be clamped to an int32
  732. // - encoding - an optional encoding, relevant is val is a string
  733. // - dir - true for indexOf, false for lastIndexOf
  734. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  735. // Empty buffer means no match
  736. if (buffer.length === 0) return -1
  737. // Normalize byteOffset
  738. if (typeof byteOffset === 'string') {
  739. encoding = byteOffset
  740. byteOffset = 0
  741. } else if (byteOffset > 0x7fffffff) {
  742. byteOffset = 0x7fffffff
  743. } else if (byteOffset < -0x80000000) {
  744. byteOffset = -0x80000000
  745. }
  746. byteOffset = +byteOffset // Coerce to Number.
  747. if (isNaN(byteOffset)) {
  748. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  749. byteOffset = dir ? 0 : (buffer.length - 1)
  750. }
  751. // Normalize byteOffset: negative offsets start from the end of the buffer
  752. if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  753. if (byteOffset >= buffer.length) {
  754. if (dir) return -1
  755. else byteOffset = buffer.length - 1
  756. } else if (byteOffset < 0) {
  757. if (dir) byteOffset = 0
  758. else return -1
  759. }
  760. // Normalize val
  761. if (typeof val === 'string') {
  762. val = Buffer.from(val, encoding)
  763. }
  764. // Finally, search either indexOf (if dir is true) or lastIndexOf
  765. if (Buffer.isBuffer(val)) {
  766. // Special case: looking for empty string/buffer always fails
  767. if (val.length === 0) {
  768. return -1
  769. }
  770. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  771. } else if (typeof val === 'number') {
  772. val = val & 0xFF // Search for a byte value [0-255]
  773. if (Buffer.TYPED_ARRAY_SUPPORT &&
  774. typeof Uint8Array.prototype.indexOf === 'function') {
  775. if (dir) {
  776. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  777. } else {
  778. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  779. }
  780. }
  781. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  782. }
  783. throw new TypeError('val must be string, number or Buffer')
  784. }
  785. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  786. var indexSize = 1
  787. var arrLength = arr.length
  788. var valLength = val.length
  789. if (encoding !== undefined) {
  790. encoding = String(encoding).toLowerCase()
  791. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  792. encoding === 'utf16le' || encoding === 'utf-16le') {
  793. if (arr.length < 2 || val.length < 2) {
  794. return -1
  795. }
  796. indexSize = 2
  797. arrLength /= 2
  798. valLength /= 2
  799. byteOffset /= 2
  800. }
  801. }
  802. function read (buf, i) {
  803. if (indexSize === 1) {
  804. return buf[i]
  805. } else {
  806. return buf.readUInt16BE(i * indexSize)
  807. }
  808. }
  809. var i
  810. if (dir) {
  811. var foundIndex = -1
  812. for (i = byteOffset; i < arrLength; i++) {
  813. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  814. if (foundIndex === -1) foundIndex = i
  815. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  816. } else {
  817. if (foundIndex !== -1) i -= i - foundIndex
  818. foundIndex = -1
  819. }
  820. }
  821. } else {
  822. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
  823. for (i = byteOffset; i >= 0; i--) {
  824. var found = true
  825. for (var j = 0; j < valLength; j++) {
  826. if (read(arr, i + j) !== read(val, j)) {
  827. found = false
  828. break
  829. }
  830. }
  831. if (found) return i
  832. }
  833. }
  834. return -1
  835. }
  836. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  837. return this.indexOf(val, byteOffset, encoding) !== -1
  838. }
  839. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  840. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  841. }
  842. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  843. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  844. }
  845. function hexWrite (buf, string, offset, length) {
  846. offset = Number(offset) || 0
  847. var remaining = buf.length - offset
  848. if (!length) {
  849. length = remaining
  850. } else {
  851. length = Number(length)
  852. if (length > remaining) {
  853. length = remaining
  854. }
  855. }
  856. // must be an even number of digits
  857. var strLen = string.length
  858. if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
  859. if (length > strLen / 2) {
  860. length = strLen / 2
  861. }
  862. for (var i = 0; i < length; ++i) {
  863. var parsed = parseInt(string.substr(i * 2, 2), 16)
  864. if (isNaN(parsed)) return i
  865. buf[offset + i] = parsed
  866. }
  867. return i
  868. }
  869. function utf8Write (buf, string, offset, length) {
  870. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  871. }
  872. function asciiWrite (buf, string, offset, length) {
  873. return blitBuffer(asciiToBytes(string), buf, offset, length)
  874. }
  875. function latin1Write (buf, string, offset, length) {
  876. return asciiWrite(buf, string, offset, length)
  877. }
  878. function base64Write (buf, string, offset, length) {
  879. return blitBuffer(base64ToBytes(string), buf, offset, length)
  880. }
  881. function ucs2Write (buf, string, offset, length) {
  882. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  883. }
  884. Buffer.prototype.write = function write (string, offset, length, encoding) {
  885. // Buffer#write(string)
  886. if (offset === undefined) {
  887. encoding = 'utf8'
  888. length = this.length
  889. offset = 0
  890. // Buffer#write(string, encoding)
  891. } else if (length === undefined && typeof offset === 'string') {
  892. encoding = offset
  893. length = this.length
  894. offset = 0
  895. // Buffer#write(string, offset[, length][, encoding])
  896. } else if (isFinite(offset)) {
  897. offset = offset | 0
  898. if (isFinite(length)) {
  899. length = length | 0
  900. if (encoding === undefined) encoding = 'utf8'
  901. } else {
  902. encoding = length
  903. length = undefined
  904. }
  905. // legacy write(string, encoding, offset, length) - remove in v0.13
  906. } else {
  907. throw new Error(
  908. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  909. )
  910. }
  911. var remaining = this.length - offset
  912. if (length === undefined || length > remaining) length = remaining
  913. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  914. throw new RangeError('Attempt to write outside buffer bounds')
  915. }
  916. if (!encoding) encoding = 'utf8'
  917. var loweredCase = false
  918. for (;;) {
  919. switch (encoding) {
  920. case 'hex':
  921. return hexWrite(this, string, offset, length)
  922. case 'utf8':
  923. case 'utf-8':
  924. return utf8Write(this, string, offset, length)
  925. case 'ascii':
  926. return asciiWrite(this, string, offset, length)
  927. case 'latin1':
  928. case 'binary':
  929. return latin1Write(this, string, offset, length)
  930. case 'base64':
  931. // Warning: maxLength not taken into account in base64Write
  932. return base64Write(this, string, offset, length)
  933. case 'ucs2':
  934. case 'ucs-2':
  935. case 'utf16le':
  936. case 'utf-16le':
  937. return ucs2Write(this, string, offset, length)
  938. default:
  939. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  940. encoding = ('' + encoding).toLowerCase()
  941. loweredCase = true
  942. }
  943. }
  944. }
  945. Buffer.prototype.toJSON = function toJSON () {
  946. return {
  947. type: 'Buffer',
  948. data: Array.prototype.slice.call(this._arr || this, 0)
  949. }
  950. }
  951. function base64Slice (buf, start, end) {
  952. if (start === 0 && end === buf.length) {
  953. return base64.fromByteArray(buf)
  954. } else {
  955. return base64.fromByteArray(buf.slice(start, end))
  956. }
  957. }
  958. function utf8Slice (buf, start, end) {
  959. end = Math.min(buf.length, end)
  960. var res = []
  961. var i = start
  962. while (i < end) {
  963. var firstByte = buf[i]
  964. var codePoint = null
  965. var bytesPerSequence = (firstByte > 0xEF) ? 4
  966. : (firstByte > 0xDF) ? 3
  967. : (firstByte > 0xBF) ? 2
  968. : 1
  969. if (i + bytesPerSequence <= end) {
  970. var secondByte, thirdByte, fourthByte, tempCodePoint
  971. switch (bytesPerSequence) {
  972. case 1:
  973. if (firstByte < 0x80) {
  974. codePoint = firstByte
  975. }
  976. break
  977. case 2:
  978. secondByte = buf[i + 1]
  979. if ((secondByte & 0xC0) === 0x80) {
  980. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  981. if (tempCodePoint > 0x7F) {
  982. codePoint = tempCodePoint
  983. }
  984. }
  985. break
  986. case 3:
  987. secondByte = buf[i + 1]
  988. thirdByte = buf[i + 2]
  989. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  990. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  991. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  992. codePoint = tempCodePoint
  993. }
  994. }
  995. break
  996. case 4:
  997. secondByte = buf[i + 1]
  998. thirdByte = buf[i + 2]
  999. fourthByte = buf[i + 3]
  1000. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  1001. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  1002. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  1003. codePoint = tempCodePoint
  1004. }
  1005. }
  1006. }
  1007. }
  1008. if (codePoint === null) {
  1009. // we did not generate a valid codePoint so insert a
  1010. // replacement char (U+FFFD) and advance only 1 byte
  1011. codePoint = 0xFFFD
  1012. bytesPerSequence = 1
  1013. } else if (codePoint > 0xFFFF) {
  1014. // encode to utf16 (surrogate pair dance)
  1015. codePoint -= 0x10000
  1016. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  1017. codePoint = 0xDC00 | codePoint & 0x3FF
  1018. }
  1019. res.push(codePoint)
  1020. i += bytesPerSequence
  1021. }
  1022. return decodeCodePointsArray(res)
  1023. }
  1024. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  1025. // the lowest limit is Chrome, with 0x10000 args.
  1026. // We go 1 magnitude less, for safety
  1027. var MAX_ARGUMENTS_LENGTH = 0x1000
  1028. function decodeCodePointsArray (codePoints) {
  1029. var len = codePoints.length
  1030. if (len <= MAX_ARGUMENTS_LENGTH) {
  1031. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  1032. }
  1033. // Decode in chunks to avoid "call stack size exceeded".
  1034. var res = ''
  1035. var i = 0
  1036. while (i < len) {
  1037. res += String.fromCharCode.apply(
  1038. String,
  1039. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  1040. )
  1041. }
  1042. return res
  1043. }
  1044. function asciiSlice (buf, start, end) {
  1045. var ret = ''
  1046. end = Math.min(buf.length, end)
  1047. for (var i = start; i < end; ++i) {
  1048. ret += String.fromCharCode(buf[i] & 0x7F)
  1049. }
  1050. return ret
  1051. }
  1052. function latin1Slice (buf, start, end) {
  1053. var ret = ''
  1054. end = Math.min(buf.length, end)
  1055. for (var i = start; i < end; ++i) {
  1056. ret += String.fromCharCode(buf[i])
  1057. }
  1058. return ret
  1059. }
  1060. function hexSlice (buf, start, end) {
  1061. var len = buf.length
  1062. if (!start || start < 0) start = 0
  1063. if (!end || end < 0 || end > len) end = len
  1064. var out = ''
  1065. for (var i = start; i < end; ++i) {
  1066. out += toHex(buf[i])
  1067. }
  1068. return out
  1069. }
  1070. function utf16leSlice (buf, start, end) {
  1071. var bytes = buf.slice(start, end)
  1072. var res = ''
  1073. for (var i = 0; i < bytes.length; i += 2) {
  1074. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
  1075. }
  1076. return res
  1077. }
  1078. Buffer.prototype.slice = function slice (start, end) {
  1079. var len = this.length
  1080. start = ~~start
  1081. end = end === undefined ? len : ~~end
  1082. if (start < 0) {
  1083. start += len
  1084. if (start < 0) start = 0
  1085. } else if (start > len) {
  1086. start = len
  1087. }
  1088. if (end < 0) {
  1089. end += len
  1090. if (end < 0) end = 0
  1091. } else if (end > len) {
  1092. end = len
  1093. }
  1094. if (end < start) end = start
  1095. var newBuf
  1096. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1097. newBuf = this.subarray(start, end)
  1098. newBuf.__proto__ = Buffer.prototype
  1099. } else {
  1100. var sliceLen = end - start
  1101. newBuf = new Buffer(sliceLen, undefined)
  1102. for (var i = 0; i < sliceLen; ++i) {
  1103. newBuf[i] = this[i + start]
  1104. }
  1105. }
  1106. return newBuf
  1107. }
  1108. /*
  1109. * Need to make sure that buffer isn't trying to write out of bounds.
  1110. */
  1111. function checkOffset (offset, ext, length) {
  1112. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  1113. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  1114. }
  1115. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  1116. offset = offset | 0
  1117. byteLength = byteLength | 0
  1118. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1119. var val = this[offset]
  1120. var mul = 1
  1121. var i = 0
  1122. while (++i < byteLength && (mul *= 0x100)) {
  1123. val += this[offset + i] * mul
  1124. }
  1125. return val
  1126. }
  1127. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  1128. offset = offset | 0
  1129. byteLength = byteLength | 0
  1130. if (!noAssert) {
  1131. checkOffset(offset, byteLength, this.length)
  1132. }
  1133. var val = this[offset + --byteLength]
  1134. var mul = 1
  1135. while (byteLength > 0 && (mul *= 0x100)) {
  1136. val += this[offset + --byteLength] * mul
  1137. }
  1138. return val
  1139. }
  1140. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  1141. if (!noAssert) checkOffset(offset, 1, this.length)
  1142. return this[offset]
  1143. }
  1144. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  1145. if (!noAssert) checkOffset(offset, 2, this.length)
  1146. return this[offset] | (this[offset + 1] << 8)
  1147. }
  1148. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  1149. if (!noAssert) checkOffset(offset, 2, this.length)
  1150. return (this[offset] << 8) | this[offset + 1]
  1151. }
  1152. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  1153. if (!noAssert) checkOffset(offset, 4, this.length)
  1154. return ((this[offset]) |
  1155. (this[offset + 1] << 8) |
  1156. (this[offset + 2] << 16)) +
  1157. (this[offset + 3] * 0x1000000)
  1158. }
  1159. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  1160. if (!noAssert) checkOffset(offset, 4, this.length)
  1161. return (this[offset] * 0x1000000) +
  1162. ((this[offset + 1] << 16) |
  1163. (this[offset + 2] << 8) |
  1164. this[offset + 3])
  1165. }
  1166. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  1167. offset = offset | 0
  1168. byteLength = byteLength | 0
  1169. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1170. var val = this[offset]
  1171. var mul = 1
  1172. var i = 0
  1173. while (++i < byteLength && (mul *= 0x100)) {
  1174. val += this[offset + i] * mul
  1175. }
  1176. mul *= 0x80
  1177. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1178. return val
  1179. }
  1180. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  1181. offset = offset | 0
  1182. byteLength = byteLength | 0
  1183. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1184. var i = byteLength
  1185. var mul = 1
  1186. var val = this[offset + --i]
  1187. while (i > 0 && (mul *= 0x100)) {
  1188. val += this[offset + --i] * mul
  1189. }
  1190. mul *= 0x80
  1191. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1192. return val
  1193. }
  1194. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  1195. if (!noAssert) checkOffset(offset, 1, this.length)
  1196. if (!(this[offset] & 0x80)) return (this[offset])
  1197. return ((0xff - this[offset] + 1) * -1)
  1198. }
  1199. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  1200. if (!noAssert) checkOffset(offset, 2, this.length)
  1201. var val = this[offset] | (this[offset + 1] << 8)
  1202. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1203. }
  1204. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  1205. if (!noAssert) checkOffset(offset, 2, this.length)
  1206. var val = this[offset + 1] | (this[offset] << 8)
  1207. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1208. }
  1209. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  1210. if (!noAssert) checkOffset(offset, 4, this.length)
  1211. return (this[offset]) |
  1212. (this[offset + 1] << 8) |
  1213. (this[offset + 2] << 16) |
  1214. (this[offset + 3] << 24)
  1215. }
  1216. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  1217. if (!noAssert) checkOffset(offset, 4, this.length)
  1218. return (this[offset] << 24) |
  1219. (this[offset + 1] << 16) |
  1220. (this[offset + 2] << 8) |
  1221. (this[offset + 3])
  1222. }
  1223. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  1224. if (!noAssert) checkOffset(offset, 4, this.length)
  1225. return ieee754.read(this, offset, true, 23, 4)
  1226. }
  1227. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  1228. if (!noAssert) checkOffset(offset, 4, this.length)
  1229. return ieee754.read(this, offset, false, 23, 4)
  1230. }
  1231. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  1232. if (!noAssert) checkOffset(offset, 8, this.length)
  1233. return ieee754.read(this, offset, true, 52, 8)
  1234. }
  1235. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  1236. if (!noAssert) checkOffset(offset, 8, this.length)
  1237. return ieee754.read(this, offset, false, 52, 8)
  1238. }
  1239. function checkInt (buf, value, offset, ext, max, min) {
  1240. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  1241. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  1242. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1243. }
  1244. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  1245. value = +value
  1246. offset = offset | 0
  1247. byteLength = byteLength | 0
  1248. if (!noAssert) {
  1249. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  1250. checkInt(this, value, offset, byteLength, maxBytes, 0)
  1251. }
  1252. var mul = 1
  1253. var i = 0
  1254. this[offset] = value & 0xFF
  1255. while (++i < byteLength && (mul *= 0x100)) {
  1256. this[offset + i] = (value / mul) & 0xFF
  1257. }
  1258. return offset + byteLength
  1259. }
  1260. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  1261. value = +value
  1262. offset = offset | 0
  1263. byteLength = byteLength | 0
  1264. if (!noAssert) {
  1265. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  1266. checkInt(this, value, offset, byteLength, maxBytes, 0)
  1267. }
  1268. var i = byteLength - 1
  1269. var mul = 1
  1270. this[offset + i] = value & 0xFF
  1271. while (--i >= 0 && (mul *= 0x100)) {
  1272. this[offset + i] = (value / mul) & 0xFF
  1273. }
  1274. return offset + byteLength
  1275. }
  1276. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  1277. value = +value
  1278. offset = offset | 0
  1279. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  1280. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1281. this[offset] = (value & 0xff)
  1282. return offset + 1
  1283. }
  1284. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  1285. if (value < 0) value = 0xffff + value + 1
  1286. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
  1287. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  1288. (littleEndian ? i : 1 - i) * 8
  1289. }
  1290. }
  1291. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  1292. value = +value
  1293. offset = offset | 0
  1294. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1295. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1296. this[offset] = (value & 0xff)
  1297. this[offset + 1] = (value >>> 8)
  1298. } else {
  1299. objectWriteUInt16(this, value, offset, true)
  1300. }
  1301. return offset + 2
  1302. }
  1303. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  1304. value = +value
  1305. offset = offset | 0
  1306. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1307. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1308. this[offset] = (value >>> 8)
  1309. this[offset + 1] = (value & 0xff)
  1310. } else {
  1311. objectWriteUInt16(this, value, offset, false)
  1312. }
  1313. return offset + 2
  1314. }
  1315. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  1316. if (value < 0) value = 0xffffffff + value + 1
  1317. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
  1318. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
  1319. }
  1320. }
  1321. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  1322. value = +value
  1323. offset = offset | 0
  1324. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1325. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1326. this[offset + 3] = (value >>> 24)
  1327. this[offset + 2] = (value >>> 16)
  1328. this[offset + 1] = (value >>> 8)
  1329. this[offset] = (value & 0xff)
  1330. } else {
  1331. objectWriteUInt32(this, value, offset, true)
  1332. }
  1333. return offset + 4
  1334. }
  1335. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  1336. value = +value
  1337. offset = offset | 0
  1338. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1339. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1340. this[offset] = (value >>> 24)
  1341. this[offset + 1] = (value >>> 16)
  1342. this[offset + 2] = (value >>> 8)
  1343. this[offset + 3] = (value & 0xff)
  1344. } else {
  1345. objectWriteUInt32(this, value, offset, false)
  1346. }
  1347. return offset + 4
  1348. }
  1349. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  1350. value = +value
  1351. offset = offset | 0
  1352. if (!noAssert) {
  1353. var limit = Math.pow(2, 8 * byteLength - 1)
  1354. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1355. }
  1356. var i = 0
  1357. var mul = 1
  1358. var sub = 0
  1359. this[offset] = value & 0xFF
  1360. while (++i < byteLength && (mul *= 0x100)) {
  1361. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  1362. sub = 1
  1363. }
  1364. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1365. }
  1366. return offset + byteLength
  1367. }
  1368. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  1369. value = +value
  1370. offset = offset | 0
  1371. if (!noAssert) {
  1372. var limit = Math.pow(2, 8 * byteLength - 1)
  1373. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1374. }
  1375. var i = byteLength - 1
  1376. var mul = 1
  1377. var sub = 0
  1378. this[offset + i] = value & 0xFF
  1379. while (--i >= 0 && (mul *= 0x100)) {
  1380. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  1381. sub = 1
  1382. }
  1383. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1384. }
  1385. return offset + byteLength
  1386. }
  1387. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  1388. value = +value
  1389. offset = offset | 0
  1390. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  1391. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1392. if (value < 0) value = 0xff + value + 1
  1393. this[offset] = (value & 0xff)
  1394. return offset + 1
  1395. }
  1396. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  1397. value = +value
  1398. offset = offset | 0
  1399. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1400. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1401. this[offset] = (value & 0xff)
  1402. this[offset + 1] = (value >>> 8)
  1403. } else {
  1404. objectWriteUInt16(this, value, offset, true)
  1405. }
  1406. return offset + 2
  1407. }
  1408. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  1409. value = +value
  1410. offset = offset | 0
  1411. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1412. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1413. this[offset] = (value >>> 8)
  1414. this[offset + 1] = (value & 0xff)
  1415. } else {
  1416. objectWriteUInt16(this, value, offset, false)
  1417. }
  1418. return offset + 2
  1419. }
  1420. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  1421. value = +value
  1422. offset = offset | 0
  1423. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1424. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1425. this[offset] = (value & 0xff)
  1426. this[offset + 1] = (value >>> 8)
  1427. this[offset + 2] = (value >>> 16)
  1428. this[offset + 3] = (value >>> 24)
  1429. } else {
  1430. objectWriteUInt32(this, value, offset, true)
  1431. }
  1432. return offset + 4
  1433. }
  1434. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  1435. value = +value
  1436. offset = offset | 0
  1437. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1438. if (value < 0) value = 0xffffffff + value + 1
  1439. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1440. this[offset] = (value >>> 24)
  1441. this[offset + 1] = (value >>> 16)
  1442. this[offset + 2] = (value >>> 8)
  1443. this[offset + 3] = (value & 0xff)
  1444. } else {
  1445. objectWriteUInt32(this, value, offset, false)
  1446. }
  1447. return offset + 4
  1448. }
  1449. function checkIEEE754 (buf, value, offset, ext, max, min) {
  1450. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1451. if (offset < 0) throw new RangeError('Index out of range')
  1452. }
  1453. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  1454. if (!noAssert) {
  1455. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  1456. }
  1457. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  1458. return offset + 4
  1459. }
  1460. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  1461. return writeFloat(this, value, offset, true, noAssert)
  1462. }
  1463. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  1464. return writeFloat(this, value, offset, false, noAssert)
  1465. }
  1466. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  1467. if (!noAssert) {
  1468. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  1469. }
  1470. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  1471. return offset + 8
  1472. }
  1473. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  1474. return writeDouble(this, value, offset, true, noAssert)
  1475. }
  1476. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  1477. return writeDouble(this, value, offset, false, noAssert)
  1478. }
  1479. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  1480. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  1481. if (!start) start = 0
  1482. if (!end && end !== 0) end = this.length
  1483. if (targetStart >= target.length) targetStart = target.length
  1484. if (!targetStart) targetStart = 0
  1485. if (end > 0 && end < start) end = start
  1486. // Copy 0 bytes; we're done
  1487. if (end === start) return 0
  1488. if (target.length === 0 || this.length === 0) return 0
  1489. // Fatal error conditions
  1490. if (targetStart < 0) {
  1491. throw new RangeError('targetStart out of bounds')
  1492. }
  1493. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  1494. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  1495. // Are we oob?
  1496. if (end > this.length) end = this.length
  1497. if (target.length - targetStart < end - start) {
  1498. end = target.length - targetStart + start
  1499. }
  1500. var len = end - start
  1501. var i
  1502. if (this === target && start < targetStart && targetStart < end) {
  1503. // descending copy from end
  1504. for (i = len - 1; i >= 0; --i) {
  1505. target[i + targetStart] = this[i + start]
  1506. }
  1507. } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
  1508. // ascending copy from start
  1509. for (i = 0; i < len; ++i) {
  1510. target[i + targetStart] = this[i + start]
  1511. }
  1512. } else {
  1513. Uint8Array.prototype.set.call(
  1514. target,
  1515. this.subarray(start, start + len),
  1516. targetStart
  1517. )
  1518. }
  1519. return len
  1520. }
  1521. // Usage:
  1522. // buffer.fill(number[, offset[, end]])
  1523. // buffer.fill(buffer[, offset[, end]])
  1524. // buffer.fill(string[, offset[, end]][, encoding])
  1525. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  1526. // Handle string cases:
  1527. if (typeof val === 'string') {
  1528. if (typeof start === 'string') {
  1529. encoding = start
  1530. start = 0
  1531. end = this.length
  1532. } else if (typeof end === 'string') {
  1533. encoding = end
  1534. end = this.length
  1535. }
  1536. if (val.length === 1) {
  1537. var code = val.charCodeAt(0)
  1538. if (code < 256) {
  1539. val = code
  1540. }
  1541. }
  1542. if (encoding !== undefined && typeof encoding !== 'string') {
  1543. throw new TypeError('encoding must be a string')
  1544. }
  1545. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  1546. throw new TypeError('Unknown encoding: ' + encoding)
  1547. }
  1548. } else if (typeof val === 'number') {
  1549. val = val & 255
  1550. }
  1551. // Invalid ranges are not set to a default, so can range check early.
  1552. if (start < 0 || this.length < start || this.length < end) {
  1553. throw new RangeError('Out of range index')
  1554. }
  1555. if (end <= start) {
  1556. return this
  1557. }
  1558. start = start >>> 0
  1559. end = end === undefined ? this.length : end >>> 0
  1560. if (!val) val = 0
  1561. var i
  1562. if (typeof val === 'number') {
  1563. for (i = start; i < end; ++i) {
  1564. this[i] = val
  1565. }
  1566. } else {
  1567. var bytes = Buffer.isBuffer(val)
  1568. ? val
  1569. : utf8ToBytes(new Buffer(val, encoding).toString())
  1570. var len = bytes.length
  1571. for (i = 0; i < end - start; ++i) {
  1572. this[i + start] = bytes[i % len]
  1573. }
  1574. }
  1575. return this
  1576. }
  1577. // HELPER FUNCTIONS
  1578. // ================
  1579. var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
  1580. function base64clean (str) {
  1581. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  1582. str = stringtrim(str).replace(INVALID_BASE64_RE, '')
  1583. // Node converts strings with length < 2 to ''
  1584. if (str.length < 2) return ''
  1585. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  1586. while (str.length % 4 !== 0) {
  1587. str = str + '='
  1588. }
  1589. return str
  1590. }
  1591. function stringtrim (str) {
  1592. if (str.trim) return str.trim()
  1593. return str.replace(/^\s+|\s+$/g, '')
  1594. }
  1595. function toHex (n) {
  1596. if (n < 16) return '0' + n.toString(16)
  1597. return n.toString(16)
  1598. }
  1599. function utf8ToBytes (string, units) {
  1600. units = units || Infinity
  1601. var codePoint
  1602. var length = string.length
  1603. var leadSurrogate = null
  1604. var bytes = []
  1605. for (var i = 0; i < length; ++i) {
  1606. codePoint = string.charCodeAt(i)
  1607. // is surrogate component
  1608. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  1609. // last char was a lead
  1610. if (!leadSurrogate) {
  1611. // no lead yet
  1612. if (codePoint > 0xDBFF) {
  1613. // unexpected trail
  1614. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1615. continue
  1616. } else if (i + 1 === length) {
  1617. // unpaired lead
  1618. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1619. continue
  1620. }
  1621. // valid lead
  1622. leadSurrogate = codePoint
  1623. continue
  1624. }
  1625. // 2 leads in a row
  1626. if (codePoint < 0xDC00) {
  1627. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1628. leadSurrogate = codePoint
  1629. continue
  1630. }
  1631. // valid surrogate pair
  1632. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  1633. } else if (leadSurrogate) {
  1634. // valid bmp char, but last char was a lead
  1635. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1636. }
  1637. leadSurrogate = null
  1638. // encode utf8
  1639. if (codePoint < 0x80) {
  1640. if ((units -= 1) < 0) break
  1641. bytes.push(codePoint)
  1642. } else if (codePoint < 0x800) {
  1643. if ((units -= 2) < 0) break
  1644. bytes.push(
  1645. codePoint >> 0x6 | 0xC0,
  1646. codePoint & 0x3F | 0x80
  1647. )
  1648. } else if (codePoint < 0x10000) {
  1649. if ((units -= 3) < 0) break
  1650. bytes.push(
  1651. codePoint >> 0xC | 0xE0,
  1652. codePoint >> 0x6 & 0x3F | 0x80,
  1653. codePoint & 0x3F | 0x80
  1654. )
  1655. } else if (codePoint < 0x110000) {
  1656. if ((units -= 4) < 0) break
  1657. bytes.push(
  1658. codePoint >> 0x12 | 0xF0,
  1659. codePoint >> 0xC & 0x3F | 0x80,
  1660. codePoint >> 0x6 & 0x3F | 0x80,
  1661. codePoint & 0x3F | 0x80
  1662. )
  1663. } else {
  1664. throw new Error('Invalid code point')
  1665. }
  1666. }
  1667. return bytes
  1668. }
  1669. function asciiToBytes (str) {
  1670. var byteArray = []
  1671. for (var i = 0; i < str.length; ++i) {
  1672. // Node's code seems to be doing this and not & 0x7F..
  1673. byteArray.push(str.charCodeAt(i) & 0xFF)
  1674. }
  1675. return byteArray
  1676. }
  1677. function utf16leToBytes (str, units) {
  1678. var c, hi, lo
  1679. var byteArray = []
  1680. for (var i = 0; i < str.length; ++i) {
  1681. if ((units -= 2) < 0) break
  1682. c = str.charCodeAt(i)
  1683. hi = c >> 8
  1684. lo = c % 256
  1685. byteArray.push(lo)
  1686. byteArray.push(hi)
  1687. }
  1688. return byteArray
  1689. }
  1690. function base64ToBytes (str) {
  1691. return base64.toByteArray(base64clean(str))
  1692. }
  1693. function blitBuffer (src, dst, offset, length) {
  1694. for (var i = 0; i < length; ++i) {
  1695. if ((i + offset >= dst.length) || (i >= src.length)) break
  1696. dst[i + offset] = src[i]
  1697. }
  1698. return i
  1699. }
  1700. function isnan (val) {
  1701. return val !== val // eslint-disable-line no-self-compare
  1702. }
  1703. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1704. },{"base64-js":3,"ieee754":15,"isarray":21}],7:[function(_dereq_,module,exports){
  1705. /**
  1706. * This is the web browser implementation of `debug()`.
  1707. *
  1708. * Expose `debug()` as the module.
  1709. */
  1710. exports = module.exports = _dereq_('./debug');
  1711. exports.log = log;
  1712. exports.formatArgs = formatArgs;
  1713. exports.save = save;
  1714. exports.load = load;
  1715. exports.useColors = useColors;
  1716. exports.storage = 'undefined' != typeof chrome
  1717. && 'undefined' != typeof chrome.storage
  1718. ? chrome.storage.local
  1719. : localstorage();
  1720. /**
  1721. * Colors.
  1722. */
  1723. exports.colors = [
  1724. 'lightseagreen',
  1725. 'forestgreen',
  1726. 'goldenrod',
  1727. 'dodgerblue',
  1728. 'darkorchid',
  1729. 'crimson'
  1730. ];
  1731. /**
  1732. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  1733. * and the Firebug extension (any Firefox version) are known
  1734. * to support "%c" CSS customizations.
  1735. *
  1736. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  1737. */
  1738. function useColors() {
  1739. // is webkit? http://stackoverflow.com/a/16459606/376773
  1740. return ('WebkitAppearance' in document.documentElement.style) ||
  1741. // is firebug? http://stackoverflow.com/a/398120/376773
  1742. (window.console && (console.firebug || (console.exception && console.table))) ||
  1743. // is firefox >= v31?
  1744. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  1745. (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
  1746. }
  1747. /**
  1748. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  1749. */
  1750. exports.formatters.j = function(v) {
  1751. return JSON.stringify(v);
  1752. };
  1753. /**
  1754. * Colorize log arguments if enabled.
  1755. *
  1756. * @api public
  1757. */
  1758. function formatArgs() {
  1759. var args = arguments;
  1760. var useColors = this.useColors;
  1761. args[0] = (useColors ? '%c' : '')
  1762. + this.namespace
  1763. + (useColors ? ' %c' : ' ')
  1764. + args[0]
  1765. + (useColors ? '%c ' : ' ');
  1766. if (!useColors) return args;
  1767. var c = 'color: ' + this.color;
  1768. args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
  1769. // the final "%c" is somewhat tricky, because there could be other
  1770. // arguments passed either before or after the %c, so we need to
  1771. // figure out the correct index to insert the CSS into
  1772. var index = 0;
  1773. var lastC = 0;
  1774. args[0].replace(/%[a-z%]/g, function(match) {
  1775. if ('%%' === match) return;
  1776. index++;
  1777. if ('%c' === match) {
  1778. // we only are interested in the *last* %c
  1779. // (the user may have provided their own)
  1780. lastC = index;
  1781. }
  1782. });
  1783. args.splice(lastC, 0, c);
  1784. return args;
  1785. }
  1786. /**
  1787. * Invokes `console.log()` when available.
  1788. * No-op when `console.log` is not a "function".
  1789. *
  1790. * @api public
  1791. */
  1792. function log() {
  1793. // this hackery is required for IE8/9, where
  1794. // the `console.log` function doesn't have 'apply'
  1795. return 'object' === typeof console
  1796. && console.log
  1797. && Function.prototype.apply.call(console.log, console, arguments);
  1798. }
  1799. /**
  1800. * Save `namespaces`.
  1801. *
  1802. * @param {String} namespaces
  1803. * @api private
  1804. */
  1805. function save(namespaces) {
  1806. try {
  1807. if (null == namespaces) {
  1808. exports.storage.removeItem('debug');
  1809. } else {
  1810. exports.storage.debug = namespaces;
  1811. }
  1812. } catch(e) {}
  1813. }
  1814. /**
  1815. * Load `namespaces`.
  1816. *
  1817. * @return {String} returns the previously persisted debug modes
  1818. * @api private
  1819. */
  1820. function load() {
  1821. var r;
  1822. try {
  1823. r = exports.storage.debug;
  1824. } catch(e) {}
  1825. return r;
  1826. }
  1827. /**
  1828. * Enable namespaces listed in `localStorage.debug` initially.
  1829. */
  1830. exports.enable(load());
  1831. /**
  1832. * Localstorage attempts to return the localstorage.
  1833. *
  1834. * This is necessary because safari throws
  1835. * when a user disables cookies/localstorage
  1836. * and you attempt to access it.
  1837. *
  1838. * @return {LocalStorage}
  1839. * @api private
  1840. */
  1841. function localstorage(){
  1842. try {
  1843. return window.localStorage;
  1844. } catch (e) {}
  1845. }
  1846. },{"./debug":8}],8:[function(_dereq_,module,exports){
  1847. /**
  1848. * This is the common logic for both the Node.js and web browser
  1849. * implementations of `debug()`.
  1850. *
  1851. * Expose `debug()` as the module.
  1852. */
  1853. exports = module.exports = debug;
  1854. exports.coerce = coerce;
  1855. exports.disable = disable;
  1856. exports.enable = enable;
  1857. exports.enabled = enabled;
  1858. /**
  1859. * The currently active debug mode names, and names to skip.
  1860. */
  1861. exports.names = [];
  1862. exports.skips = [];
  1863. /**
  1864. * Map of special "%n" handling functions, for the debug "format" argument.
  1865. *
  1866. * Valid key names are a single, lowercased letter, i.e. "n".
  1867. */
  1868. exports.formatters = {};
  1869. /**
  1870. * Previously assigned color.
  1871. */
  1872. var prevColor = 0;
  1873. /**
  1874. * Select a color.
  1875. *
  1876. * @return {Number}
  1877. * @api private
  1878. */
  1879. function selectColor() {
  1880. return exports.colors[prevColor++ % exports.colors.length];
  1881. }
  1882. /**
  1883. * Create a debugger with the given `namespace`.
  1884. *
  1885. * @param {String} namespace
  1886. * @return {Function}
  1887. * @api public
  1888. */
  1889. function debug(namespace) {
  1890. // define the `disabled` version
  1891. function disabled() {
  1892. }
  1893. disabled.enabled = false;
  1894. // define the `enabled` version
  1895. function enabled() {
  1896. var self = enabled;
  1897. // add the `color` if not set
  1898. if (null == self.useColors) self.useColors = exports.useColors();
  1899. if (null == self.color && self.useColors) self.color = selectColor();
  1900. var args = Array.prototype.slice.call(arguments);
  1901. args[0] = exports.coerce(args[0]);
  1902. if ('string' !== typeof args[0]) {
  1903. // anything else let's inspect with %o
  1904. args = ['%o'].concat(args);
  1905. }
  1906. // apply any `formatters` transformations
  1907. var index = 0;
  1908. args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
  1909. // if we encounter an escaped % then don't increase the array index
  1910. if (match === '%%') return match;
  1911. index++;
  1912. var formatter = exports.formatters[format];
  1913. if ('function' === typeof formatter) {
  1914. var val = args[index];
  1915. match = formatter.call(self, val);
  1916. // now we need to remove `args[index]` since it's inlined in the `format`
  1917. args.splice(index, 1);
  1918. index--;
  1919. }
  1920. return match;
  1921. });
  1922. if ('function' === typeof exports.formatArgs) {
  1923. args = exports.formatArgs.apply(self, args);
  1924. }
  1925. var logFn = enabled.log || exports.log || console.log.bind(console);
  1926. logFn.apply(self, args);
  1927. }
  1928. enabled.enabled = true;
  1929. var fn = exports.enabled(namespace) ? enabled : disabled;
  1930. fn.namespace = namespace;
  1931. return fn;
  1932. }
  1933. /**
  1934. * Enables a debug mode by namespaces. This can include modes
  1935. * separated by a colon and wildcards.
  1936. *
  1937. * @param {String} namespaces
  1938. * @api public
  1939. */
  1940. function enable(namespaces) {
  1941. exports.save(namespaces);
  1942. var split = (namespaces || '').split(/[\s,]+/);
  1943. var len = split.length;
  1944. for (var i = 0; i < len; i++) {
  1945. if (!split[i]) continue; // ignore empty strings
  1946. namespaces = split[i].replace(/\*/g, '.*?');
  1947. if (namespaces[0] === '-') {
  1948. exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  1949. } else {
  1950. exports.names.push(new RegExp('^' + namespaces + '$'));
  1951. }
  1952. }
  1953. }
  1954. /**
  1955. * Disable debug output.
  1956. *
  1957. * @api public
  1958. */
  1959. function disable() {
  1960. exports.enable('');
  1961. }
  1962. /**
  1963. * Returns true if the given mode name is enabled, false otherwise.
  1964. *
  1965. * @param {String} name
  1966. * @return {Boolean}
  1967. * @api public
  1968. */
  1969. function enabled(name) {
  1970. var i, len;
  1971. for (i = 0, len = exports.skips.length; i < len; i++) {
  1972. if (exports.skips[i].test(name)) {
  1973. return false;
  1974. }
  1975. }
  1976. for (i = 0, len = exports.names.length; i < len; i++) {
  1977. if (exports.names[i].test(name)) {
  1978. return true;
  1979. }
  1980. }
  1981. return false;
  1982. }
  1983. /**
  1984. * Coerce `val`.
  1985. *
  1986. * @param {Mixed} val
  1987. * @return {Mixed}
  1988. * @api private
  1989. */
  1990. function coerce(val) {
  1991. if (val instanceof Error) return val.stack || val.message;
  1992. return val;
  1993. }
  1994. },{}],9:[function(_dereq_,module,exports){
  1995. 'use strict';
  1996. var isObj = _dereq_('is-obj');
  1997. var hasOwnProperty = Object.prototype.hasOwnProperty;
  1998. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  1999. function toObject(val) {
  2000. if (val === null || val === undefined) {
  2001. throw new TypeError('Sources cannot be null or undefined');
  2002. }
  2003. return Object(val);
  2004. }
  2005. function assignKey(to, from, key) {
  2006. var val = from[key];
  2007. if (val === undefined || val === null) {
  2008. return;
  2009. }
  2010. if (hasOwnProperty.call(to, key)) {
  2011. if (to[key] === undefined || to[key] === null) {
  2012. throw new TypeError('Cannot convert undefined or null to object (' + key + ')');
  2013. }
  2014. }
  2015. if (!hasOwnProperty.call(to, key) || !isObj(val)) {
  2016. to[key] = val;
  2017. } else {
  2018. to[key] = assign(Object(to[key]), from[key]);
  2019. }
  2020. }
  2021. function assign(to, from) {
  2022. if (to === from) {
  2023. return to;
  2024. }
  2025. from = Object(from);
  2026. for (var key in from) {
  2027. if (hasOwnProperty.call(from, key)) {
  2028. assignKey(to, from, key);
  2029. }
  2030. }
  2031. if (Object.getOwnPropertySymbols) {
  2032. var symbols = Object.getOwnPropertySymbols(from);
  2033. for (var i = 0; i < symbols.length; i++) {
  2034. if (propIsEnumerable.call(from, symbols[i])) {
  2035. assignKey(to, from, symbols[i]);
  2036. }
  2037. }
  2038. }
  2039. return to;
  2040. }
  2041. module.exports = function deepAssign(target) {
  2042. target = toObject(target);
  2043. for (var s = 1; s < arguments.length; s++) {
  2044. assign(target, arguments[s]);
  2045. }
  2046. return target;
  2047. };
  2048. },{"is-obj":20}],10:[function(_dereq_,module,exports){
  2049. /*! (C) WebReflection Mit Style License */
  2050. (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");
  2051. },{}],11:[function(_dereq_,module,exports){
  2052. module.exports = function(dtype) {
  2053. switch (dtype) {
  2054. case 'int8':
  2055. return Int8Array
  2056. case 'int16':
  2057. return Int16Array
  2058. case 'int32':
  2059. return Int32Array
  2060. case 'uint8':
  2061. return Uint8Array
  2062. case 'uint16':
  2063. return Uint16Array
  2064. case 'uint32':
  2065. return Uint32Array
  2066. case 'float32':
  2067. return Float32Array
  2068. case 'float64':
  2069. return Float64Array
  2070. case 'array':
  2071. return Array
  2072. case 'uint8_clamped':
  2073. return Uint8ClampedArray
  2074. }
  2075. }
  2076. },{}],12:[function(_dereq_,module,exports){
  2077. /*eslint new-cap:0*/
  2078. var dtype = _dereq_('dtype')
  2079. module.exports = flattenVertexData
  2080. function flattenVertexData (data, output, offset) {
  2081. if (!data) throw new TypeError('must specify data as first parameter')
  2082. offset = +(offset || 0) | 0
  2083. if (Array.isArray(data) && Array.isArray(data[0])) {
  2084. var dim = data[0].length
  2085. var length = data.length * dim
  2086. // no output specified, create a new typed array
  2087. if (!output || typeof output === 'string') {
  2088. output = new (dtype(output || 'float32'))(length + offset)
  2089. }
  2090. var dstLength = output.length - offset
  2091. if (length !== dstLength) {
  2092. throw new Error('source length ' + length + ' (' + dim + 'x' + data.length + ')' +
  2093. ' does not match destination length ' + dstLength)
  2094. }
  2095. for (var i = 0, k = offset; i < data.length; i++) {
  2096. for (var j = 0; j < dim; j++) {
  2097. output[k++] = data[i][j]
  2098. }
  2099. }
  2100. } else {
  2101. if (!output || typeof output === 'string') {
  2102. // no output, create a new one
  2103. var Ctor = dtype(output || 'float32')
  2104. if (offset === 0) {
  2105. output = new Ctor(data)
  2106. } else {
  2107. output = new Ctor(data.length + offset)
  2108. output.set(data, offset)
  2109. }
  2110. } else {
  2111. // store output in existing array
  2112. output.set(data, offset)
  2113. }
  2114. }
  2115. return output
  2116. }
  2117. },{"dtype":11}],13:[function(_dereq_,module,exports){
  2118. var isFunction = _dereq_('is-function')
  2119. module.exports = forEach
  2120. var toString = Object.prototype.toString
  2121. var hasOwnProperty = Object.prototype.hasOwnProperty
  2122. function forEach(list, iterator, context) {
  2123. if (!isFunction(iterator)) {
  2124. throw new TypeError('iterator must be a function')
  2125. }
  2126. if (arguments.length < 3) {
  2127. context = this
  2128. }
  2129. if (toString.call(list) === '[object Array]')
  2130. forEachArray(list, iterator, context)
  2131. else if (typeof list === 'string')
  2132. forEachString(list, iterator, context)
  2133. else
  2134. forEachObject(list, iterator, context)
  2135. }
  2136. function forEachArray(array, iterator, context) {
  2137. for (var i = 0, len = array.length; i < len; i++) {
  2138. if (hasOwnProperty.call(array, i)) {
  2139. iterator.call(context, array[i], i, array)
  2140. }
  2141. }
  2142. }
  2143. function forEachString(string, iterator, context) {
  2144. for (var i = 0, len = string.length; i < len; i++) {
  2145. // no such thing as a sparse string.
  2146. iterator.call(context, string.charAt(i), i, string)
  2147. }
  2148. }
  2149. function forEachObject(object, iterator, context) {
  2150. for (var k in object) {
  2151. if (hasOwnProperty.call(object, k)) {
  2152. iterator.call(context, object[k], k, object)
  2153. }
  2154. }
  2155. }
  2156. },{"is-function":19}],14:[function(_dereq_,module,exports){
  2157. (function (global){
  2158. if (typeof window !== "undefined") {
  2159. module.exports = window;
  2160. } else if (typeof global !== "undefined") {
  2161. module.exports = global;
  2162. } else if (typeof self !== "undefined"){
  2163. module.exports = self;
  2164. } else {
  2165. module.exports = {};
  2166. }
  2167. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2168. },{}],15:[function(_dereq_,module,exports){
  2169. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  2170. var e, m
  2171. var eLen = nBytes * 8 - mLen - 1
  2172. var eMax = (1 << eLen) - 1
  2173. var eBias = eMax >> 1
  2174. var nBits = -7
  2175. var i = isLE ? (nBytes - 1) : 0
  2176. var d = isLE ? -1 : 1
  2177. var s = buffer[offset + i]
  2178. i += d
  2179. e = s & ((1 << (-nBits)) - 1)
  2180. s >>= (-nBits)
  2181. nBits += eLen
  2182. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  2183. m = e & ((1 << (-nBits)) - 1)
  2184. e >>= (-nBits)
  2185. nBits += mLen
  2186. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  2187. if (e === 0) {
  2188. e = 1 - eBias
  2189. } else if (e === eMax) {
  2190. return m ? NaN : ((s ? -1 : 1) * Infinity)
  2191. } else {
  2192. m = m + Math.pow(2, mLen)
  2193. e = e - eBias
  2194. }
  2195. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  2196. }
  2197. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  2198. var e, m, c
  2199. var eLen = nBytes * 8 - mLen - 1
  2200. var eMax = (1 << eLen) - 1
  2201. var eBias = eMax >> 1
  2202. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  2203. var i = isLE ? 0 : (nBytes - 1)
  2204. var d = isLE ? 1 : -1
  2205. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  2206. value = Math.abs(value)
  2207. if (isNaN(value) || value === Infinity) {
  2208. m = isNaN(value) ? 1 : 0
  2209. e = eMax
  2210. } else {
  2211. e = Math.floor(Math.log(value) / Math.LN2)
  2212. if (value * (c = Math.pow(2, -e)) < 1) {
  2213. e--
  2214. c *= 2
  2215. }
  2216. if (e + eBias >= 1) {
  2217. value += rt / c
  2218. } else {
  2219. value += rt * Math.pow(2, 1 - eBias)
  2220. }
  2221. if (value * c >= 2) {
  2222. e++
  2223. c /= 2
  2224. }
  2225. if (e + eBias >= eMax) {
  2226. m = 0
  2227. e = eMax
  2228. } else if (e + eBias >= 1) {
  2229. m = (value * c - 1) * Math.pow(2, mLen)
  2230. e = e + eBias
  2231. } else {
  2232. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  2233. e = 0
  2234. }
  2235. }
  2236. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  2237. e = (e << mLen) | m
  2238. eLen += mLen
  2239. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  2240. buffer[offset + i - d] |= s * 128
  2241. }
  2242. },{}],16:[function(_dereq_,module,exports){
  2243. module.exports = function compile(property) {
  2244. if (!property || typeof property !== 'string')
  2245. throw new Error('must specify property for indexof search')
  2246. return new Function('array', 'value', 'start', [
  2247. 'start = start || 0',
  2248. 'for (var i=start; i<array.length; i++)',
  2249. ' if (array[i]["' + property +'"] === value)',
  2250. ' return i',
  2251. 'return -1'
  2252. ].join('\n'))
  2253. }
  2254. },{}],17:[function(_dereq_,module,exports){
  2255. if (typeof Object.create === 'function') {
  2256. // implementation from standard node.js 'util' module
  2257. module.exports = function inherits(ctor, superCtor) {
  2258. ctor.super_ = superCtor
  2259. ctor.prototype = Object.create(superCtor.prototype, {
  2260. constructor: {
  2261. value: ctor,
  2262. enumerable: false,
  2263. writable: true,
  2264. configurable: true
  2265. }
  2266. });
  2267. };
  2268. } else {
  2269. // old school shim for old browsers
  2270. module.exports = function inherits(ctor, superCtor) {
  2271. ctor.super_ = superCtor
  2272. var TempCtor = function () {}
  2273. TempCtor.prototype = superCtor.prototype
  2274. ctor.prototype = new TempCtor()
  2275. ctor.prototype.constructor = ctor
  2276. }
  2277. }
  2278. },{}],18:[function(_dereq_,module,exports){
  2279. /*!
  2280. * Determine if an object is a Buffer
  2281. *
  2282. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  2283. * @license MIT
  2284. */
  2285. // The _isBuffer check is for Safari 5-7 support, because it's missing
  2286. // Object.prototype.constructor. Remove this eventually
  2287. module.exports = function (obj) {
  2288. return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
  2289. }
  2290. function isBuffer (obj) {
  2291. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  2292. }
  2293. // For Node v0.10 support. Remove this eventually.
  2294. function isSlowBuffer (obj) {
  2295. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
  2296. }
  2297. },{}],19:[function(_dereq_,module,exports){
  2298. module.exports = isFunction
  2299. var toString = Object.prototype.toString
  2300. function isFunction (fn) {
  2301. var string = toString.call(fn)
  2302. return string === '[object Function]' ||
  2303. (typeof fn === 'function' && string !== '[object RegExp]') ||
  2304. (typeof window !== 'undefined' &&
  2305. // IE8 and below
  2306. (fn === window.setTimeout ||
  2307. fn === window.alert ||
  2308. fn === window.confirm ||
  2309. fn === window.prompt))
  2310. };
  2311. },{}],20:[function(_dereq_,module,exports){
  2312. 'use strict';
  2313. module.exports = function (x) {
  2314. var type = typeof x;
  2315. return x !== null && (type === 'object' || type === 'function');
  2316. };
  2317. },{}],21:[function(_dereq_,module,exports){
  2318. var toString = {}.toString;
  2319. module.exports = Array.isArray || function (arr) {
  2320. return toString.call(arr) == '[object Array]';
  2321. };
  2322. },{}],22:[function(_dereq_,module,exports){
  2323. var wordWrap = _dereq_('word-wrapper')
  2324. var xtend = _dereq_('xtend')
  2325. var findChar = _dereq_('indexof-property')('id')
  2326. var number = _dereq_('as-number')
  2327. var X_HEIGHTS = ['x', 'e', 'a', 'o', 'n', 's', 'r', 'c', 'u', 'm', 'v', 'w', 'z']
  2328. var M_WIDTHS = ['m', 'w']
  2329. var CAP_HEIGHTS = ['H', 'I', 'N', 'E', 'F', 'K', 'L', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  2330. var TAB_ID = '\t'.charCodeAt(0)
  2331. var SPACE_ID = ' '.charCodeAt(0)
  2332. var ALIGN_LEFT = 0,
  2333. ALIGN_CENTER = 1,
  2334. ALIGN_RIGHT = 2
  2335. module.exports = function createLayout(opt) {
  2336. return new TextLayout(opt)
  2337. }
  2338. function TextLayout(opt) {
  2339. this.glyphs = []
  2340. this._measure = this.computeMetrics.bind(this)
  2341. this.update(opt)
  2342. }
  2343. TextLayout.prototype.update = function(opt) {
  2344. opt = xtend({
  2345. measure: this._measure
  2346. }, opt)
  2347. this._opt = opt
  2348. this._opt.tabSize = number(this._opt.tabSize, 4)
  2349. if (!opt.font)
  2350. throw new Error('must provide a valid bitmap font')
  2351. var glyphs = this.glyphs
  2352. var text = opt.text||''
  2353. var font = opt.font
  2354. this._setupSpaceGlyphs(font)
  2355. var lines = wordWrap.lines(text, opt)
  2356. var minWidth = opt.width || 0
  2357. //clear glyphs
  2358. glyphs.length = 0
  2359. //get max line width
  2360. var maxLineWidth = lines.reduce(function(prev, line) {
  2361. return Math.max(prev, line.width, minWidth)
  2362. }, 0)
  2363. //the pen position
  2364. var x = 0
  2365. var y = 0
  2366. var lineHeight = number(opt.lineHeight, font.common.lineHeight)
  2367. var baseline = font.common.base
  2368. var descender = lineHeight-baseline
  2369. var letterSpacing = opt.letterSpacing || 0
  2370. var height = lineHeight * lines.length - descender
  2371. var align = getAlignType(this._opt.align)
  2372. //draw text along baseline
  2373. y -= height
  2374. //the metrics for this text layout
  2375. this._width = maxLineWidth
  2376. this._height = height
  2377. this._descender = lineHeight - baseline
  2378. this._baseline = baseline
  2379. this._xHeight = getXHeight(font)
  2380. this._capHeight = getCapHeight(font)
  2381. this._lineHeight = lineHeight
  2382. this._ascender = lineHeight - descender - this._xHeight
  2383. //layout each glyph
  2384. var self = this
  2385. lines.forEach(function(line, lineIndex) {
  2386. var start = line.start
  2387. var end = line.end
  2388. var lineWidth = line.width
  2389. var lastGlyph
  2390. //for each glyph in that line...
  2391. for (var i=start; i<end; i++) {
  2392. var id = text.charCodeAt(i)
  2393. var glyph = self.getGlyph(font, id)
  2394. if (glyph) {
  2395. if (lastGlyph)
  2396. x += getKerning(font, lastGlyph.id, glyph.id)
  2397. var tx = x
  2398. if (align === ALIGN_CENTER)
  2399. tx += (maxLineWidth-lineWidth)/2
  2400. else if (align === ALIGN_RIGHT)
  2401. tx += (maxLineWidth-lineWidth)
  2402. glyphs.push({
  2403. position: [tx, y],
  2404. data: glyph,
  2405. index: i,
  2406. line: lineIndex
  2407. })
  2408. //move pen forward
  2409. x += glyph.xadvance + letterSpacing
  2410. lastGlyph = glyph
  2411. }
  2412. }
  2413. //next line down
  2414. y += lineHeight
  2415. x = 0
  2416. })
  2417. this._linesTotal = lines.length;
  2418. }
  2419. TextLayout.prototype._setupSpaceGlyphs = function(font) {
  2420. //These are fallbacks, when the font doesn't include
  2421. //' ' or '\t' glyphs
  2422. this._fallbackSpaceGlyph = null
  2423. this._fallbackTabGlyph = null
  2424. if (!font.chars || font.chars.length === 0)
  2425. return
  2426. //try to get space glyph
  2427. //then fall back to the 'm' or 'w' glyphs
  2428. //then fall back to the first glyph available
  2429. var space = getGlyphById(font, SPACE_ID)
  2430. || getMGlyph(font)
  2431. || font.chars[0]
  2432. //and create a fallback for tab
  2433. var tabWidth = this._opt.tabSize * space.xadvance
  2434. this._fallbackSpaceGlyph = space
  2435. this._fallbackTabGlyph = xtend(space, {
  2436. x: 0, y: 0, xadvance: tabWidth, id: TAB_ID,
  2437. xoffset: 0, yoffset: 0, width: 0, height: 0
  2438. })
  2439. }
  2440. TextLayout.prototype.getGlyph = function(font, id) {
  2441. var glyph = getGlyphById(font, id)
  2442. if (glyph)
  2443. return glyph
  2444. else if (id === TAB_ID)
  2445. return this._fallbackTabGlyph
  2446. else if (id === SPACE_ID)
  2447. return this._fallbackSpaceGlyph
  2448. return null
  2449. }
  2450. TextLayout.prototype.computeMetrics = function(text, start, end, width) {
  2451. var letterSpacing = this._opt.letterSpacing || 0
  2452. var font = this._opt.font
  2453. var curPen = 0
  2454. var curWidth = 0
  2455. var count = 0
  2456. var glyph
  2457. var lastGlyph
  2458. if (!font.chars || font.chars.length === 0) {
  2459. return {
  2460. start: start,
  2461. end: start,
  2462. width: 0
  2463. }
  2464. }
  2465. end = Math.min(text.length, end)
  2466. for (var i=start; i < end; i++) {
  2467. var id = text.charCodeAt(i)
  2468. var glyph = this.getGlyph(font, id)
  2469. if (glyph) {
  2470. //move pen forward
  2471. var xoff = glyph.xoffset
  2472. var kern = lastGlyph ? getKerning(font, lastGlyph.id, glyph.id) : 0
  2473. curPen += kern
  2474. var nextPen = curPen + glyph.xadvance + letterSpacing
  2475. var nextWidth = curPen + glyph.width
  2476. //we've hit our limit; we can't move onto the next glyph
  2477. if (nextWidth >= width || nextPen >= width)
  2478. break
  2479. //otherwise continue along our line
  2480. curPen = nextPen
  2481. curWidth = nextWidth
  2482. lastGlyph = glyph
  2483. }
  2484. count++
  2485. }
  2486. //make sure rightmost edge lines up with rendered glyphs
  2487. if (lastGlyph)
  2488. curWidth += lastGlyph.xoffset
  2489. return {
  2490. start: start,
  2491. end: start + count,
  2492. width: curWidth
  2493. }
  2494. }
  2495. //getters for the private vars
  2496. ;['width', 'height',
  2497. 'descender', 'ascender',
  2498. 'xHeight', 'baseline',
  2499. 'capHeight',
  2500. 'lineHeight' ].forEach(addGetter)
  2501. function addGetter(name) {
  2502. Object.defineProperty(TextLayout.prototype, name, {
  2503. get: wrapper(name),
  2504. configurable: true
  2505. })
  2506. }
  2507. //create lookups for private vars
  2508. function wrapper(name) {
  2509. return (new Function([
  2510. 'return function '+name+'() {',
  2511. ' return this._'+name,
  2512. '}'
  2513. ].join('\n')))()
  2514. }
  2515. function getGlyphById(font, id) {
  2516. if (!font.chars || font.chars.length === 0)
  2517. return null
  2518. var glyphIdx = findChar(font.chars, id)
  2519. if (glyphIdx >= 0)
  2520. return font.chars[glyphIdx]
  2521. return null
  2522. }
  2523. function getXHeight(font) {
  2524. for (var i=0; i<X_HEIGHTS.length; i++) {
  2525. var id = X_HEIGHTS[i].charCodeAt(0)
  2526. var idx = findChar(font.chars, id)
  2527. if (idx >= 0)
  2528. return font.chars[idx].height
  2529. }
  2530. return 0
  2531. }
  2532. function getMGlyph(font) {
  2533. for (var i=0; i<M_WIDTHS.length; i++) {
  2534. var id = M_WIDTHS[i].charCodeAt(0)
  2535. var idx = findChar(font.chars, id)
  2536. if (idx >= 0)
  2537. return font.chars[idx]
  2538. }
  2539. return 0
  2540. }
  2541. function getCapHeight(font) {
  2542. for (var i=0; i<CAP_HEIGHTS.length; i++) {
  2543. var id = CAP_HEIGHTS[i].charCodeAt(0)
  2544. var idx = findChar(font.chars, id)
  2545. if (idx >= 0)
  2546. return font.chars[idx].height
  2547. }
  2548. return 0
  2549. }
  2550. function getKerning(font, left, right) {
  2551. if (!font.kernings || font.kernings.length === 0)
  2552. return 0
  2553. var table = font.kernings
  2554. for (var i=0; i<table.length; i++) {
  2555. var kern = table[i]
  2556. if (kern.first === left && kern.second === right)
  2557. return kern.amount
  2558. }
  2559. return 0
  2560. }
  2561. function getAlignType(align) {
  2562. if (align === 'center')
  2563. return ALIGN_CENTER
  2564. else if (align === 'right')
  2565. return ALIGN_RIGHT
  2566. return ALIGN_LEFT
  2567. }
  2568. },{"as-number":2,"indexof-property":16,"word-wrapper":50,"xtend":53}],23:[function(_dereq_,module,exports){
  2569. (function (Buffer){
  2570. var xhr = _dereq_('xhr')
  2571. var noop = function(){}
  2572. var parseASCII = _dereq_('parse-bmfont-ascii')
  2573. var parseXML = _dereq_('parse-bmfont-xml')
  2574. var readBinary = _dereq_('parse-bmfont-binary')
  2575. var isBinaryFormat = _dereq_('./lib/is-binary')
  2576. var xtend = _dereq_('xtend')
  2577. var xml2 = (function hasXML2() {
  2578. return window.XMLHttpRequest && "withCredentials" in new XMLHttpRequest
  2579. })()
  2580. module.exports = function(opt, cb) {
  2581. cb = typeof cb === 'function' ? cb : noop
  2582. if (typeof opt === 'string')
  2583. opt = { uri: opt }
  2584. else if (!opt)
  2585. opt = {}
  2586. var expectBinary = opt.binary
  2587. if (expectBinary)
  2588. opt = getBinaryOpts(opt)
  2589. xhr(opt, function(err, res, body) {
  2590. if (err)
  2591. return cb(err)
  2592. if (!/^2/.test(res.statusCode))
  2593. return cb(new Error('http status code: '+res.statusCode))
  2594. if (!body)
  2595. return cb(new Error('no body result'))
  2596. var binary = false
  2597. //if the response type is an array buffer,
  2598. //we need to convert it into a regular Buffer object
  2599. if (isArrayBuffer(body)) {
  2600. var array = new Uint8Array(body)
  2601. body = new Buffer(array, 'binary')
  2602. }
  2603. //now check the string/Buffer response
  2604. //and see if it has a binary BMF header
  2605. if (isBinaryFormat(body)) {
  2606. binary = true
  2607. //if we have a string, turn it into a Buffer
  2608. if (typeof body === 'string')
  2609. body = new Buffer(body, 'binary')
  2610. }
  2611. //we are not parsing a binary format, just ASCII/XML/etc
  2612. if (!binary) {
  2613. //might still be a buffer if responseType is 'arraybuffer'
  2614. if (Buffer.isBuffer(body))
  2615. body = body.toString(opt.encoding)
  2616. body = body.trim()
  2617. }
  2618. var result
  2619. try {
  2620. var type = res.headers['content-type']
  2621. if (binary)
  2622. result = readBinary(body)
  2623. else if (/json/.test(type) || body.charAt(0) === '{')
  2624. result = JSON.parse(body)
  2625. else if (/xml/.test(type) || body.charAt(0) === '<')
  2626. result = parseXML(body)
  2627. else
  2628. result = parseASCII(body)
  2629. } catch (e) {
  2630. cb(new Error('error parsing font '+e.message))
  2631. cb = noop
  2632. }
  2633. cb(null, result)
  2634. })
  2635. }
  2636. function isArrayBuffer(arr) {
  2637. var str = Object.prototype.toString
  2638. return str.call(arr) === '[object ArrayBuffer]'
  2639. }
  2640. function getBinaryOpts(opt) {
  2641. //IE10+ and other modern browsers support array buffers
  2642. if (xml2)
  2643. return xtend(opt, { responseType: 'arraybuffer' })
  2644. if (typeof window.XMLHttpRequest === 'undefined')
  2645. throw new Error('your browser does not support XHR loading')
  2646. //IE9 and XML1 browsers could still use an override
  2647. var req = new window.XMLHttpRequest()
  2648. req.overrideMimeType('text/plain; charset=x-user-defined')
  2649. return xtend({
  2650. xhr: req
  2651. }, opt)
  2652. }
  2653. }).call(this,_dereq_("buffer").Buffer)
  2654. },{"./lib/is-binary":24,"buffer":6,"parse-bmfont-ascii":26,"parse-bmfont-binary":27,"parse-bmfont-xml":28,"xhr":51,"xtend":53}],24:[function(_dereq_,module,exports){
  2655. (function (Buffer){
  2656. var equal = _dereq_('buffer-equal')
  2657. var HEADER = new Buffer([66, 77, 70, 3])
  2658. module.exports = function(buf) {
  2659. if (typeof buf === 'string')
  2660. return buf.substring(0, 3) === 'BMF'
  2661. return buf.length > 4 && equal(buf.slice(0, 4), HEADER)
  2662. }
  2663. }).call(this,_dereq_("buffer").Buffer)
  2664. },{"buffer":6,"buffer-equal":5}],25:[function(_dereq_,module,exports){
  2665. 'use strict';
  2666. /* eslint-disable no-unused-vars */
  2667. var hasOwnProperty = Object.prototype.hasOwnProperty;
  2668. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  2669. function toObject(val) {
  2670. if (val === null || val === undefined) {
  2671. throw new TypeError('Object.assign cannot be called with null or undefined');
  2672. }
  2673. return Object(val);
  2674. }
  2675. function shouldUseNative() {
  2676. try {
  2677. if (!Object.assign) {
  2678. return false;
  2679. }
  2680. // Detect buggy property enumeration order in older V8 versions.
  2681. // https://bugs.chromium.org/p/v8/issues/detail?id=4118
  2682. var test1 = new String('abc'); // eslint-disable-line
  2683. test1[5] = 'de';
  2684. if (Object.getOwnPropertyNames(test1)[0] === '5') {
  2685. return false;
  2686. }
  2687. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  2688. var test2 = {};
  2689. for (var i = 0; i < 10; i++) {
  2690. test2['_' + String.fromCharCode(i)] = i;
  2691. }
  2692. var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
  2693. return test2[n];
  2694. });
  2695. if (order2.join('') !== '0123456789') {
  2696. return false;
  2697. }
  2698. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  2699. var test3 = {};
  2700. 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
  2701. test3[letter] = letter;
  2702. });
  2703. if (Object.keys(Object.assign({}, test3)).join('') !==
  2704. 'abcdefghijklmnopqrst') {
  2705. return false;
  2706. }
  2707. return true;
  2708. } catch (e) {
  2709. // We don't expect any of the above to throw, but better to be safe.
  2710. return false;
  2711. }
  2712. }
  2713. module.exports = shouldUseNative() ? Object.assign : function (target, source) {
  2714. var from;
  2715. var to = toObject(target);
  2716. var symbols;
  2717. for (var s = 1; s < arguments.length; s++) {
  2718. from = Object(arguments[s]);
  2719. for (var key in from) {
  2720. if (hasOwnProperty.call(from, key)) {
  2721. to[key] = from[key];
  2722. }
  2723. }
  2724. if (Object.getOwnPropertySymbols) {
  2725. symbols = Object.getOwnPropertySymbols(from);
  2726. for (var i = 0; i < symbols.length; i++) {
  2727. if (propIsEnumerable.call(from, symbols[i])) {
  2728. to[symbols[i]] = from[symbols[i]];
  2729. }
  2730. }
  2731. }
  2732. }
  2733. return to;
  2734. };
  2735. },{}],26:[function(_dereq_,module,exports){
  2736. module.exports = function parseBMFontAscii(data) {
  2737. if (!data)
  2738. throw new Error('no data provided')
  2739. data = data.toString().trim()
  2740. var output = {
  2741. pages: [],
  2742. chars: [],
  2743. kernings: []
  2744. }
  2745. var lines = data.split(/\r\n?|\n/g)
  2746. if (lines.length === 0)
  2747. throw new Error('no data in BMFont file')
  2748. for (var i = 0; i < lines.length; i++) {
  2749. var lineData = splitLine(lines[i], i)
  2750. if (!lineData) //skip empty lines
  2751. continue
  2752. if (lineData.key === 'page') {
  2753. if (typeof lineData.data.id !== 'number')
  2754. throw new Error('malformed file at line ' + i + ' -- needs page id=N')
  2755. if (typeof lineData.data.file !== 'string')
  2756. throw new Error('malformed file at line ' + i + ' -- needs page file="path"')
  2757. output.pages[lineData.data.id] = lineData.data.file
  2758. } else if (lineData.key === 'chars' || lineData.key === 'kernings') {
  2759. //... do nothing for these two ...
  2760. } else if (lineData.key === 'char') {
  2761. output.chars.push(lineData.data)
  2762. } else if (lineData.key === 'kerning') {
  2763. output.kernings.push(lineData.data)
  2764. } else {
  2765. output[lineData.key] = lineData.data
  2766. }
  2767. }
  2768. return output
  2769. }
  2770. function splitLine(line, idx) {
  2771. line = line.replace(/\t+/g, ' ').trim()
  2772. if (!line)
  2773. return null
  2774. var space = line.indexOf(' ')
  2775. if (space === -1)
  2776. throw new Error("no named row at line " + idx)
  2777. var key = line.substring(0, space)
  2778. line = line.substring(space + 1)
  2779. //clear "letter" field as it is non-standard and
  2780. //requires additional complexity to parse " / = symbols
  2781. line = line.replace(/letter=[\'\"]\S+[\'\"]/gi, '')
  2782. line = line.split("=")
  2783. line = line.map(function(str) {
  2784. return str.trim().match((/(".*?"|[^"\s]+)+(?=\s*|\s*$)/g))
  2785. })
  2786. var data = []
  2787. for (var i = 0; i < line.length; i++) {
  2788. var dt = line[i]
  2789. if (i === 0) {
  2790. data.push({
  2791. key: dt[0],
  2792. data: ""
  2793. })
  2794. } else if (i === line.length - 1) {
  2795. data[data.length - 1].data = parseData(dt[0])
  2796. } else {
  2797. data[data.length - 1].data = parseData(dt[0])
  2798. data.push({
  2799. key: dt[1],
  2800. data: ""
  2801. })
  2802. }
  2803. }
  2804. var out = {
  2805. key: key,
  2806. data: {}
  2807. }
  2808. data.forEach(function(v) {
  2809. out.data[v.key] = v.data;
  2810. })
  2811. return out
  2812. }
  2813. function parseData(data) {
  2814. if (!data || data.length === 0)
  2815. return ""
  2816. if (data.indexOf('"') === 0 || data.indexOf("'") === 0)
  2817. return data.substring(1, data.length - 1)
  2818. if (data.indexOf(',') !== -1)
  2819. return parseIntList(data)
  2820. return parseInt(data, 10)
  2821. }
  2822. function parseIntList(data) {
  2823. return data.split(',').map(function(val) {
  2824. return parseInt(val, 10)
  2825. })
  2826. }
  2827. },{}],27:[function(_dereq_,module,exports){
  2828. var HEADER = [66, 77, 70]
  2829. module.exports = function readBMFontBinary(buf) {
  2830. if (buf.length < 6)
  2831. throw new Error('invalid buffer length for BMFont')
  2832. var header = HEADER.every(function(byte, i) {
  2833. return buf.readUInt8(i) === byte
  2834. })
  2835. if (!header)
  2836. throw new Error('BMFont missing BMF byte header')
  2837. var i = 3
  2838. var vers = buf.readUInt8(i++)
  2839. if (vers > 3)
  2840. throw new Error('Only supports BMFont Binary v3 (BMFont App v1.10)')
  2841. var target = { kernings: [], chars: [] }
  2842. for (var b=0; b<5; b++)
  2843. i += readBlock(target, buf, i)
  2844. return target
  2845. }
  2846. function readBlock(target, buf, i) {
  2847. if (i > buf.length-1)
  2848. return 0
  2849. var blockID = buf.readUInt8(i++)
  2850. var blockSize = buf.readInt32LE(i)
  2851. i += 4
  2852. switch(blockID) {
  2853. case 1:
  2854. target.info = readInfo(buf, i)
  2855. break
  2856. case 2:
  2857. target.common = readCommon(buf, i)
  2858. break
  2859. case 3:
  2860. target.pages = readPages(buf, i, blockSize)
  2861. break
  2862. case 4:
  2863. target.chars = readChars(buf, i, blockSize)
  2864. break
  2865. case 5:
  2866. target.kernings = readKernings(buf, i, blockSize)
  2867. break
  2868. }
  2869. return 5 + blockSize
  2870. }
  2871. function readInfo(buf, i) {
  2872. var info = {}
  2873. info.size = buf.readInt16LE(i)
  2874. var bitField = buf.readUInt8(i+2)
  2875. info.smooth = (bitField >> 7) & 1
  2876. info.unicode = (bitField >> 6) & 1
  2877. info.italic = (bitField >> 5) & 1
  2878. info.bold = (bitField >> 4) & 1
  2879. //fixedHeight is only mentioned in binary spec
  2880. if ((bitField >> 3) & 1)
  2881. info.fixedHeight = 1
  2882. info.charset = buf.readUInt8(i+3) || ''
  2883. info.stretchH = buf.readUInt16LE(i+4)
  2884. info.aa = buf.readUInt8(i+6)
  2885. info.padding = [
  2886. buf.readInt8(i+7),
  2887. buf.readInt8(i+8),
  2888. buf.readInt8(i+9),
  2889. buf.readInt8(i+10)
  2890. ]
  2891. info.spacing = [
  2892. buf.readInt8(i+11),
  2893. buf.readInt8(i+12)
  2894. ]
  2895. info.outline = buf.readUInt8(i+13)
  2896. info.face = readStringNT(buf, i+14)
  2897. return info
  2898. }
  2899. function readCommon(buf, i) {
  2900. var common = {}
  2901. common.lineHeight = buf.readUInt16LE(i)
  2902. common.base = buf.readUInt16LE(i+2)
  2903. common.scaleW = buf.readUInt16LE(i+4)
  2904. common.scaleH = buf.readUInt16LE(i+6)
  2905. common.pages = buf.readUInt16LE(i+8)
  2906. var bitField = buf.readUInt8(i+10)
  2907. common.packed = 0
  2908. common.alphaChnl = buf.readUInt8(i+11)
  2909. common.redChnl = buf.readUInt8(i+12)
  2910. common.greenChnl = buf.readUInt8(i+13)
  2911. common.blueChnl = buf.readUInt8(i+14)
  2912. return common
  2913. }
  2914. function readPages(buf, i, size) {
  2915. var pages = []
  2916. var text = readNameNT(buf, i)
  2917. var len = text.length+1
  2918. var count = size / len
  2919. for (var c=0; c<count; c++) {
  2920. pages[c] = buf.slice(i, i+text.length).toString('utf8')
  2921. i += len
  2922. }
  2923. return pages
  2924. }
  2925. function readChars(buf, i, blockSize) {
  2926. var chars = []
  2927. var count = blockSize / 20
  2928. for (var c=0; c<count; c++) {
  2929. var char = {}
  2930. var off = c*20
  2931. char.id = buf.readUInt32LE(i + 0 + off)
  2932. char.x = buf.readUInt16LE(i + 4 + off)
  2933. char.y = buf.readUInt16LE(i + 6 + off)
  2934. char.width = buf.readUInt16LE(i + 8 + off)
  2935. char.height = buf.readUInt16LE(i + 10 + off)
  2936. char.xoffset = buf.readInt16LE(i + 12 + off)
  2937. char.yoffset = buf.readInt16LE(i + 14 + off)
  2938. char.xadvance = buf.readInt16LE(i + 16 + off)
  2939. char.page = buf.readUInt8(i + 18 + off)
  2940. char.chnl = buf.readUInt8(i + 19 + off)
  2941. chars[c] = char
  2942. }
  2943. return chars
  2944. }
  2945. function readKernings(buf, i, blockSize) {
  2946. var kernings = []
  2947. var count = blockSize / 10
  2948. for (var c=0; c<count; c++) {
  2949. var kern = {}
  2950. var off = c*10
  2951. kern.first = buf.readUInt32LE(i + 0 + off)
  2952. kern.second = buf.readUInt32LE(i + 4 + off)
  2953. kern.amount = buf.readInt16LE(i + 8 + off)
  2954. kernings[c] = kern
  2955. }
  2956. return kernings
  2957. }
  2958. function readNameNT(buf, offset) {
  2959. var pos=offset
  2960. for (; pos<buf.length; pos++) {
  2961. if (buf[pos] === 0x00)
  2962. break
  2963. }
  2964. return buf.slice(offset, pos)
  2965. }
  2966. function readStringNT(buf, offset) {
  2967. return readNameNT(buf, offset).toString('utf8')
  2968. }
  2969. },{}],28:[function(_dereq_,module,exports){
  2970. var parseAttributes = _dereq_('./parse-attribs')
  2971. var parseFromString = _dereq_('xml-parse-from-string')
  2972. //In some cases element.attribute.nodeName can return
  2973. //all lowercase values.. so we need to map them to the correct
  2974. //case
  2975. var NAME_MAP = {
  2976. scaleh: 'scaleH',
  2977. scalew: 'scaleW',
  2978. stretchh: 'stretchH',
  2979. lineheight: 'lineHeight',
  2980. alphachnl: 'alphaChnl',
  2981. redchnl: 'redChnl',
  2982. greenchnl: 'greenChnl',
  2983. bluechnl: 'blueChnl'
  2984. }
  2985. module.exports = function parse(data) {
  2986. data = data.toString()
  2987. var xmlRoot = parseFromString(data)
  2988. var output = {
  2989. pages: [],
  2990. chars: [],
  2991. kernings: []
  2992. }
  2993. //get config settings
  2994. ;['info', 'common'].forEach(function(key) {
  2995. var element = xmlRoot.getElementsByTagName(key)[0]
  2996. if (element)
  2997. output[key] = parseAttributes(getAttribs(element))
  2998. })
  2999. //get page info
  3000. var pageRoot = xmlRoot.getElementsByTagName('pages')[0]
  3001. if (!pageRoot)
  3002. throw new Error('malformed file -- no <pages> element')
  3003. var pages = pageRoot.getElementsByTagName('page')
  3004. for (var i=0; i<pages.length; i++) {
  3005. var p = pages[i]
  3006. var id = parseInt(p.getAttribute('id'), 10)
  3007. var file = p.getAttribute('file')
  3008. if (isNaN(id))
  3009. throw new Error('malformed file -- page "id" attribute is NaN')
  3010. if (!file)
  3011. throw new Error('malformed file -- needs page "file" attribute')
  3012. output.pages[parseInt(id, 10)] = file
  3013. }
  3014. //get kernings / chars
  3015. ;['chars', 'kernings'].forEach(function(key) {
  3016. var element = xmlRoot.getElementsByTagName(key)[0]
  3017. if (!element)
  3018. return
  3019. var childTag = key.substring(0, key.length-1)
  3020. var children = element.getElementsByTagName(childTag)
  3021. for (var i=0; i<children.length; i++) {
  3022. var child = children[i]
  3023. output[key].push(parseAttributes(getAttribs(child)))
  3024. }
  3025. })
  3026. return output
  3027. }
  3028. function getAttribs(element) {
  3029. var attribs = getAttribList(element)
  3030. return attribs.reduce(function(dict, attrib) {
  3031. var key = mapName(attrib.nodeName)
  3032. dict[key] = attrib.nodeValue
  3033. return dict
  3034. }, {})
  3035. }
  3036. function getAttribList(element) {
  3037. //IE8+ and modern browsers
  3038. var attribs = []
  3039. for (var i=0; i<element.attributes.length; i++)
  3040. attribs.push(element.attributes[i])
  3041. return attribs
  3042. }
  3043. function mapName(nodeName) {
  3044. return NAME_MAP[nodeName.toLowerCase()] || nodeName
  3045. }
  3046. },{"./parse-attribs":29,"xml-parse-from-string":52}],29:[function(_dereq_,module,exports){
  3047. //Some versions of GlyphDesigner have a typo
  3048. //that causes some bugs with parsing.
  3049. //Need to confirm with recent version of the software
  3050. //to see whether this is still an issue or not.
  3051. var GLYPH_DESIGNER_ERROR = 'chasrset'
  3052. module.exports = function parseAttributes(obj) {
  3053. if (GLYPH_DESIGNER_ERROR in obj) {
  3054. obj['charset'] = obj[GLYPH_DESIGNER_ERROR]
  3055. delete obj[GLYPH_DESIGNER_ERROR]
  3056. }
  3057. for (var k in obj) {
  3058. if (k === 'face' || k === 'charset')
  3059. continue
  3060. else if (k === 'padding' || k === 'spacing')
  3061. obj[k] = parseIntList(obj[k])
  3062. else
  3063. obj[k] = parseInt(obj[k], 10)
  3064. }
  3065. return obj
  3066. }
  3067. function parseIntList(data) {
  3068. return data.split(',').map(function(val) {
  3069. return parseInt(val, 10)
  3070. })
  3071. }
  3072. },{}],30:[function(_dereq_,module,exports){
  3073. var trim = _dereq_('trim')
  3074. , forEach = _dereq_('for-each')
  3075. , isArray = function(arg) {
  3076. return Object.prototype.toString.call(arg) === '[object Array]';
  3077. }
  3078. module.exports = function (headers) {
  3079. if (!headers)
  3080. return {}
  3081. var result = {}
  3082. forEach(
  3083. trim(headers).split('\n')
  3084. , function (row) {
  3085. var index = row.indexOf(':')
  3086. , key = trim(row.slice(0, index)).toLowerCase()
  3087. , value = trim(row.slice(index + 1))
  3088. if (typeof(result[key]) === 'undefined') {
  3089. result[key] = value
  3090. } else if (isArray(result[key])) {
  3091. result[key].push(value)
  3092. } else {
  3093. result[key] = [ result[key], value ]
  3094. }
  3095. }
  3096. )
  3097. return result
  3098. }
  3099. },{"for-each":13,"trim":47}],31:[function(_dereq_,module,exports){
  3100. (function (process){
  3101. // Copyright Joyent, Inc. and other Node contributors.
  3102. //
  3103. // Permission is hereby granted, free of charge, to any person obtaining a
  3104. // copy of this software and associated documentation files (the
  3105. // "Software"), to deal in the Software without restriction, including
  3106. // without limitation the rights to use, copy, modify, merge, publish,
  3107. // distribute, sublicense, and/or sell copies of the Software, and to permit
  3108. // persons to whom the Software is furnished to do so, subject to the
  3109. // following conditions:
  3110. //
  3111. // The above copyright notice and this permission notice shall be included
  3112. // in all copies or substantial portions of the Software.
  3113. //
  3114. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  3115. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  3116. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  3117. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  3118. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  3119. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  3120. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  3121. // resolves . and .. elements in a path array with directory names there
  3122. // must be no slashes, empty elements, or device names (c:\) in the array
  3123. // (so also no leading and trailing slashes - it does not distinguish
  3124. // relative and absolute paths)
  3125. function normalizeArray(parts, allowAboveRoot) {
  3126. // if the path tries to go above the root, `up` ends up > 0
  3127. var up = 0;
  3128. for (var i = parts.length - 1; i >= 0; i--) {
  3129. var last = parts[i];
  3130. if (last === '.') {
  3131. parts.splice(i, 1);
  3132. } else if (last === '..') {
  3133. parts.splice(i, 1);
  3134. up++;
  3135. } else if (up) {
  3136. parts.splice(i, 1);
  3137. up--;
  3138. }
  3139. }
  3140. // if the path is allowed to go above the root, restore leading ..s
  3141. if (allowAboveRoot) {
  3142. for (; up--; up) {
  3143. parts.unshift('..');
  3144. }
  3145. }
  3146. return parts;
  3147. }
  3148. // Split a filename into [root, dir, basename, ext], unix version
  3149. // 'root' is just a slash, or nothing.
  3150. var splitPathRe =
  3151. /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
  3152. var splitPath = function(filename) {
  3153. return splitPathRe.exec(filename).slice(1);
  3154. };
  3155. // path.resolve([from ...], to)
  3156. // posix version
  3157. exports.resolve = function() {
  3158. var resolvedPath = '',
  3159. resolvedAbsolute = false;
  3160. for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
  3161. var path = (i >= 0) ? arguments[i] : process.cwd();
  3162. // Skip empty and invalid entries
  3163. if (typeof path !== 'string') {
  3164. throw new TypeError('Arguments to path.resolve must be strings');
  3165. } else if (!path) {
  3166. continue;
  3167. }
  3168. resolvedPath = path + '/' + resolvedPath;
  3169. resolvedAbsolute = path.charAt(0) === '/';
  3170. }
  3171. // At this point the path should be resolved to a full absolute path, but
  3172. // handle relative paths to be safe (might happen when process.cwd() fails)
  3173. // Normalize the path
  3174. resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
  3175. return !!p;
  3176. }), !resolvedAbsolute).join('/');
  3177. return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
  3178. };
  3179. // path.normalize(path)
  3180. // posix version
  3181. exports.normalize = function(path) {
  3182. var isAbsolute = exports.isAbsolute(path),
  3183. trailingSlash = substr(path, -1) === '/';
  3184. // Normalize the path
  3185. path = normalizeArray(filter(path.split('/'), function(p) {
  3186. return !!p;
  3187. }), !isAbsolute).join('/');
  3188. if (!path && !isAbsolute) {
  3189. path = '.';
  3190. }
  3191. if (path && trailingSlash) {
  3192. path += '/';
  3193. }
  3194. return (isAbsolute ? '/' : '') + path;
  3195. };
  3196. // posix version
  3197. exports.isAbsolute = function(path) {
  3198. return path.charAt(0) === '/';
  3199. };
  3200. // posix version
  3201. exports.join = function() {
  3202. var paths = Array.prototype.slice.call(arguments, 0);
  3203. return exports.normalize(filter(paths, function(p, index) {
  3204. if (typeof p !== 'string') {
  3205. throw new TypeError('Arguments to path.join must be strings');
  3206. }
  3207. return p;
  3208. }).join('/'));
  3209. };
  3210. // path.relative(from, to)
  3211. // posix version
  3212. exports.relative = function(from, to) {
  3213. from = exports.resolve(from).substr(1);
  3214. to = exports.resolve(to).substr(1);
  3215. function trim(arr) {
  3216. var start = 0;
  3217. for (; start < arr.length; start++) {
  3218. if (arr[start] !== '') break;
  3219. }
  3220. var end = arr.length - 1;
  3221. for (; end >= 0; end--) {
  3222. if (arr[end] !== '') break;
  3223. }
  3224. if (start > end) return [];
  3225. return arr.slice(start, end - start + 1);
  3226. }
  3227. var fromParts = trim(from.split('/'));
  3228. var toParts = trim(to.split('/'));
  3229. var length = Math.min(fromParts.length, toParts.length);
  3230. var samePartsLength = length;
  3231. for (var i = 0; i < length; i++) {
  3232. if (fromParts[i] !== toParts[i]) {
  3233. samePartsLength = i;
  3234. break;
  3235. }
  3236. }
  3237. var outputParts = [];
  3238. for (var i = samePartsLength; i < fromParts.length; i++) {
  3239. outputParts.push('..');
  3240. }
  3241. outputParts = outputParts.concat(toParts.slice(samePartsLength));
  3242. return outputParts.join('/');
  3243. };
  3244. exports.sep = '/';
  3245. exports.delimiter = ':';
  3246. exports.dirname = function(path) {
  3247. var result = splitPath(path),
  3248. root = result[0],
  3249. dir = result[1];
  3250. if (!root && !dir) {
  3251. // No dirname whatsoever
  3252. return '.';
  3253. }
  3254. if (dir) {
  3255. // It has a dirname, strip trailing slash
  3256. dir = dir.substr(0, dir.length - 1);
  3257. }
  3258. return root + dir;
  3259. };
  3260. exports.basename = function(path, ext) {
  3261. var f = splitPath(path)[2];
  3262. // TODO: make this comparison case-insensitive on windows?
  3263. if (ext && f.substr(-1 * ext.length) === ext) {
  3264. f = f.substr(0, f.length - ext.length);
  3265. }
  3266. return f;
  3267. };
  3268. exports.extname = function(path) {
  3269. return splitPath(path)[3];
  3270. };
  3271. function filter (xs, f) {
  3272. if (xs.filter) return xs.filter(f);
  3273. var res = [];
  3274. for (var i = 0; i < xs.length; i++) {
  3275. if (f(xs[i], i, xs)) res.push(xs[i]);
  3276. }
  3277. return res;
  3278. }
  3279. // String.prototype.substr - negative index don't work in IE8
  3280. var substr = 'ab'.substr(-1) === 'b'
  3281. ? function (str, start, len) { return str.substr(start, len) }
  3282. : function (str, start, len) {
  3283. if (start < 0) start = str.length + start;
  3284. return str.substr(start, len);
  3285. }
  3286. ;
  3287. }).call(this,_dereq_('_process'))
  3288. },{"_process":33}],32:[function(_dereq_,module,exports){
  3289. (function (global){
  3290. var performance = global.performance || {};
  3291. var present = (function () {
  3292. var names = ['now', 'webkitNow', 'msNow', 'mozNow', 'oNow'];
  3293. while (names.length) {
  3294. var name = names.shift();
  3295. if (name in performance) {
  3296. return performance[name].bind(performance);
  3297. }
  3298. }
  3299. var dateNow = Date.now || function () { return new Date().getTime(); };
  3300. var navigationStart = (performance.timing || {}).navigationStart || dateNow();
  3301. return function () {
  3302. return dateNow() - navigationStart;
  3303. };
  3304. }());
  3305. present.performanceNow = performance.now;
  3306. present.noConflict = function () {
  3307. performance.now = present.performanceNow;
  3308. };
  3309. present.conflict = function () {
  3310. performance.now = present;
  3311. };
  3312. present.conflict();
  3313. module.exports = present;
  3314. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  3315. },{}],33:[function(_dereq_,module,exports){
  3316. // shim for using process in browser
  3317. var process = module.exports = {};
  3318. // cached from whatever global is present so that test runners that stub it
  3319. // don't break things. But we need to wrap it in a try catch in case it is
  3320. // wrapped in strict mode code which doesn't define any globals. It's inside a
  3321. // function because try/catches deoptimize in certain engines.
  3322. var cachedSetTimeout;
  3323. var cachedClearTimeout;
  3324. function defaultSetTimout() {
  3325. throw new Error('setTimeout has not been defined');
  3326. }
  3327. function defaultClearTimeout () {
  3328. throw new Error('clearTimeout has not been defined');
  3329. }
  3330. (function () {
  3331. try {
  3332. if (typeof setTimeout === 'function') {
  3333. cachedSetTimeout = setTimeout;
  3334. } else {
  3335. cachedSetTimeout = defaultSetTimout;
  3336. }
  3337. } catch (e) {
  3338. cachedSetTimeout = defaultSetTimout;
  3339. }
  3340. try {
  3341. if (typeof clearTimeout === 'function') {
  3342. cachedClearTimeout = clearTimeout;
  3343. } else {
  3344. cachedClearTimeout = defaultClearTimeout;
  3345. }
  3346. } catch (e) {
  3347. cachedClearTimeout = defaultClearTimeout;
  3348. }
  3349. } ())
  3350. function runTimeout(fun) {
  3351. if (cachedSetTimeout === setTimeout) {
  3352. //normal enviroments in sane situations
  3353. return setTimeout(fun, 0);
  3354. }
  3355. // if setTimeout wasn't available but was latter defined
  3356. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  3357. cachedSetTimeout = setTimeout;
  3358. return setTimeout(fun, 0);
  3359. }
  3360. try {
  3361. // when when somebody has screwed with setTimeout but no I.E. maddness
  3362. return cachedSetTimeout(fun, 0);
  3363. } catch(e){
  3364. try {
  3365. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  3366. return cachedSetTimeout.call(null, fun, 0);
  3367. } catch(e){
  3368. // 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
  3369. return cachedSetTimeout.call(this, fun, 0);
  3370. }
  3371. }
  3372. }
  3373. function runClearTimeout(marker) {
  3374. if (cachedClearTimeout === clearTimeout) {
  3375. //normal enviroments in sane situations
  3376. return clearTimeout(marker);
  3377. }
  3378. // if clearTimeout wasn't available but was latter defined
  3379. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  3380. cachedClearTimeout = clearTimeout;
  3381. return clearTimeout(marker);
  3382. }
  3383. try {
  3384. // when when somebody has screwed with setTimeout but no I.E. maddness
  3385. return cachedClearTimeout(marker);
  3386. } catch (e){
  3387. try {
  3388. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  3389. return cachedClearTimeout.call(null, marker);
  3390. } catch (e){
  3391. // 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.
  3392. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  3393. return cachedClearTimeout.call(this, marker);
  3394. }
  3395. }
  3396. }
  3397. var queue = [];
  3398. var draining = false;
  3399. var currentQueue;
  3400. var queueIndex = -1;
  3401. function cleanUpNextTick() {
  3402. if (!draining || !currentQueue) {
  3403. return;
  3404. }
  3405. draining = false;
  3406. if (currentQueue.length) {
  3407. queue = currentQueue.concat(queue);
  3408. } else {
  3409. queueIndex = -1;
  3410. }
  3411. if (queue.length) {
  3412. drainQueue();
  3413. }
  3414. }
  3415. function drainQueue() {
  3416. if (draining) {
  3417. return;
  3418. }
  3419. var timeout = runTimeout(cleanUpNextTick);
  3420. draining = true;
  3421. var len = queue.length;
  3422. while(len) {
  3423. currentQueue = queue;
  3424. queue = [];
  3425. while (++queueIndex < len) {
  3426. if (currentQueue) {
  3427. currentQueue[queueIndex].run();
  3428. }
  3429. }
  3430. queueIndex = -1;
  3431. len = queue.length;
  3432. }
  3433. currentQueue = null;
  3434. draining = false;
  3435. runClearTimeout(timeout);
  3436. }
  3437. process.nextTick = function (fun) {
  3438. var args = new Array(arguments.length - 1);
  3439. if (arguments.length > 1) {
  3440. for (var i = 1; i < arguments.length; i++) {
  3441. args[i - 1] = arguments[i];
  3442. }
  3443. }
  3444. queue.push(new Item(fun, args));
  3445. if (queue.length === 1 && !draining) {
  3446. runTimeout(drainQueue);
  3447. }
  3448. };
  3449. // v8 likes predictible objects
  3450. function Item(fun, array) {
  3451. this.fun = fun;
  3452. this.array = array;
  3453. }
  3454. Item.prototype.run = function () {
  3455. this.fun.apply(null, this.array);
  3456. };
  3457. process.title = 'browser';
  3458. process.browser = true;
  3459. process.env = {};
  3460. process.argv = [];
  3461. process.version = ''; // empty string to avoid regexp issues
  3462. process.versions = {};
  3463. function noop() {}
  3464. process.on = noop;
  3465. process.addListener = noop;
  3466. process.once = noop;
  3467. process.off = noop;
  3468. process.removeListener = noop;
  3469. process.removeAllListeners = noop;
  3470. process.emit = noop;
  3471. process.binding = function (name) {
  3472. throw new Error('process.binding is not supported');
  3473. };
  3474. process.cwd = function () { return '/' };
  3475. process.chdir = function (dir) {
  3476. throw new Error('process.chdir is not supported');
  3477. };
  3478. process.umask = function() { return 0; };
  3479. },{}],34:[function(_dereq_,module,exports){
  3480. (function(root) {
  3481. // Store setTimeout reference so promise-polyfill will be unaffected by
  3482. // other code modifying setTimeout (like sinon.useFakeTimers())
  3483. var setTimeoutFunc = setTimeout;
  3484. // Use polyfill for setImmediate for performance gains
  3485. var asap = (typeof setImmediate === 'function' && setImmediate) ||
  3486. function(fn) { setTimeoutFunc(fn, 1); };
  3487. // Polyfill for Function.prototype.bind
  3488. function bind(fn, thisArg) {
  3489. return function() {
  3490. fn.apply(thisArg, arguments);
  3491. }
  3492. }
  3493. var isArray = Array.isArray || function(value) { return Object.prototype.toString.call(value) === "[object Array]" };
  3494. function Promise(fn) {
  3495. if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new');
  3496. if (typeof fn !== 'function') throw new TypeError('not a function');
  3497. this._state = null;
  3498. this._value = null;
  3499. this._deferreds = []
  3500. doResolve(fn, bind(resolve, this), bind(reject, this))
  3501. }
  3502. function handle(deferred) {
  3503. var me = this;
  3504. if (this._state === null) {
  3505. this._deferreds.push(deferred);
  3506. return
  3507. }
  3508. asap(function() {
  3509. var cb = me._state ? deferred.onFulfilled : deferred.onRejected
  3510. if (cb === null) {
  3511. (me._state ? deferred.resolve : deferred.reject)(me._value);
  3512. return;
  3513. }
  3514. var ret;
  3515. try {
  3516. ret = cb(me._value);
  3517. }
  3518. catch (e) {
  3519. deferred.reject(e);
  3520. return;
  3521. }
  3522. deferred.resolve(ret);
  3523. })
  3524. }
  3525. function resolve(newValue) {
  3526. try { //Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
  3527. if (newValue === this) throw new TypeError('A promise cannot be resolved with itself.');
  3528. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  3529. var then = newValue.then;
  3530. if (typeof then === 'function') {
  3531. doResolve(bind(then, newValue), bind(resolve, this), bind(reject, this));
  3532. return;
  3533. }
  3534. }
  3535. this._state = true;
  3536. this._value = newValue;
  3537. finale.call(this);
  3538. } catch (e) { reject.call(this, e); }
  3539. }
  3540. function reject(newValue) {
  3541. this._state = false;
  3542. this._value = newValue;
  3543. finale.call(this);
  3544. }
  3545. function finale() {
  3546. for (var i = 0, len = this._deferreds.length; i < len; i++) {
  3547. handle.call(this, this._deferreds[i]);
  3548. }
  3549. this._deferreds = null;
  3550. }
  3551. function Handler(onFulfilled, onRejected, resolve, reject){
  3552. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  3553. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  3554. this.resolve = resolve;
  3555. this.reject = reject;
  3556. }
  3557. /**
  3558. * Take a potentially misbehaving resolver function and make sure
  3559. * onFulfilled and onRejected are only called once.
  3560. *
  3561. * Makes no guarantees about asynchrony.
  3562. */
  3563. function doResolve(fn, onFulfilled, onRejected) {
  3564. var done = false;
  3565. try {
  3566. fn(function (value) {
  3567. if (done) return;
  3568. done = true;
  3569. onFulfilled(value);
  3570. }, function (reason) {
  3571. if (done) return;
  3572. done = true;
  3573. onRejected(reason);
  3574. })
  3575. } catch (ex) {
  3576. if (done) return;
  3577. done = true;
  3578. onRejected(ex);
  3579. }
  3580. }
  3581. Promise.prototype['catch'] = function (onRejected) {
  3582. return this.then(null, onRejected);
  3583. };
  3584. Promise.prototype.then = function(onFulfilled, onRejected) {
  3585. var me = this;
  3586. return new Promise(function(resolve, reject) {
  3587. handle.call(me, new Handler(onFulfilled, onRejected, resolve, reject));
  3588. })
  3589. };
  3590. Promise.all = function () {
  3591. var args = Array.prototype.slice.call(arguments.length === 1 && isArray(arguments[0]) ? arguments[0] : arguments);
  3592. return new Promise(function (resolve, reject) {
  3593. if (args.length === 0) return resolve([]);
  3594. var remaining = args.length;
  3595. function res(i, val) {
  3596. try {
  3597. if (val && (typeof val === 'object' || typeof val === 'function')) {
  3598. var then = val.then;
  3599. if (typeof then === 'function') {
  3600. then.call(val, function (val) { res(i, val) }, reject);
  3601. return;
  3602. }
  3603. }
  3604. args[i] = val;
  3605. if (--remaining === 0) {
  3606. resolve(args);
  3607. }
  3608. } catch (ex) {
  3609. reject(ex);
  3610. }
  3611. }
  3612. for (var i = 0; i < args.length; i++) {
  3613. res(i, args[i]);
  3614. }
  3615. });
  3616. };
  3617. Promise.resolve = function (value) {
  3618. if (value && typeof value === 'object' && value.constructor === Promise) {
  3619. return value;
  3620. }
  3621. return new Promise(function (resolve) {
  3622. resolve(value);
  3623. });
  3624. };
  3625. Promise.reject = function (value) {
  3626. return new Promise(function (resolve, reject) {
  3627. reject(value);
  3628. });
  3629. };
  3630. Promise.race = function (values) {
  3631. return new Promise(function (resolve, reject) {
  3632. for(var i = 0, len = values.length; i < len; i++) {
  3633. values[i].then(resolve, reject);
  3634. }
  3635. });
  3636. };
  3637. /**
  3638. * Set the immediate function to execute callbacks
  3639. * @param fn {function} Function to execute
  3640. * @private
  3641. */
  3642. Promise._setImmediateFn = function _setImmediateFn(fn) {
  3643. asap = fn;
  3644. };
  3645. if (typeof module !== 'undefined' && module.exports) {
  3646. module.exports = Promise;
  3647. } else if (!root.Promise) {
  3648. root.Promise = Promise;
  3649. }
  3650. })(this);
  3651. },{}],35:[function(_dereq_,module,exports){
  3652. var dtype = _dereq_('dtype')
  3653. var anArray = _dereq_('an-array')
  3654. var isBuffer = _dereq_('is-buffer')
  3655. var CW = [0, 2, 3]
  3656. var CCW = [2, 1, 3]
  3657. module.exports = function createQuadElements(array, opt) {
  3658. //if user didn't specify an output array
  3659. if (!array || !(anArray(array) || isBuffer(array))) {
  3660. opt = array || {}
  3661. array = null
  3662. }
  3663. if (typeof opt === 'number') //backwards-compatible
  3664. opt = { count: opt }
  3665. else
  3666. opt = opt || {}
  3667. var type = typeof opt.type === 'string' ? opt.type : 'uint16'
  3668. var count = typeof opt.count === 'number' ? opt.count : 1
  3669. var start = (opt.start || 0)
  3670. var dir = opt.clockwise !== false ? CW : CCW,
  3671. a = dir[0],
  3672. b = dir[1],
  3673. c = dir[2]
  3674. var numIndices = count * 6
  3675. var indices = array || new (dtype(type))(numIndices)
  3676. for (var i = 0, j = 0; i < numIndices; i += 6, j += 4) {
  3677. var x = i + start
  3678. indices[x + 0] = j + 0
  3679. indices[x + 1] = j + 1
  3680. indices[x + 2] = j + 2
  3681. indices[x + 3] = j + a
  3682. indices[x + 4] = j + b
  3683. indices[x + 5] = j + c
  3684. }
  3685. return indices
  3686. }
  3687. },{"an-array":1,"dtype":11,"is-buffer":18}],36:[function(_dereq_,module,exports){
  3688. /*:: type Attr = { [key: string]: string } */
  3689. /*
  3690. style-attr
  3691. ====
  3692. Very simple parsing and stringifying of style attributes.
  3693. `parse`
  3694. ----
  3695. Convert a style attribute string to an object.
  3696. */
  3697. /*:: declare function parse (raw: string): Attr */
  3698. function parse(raw) {
  3699. var trim = function (s) {
  3700. return s.trim();
  3701. };
  3702. var obj = {};
  3703. getKeyValueChunks(raw).map(trim).filter(Boolean).forEach(function (item) {
  3704. // split with `.indexOf` rather than `.split` because the value may also contain colons.
  3705. var pos = item.indexOf(':');
  3706. var key = item.substr(0, pos).trim();
  3707. var val = item.substr(pos + 1).trim();
  3708. obj[key] = val;
  3709. });
  3710. return obj;
  3711. }
  3712. /*
  3713. `getKeyValueChunks`
  3714. ----
  3715. Split a string into chunks matching `<key>: <value>`
  3716. */
  3717. /*:: declare function getKeyValueChunks (raw: string): Array<string> */
  3718. function getKeyValueChunks(raw) {
  3719. var chunks = [];
  3720. var offset = 0;
  3721. var sep = ';';
  3722. var hasUnclosedUrl = /url\([^\)]+$/;
  3723. var chunk = '';
  3724. var nextSplit;
  3725. while (offset < raw.length) {
  3726. nextSplit = raw.indexOf(sep, offset);
  3727. if (nextSplit === -1) {
  3728. nextSplit = raw.length;
  3729. }
  3730. chunk += raw.substring(offset, nextSplit);
  3731. // data URIs can contain semicolons, so make sure we get the whole thing
  3732. if (hasUnclosedUrl.test(chunk)) {
  3733. chunk += ';';
  3734. offset = nextSplit + 1;
  3735. continue;
  3736. }
  3737. chunks.push(chunk);
  3738. chunk = '';
  3739. offset = nextSplit + 1;
  3740. }
  3741. return chunks;
  3742. }
  3743. /*
  3744. `stringify`
  3745. ----
  3746. Convert an object into an attribute string
  3747. */
  3748. /*:: declare function stringify (obj: Attr): string */
  3749. function stringify(obj) {
  3750. return Object.keys(obj).map(function (key) {
  3751. return key + ':' + obj[key];
  3752. }).join(';');
  3753. }
  3754. /*
  3755. `normalize`
  3756. ----
  3757. Normalize an attribute string (eg. collapse duplicates)
  3758. */
  3759. /*:: declare function normalize (str: string): string */
  3760. function normalize(str) {
  3761. return stringify(parse(str));
  3762. }
  3763. module.exports.parse = parse;
  3764. module.exports.stringify = stringify;
  3765. module.exports.normalize = normalize;
  3766. },{}],37:[function(_dereq_,module,exports){
  3767. var createLayout = _dereq_('layout-bmfont-text')
  3768. var inherits = _dereq_('inherits')
  3769. var createIndices = _dereq_('quad-indices')
  3770. var buffer = _dereq_('three-buffer-vertex-data')
  3771. var assign = _dereq_('object-assign')
  3772. var vertices = _dereq_('./lib/vertices')
  3773. var utils = _dereq_('./lib/utils')
  3774. var Base = THREE.BufferGeometry
  3775. module.exports = function createTextGeometry (opt) {
  3776. return new TextGeometry(opt)
  3777. }
  3778. function TextGeometry (opt) {
  3779. Base.call(this)
  3780. if (typeof opt === 'string') {
  3781. opt = { text: opt }
  3782. }
  3783. // use these as default values for any subsequent
  3784. // calls to update()
  3785. this._opt = assign({}, opt)
  3786. // also do an initial setup...
  3787. if (opt) this.update(opt)
  3788. }
  3789. inherits(TextGeometry, Base)
  3790. TextGeometry.prototype.update = function (opt) {
  3791. if (typeof opt === 'string') {
  3792. opt = { text: opt }
  3793. }
  3794. // use constructor defaults
  3795. opt = assign({}, this._opt, opt)
  3796. if (!opt.font) {
  3797. throw new TypeError('must specify a { font } in options')
  3798. }
  3799. this.layout = createLayout(opt)
  3800. // get vec2 texcoords
  3801. var flipY = opt.flipY !== false
  3802. // the desired BMFont data
  3803. var font = opt.font
  3804. // determine texture size from font file
  3805. var texWidth = font.common.scaleW
  3806. var texHeight = font.common.scaleH
  3807. // get visible glyphs
  3808. var glyphs = this.layout.glyphs.filter(function (glyph) {
  3809. var bitmap = glyph.data
  3810. return bitmap.width * bitmap.height > 0
  3811. })
  3812. // provide visible glyphs for convenience
  3813. this.visibleGlyphs = glyphs
  3814. // get common vertex data
  3815. var positions = vertices.positions(glyphs)
  3816. var uvs = vertices.uvs(glyphs, texWidth, texHeight, flipY)
  3817. var indices = createIndices({
  3818. clockwise: true,
  3819. type: 'uint16',
  3820. count: glyphs.length
  3821. })
  3822. // update vertex data
  3823. buffer.index(this, indices, 1, 'uint16')
  3824. buffer.attr(this, 'position', positions, 2)
  3825. buffer.attr(this, 'uv', uvs, 2)
  3826. // update multipage data
  3827. if (!opt.multipage && 'page' in this.attributes) {
  3828. // disable multipage rendering
  3829. this.removeAttribute('page')
  3830. } else if (opt.multipage) {
  3831. var pages = vertices.pages(glyphs)
  3832. // enable multipage rendering
  3833. buffer.attr(this, 'page', pages, 1)
  3834. }
  3835. }
  3836. TextGeometry.prototype.computeBoundingSphere = function () {
  3837. if (this.boundingSphere === null) {
  3838. this.boundingSphere = new THREE.Sphere()
  3839. }
  3840. var positions = this.attributes.position.array
  3841. var itemSize = this.attributes.position.itemSize
  3842. if (!positions || !itemSize || positions.length < 2) {
  3843. this.boundingSphere.radius = 0
  3844. this.boundingSphere.center.set(0, 0, 0)
  3845. return
  3846. }
  3847. utils.computeSphere(positions, this.boundingSphere)
  3848. if (isNaN(this.boundingSphere.radius)) {
  3849. console.error('THREE.BufferGeometry.computeBoundingSphere(): ' +
  3850. 'Computed radius is NaN. The ' +
  3851. '"position" attribute is likely to have NaN values.')
  3852. }
  3853. }
  3854. TextGeometry.prototype.computeBoundingBox = function () {
  3855. if (this.boundingBox === null) {
  3856. this.boundingBox = new THREE.Box3()
  3857. }
  3858. var bbox = this.boundingBox
  3859. var positions = this.attributes.position.array
  3860. var itemSize = this.attributes.position.itemSize
  3861. if (!positions || !itemSize || positions.length < 2) {
  3862. bbox.makeEmpty()
  3863. return
  3864. }
  3865. utils.computeBox(positions, bbox)
  3866. }
  3867. },{"./lib/utils":38,"./lib/vertices":39,"inherits":17,"layout-bmfont-text":22,"object-assign":25,"quad-indices":35,"three-buffer-vertex-data":40}],38:[function(_dereq_,module,exports){
  3868. var itemSize = 2
  3869. var box = { min: [0, 0], max: [0, 0] }
  3870. function bounds (positions) {
  3871. var count = positions.length / itemSize
  3872. box.min[0] = positions[0]
  3873. box.min[1] = positions[1]
  3874. box.max[0] = positions[0]
  3875. box.max[1] = positions[1]
  3876. for (var i = 0; i < count; i++) {
  3877. var x = positions[i * itemSize + 0]
  3878. var y = positions[i * itemSize + 1]
  3879. box.min[0] = Math.min(x, box.min[0])
  3880. box.min[1] = Math.min(y, box.min[1])
  3881. box.max[0] = Math.max(x, box.max[0])
  3882. box.max[1] = Math.max(y, box.max[1])
  3883. }
  3884. }
  3885. module.exports.computeBox = function (positions, output) {
  3886. bounds(positions)
  3887. output.min.set(box.min[0], box.min[1], 0)
  3888. output.max.set(box.max[0], box.max[1], 0)
  3889. }
  3890. module.exports.computeSphere = function (positions, output) {
  3891. bounds(positions)
  3892. var minX = box.min[0]
  3893. var minY = box.min[1]
  3894. var maxX = box.max[0]
  3895. var maxY = box.max[1]
  3896. var width = maxX - minX
  3897. var height = maxY - minY
  3898. var length = Math.sqrt(width * width + height * height)
  3899. output.center.set(minX + width / 2, minY + height / 2, 0)
  3900. output.radius = length / 2
  3901. }
  3902. },{}],39:[function(_dereq_,module,exports){
  3903. module.exports.pages = function pages (glyphs) {
  3904. var pages = new Float32Array(glyphs.length * 4 * 1)
  3905. var i = 0
  3906. glyphs.forEach(function (glyph) {
  3907. var id = glyph.data.page || 0
  3908. pages[i++] = id
  3909. pages[i++] = id
  3910. pages[i++] = id
  3911. pages[i++] = id
  3912. })
  3913. return pages
  3914. }
  3915. module.exports.uvs = function uvs (glyphs, texWidth, texHeight, flipY) {
  3916. var uvs = new Float32Array(glyphs.length * 4 * 2)
  3917. var i = 0
  3918. glyphs.forEach(function (glyph) {
  3919. var bitmap = glyph.data
  3920. var bw = (bitmap.x + bitmap.width)
  3921. var bh = (bitmap.y + bitmap.height)
  3922. // top left position
  3923. var u0 = bitmap.x / texWidth
  3924. var v1 = bitmap.y / texHeight
  3925. var u1 = bw / texWidth
  3926. var v0 = bh / texHeight
  3927. if (flipY) {
  3928. v1 = (texHeight - bitmap.y) / texHeight
  3929. v0 = (texHeight - bh) / texHeight
  3930. }
  3931. // BL
  3932. uvs[i++] = u0
  3933. uvs[i++] = v1
  3934. // TL
  3935. uvs[i++] = u0
  3936. uvs[i++] = v0
  3937. // TR
  3938. uvs[i++] = u1
  3939. uvs[i++] = v0
  3940. // BR
  3941. uvs[i++] = u1
  3942. uvs[i++] = v1
  3943. })
  3944. return uvs
  3945. }
  3946. module.exports.positions = function positions (glyphs) {
  3947. var positions = new Float32Array(glyphs.length * 4 * 2)
  3948. var i = 0
  3949. glyphs.forEach(function (glyph) {
  3950. var bitmap = glyph.data
  3951. // bottom left position
  3952. var x = glyph.position[0] + bitmap.xoffset
  3953. var y = glyph.position[1] + bitmap.yoffset
  3954. // quad size
  3955. var w = bitmap.width
  3956. var h = bitmap.height
  3957. // BL
  3958. positions[i++] = x
  3959. positions[i++] = y
  3960. // TL
  3961. positions[i++] = x
  3962. positions[i++] = y + h
  3963. // TR
  3964. positions[i++] = x + w
  3965. positions[i++] = y + h
  3966. // BR
  3967. positions[i++] = x + w
  3968. positions[i++] = y
  3969. })
  3970. return positions
  3971. }
  3972. },{}],40:[function(_dereq_,module,exports){
  3973. var flatten = _dereq_('flatten-vertex-data')
  3974. var warned = false;
  3975. module.exports.attr = setAttribute
  3976. module.exports.index = setIndex
  3977. function setIndex (geometry, data, itemSize, dtype) {
  3978. if (typeof itemSize !== 'number') itemSize = 1
  3979. if (typeof dtype !== 'string') dtype = 'uint16'
  3980. var isR69 = !geometry.index && typeof geometry.setIndex !== 'function'
  3981. var attrib = isR69 ? geometry.getAttribute('index') : geometry.index
  3982. var newAttrib = updateAttribute(attrib, data, itemSize, dtype)
  3983. if (newAttrib) {
  3984. if (isR69) geometry.addAttribute('index', newAttrib)
  3985. else geometry.index = newAttrib
  3986. }
  3987. }
  3988. function setAttribute (geometry, key, data, itemSize, dtype) {
  3989. if (typeof itemSize !== 'number') itemSize = 3
  3990. if (typeof dtype !== 'string') dtype = 'float32'
  3991. if (Array.isArray(data) &&
  3992. Array.isArray(data[0]) &&
  3993. data[0].length !== itemSize) {
  3994. throw new Error('Nested vertex array has unexpected size; expected ' +
  3995. itemSize + ' but found ' + data[0].length)
  3996. }
  3997. var attrib = geometry.getAttribute(key)
  3998. var newAttrib = updateAttribute(attrib, data, itemSize, dtype)
  3999. if (newAttrib) {
  4000. geometry.addAttribute(key, newAttrib)
  4001. }
  4002. }
  4003. function updateAttribute (attrib, data, itemSize, dtype) {
  4004. data = data || []
  4005. if (!attrib || rebuildAttribute(attrib, data, itemSize)) {
  4006. // create a new array with desired type
  4007. data = flatten(data, dtype)
  4008. var needsNewBuffer = attrib && typeof attrib.setArray !== 'function'
  4009. if (!attrib || needsNewBuffer) {
  4010. // We are on an old version of ThreeJS which can't
  4011. // support growing / shrinking buffers, so we need
  4012. // to build a new buffer
  4013. if (needsNewBuffer && !warned) {
  4014. warned = true
  4015. console.warn([
  4016. 'A WebGL buffer is being updated with a new size or itemSize, ',
  4017. 'however this version of ThreeJS only supports fixed-size buffers.',
  4018. '\nThe old buffer may still be kept in memory.\n',
  4019. 'To avoid memory leaks, it is recommended that you dispose ',
  4020. 'your geometries and create new ones, or update to ThreeJS r82 or newer.\n',
  4021. 'See here for discussion:\n',
  4022. 'https://github.com/mrdoob/three.js/pull/9631'
  4023. ].join(''))
  4024. }
  4025. // Build a new attribute
  4026. attrib = new THREE.BufferAttribute(data, itemSize);
  4027. }
  4028. attrib.itemSize = itemSize
  4029. attrib.needsUpdate = true
  4030. // New versions of ThreeJS suggest using setArray
  4031. // to change the data. It will use bufferData internally,
  4032. // so you can change the array size without any issues
  4033. if (typeof attrib.setArray === 'function') {
  4034. attrib.setArray(data)
  4035. }
  4036. return attrib
  4037. } else {
  4038. // copy data into the existing array
  4039. flatten(data, attrib.array)
  4040. attrib.needsUpdate = true
  4041. return null
  4042. }
  4043. }
  4044. // Test whether the attribute needs to be re-created,
  4045. // returns false if we can re-use it as-is.
  4046. function rebuildAttribute (attrib, data, itemSize) {
  4047. if (attrib.itemSize !== itemSize) return true
  4048. if (!attrib.array) return true
  4049. var attribLength = attrib.array.length
  4050. if (Array.isArray(data) && Array.isArray(data[0])) {
  4051. // [ [ x, y, z ] ]
  4052. return attribLength !== data.length * itemSize
  4053. } else {
  4054. // [ x, y, z ]
  4055. return attribLength !== data.length
  4056. }
  4057. return false
  4058. }
  4059. },{"flatten-vertex-data":12}],41:[function(_dereq_,module,exports){
  4060. (function (global, factory) {
  4061. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  4062. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4063. (factory((global.THREE = global.THREE || {})));
  4064. }(this, (function (exports) { 'use strict';
  4065. // Polyfills
  4066. if ( Number.EPSILON === undefined ) {
  4067. Number.EPSILON = Math.pow( 2, - 52 );
  4068. }
  4069. //
  4070. if ( Math.sign === undefined ) {
  4071. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  4072. Math.sign = function ( x ) {
  4073. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x;
  4074. };
  4075. }
  4076. if ( Function.prototype.name === undefined ) {
  4077. // Missing in IE9-11.
  4078. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  4079. Object.defineProperty( Function.prototype, 'name', {
  4080. get: function () {
  4081. return this.toString().match( /^\s*function\s*([^\(\s]*)/ )[ 1 ];
  4082. }
  4083. } );
  4084. }
  4085. if ( Object.assign === undefined ) {
  4086. // Missing in IE.
  4087. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  4088. ( function () {
  4089. Object.assign = function ( target ) {
  4090. 'use strict';
  4091. if ( target === undefined || target === null ) {
  4092. throw new TypeError( 'Cannot convert undefined or null to object' );
  4093. }
  4094. var output = Object( target );
  4095. for ( var index = 1; index < arguments.length; index ++ ) {
  4096. var source = arguments[ index ];
  4097. if ( source !== undefined && source !== null ) {
  4098. for ( var nextKey in source ) {
  4099. if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) {
  4100. output[ nextKey ] = source[ nextKey ];
  4101. }
  4102. }
  4103. }
  4104. }
  4105. return output;
  4106. };
  4107. } )();
  4108. }
  4109. /**
  4110. * https://github.com/mrdoob/eventdispatcher.js/
  4111. */
  4112. function EventDispatcher() {}
  4113. EventDispatcher.prototype = {
  4114. addEventListener: function ( type, listener ) {
  4115. if ( this._listeners === undefined ) this._listeners = {};
  4116. var listeners = this._listeners;
  4117. if ( listeners[ type ] === undefined ) {
  4118. listeners[ type ] = [];
  4119. }
  4120. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  4121. listeners[ type ].push( listener );
  4122. }
  4123. },
  4124. hasEventListener: function ( type, listener ) {
  4125. if ( this._listeners === undefined ) return false;
  4126. var listeners = this._listeners;
  4127. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  4128. },
  4129. removeEventListener: function ( type, listener ) {
  4130. if ( this._listeners === undefined ) return;
  4131. var listeners = this._listeners;
  4132. var listenerArray = listeners[ type ];
  4133. if ( listenerArray !== undefined ) {
  4134. var index = listenerArray.indexOf( listener );
  4135. if ( index !== - 1 ) {
  4136. listenerArray.splice( index, 1 );
  4137. }
  4138. }
  4139. },
  4140. dispatchEvent: function ( event ) {
  4141. if ( this._listeners === undefined ) return;
  4142. var listeners = this._listeners;
  4143. var listenerArray = listeners[ event.type ];
  4144. if ( listenerArray !== undefined ) {
  4145. event.target = this;
  4146. var array = [], i = 0;
  4147. var length = listenerArray.length;
  4148. for ( i = 0; i < length; i ++ ) {
  4149. array[ i ] = listenerArray[ i ];
  4150. }
  4151. for ( i = 0; i < length; i ++ ) {
  4152. array[ i ].call( this, event );
  4153. }
  4154. }
  4155. }
  4156. };
  4157. var REVISION = '84';
  4158. var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 };
  4159. var CullFaceNone = 0;
  4160. var CullFaceBack = 1;
  4161. var CullFaceFront = 2;
  4162. var CullFaceFrontBack = 3;
  4163. var FrontFaceDirectionCW = 0;
  4164. var FrontFaceDirectionCCW = 1;
  4165. var BasicShadowMap = 0;
  4166. var PCFShadowMap = 1;
  4167. var PCFSoftShadowMap = 2;
  4168. var FrontSide = 0;
  4169. var BackSide = 1;
  4170. var DoubleSide = 2;
  4171. var FlatShading = 1;
  4172. var SmoothShading = 2;
  4173. var NoColors = 0;
  4174. var FaceColors = 1;
  4175. var VertexColors = 2;
  4176. var NoBlending = 0;
  4177. var NormalBlending = 1;
  4178. var AdditiveBlending = 2;
  4179. var SubtractiveBlending = 3;
  4180. var MultiplyBlending = 4;
  4181. var CustomBlending = 5;
  4182. var AddEquation = 100;
  4183. var SubtractEquation = 101;
  4184. var ReverseSubtractEquation = 102;
  4185. var MinEquation = 103;
  4186. var MaxEquation = 104;
  4187. var ZeroFactor = 200;
  4188. var OneFactor = 201;
  4189. var SrcColorFactor = 202;
  4190. var OneMinusSrcColorFactor = 203;
  4191. var SrcAlphaFactor = 204;
  4192. var OneMinusSrcAlphaFactor = 205;
  4193. var DstAlphaFactor = 206;
  4194. var OneMinusDstAlphaFactor = 207;
  4195. var DstColorFactor = 208;
  4196. var OneMinusDstColorFactor = 209;
  4197. var SrcAlphaSaturateFactor = 210;
  4198. var NeverDepth = 0;
  4199. var AlwaysDepth = 1;
  4200. var LessDepth = 2;
  4201. var LessEqualDepth = 3;
  4202. var EqualDepth = 4;
  4203. var GreaterEqualDepth = 5;
  4204. var GreaterDepth = 6;
  4205. var NotEqualDepth = 7;
  4206. var MultiplyOperation = 0;
  4207. var MixOperation = 1;
  4208. var AddOperation = 2;
  4209. var NoToneMapping = 0;
  4210. var LinearToneMapping = 1;
  4211. var ReinhardToneMapping = 2;
  4212. var Uncharted2ToneMapping = 3;
  4213. var CineonToneMapping = 4;
  4214. var UVMapping = 300;
  4215. var CubeReflectionMapping = 301;
  4216. var CubeRefractionMapping = 302;
  4217. var EquirectangularReflectionMapping = 303;
  4218. var EquirectangularRefractionMapping = 304;
  4219. var SphericalReflectionMapping = 305;
  4220. var CubeUVReflectionMapping = 306;
  4221. var CubeUVRefractionMapping = 307;
  4222. var RepeatWrapping = 1000;
  4223. var ClampToEdgeWrapping = 1001;
  4224. var MirroredRepeatWrapping = 1002;
  4225. var NearestFilter = 1003;
  4226. var NearestMipMapNearestFilter = 1004;
  4227. var NearestMipMapLinearFilter = 1005;
  4228. var LinearFilter = 1006;
  4229. var LinearMipMapNearestFilter = 1007;
  4230. var LinearMipMapLinearFilter = 1008;
  4231. var UnsignedByteType = 1009;
  4232. var ByteType = 1010;
  4233. var ShortType = 1011;
  4234. var UnsignedShortType = 1012;
  4235. var IntType = 1013;
  4236. var UnsignedIntType = 1014;
  4237. var FloatType = 1015;
  4238. var HalfFloatType = 1016;
  4239. var UnsignedShort4444Type = 1017;
  4240. var UnsignedShort5551Type = 1018;
  4241. var UnsignedShort565Type = 1019;
  4242. var UnsignedInt248Type = 1020;
  4243. var AlphaFormat = 1021;
  4244. var RGBFormat = 1022;
  4245. var RGBAFormat = 1023;
  4246. var LuminanceFormat = 1024;
  4247. var LuminanceAlphaFormat = 1025;
  4248. var RGBEFormat = RGBAFormat;
  4249. var DepthFormat = 1026;
  4250. var DepthStencilFormat = 1027;
  4251. var RGB_S3TC_DXT1_Format = 2001;
  4252. var RGBA_S3TC_DXT1_Format = 2002;
  4253. var RGBA_S3TC_DXT3_Format = 2003;
  4254. var RGBA_S3TC_DXT5_Format = 2004;
  4255. var RGB_PVRTC_4BPPV1_Format = 2100;
  4256. var RGB_PVRTC_2BPPV1_Format = 2101;
  4257. var RGBA_PVRTC_4BPPV1_Format = 2102;
  4258. var RGBA_PVRTC_2BPPV1_Format = 2103;
  4259. var RGB_ETC1_Format = 2151;
  4260. var LoopOnce = 2200;
  4261. var LoopRepeat = 2201;
  4262. var LoopPingPong = 2202;
  4263. var InterpolateDiscrete = 2300;
  4264. var InterpolateLinear = 2301;
  4265. var InterpolateSmooth = 2302;
  4266. var ZeroCurvatureEnding = 2400;
  4267. var ZeroSlopeEnding = 2401;
  4268. var WrapAroundEnding = 2402;
  4269. var TrianglesDrawMode = 0;
  4270. var TriangleStripDrawMode = 1;
  4271. var TriangleFanDrawMode = 2;
  4272. var LinearEncoding = 3000;
  4273. var sRGBEncoding = 3001;
  4274. var GammaEncoding = 3007;
  4275. var RGBEEncoding = 3002;
  4276. var LogLuvEncoding = 3003;
  4277. var RGBM7Encoding = 3004;
  4278. var RGBM16Encoding = 3005;
  4279. var RGBDEncoding = 3006;
  4280. var BasicDepthPacking = 3200;
  4281. var RGBADepthPacking = 3201;
  4282. /**
  4283. * @author alteredq / http://alteredqualia.com/
  4284. * @author mrdoob / http://mrdoob.com/
  4285. */
  4286. var _Math = {
  4287. DEG2RAD: Math.PI / 180,
  4288. RAD2DEG: 180 / Math.PI,
  4289. generateUUID: function () {
  4290. // http://www.broofa.com/Tools/Math.uuid.htm
  4291. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' );
  4292. var uuid = new Array( 36 );
  4293. var rnd = 0, r;
  4294. return function generateUUID() {
  4295. for ( var i = 0; i < 36; i ++ ) {
  4296. if ( i === 8 || i === 13 || i === 18 || i === 23 ) {
  4297. uuid[ i ] = '-';
  4298. } else if ( i === 14 ) {
  4299. uuid[ i ] = '4';
  4300. } else {
  4301. if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0;
  4302. r = rnd & 0xf;
  4303. rnd = rnd >> 4;
  4304. uuid[ i ] = chars[ ( i === 19 ) ? ( r & 0x3 ) | 0x8 : r ];
  4305. }
  4306. }
  4307. return uuid.join( '' );
  4308. };
  4309. }(),
  4310. clamp: function ( value, min, max ) {
  4311. return Math.max( min, Math.min( max, value ) );
  4312. },
  4313. // compute euclidian modulo of m % n
  4314. // https://en.wikipedia.org/wiki/Modulo_operation
  4315. euclideanModulo: function ( n, m ) {
  4316. return ( ( n % m ) + m ) % m;
  4317. },
  4318. // Linear mapping from range <a1, a2> to range <b1, b2>
  4319. mapLinear: function ( x, a1, a2, b1, b2 ) {
  4320. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  4321. },
  4322. // https://en.wikipedia.org/wiki/Linear_interpolation
  4323. lerp: function ( x, y, t ) {
  4324. return ( 1 - t ) * x + t * y;
  4325. },
  4326. // http://en.wikipedia.org/wiki/Smoothstep
  4327. smoothstep: function ( x, min, max ) {
  4328. if ( x <= min ) return 0;
  4329. if ( x >= max ) return 1;
  4330. x = ( x - min ) / ( max - min );
  4331. return x * x * ( 3 - 2 * x );
  4332. },
  4333. smootherstep: function ( x, min, max ) {
  4334. if ( x <= min ) return 0;
  4335. if ( x >= max ) return 1;
  4336. x = ( x - min ) / ( max - min );
  4337. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  4338. },
  4339. // Random integer from <low, high> interval
  4340. randInt: function ( low, high ) {
  4341. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  4342. },
  4343. // Random float from <low, high> interval
  4344. randFloat: function ( low, high ) {
  4345. return low + Math.random() * ( high - low );
  4346. },
  4347. // Random float from <-range/2, range/2> interval
  4348. randFloatSpread: function ( range ) {
  4349. return range * ( 0.5 - Math.random() );
  4350. },
  4351. degToRad: function ( degrees ) {
  4352. return degrees * _Math.DEG2RAD;
  4353. },
  4354. radToDeg: function ( radians ) {
  4355. return radians * _Math.RAD2DEG;
  4356. },
  4357. isPowerOfTwo: function ( value ) {
  4358. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  4359. },
  4360. nearestPowerOfTwo: function ( value ) {
  4361. return Math.pow( 2, Math.round( Math.log( value ) / Math.LN2 ) );
  4362. },
  4363. nextPowerOfTwo: function ( value ) {
  4364. value --;
  4365. value |= value >> 1;
  4366. value |= value >> 2;
  4367. value |= value >> 4;
  4368. value |= value >> 8;
  4369. value |= value >> 16;
  4370. value ++;
  4371. return value;
  4372. }
  4373. };
  4374. /**
  4375. * @author mrdoob / http://mrdoob.com/
  4376. * @author philogb / http://blog.thejit.org/
  4377. * @author egraether / http://egraether.com/
  4378. * @author zz85 / http://www.lab4games.net/zz85/blog
  4379. */
  4380. function Vector2( x, y ) {
  4381. this.x = x || 0;
  4382. this.y = y || 0;
  4383. }
  4384. Vector2.prototype = {
  4385. constructor: Vector2,
  4386. isVector2: true,
  4387. get width() {
  4388. return this.x;
  4389. },
  4390. set width( value ) {
  4391. this.x = value;
  4392. },
  4393. get height() {
  4394. return this.y;
  4395. },
  4396. set height( value ) {
  4397. this.y = value;
  4398. },
  4399. //
  4400. set: function ( x, y ) {
  4401. this.x = x;
  4402. this.y = y;
  4403. return this;
  4404. },
  4405. setScalar: function ( scalar ) {
  4406. this.x = scalar;
  4407. this.y = scalar;
  4408. return this;
  4409. },
  4410. setX: function ( x ) {
  4411. this.x = x;
  4412. return this;
  4413. },
  4414. setY: function ( y ) {
  4415. this.y = y;
  4416. return this;
  4417. },
  4418. setComponent: function ( index, value ) {
  4419. switch ( index ) {
  4420. case 0: this.x = value; break;
  4421. case 1: this.y = value; break;
  4422. default: throw new Error( 'index is out of range: ' + index );
  4423. }
  4424. return this;
  4425. },
  4426. getComponent: function ( index ) {
  4427. switch ( index ) {
  4428. case 0: return this.x;
  4429. case 1: return this.y;
  4430. default: throw new Error( 'index is out of range: ' + index );
  4431. }
  4432. },
  4433. clone: function () {
  4434. return new this.constructor( this.x, this.y );
  4435. },
  4436. copy: function ( v ) {
  4437. this.x = v.x;
  4438. this.y = v.y;
  4439. return this;
  4440. },
  4441. add: function ( v, w ) {
  4442. if ( w !== undefined ) {
  4443. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  4444. return this.addVectors( v, w );
  4445. }
  4446. this.x += v.x;
  4447. this.y += v.y;
  4448. return this;
  4449. },
  4450. addScalar: function ( s ) {
  4451. this.x += s;
  4452. this.y += s;
  4453. return this;
  4454. },
  4455. addVectors: function ( a, b ) {
  4456. this.x = a.x + b.x;
  4457. this.y = a.y + b.y;
  4458. return this;
  4459. },
  4460. addScaledVector: function ( v, s ) {
  4461. this.x += v.x * s;
  4462. this.y += v.y * s;
  4463. return this;
  4464. },
  4465. sub: function ( v, w ) {
  4466. if ( w !== undefined ) {
  4467. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  4468. return this.subVectors( v, w );
  4469. }
  4470. this.x -= v.x;
  4471. this.y -= v.y;
  4472. return this;
  4473. },
  4474. subScalar: function ( s ) {
  4475. this.x -= s;
  4476. this.y -= s;
  4477. return this;
  4478. },
  4479. subVectors: function ( a, b ) {
  4480. this.x = a.x - b.x;
  4481. this.y = a.y - b.y;
  4482. return this;
  4483. },
  4484. multiply: function ( v ) {
  4485. this.x *= v.x;
  4486. this.y *= v.y;
  4487. return this;
  4488. },
  4489. multiplyScalar: function ( scalar ) {
  4490. if ( isFinite( scalar ) ) {
  4491. this.x *= scalar;
  4492. this.y *= scalar;
  4493. } else {
  4494. this.x = 0;
  4495. this.y = 0;
  4496. }
  4497. return this;
  4498. },
  4499. divide: function ( v ) {
  4500. this.x /= v.x;
  4501. this.y /= v.y;
  4502. return this;
  4503. },
  4504. divideScalar: function ( scalar ) {
  4505. return this.multiplyScalar( 1 / scalar );
  4506. },
  4507. min: function ( v ) {
  4508. this.x = Math.min( this.x, v.x );
  4509. this.y = Math.min( this.y, v.y );
  4510. return this;
  4511. },
  4512. max: function ( v ) {
  4513. this.x = Math.max( this.x, v.x );
  4514. this.y = Math.max( this.y, v.y );
  4515. return this;
  4516. },
  4517. clamp: function ( min, max ) {
  4518. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  4519. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  4520. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  4521. return this;
  4522. },
  4523. clampScalar: function () {
  4524. var min, max;
  4525. return function clampScalar( minVal, maxVal ) {
  4526. if ( min === undefined ) {
  4527. min = new Vector2();
  4528. max = new Vector2();
  4529. }
  4530. min.set( minVal, minVal );
  4531. max.set( maxVal, maxVal );
  4532. return this.clamp( min, max );
  4533. };
  4534. }(),
  4535. clampLength: function ( min, max ) {
  4536. var length = this.length();
  4537. return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  4538. },
  4539. floor: function () {
  4540. this.x = Math.floor( this.x );
  4541. this.y = Math.floor( this.y );
  4542. return this;
  4543. },
  4544. ceil: function () {
  4545. this.x = Math.ceil( this.x );
  4546. this.y = Math.ceil( this.y );
  4547. return this;
  4548. },
  4549. round: function () {
  4550. this.x = Math.round( this.x );
  4551. this.y = Math.round( this.y );
  4552. return this;
  4553. },
  4554. roundToZero: function () {
  4555. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  4556. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  4557. return this;
  4558. },
  4559. negate: function () {
  4560. this.x = - this.x;
  4561. this.y = - this.y;
  4562. return this;
  4563. },
  4564. dot: function ( v ) {
  4565. return this.x * v.x + this.y * v.y;
  4566. },
  4567. lengthSq: function () {
  4568. return this.x * this.x + this.y * this.y;
  4569. },
  4570. length: function () {
  4571. return Math.sqrt( this.x * this.x + this.y * this.y );
  4572. },
  4573. lengthManhattan: function() {
  4574. return Math.abs( this.x ) + Math.abs( this.y );
  4575. },
  4576. normalize: function () {
  4577. return this.divideScalar( this.length() );
  4578. },
  4579. angle: function () {
  4580. // computes the angle in radians with respect to the positive x-axis
  4581. var angle = Math.atan2( this.y, this.x );
  4582. if ( angle < 0 ) angle += 2 * Math.PI;
  4583. return angle;
  4584. },
  4585. distanceTo: function ( v ) {
  4586. return Math.sqrt( this.distanceToSquared( v ) );
  4587. },
  4588. distanceToSquared: function ( v ) {
  4589. var dx = this.x - v.x, dy = this.y - v.y;
  4590. return dx * dx + dy * dy;
  4591. },
  4592. distanceToManhattan: function ( v ) {
  4593. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  4594. },
  4595. setLength: function ( length ) {
  4596. return this.multiplyScalar( length / this.length() );
  4597. },
  4598. lerp: function ( v, alpha ) {
  4599. this.x += ( v.x - this.x ) * alpha;
  4600. this.y += ( v.y - this.y ) * alpha;
  4601. return this;
  4602. },
  4603. lerpVectors: function ( v1, v2, alpha ) {
  4604. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  4605. },
  4606. equals: function ( v ) {
  4607. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  4608. },
  4609. fromArray: function ( array, offset ) {
  4610. if ( offset === undefined ) offset = 0;
  4611. this.x = array[ offset ];
  4612. this.y = array[ offset + 1 ];
  4613. return this;
  4614. },
  4615. toArray: function ( array, offset ) {
  4616. if ( array === undefined ) array = [];
  4617. if ( offset === undefined ) offset = 0;
  4618. array[ offset ] = this.x;
  4619. array[ offset + 1 ] = this.y;
  4620. return array;
  4621. },
  4622. fromBufferAttribute: function ( attribute, index, offset ) {
  4623. if ( offset !== undefined ) {
  4624. console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' );
  4625. }
  4626. this.x = attribute.getX( index );
  4627. this.y = attribute.getY( index );
  4628. return this;
  4629. },
  4630. rotateAround: function ( center, angle ) {
  4631. var c = Math.cos( angle ), s = Math.sin( angle );
  4632. var x = this.x - center.x;
  4633. var y = this.y - center.y;
  4634. this.x = x * c - y * s + center.x;
  4635. this.y = x * s + y * c + center.y;
  4636. return this;
  4637. }
  4638. };
  4639. /**
  4640. * @author mrdoob / http://mrdoob.com/
  4641. * @author alteredq / http://alteredqualia.com/
  4642. * @author szimek / https://github.com/szimek/
  4643. */
  4644. var textureId = 0;
  4645. function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  4646. Object.defineProperty( this, 'id', { value: textureId ++ } );
  4647. this.uuid = _Math.generateUUID();
  4648. this.name = '';
  4649. this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
  4650. this.mipmaps = [];
  4651. this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
  4652. this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
  4653. this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
  4654. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  4655. this.minFilter = minFilter !== undefined ? minFilter : LinearMipMapLinearFilter;
  4656. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  4657. this.format = format !== undefined ? format : RGBAFormat;
  4658. this.type = type !== undefined ? type : UnsignedByteType;
  4659. this.offset = new Vector2( 0, 0 );
  4660. this.repeat = new Vector2( 1, 1 );
  4661. this.generateMipmaps = true;
  4662. this.premultiplyAlpha = false;
  4663. this.flipY = true;
  4664. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  4665. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  4666. //
  4667. // Also changing the encoding after already used by a Material will not automatically make the Material
  4668. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  4669. this.encoding = encoding !== undefined ? encoding : LinearEncoding;
  4670. this.version = 0;
  4671. this.onUpdate = null;
  4672. }
  4673. Texture.DEFAULT_IMAGE = undefined;
  4674. Texture.DEFAULT_MAPPING = UVMapping;
  4675. Texture.prototype = {
  4676. constructor: Texture,
  4677. isTexture: true,
  4678. set needsUpdate( value ) {
  4679. if ( value === true ) this.version ++;
  4680. },
  4681. clone: function () {
  4682. return new this.constructor().copy( this );
  4683. },
  4684. copy: function ( source ) {
  4685. this.image = source.image;
  4686. this.mipmaps = source.mipmaps.slice( 0 );
  4687. this.mapping = source.mapping;
  4688. this.wrapS = source.wrapS;
  4689. this.wrapT = source.wrapT;
  4690. this.magFilter = source.magFilter;
  4691. this.minFilter = source.minFilter;
  4692. this.anisotropy = source.anisotropy;
  4693. this.format = source.format;
  4694. this.type = source.type;
  4695. this.offset.copy( source.offset );
  4696. this.repeat.copy( source.repeat );
  4697. this.generateMipmaps = source.generateMipmaps;
  4698. this.premultiplyAlpha = source.premultiplyAlpha;
  4699. this.flipY = source.flipY;
  4700. this.unpackAlignment = source.unpackAlignment;
  4701. this.encoding = source.encoding;
  4702. return this;
  4703. },
  4704. toJSON: function ( meta ) {
  4705. if ( meta.textures[ this.uuid ] !== undefined ) {
  4706. return meta.textures[ this.uuid ];
  4707. }
  4708. function getDataURL( image ) {
  4709. var canvas;
  4710. if ( image.toDataURL !== undefined ) {
  4711. canvas = image;
  4712. } else {
  4713. canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  4714. canvas.width = image.width;
  4715. canvas.height = image.height;
  4716. canvas.getContext( '2d' ).drawImage( image, 0, 0, image.width, image.height );
  4717. }
  4718. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  4719. return canvas.toDataURL( 'image/jpeg', 0.6 );
  4720. } else {
  4721. return canvas.toDataURL( 'image/png' );
  4722. }
  4723. }
  4724. var output = {
  4725. metadata: {
  4726. version: 4.4,
  4727. type: 'Texture',
  4728. generator: 'Texture.toJSON'
  4729. },
  4730. uuid: this.uuid,
  4731. name: this.name,
  4732. mapping: this.mapping,
  4733. repeat: [ this.repeat.x, this.repeat.y ],
  4734. offset: [ this.offset.x, this.offset.y ],
  4735. wrap: [ this.wrapS, this.wrapT ],
  4736. minFilter: this.minFilter,
  4737. magFilter: this.magFilter,
  4738. anisotropy: this.anisotropy,
  4739. flipY: this.flipY
  4740. };
  4741. if ( this.image !== undefined ) {
  4742. // TODO: Move to THREE.Image
  4743. var image = this.image;
  4744. if ( image.uuid === undefined ) {
  4745. image.uuid = _Math.generateUUID(); // UGH
  4746. }
  4747. if ( meta.images[ image.uuid ] === undefined ) {
  4748. meta.images[ image.uuid ] = {
  4749. uuid: image.uuid,
  4750. url: getDataURL( image )
  4751. };
  4752. }
  4753. output.image = image.uuid;
  4754. }
  4755. meta.textures[ this.uuid ] = output;
  4756. return output;
  4757. },
  4758. dispose: function () {
  4759. this.dispatchEvent( { type: 'dispose' } );
  4760. },
  4761. transformUv: function ( uv ) {
  4762. if ( this.mapping !== UVMapping ) return;
  4763. uv.multiply( this.repeat );
  4764. uv.add( this.offset );
  4765. if ( uv.x < 0 || uv.x > 1 ) {
  4766. switch ( this.wrapS ) {
  4767. case RepeatWrapping:
  4768. uv.x = uv.x - Math.floor( uv.x );
  4769. break;
  4770. case ClampToEdgeWrapping:
  4771. uv.x = uv.x < 0 ? 0 : 1;
  4772. break;
  4773. case MirroredRepeatWrapping:
  4774. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  4775. uv.x = Math.ceil( uv.x ) - uv.x;
  4776. } else {
  4777. uv.x = uv.x - Math.floor( uv.x );
  4778. }
  4779. break;
  4780. }
  4781. }
  4782. if ( uv.y < 0 || uv.y > 1 ) {
  4783. switch ( this.wrapT ) {
  4784. case RepeatWrapping:
  4785. uv.y = uv.y - Math.floor( uv.y );
  4786. break;
  4787. case ClampToEdgeWrapping:
  4788. uv.y = uv.y < 0 ? 0 : 1;
  4789. break;
  4790. case MirroredRepeatWrapping:
  4791. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  4792. uv.y = Math.ceil( uv.y ) - uv.y;
  4793. } else {
  4794. uv.y = uv.y - Math.floor( uv.y );
  4795. }
  4796. break;
  4797. }
  4798. }
  4799. if ( this.flipY ) {
  4800. uv.y = 1 - uv.y;
  4801. }
  4802. }
  4803. };
  4804. Object.assign( Texture.prototype, EventDispatcher.prototype );
  4805. /**
  4806. * @author supereggbert / http://www.paulbrunt.co.uk/
  4807. * @author philogb / http://blog.thejit.org/
  4808. * @author mikael emtinger / http://gomo.se/
  4809. * @author egraether / http://egraether.com/
  4810. * @author WestLangley / http://github.com/WestLangley
  4811. */
  4812. function Vector4( x, y, z, w ) {
  4813. this.x = x || 0;
  4814. this.y = y || 0;
  4815. this.z = z || 0;
  4816. this.w = ( w !== undefined ) ? w : 1;
  4817. }
  4818. Vector4.prototype = {
  4819. constructor: Vector4,
  4820. isVector4: true,
  4821. set: function ( x, y, z, w ) {
  4822. this.x = x;
  4823. this.y = y;
  4824. this.z = z;
  4825. this.w = w;
  4826. return this;
  4827. },
  4828. setScalar: function ( scalar ) {
  4829. this.x = scalar;
  4830. this.y = scalar;
  4831. this.z = scalar;
  4832. this.w = scalar;
  4833. return this;
  4834. },
  4835. setX: function ( x ) {
  4836. this.x = x;
  4837. return this;
  4838. },
  4839. setY: function ( y ) {
  4840. this.y = y;
  4841. return this;
  4842. },
  4843. setZ: function ( z ) {
  4844. this.z = z;
  4845. return this;
  4846. },
  4847. setW: function ( w ) {
  4848. this.w = w;
  4849. return this;
  4850. },
  4851. setComponent: function ( index, value ) {
  4852. switch ( index ) {
  4853. case 0: this.x = value; break;
  4854. case 1: this.y = value; break;
  4855. case 2: this.z = value; break;
  4856. case 3: this.w = value; break;
  4857. default: throw new Error( 'index is out of range: ' + index );
  4858. }
  4859. return this;
  4860. },
  4861. getComponent: function ( index ) {
  4862. switch ( index ) {
  4863. case 0: return this.x;
  4864. case 1: return this.y;
  4865. case 2: return this.z;
  4866. case 3: return this.w;
  4867. default: throw new Error( 'index is out of range: ' + index );
  4868. }
  4869. },
  4870. clone: function () {
  4871. return new this.constructor( this.x, this.y, this.z, this.w );
  4872. },
  4873. copy: function ( v ) {
  4874. this.x = v.x;
  4875. this.y = v.y;
  4876. this.z = v.z;
  4877. this.w = ( v.w !== undefined ) ? v.w : 1;
  4878. return this;
  4879. },
  4880. add: function ( v, w ) {
  4881. if ( w !== undefined ) {
  4882. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  4883. return this.addVectors( v, w );
  4884. }
  4885. this.x += v.x;
  4886. this.y += v.y;
  4887. this.z += v.z;
  4888. this.w += v.w;
  4889. return this;
  4890. },
  4891. addScalar: function ( s ) {
  4892. this.x += s;
  4893. this.y += s;
  4894. this.z += s;
  4895. this.w += s;
  4896. return this;
  4897. },
  4898. addVectors: function ( a, b ) {
  4899. this.x = a.x + b.x;
  4900. this.y = a.y + b.y;
  4901. this.z = a.z + b.z;
  4902. this.w = a.w + b.w;
  4903. return this;
  4904. },
  4905. addScaledVector: function ( v, s ) {
  4906. this.x += v.x * s;
  4907. this.y += v.y * s;
  4908. this.z += v.z * s;
  4909. this.w += v.w * s;
  4910. return this;
  4911. },
  4912. sub: function ( v, w ) {
  4913. if ( w !== undefined ) {
  4914. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  4915. return this.subVectors( v, w );
  4916. }
  4917. this.x -= v.x;
  4918. this.y -= v.y;
  4919. this.z -= v.z;
  4920. this.w -= v.w;
  4921. return this;
  4922. },
  4923. subScalar: function ( s ) {
  4924. this.x -= s;
  4925. this.y -= s;
  4926. this.z -= s;
  4927. this.w -= s;
  4928. return this;
  4929. },
  4930. subVectors: function ( a, b ) {
  4931. this.x = a.x - b.x;
  4932. this.y = a.y - b.y;
  4933. this.z = a.z - b.z;
  4934. this.w = a.w - b.w;
  4935. return this;
  4936. },
  4937. multiplyScalar: function ( scalar ) {
  4938. if ( isFinite( scalar ) ) {
  4939. this.x *= scalar;
  4940. this.y *= scalar;
  4941. this.z *= scalar;
  4942. this.w *= scalar;
  4943. } else {
  4944. this.x = 0;
  4945. this.y = 0;
  4946. this.z = 0;
  4947. this.w = 0;
  4948. }
  4949. return this;
  4950. },
  4951. applyMatrix4: function ( m ) {
  4952. var x = this.x, y = this.y, z = this.z, w = this.w;
  4953. var e = m.elements;
  4954. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  4955. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  4956. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  4957. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  4958. return this;
  4959. },
  4960. divideScalar: function ( scalar ) {
  4961. return this.multiplyScalar( 1 / scalar );
  4962. },
  4963. setAxisAngleFromQuaternion: function ( q ) {
  4964. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  4965. // q is assumed to be normalized
  4966. this.w = 2 * Math.acos( q.w );
  4967. var s = Math.sqrt( 1 - q.w * q.w );
  4968. if ( s < 0.0001 ) {
  4969. this.x = 1;
  4970. this.y = 0;
  4971. this.z = 0;
  4972. } else {
  4973. this.x = q.x / s;
  4974. this.y = q.y / s;
  4975. this.z = q.z / s;
  4976. }
  4977. return this;
  4978. },
  4979. setAxisAngleFromRotationMatrix: function ( m ) {
  4980. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  4981. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4982. var angle, x, y, z, // variables for result
  4983. epsilon = 0.01, // margin to allow for rounding errors
  4984. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  4985. te = m.elements,
  4986. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  4987. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  4988. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4989. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  4990. ( Math.abs( m13 - m31 ) < epsilon ) &&
  4991. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  4992. // singularity found
  4993. // first check for identity matrix which must have +1 for all terms
  4994. // in leading diagonal and zero in other terms
  4995. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  4996. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  4997. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  4998. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  4999. // this singularity is identity matrix so angle = 0
  5000. this.set( 1, 0, 0, 0 );
  5001. return this; // zero angle, arbitrary axis
  5002. }
  5003. // otherwise this singularity is angle = 180
  5004. angle = Math.PI;
  5005. var xx = ( m11 + 1 ) / 2;
  5006. var yy = ( m22 + 1 ) / 2;
  5007. var zz = ( m33 + 1 ) / 2;
  5008. var xy = ( m12 + m21 ) / 4;
  5009. var xz = ( m13 + m31 ) / 4;
  5010. var yz = ( m23 + m32 ) / 4;
  5011. if ( ( xx > yy ) && ( xx > zz ) ) {
  5012. // m11 is the largest diagonal term
  5013. if ( xx < epsilon ) {
  5014. x = 0;
  5015. y = 0.707106781;
  5016. z = 0.707106781;
  5017. } else {
  5018. x = Math.sqrt( xx );
  5019. y = xy / x;
  5020. z = xz / x;
  5021. }
  5022. } else if ( yy > zz ) {
  5023. // m22 is the largest diagonal term
  5024. if ( yy < epsilon ) {
  5025. x = 0.707106781;
  5026. y = 0;
  5027. z = 0.707106781;
  5028. } else {
  5029. y = Math.sqrt( yy );
  5030. x = xy / y;
  5031. z = yz / y;
  5032. }
  5033. } else {
  5034. // m33 is the largest diagonal term so base result on this
  5035. if ( zz < epsilon ) {
  5036. x = 0.707106781;
  5037. y = 0.707106781;
  5038. z = 0;
  5039. } else {
  5040. z = Math.sqrt( zz );
  5041. x = xz / z;
  5042. y = yz / z;
  5043. }
  5044. }
  5045. this.set( x, y, z, angle );
  5046. return this; // return 180 deg rotation
  5047. }
  5048. // as we have reached here there are no singularities so we can handle normally
  5049. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  5050. ( m13 - m31 ) * ( m13 - m31 ) +
  5051. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  5052. if ( Math.abs( s ) < 0.001 ) s = 1;
  5053. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  5054. // caught by singularity test above, but I've left it in just in case
  5055. this.x = ( m32 - m23 ) / s;
  5056. this.y = ( m13 - m31 ) / s;
  5057. this.z = ( m21 - m12 ) / s;
  5058. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  5059. return this;
  5060. },
  5061. min: function ( v ) {
  5062. this.x = Math.min( this.x, v.x );
  5063. this.y = Math.min( this.y, v.y );
  5064. this.z = Math.min( this.z, v.z );
  5065. this.w = Math.min( this.w, v.w );
  5066. return this;
  5067. },
  5068. max: function ( v ) {
  5069. this.x = Math.max( this.x, v.x );
  5070. this.y = Math.max( this.y, v.y );
  5071. this.z = Math.max( this.z, v.z );
  5072. this.w = Math.max( this.w, v.w );
  5073. return this;
  5074. },
  5075. clamp: function ( min, max ) {
  5076. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  5077. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  5078. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  5079. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  5080. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  5081. return this;
  5082. },
  5083. clampScalar: function () {
  5084. var min, max;
  5085. return function clampScalar( minVal, maxVal ) {
  5086. if ( min === undefined ) {
  5087. min = new Vector4();
  5088. max = new Vector4();
  5089. }
  5090. min.set( minVal, minVal, minVal, minVal );
  5091. max.set( maxVal, maxVal, maxVal, maxVal );
  5092. return this.clamp( min, max );
  5093. };
  5094. }(),
  5095. floor: function () {
  5096. this.x = Math.floor( this.x );
  5097. this.y = Math.floor( this.y );
  5098. this.z = Math.floor( this.z );
  5099. this.w = Math.floor( this.w );
  5100. return this;
  5101. },
  5102. ceil: function () {
  5103. this.x = Math.ceil( this.x );
  5104. this.y = Math.ceil( this.y );
  5105. this.z = Math.ceil( this.z );
  5106. this.w = Math.ceil( this.w );
  5107. return this;
  5108. },
  5109. round: function () {
  5110. this.x = Math.round( this.x );
  5111. this.y = Math.round( this.y );
  5112. this.z = Math.round( this.z );
  5113. this.w = Math.round( this.w );
  5114. return this;
  5115. },
  5116. roundToZero: function () {
  5117. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  5118. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  5119. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  5120. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  5121. return this;
  5122. },
  5123. negate: function () {
  5124. this.x = - this.x;
  5125. this.y = - this.y;
  5126. this.z = - this.z;
  5127. this.w = - this.w;
  5128. return this;
  5129. },
  5130. dot: function ( v ) {
  5131. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  5132. },
  5133. lengthSq: function () {
  5134. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  5135. },
  5136. length: function () {
  5137. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  5138. },
  5139. lengthManhattan: function () {
  5140. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  5141. },
  5142. normalize: function () {
  5143. return this.divideScalar( this.length() );
  5144. },
  5145. setLength: function ( length ) {
  5146. return this.multiplyScalar( length / this.length() );
  5147. },
  5148. lerp: function ( v, alpha ) {
  5149. this.x += ( v.x - this.x ) * alpha;
  5150. this.y += ( v.y - this.y ) * alpha;
  5151. this.z += ( v.z - this.z ) * alpha;
  5152. this.w += ( v.w - this.w ) * alpha;
  5153. return this;
  5154. },
  5155. lerpVectors: function ( v1, v2, alpha ) {
  5156. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  5157. },
  5158. equals: function ( v ) {
  5159. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  5160. },
  5161. fromArray: function ( array, offset ) {
  5162. if ( offset === undefined ) offset = 0;
  5163. this.x = array[ offset ];
  5164. this.y = array[ offset + 1 ];
  5165. this.z = array[ offset + 2 ];
  5166. this.w = array[ offset + 3 ];
  5167. return this;
  5168. },
  5169. toArray: function ( array, offset ) {
  5170. if ( array === undefined ) array = [];
  5171. if ( offset === undefined ) offset = 0;
  5172. array[ offset ] = this.x;
  5173. array[ offset + 1 ] = this.y;
  5174. array[ offset + 2 ] = this.z;
  5175. array[ offset + 3 ] = this.w;
  5176. return array;
  5177. },
  5178. fromBufferAttribute: function ( attribute, index, offset ) {
  5179. if ( offset !== undefined ) {
  5180. console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' );
  5181. }
  5182. this.x = attribute.getX( index );
  5183. this.y = attribute.getY( index );
  5184. this.z = attribute.getZ( index );
  5185. this.w = attribute.getW( index );
  5186. return this;
  5187. }
  5188. };
  5189. /**
  5190. * @author szimek / https://github.com/szimek/
  5191. * @author alteredq / http://alteredqualia.com/
  5192. * @author Marius Kintel / https://github.com/kintel
  5193. */
  5194. /*
  5195. In options, we can specify:
  5196. * Texture parameters for an auto-generated target texture
  5197. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  5198. */
  5199. function WebGLRenderTarget( width, height, options ) {
  5200. this.uuid = _Math.generateUUID();
  5201. this.width = width;
  5202. this.height = height;
  5203. this.scissor = new Vector4( 0, 0, width, height );
  5204. this.scissorTest = false;
  5205. this.viewport = new Vector4( 0, 0, width, height );
  5206. options = options || {};
  5207. if ( options.minFilter === undefined ) options.minFilter = LinearFilter;
  5208. this.texture = new Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  5209. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  5210. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  5211. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  5212. }
  5213. WebGLRenderTarget.prototype = {
  5214. constructor: WebGLRenderTarget,
  5215. isWebGLRenderTarget: true,
  5216. setSize: function ( width, height ) {
  5217. if ( this.width !== width || this.height !== height ) {
  5218. this.width = width;
  5219. this.height = height;
  5220. this.dispose();
  5221. }
  5222. this.viewport.set( 0, 0, width, height );
  5223. this.scissor.set( 0, 0, width, height );
  5224. },
  5225. clone: function () {
  5226. return new this.constructor().copy( this );
  5227. },
  5228. copy: function ( source ) {
  5229. this.width = source.width;
  5230. this.height = source.height;
  5231. this.viewport.copy( source.viewport );
  5232. this.texture = source.texture.clone();
  5233. this.depthBuffer = source.depthBuffer;
  5234. this.stencilBuffer = source.stencilBuffer;
  5235. this.depthTexture = source.depthTexture;
  5236. return this;
  5237. },
  5238. dispose: function () {
  5239. this.dispatchEvent( { type: 'dispose' } );
  5240. }
  5241. };
  5242. Object.assign( WebGLRenderTarget.prototype, EventDispatcher.prototype );
  5243. /**
  5244. * @author alteredq / http://alteredqualia.com
  5245. */
  5246. function WebGLRenderTargetCube( width, height, options ) {
  5247. WebGLRenderTarget.call( this, width, height, options );
  5248. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  5249. this.activeMipMapLevel = 0;
  5250. }
  5251. WebGLRenderTargetCube.prototype = Object.create( WebGLRenderTarget.prototype );
  5252. WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube;
  5253. WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true;
  5254. /**
  5255. * @author mikael emtinger / http://gomo.se/
  5256. * @author alteredq / http://alteredqualia.com/
  5257. * @author WestLangley / http://github.com/WestLangley
  5258. * @author bhouston / http://clara.io
  5259. */
  5260. function Quaternion( x, y, z, w ) {
  5261. this._x = x || 0;
  5262. this._y = y || 0;
  5263. this._z = z || 0;
  5264. this._w = ( w !== undefined ) ? w : 1;
  5265. }
  5266. Quaternion.prototype = {
  5267. constructor: Quaternion,
  5268. get x () {
  5269. return this._x;
  5270. },
  5271. set x ( value ) {
  5272. this._x = value;
  5273. this.onChangeCallback();
  5274. },
  5275. get y () {
  5276. return this._y;
  5277. },
  5278. set y ( value ) {
  5279. this._y = value;
  5280. this.onChangeCallback();
  5281. },
  5282. get z () {
  5283. return this._z;
  5284. },
  5285. set z ( value ) {
  5286. this._z = value;
  5287. this.onChangeCallback();
  5288. },
  5289. get w () {
  5290. return this._w;
  5291. },
  5292. set w ( value ) {
  5293. this._w = value;
  5294. this.onChangeCallback();
  5295. },
  5296. set: function ( x, y, z, w ) {
  5297. this._x = x;
  5298. this._y = y;
  5299. this._z = z;
  5300. this._w = w;
  5301. this.onChangeCallback();
  5302. return this;
  5303. },
  5304. clone: function () {
  5305. return new this.constructor( this._x, this._y, this._z, this._w );
  5306. },
  5307. copy: function ( quaternion ) {
  5308. this._x = quaternion.x;
  5309. this._y = quaternion.y;
  5310. this._z = quaternion.z;
  5311. this._w = quaternion.w;
  5312. this.onChangeCallback();
  5313. return this;
  5314. },
  5315. setFromEuler: function ( euler, update ) {
  5316. if ( (euler && euler.isEuler) === false ) {
  5317. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  5318. }
  5319. // http://www.mathworks.com/matlabcentral/fileexchange/
  5320. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  5321. // content/SpinCalc.m
  5322. var c1 = Math.cos( euler._x / 2 );
  5323. var c2 = Math.cos( euler._y / 2 );
  5324. var c3 = Math.cos( euler._z / 2 );
  5325. var s1 = Math.sin( euler._x / 2 );
  5326. var s2 = Math.sin( euler._y / 2 );
  5327. var s3 = Math.sin( euler._z / 2 );
  5328. var order = euler.order;
  5329. if ( order === 'XYZ' ) {
  5330. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  5331. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  5332. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  5333. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  5334. } else if ( order === 'YXZ' ) {
  5335. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  5336. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  5337. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  5338. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  5339. } else if ( order === 'ZXY' ) {
  5340. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  5341. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  5342. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  5343. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  5344. } else if ( order === 'ZYX' ) {
  5345. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  5346. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  5347. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  5348. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  5349. } else if ( order === 'YZX' ) {
  5350. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  5351. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  5352. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  5353. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  5354. } else if ( order === 'XZY' ) {
  5355. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  5356. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  5357. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  5358. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  5359. }
  5360. if ( update !== false ) this.onChangeCallback();
  5361. return this;
  5362. },
  5363. setFromAxisAngle: function ( axis, angle ) {
  5364. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  5365. // assumes axis is normalized
  5366. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  5367. this._x = axis.x * s;
  5368. this._y = axis.y * s;
  5369. this._z = axis.z * s;
  5370. this._w = Math.cos( halfAngle );
  5371. this.onChangeCallback();
  5372. return this;
  5373. },
  5374. setFromRotationMatrix: function ( m ) {
  5375. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  5376. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  5377. var te = m.elements,
  5378. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  5379. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  5380. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  5381. trace = m11 + m22 + m33,
  5382. s;
  5383. if ( trace > 0 ) {
  5384. s = 0.5 / Math.sqrt( trace + 1.0 );
  5385. this._w = 0.25 / s;
  5386. this._x = ( m32 - m23 ) * s;
  5387. this._y = ( m13 - m31 ) * s;
  5388. this._z = ( m21 - m12 ) * s;
  5389. } else if ( m11 > m22 && m11 > m33 ) {
  5390. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  5391. this._w = ( m32 - m23 ) / s;
  5392. this._x = 0.25 * s;
  5393. this._y = ( m12 + m21 ) / s;
  5394. this._z = ( m13 + m31 ) / s;
  5395. } else if ( m22 > m33 ) {
  5396. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  5397. this._w = ( m13 - m31 ) / s;
  5398. this._x = ( m12 + m21 ) / s;
  5399. this._y = 0.25 * s;
  5400. this._z = ( m23 + m32 ) / s;
  5401. } else {
  5402. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  5403. this._w = ( m21 - m12 ) / s;
  5404. this._x = ( m13 + m31 ) / s;
  5405. this._y = ( m23 + m32 ) / s;
  5406. this._z = 0.25 * s;
  5407. }
  5408. this.onChangeCallback();
  5409. return this;
  5410. },
  5411. setFromUnitVectors: function () {
  5412. // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final
  5413. // assumes direction vectors vFrom and vTo are normalized
  5414. var v1, r;
  5415. var EPS = 0.000001;
  5416. return function setFromUnitVectors( vFrom, vTo ) {
  5417. if ( v1 === undefined ) v1 = new Vector3();
  5418. r = vFrom.dot( vTo ) + 1;
  5419. if ( r < EPS ) {
  5420. r = 0;
  5421. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  5422. v1.set( - vFrom.y, vFrom.x, 0 );
  5423. } else {
  5424. v1.set( 0, - vFrom.z, vFrom.y );
  5425. }
  5426. } else {
  5427. v1.crossVectors( vFrom, vTo );
  5428. }
  5429. this._x = v1.x;
  5430. this._y = v1.y;
  5431. this._z = v1.z;
  5432. this._w = r;
  5433. return this.normalize();
  5434. };
  5435. }(),
  5436. inverse: function () {
  5437. return this.conjugate().normalize();
  5438. },
  5439. conjugate: function () {
  5440. this._x *= - 1;
  5441. this._y *= - 1;
  5442. this._z *= - 1;
  5443. this.onChangeCallback();
  5444. return this;
  5445. },
  5446. dot: function ( v ) {
  5447. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  5448. },
  5449. lengthSq: function () {
  5450. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  5451. },
  5452. length: function () {
  5453. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  5454. },
  5455. normalize: function () {
  5456. var l = this.length();
  5457. if ( l === 0 ) {
  5458. this._x = 0;
  5459. this._y = 0;
  5460. this._z = 0;
  5461. this._w = 1;
  5462. } else {
  5463. l = 1 / l;
  5464. this._x = this._x * l;
  5465. this._y = this._y * l;
  5466. this._z = this._z * l;
  5467. this._w = this._w * l;
  5468. }
  5469. this.onChangeCallback();
  5470. return this;
  5471. },
  5472. multiply: function ( q, p ) {
  5473. if ( p !== undefined ) {
  5474. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  5475. return this.multiplyQuaternions( q, p );
  5476. }
  5477. return this.multiplyQuaternions( this, q );
  5478. },
  5479. premultiply: function ( q ) {
  5480. return this.multiplyQuaternions( q, this );
  5481. },
  5482. multiplyQuaternions: function ( a, b ) {
  5483. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  5484. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  5485. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  5486. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  5487. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  5488. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  5489. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  5490. this.onChangeCallback();
  5491. return this;
  5492. },
  5493. slerp: function ( qb, t ) {
  5494. if ( t === 0 ) return this;
  5495. if ( t === 1 ) return this.copy( qb );
  5496. var x = this._x, y = this._y, z = this._z, w = this._w;
  5497. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  5498. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  5499. if ( cosHalfTheta < 0 ) {
  5500. this._w = - qb._w;
  5501. this._x = - qb._x;
  5502. this._y = - qb._y;
  5503. this._z = - qb._z;
  5504. cosHalfTheta = - cosHalfTheta;
  5505. } else {
  5506. this.copy( qb );
  5507. }
  5508. if ( cosHalfTheta >= 1.0 ) {
  5509. this._w = w;
  5510. this._x = x;
  5511. this._y = y;
  5512. this._z = z;
  5513. return this;
  5514. }
  5515. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  5516. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  5517. this._w = 0.5 * ( w + this._w );
  5518. this._x = 0.5 * ( x + this._x );
  5519. this._y = 0.5 * ( y + this._y );
  5520. this._z = 0.5 * ( z + this._z );
  5521. return this;
  5522. }
  5523. var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  5524. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  5525. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  5526. this._w = ( w * ratioA + this._w * ratioB );
  5527. this._x = ( x * ratioA + this._x * ratioB );
  5528. this._y = ( y * ratioA + this._y * ratioB );
  5529. this._z = ( z * ratioA + this._z * ratioB );
  5530. this.onChangeCallback();
  5531. return this;
  5532. },
  5533. equals: function ( quaternion ) {
  5534. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  5535. },
  5536. fromArray: function ( array, offset ) {
  5537. if ( offset === undefined ) offset = 0;
  5538. this._x = array[ offset ];
  5539. this._y = array[ offset + 1 ];
  5540. this._z = array[ offset + 2 ];
  5541. this._w = array[ offset + 3 ];
  5542. this.onChangeCallback();
  5543. return this;
  5544. },
  5545. toArray: function ( array, offset ) {
  5546. if ( array === undefined ) array = [];
  5547. if ( offset === undefined ) offset = 0;
  5548. array[ offset ] = this._x;
  5549. array[ offset + 1 ] = this._y;
  5550. array[ offset + 2 ] = this._z;
  5551. array[ offset + 3 ] = this._w;
  5552. return array;
  5553. },
  5554. onChange: function ( callback ) {
  5555. this.onChangeCallback = callback;
  5556. return this;
  5557. },
  5558. onChangeCallback: function () {}
  5559. };
  5560. Object.assign( Quaternion, {
  5561. slerp: function( qa, qb, qm, t ) {
  5562. return qm.copy( qa ).slerp( qb, t );
  5563. },
  5564. slerpFlat: function(
  5565. dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  5566. // fuzz-free, array-based Quaternion SLERP operation
  5567. var x0 = src0[ srcOffset0 + 0 ],
  5568. y0 = src0[ srcOffset0 + 1 ],
  5569. z0 = src0[ srcOffset0 + 2 ],
  5570. w0 = src0[ srcOffset0 + 3 ],
  5571. x1 = src1[ srcOffset1 + 0 ],
  5572. y1 = src1[ srcOffset1 + 1 ],
  5573. z1 = src1[ srcOffset1 + 2 ],
  5574. w1 = src1[ srcOffset1 + 3 ];
  5575. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  5576. var s = 1 - t,
  5577. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  5578. dir = ( cos >= 0 ? 1 : - 1 ),
  5579. sqrSin = 1 - cos * cos;
  5580. // Skip the Slerp for tiny steps to avoid numeric problems:
  5581. if ( sqrSin > Number.EPSILON ) {
  5582. var sin = Math.sqrt( sqrSin ),
  5583. len = Math.atan2( sin, cos * dir );
  5584. s = Math.sin( s * len ) / sin;
  5585. t = Math.sin( t * len ) / sin;
  5586. }
  5587. var tDir = t * dir;
  5588. x0 = x0 * s + x1 * tDir;
  5589. y0 = y0 * s + y1 * tDir;
  5590. z0 = z0 * s + z1 * tDir;
  5591. w0 = w0 * s + w1 * tDir;
  5592. // Normalize in case we just did a lerp:
  5593. if ( s === 1 - t ) {
  5594. var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  5595. x0 *= f;
  5596. y0 *= f;
  5597. z0 *= f;
  5598. w0 *= f;
  5599. }
  5600. }
  5601. dst[ dstOffset ] = x0;
  5602. dst[ dstOffset + 1 ] = y0;
  5603. dst[ dstOffset + 2 ] = z0;
  5604. dst[ dstOffset + 3 ] = w0;
  5605. }
  5606. } );
  5607. /**
  5608. * @author mrdoob / http://mrdoob.com/
  5609. * @author *kile / http://kile.stravaganza.org/
  5610. * @author philogb / http://blog.thejit.org/
  5611. * @author mikael emtinger / http://gomo.se/
  5612. * @author egraether / http://egraether.com/
  5613. * @author WestLangley / http://github.com/WestLangley
  5614. */
  5615. function Vector3( x, y, z ) {
  5616. this.x = x || 0;
  5617. this.y = y || 0;
  5618. this.z = z || 0;
  5619. }
  5620. Vector3.prototype = {
  5621. constructor: Vector3,
  5622. isVector3: true,
  5623. set: function ( x, y, z ) {
  5624. this.x = x;
  5625. this.y = y;
  5626. this.z = z;
  5627. return this;
  5628. },
  5629. setScalar: function ( scalar ) {
  5630. this.x = scalar;
  5631. this.y = scalar;
  5632. this.z = scalar;
  5633. return this;
  5634. },
  5635. setX: function ( x ) {
  5636. this.x = x;
  5637. return this;
  5638. },
  5639. setY: function ( y ) {
  5640. this.y = y;
  5641. return this;
  5642. },
  5643. setZ: function ( z ) {
  5644. this.z = z;
  5645. return this;
  5646. },
  5647. setComponent: function ( index, value ) {
  5648. switch ( index ) {
  5649. case 0: this.x = value; break;
  5650. case 1: this.y = value; break;
  5651. case 2: this.z = value; break;
  5652. default: throw new Error( 'index is out of range: ' + index );
  5653. }
  5654. return this;
  5655. },
  5656. getComponent: function ( index ) {
  5657. switch ( index ) {
  5658. case 0: return this.x;
  5659. case 1: return this.y;
  5660. case 2: return this.z;
  5661. default: throw new Error( 'index is out of range: ' + index );
  5662. }
  5663. },
  5664. clone: function () {
  5665. return new this.constructor( this.x, this.y, this.z );
  5666. },
  5667. copy: function ( v ) {
  5668. this.x = v.x;
  5669. this.y = v.y;
  5670. this.z = v.z;
  5671. return this;
  5672. },
  5673. add: function ( v, w ) {
  5674. if ( w !== undefined ) {
  5675. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  5676. return this.addVectors( v, w );
  5677. }
  5678. this.x += v.x;
  5679. this.y += v.y;
  5680. this.z += v.z;
  5681. return this;
  5682. },
  5683. addScalar: function ( s ) {
  5684. this.x += s;
  5685. this.y += s;
  5686. this.z += s;
  5687. return this;
  5688. },
  5689. addVectors: function ( a, b ) {
  5690. this.x = a.x + b.x;
  5691. this.y = a.y + b.y;
  5692. this.z = a.z + b.z;
  5693. return this;
  5694. },
  5695. addScaledVector: function ( v, s ) {
  5696. this.x += v.x * s;
  5697. this.y += v.y * s;
  5698. this.z += v.z * s;
  5699. return this;
  5700. },
  5701. sub: function ( v, w ) {
  5702. if ( w !== undefined ) {
  5703. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  5704. return this.subVectors( v, w );
  5705. }
  5706. this.x -= v.x;
  5707. this.y -= v.y;
  5708. this.z -= v.z;
  5709. return this;
  5710. },
  5711. subScalar: function ( s ) {
  5712. this.x -= s;
  5713. this.y -= s;
  5714. this.z -= s;
  5715. return this;
  5716. },
  5717. subVectors: function ( a, b ) {
  5718. this.x = a.x - b.x;
  5719. this.y = a.y - b.y;
  5720. this.z = a.z - b.z;
  5721. return this;
  5722. },
  5723. multiply: function ( v, w ) {
  5724. if ( w !== undefined ) {
  5725. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  5726. return this.multiplyVectors( v, w );
  5727. }
  5728. this.x *= v.x;
  5729. this.y *= v.y;
  5730. this.z *= v.z;
  5731. return this;
  5732. },
  5733. multiplyScalar: function ( scalar ) {
  5734. if ( isFinite( scalar ) ) {
  5735. this.x *= scalar;
  5736. this.y *= scalar;
  5737. this.z *= scalar;
  5738. } else {
  5739. this.x = 0;
  5740. this.y = 0;
  5741. this.z = 0;
  5742. }
  5743. return this;
  5744. },
  5745. multiplyVectors: function ( a, b ) {
  5746. this.x = a.x * b.x;
  5747. this.y = a.y * b.y;
  5748. this.z = a.z * b.z;
  5749. return this;
  5750. },
  5751. applyEuler: function () {
  5752. var quaternion;
  5753. return function applyEuler( euler ) {
  5754. if ( (euler && euler.isEuler) === false ) {
  5755. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  5756. }
  5757. if ( quaternion === undefined ) quaternion = new Quaternion();
  5758. return this.applyQuaternion( quaternion.setFromEuler( euler ) );
  5759. };
  5760. }(),
  5761. applyAxisAngle: function () {
  5762. var quaternion;
  5763. return function applyAxisAngle( axis, angle ) {
  5764. if ( quaternion === undefined ) quaternion = new Quaternion();
  5765. return this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  5766. };
  5767. }(),
  5768. applyMatrix3: function ( m ) {
  5769. var x = this.x, y = this.y, z = this.z;
  5770. var e = m.elements;
  5771. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  5772. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  5773. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  5774. return this;
  5775. },
  5776. applyMatrix4: function ( m ) {
  5777. var x = this.x, y = this.y, z = this.z;
  5778. var e = m.elements;
  5779. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ];
  5780. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ];
  5781. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ];
  5782. var w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ];
  5783. return this.divideScalar( w );
  5784. },
  5785. applyQuaternion: function ( q ) {
  5786. var x = this.x, y = this.y, z = this.z;
  5787. var qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  5788. // calculate quat * vector
  5789. var ix = qw * x + qy * z - qz * y;
  5790. var iy = qw * y + qz * x - qx * z;
  5791. var iz = qw * z + qx * y - qy * x;
  5792. var iw = - qx * x - qy * y - qz * z;
  5793. // calculate result * inverse quat
  5794. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  5795. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  5796. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  5797. return this;
  5798. },
  5799. project: function () {
  5800. var matrix;
  5801. return function project( camera ) {
  5802. if ( matrix === undefined ) matrix = new Matrix4();
  5803. matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) );
  5804. return this.applyMatrix4( matrix );
  5805. };
  5806. }(),
  5807. unproject: function () {
  5808. var matrix;
  5809. return function unproject( camera ) {
  5810. if ( matrix === undefined ) matrix = new Matrix4();
  5811. matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) );
  5812. return this.applyMatrix4( matrix );
  5813. };
  5814. }(),
  5815. transformDirection: function ( m ) {
  5816. // input: THREE.Matrix4 affine matrix
  5817. // vector interpreted as a direction
  5818. var x = this.x, y = this.y, z = this.z;
  5819. var e = m.elements;
  5820. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  5821. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  5822. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  5823. return this.normalize();
  5824. },
  5825. divide: function ( v ) {
  5826. this.x /= v.x;
  5827. this.y /= v.y;
  5828. this.z /= v.z;
  5829. return this;
  5830. },
  5831. divideScalar: function ( scalar ) {
  5832. return this.multiplyScalar( 1 / scalar );
  5833. },
  5834. min: function ( v ) {
  5835. this.x = Math.min( this.x, v.x );
  5836. this.y = Math.min( this.y, v.y );
  5837. this.z = Math.min( this.z, v.z );
  5838. return this;
  5839. },
  5840. max: function ( v ) {
  5841. this.x = Math.max( this.x, v.x );
  5842. this.y = Math.max( this.y, v.y );
  5843. this.z = Math.max( this.z, v.z );
  5844. return this;
  5845. },
  5846. clamp: function ( min, max ) {
  5847. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  5848. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  5849. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  5850. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  5851. return this;
  5852. },
  5853. clampScalar: function () {
  5854. var min, max;
  5855. return function clampScalar( minVal, maxVal ) {
  5856. if ( min === undefined ) {
  5857. min = new Vector3();
  5858. max = new Vector3();
  5859. }
  5860. min.set( minVal, minVal, minVal );
  5861. max.set( maxVal, maxVal, maxVal );
  5862. return this.clamp( min, max );
  5863. };
  5864. }(),
  5865. clampLength: function ( min, max ) {
  5866. var length = this.length();
  5867. return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  5868. },
  5869. floor: function () {
  5870. this.x = Math.floor( this.x );
  5871. this.y = Math.floor( this.y );
  5872. this.z = Math.floor( this.z );
  5873. return this;
  5874. },
  5875. ceil: function () {
  5876. this.x = Math.ceil( this.x );
  5877. this.y = Math.ceil( this.y );
  5878. this.z = Math.ceil( this.z );
  5879. return this;
  5880. },
  5881. round: function () {
  5882. this.x = Math.round( this.x );
  5883. this.y = Math.round( this.y );
  5884. this.z = Math.round( this.z );
  5885. return this;
  5886. },
  5887. roundToZero: function () {
  5888. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  5889. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  5890. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  5891. return this;
  5892. },
  5893. negate: function () {
  5894. this.x = - this.x;
  5895. this.y = - this.y;
  5896. this.z = - this.z;
  5897. return this;
  5898. },
  5899. dot: function ( v ) {
  5900. return this.x * v.x + this.y * v.y + this.z * v.z;
  5901. },
  5902. lengthSq: function () {
  5903. return this.x * this.x + this.y * this.y + this.z * this.z;
  5904. },
  5905. length: function () {
  5906. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  5907. },
  5908. lengthManhattan: function () {
  5909. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  5910. },
  5911. normalize: function () {
  5912. return this.divideScalar( this.length() );
  5913. },
  5914. setLength: function ( length ) {
  5915. return this.multiplyScalar( length / this.length() );
  5916. },
  5917. lerp: function ( v, alpha ) {
  5918. this.x += ( v.x - this.x ) * alpha;
  5919. this.y += ( v.y - this.y ) * alpha;
  5920. this.z += ( v.z - this.z ) * alpha;
  5921. return this;
  5922. },
  5923. lerpVectors: function ( v1, v2, alpha ) {
  5924. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  5925. },
  5926. cross: function ( v, w ) {
  5927. if ( w !== undefined ) {
  5928. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  5929. return this.crossVectors( v, w );
  5930. }
  5931. var x = this.x, y = this.y, z = this.z;
  5932. this.x = y * v.z - z * v.y;
  5933. this.y = z * v.x - x * v.z;
  5934. this.z = x * v.y - y * v.x;
  5935. return this;
  5936. },
  5937. crossVectors: function ( a, b ) {
  5938. var ax = a.x, ay = a.y, az = a.z;
  5939. var bx = b.x, by = b.y, bz = b.z;
  5940. this.x = ay * bz - az * by;
  5941. this.y = az * bx - ax * bz;
  5942. this.z = ax * by - ay * bx;
  5943. return this;
  5944. },
  5945. projectOnVector: function ( vector ) {
  5946. var scalar = vector.dot( this ) / vector.lengthSq();
  5947. return this.copy( vector ).multiplyScalar( scalar );
  5948. },
  5949. projectOnPlane: function () {
  5950. var v1;
  5951. return function projectOnPlane( planeNormal ) {
  5952. if ( v1 === undefined ) v1 = new Vector3();
  5953. v1.copy( this ).projectOnVector( planeNormal );
  5954. return this.sub( v1 );
  5955. };
  5956. }(),
  5957. reflect: function () {
  5958. // reflect incident vector off plane orthogonal to normal
  5959. // normal is assumed to have unit length
  5960. var v1;
  5961. return function reflect( normal ) {
  5962. if ( v1 === undefined ) v1 = new Vector3();
  5963. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  5964. };
  5965. }(),
  5966. angleTo: function ( v ) {
  5967. var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) );
  5968. // clamp, to handle numerical problems
  5969. return Math.acos( _Math.clamp( theta, - 1, 1 ) );
  5970. },
  5971. distanceTo: function ( v ) {
  5972. return Math.sqrt( this.distanceToSquared( v ) );
  5973. },
  5974. distanceToSquared: function ( v ) {
  5975. var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  5976. return dx * dx + dy * dy + dz * dz;
  5977. },
  5978. distanceToManhattan: function ( v ) {
  5979. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  5980. },
  5981. setFromSpherical: function( s ) {
  5982. var sinPhiRadius = Math.sin( s.phi ) * s.radius;
  5983. this.x = sinPhiRadius * Math.sin( s.theta );
  5984. this.y = Math.cos( s.phi ) * s.radius;
  5985. this.z = sinPhiRadius * Math.cos( s.theta );
  5986. return this;
  5987. },
  5988. setFromCylindrical: function( c ) {
  5989. this.x = c.radius * Math.sin( c.theta );
  5990. this.y = c.y;
  5991. this.z = c.radius * Math.cos( c.theta );
  5992. return this;
  5993. },
  5994. setFromMatrixPosition: function ( m ) {
  5995. return this.setFromMatrixColumn( m, 3 );
  5996. },
  5997. setFromMatrixScale: function ( m ) {
  5998. var sx = this.setFromMatrixColumn( m, 0 ).length();
  5999. var sy = this.setFromMatrixColumn( m, 1 ).length();
  6000. var sz = this.setFromMatrixColumn( m, 2 ).length();
  6001. this.x = sx;
  6002. this.y = sy;
  6003. this.z = sz;
  6004. return this;
  6005. },
  6006. setFromMatrixColumn: function ( m, index ) {
  6007. if ( typeof m === 'number' ) {
  6008. console.warn( 'THREE.Vector3: setFromMatrixColumn now expects ( matrix, index ).' );
  6009. var temp = m;
  6010. m = index;
  6011. index = temp;
  6012. }
  6013. return this.fromArray( m.elements, index * 4 );
  6014. },
  6015. equals: function ( v ) {
  6016. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  6017. },
  6018. fromArray: function ( array, offset ) {
  6019. if ( offset === undefined ) offset = 0;
  6020. this.x = array[ offset ];
  6021. this.y = array[ offset + 1 ];
  6022. this.z = array[ offset + 2 ];
  6023. return this;
  6024. },
  6025. toArray: function ( array, offset ) {
  6026. if ( array === undefined ) array = [];
  6027. if ( offset === undefined ) offset = 0;
  6028. array[ offset ] = this.x;
  6029. array[ offset + 1 ] = this.y;
  6030. array[ offset + 2 ] = this.z;
  6031. return array;
  6032. },
  6033. fromBufferAttribute: function ( attribute, index, offset ) {
  6034. if ( offset !== undefined ) {
  6035. console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' );
  6036. }
  6037. this.x = attribute.getX( index );
  6038. this.y = attribute.getY( index );
  6039. this.z = attribute.getZ( index );
  6040. return this;
  6041. }
  6042. };
  6043. /**
  6044. * @author mrdoob / http://mrdoob.com/
  6045. * @author supereggbert / http://www.paulbrunt.co.uk/
  6046. * @author philogb / http://blog.thejit.org/
  6047. * @author jordi_ros / http://plattsoft.com
  6048. * @author D1plo1d / http://github.com/D1plo1d
  6049. * @author alteredq / http://alteredqualia.com/
  6050. * @author mikael emtinger / http://gomo.se/
  6051. * @author timknip / http://www.floorplanner.com/
  6052. * @author bhouston / http://clara.io
  6053. * @author WestLangley / http://github.com/WestLangley
  6054. */
  6055. function Matrix4() {
  6056. this.elements = new Float32Array( [
  6057. 1, 0, 0, 0,
  6058. 0, 1, 0, 0,
  6059. 0, 0, 1, 0,
  6060. 0, 0, 0, 1
  6061. ] );
  6062. if ( arguments.length > 0 ) {
  6063. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  6064. }
  6065. }
  6066. Matrix4.prototype = {
  6067. constructor: Matrix4,
  6068. isMatrix4: true,
  6069. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  6070. var te = this.elements;
  6071. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  6072. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  6073. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  6074. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  6075. return this;
  6076. },
  6077. identity: function () {
  6078. this.set(
  6079. 1, 0, 0, 0,
  6080. 0, 1, 0, 0,
  6081. 0, 0, 1, 0,
  6082. 0, 0, 0, 1
  6083. );
  6084. return this;
  6085. },
  6086. clone: function () {
  6087. return new Matrix4().fromArray( this.elements );
  6088. },
  6089. copy: function ( m ) {
  6090. this.elements.set( m.elements );
  6091. return this;
  6092. },
  6093. copyPosition: function ( m ) {
  6094. var te = this.elements;
  6095. var me = m.elements;
  6096. te[ 12 ] = me[ 12 ];
  6097. te[ 13 ] = me[ 13 ];
  6098. te[ 14 ] = me[ 14 ];
  6099. return this;
  6100. },
  6101. extractBasis: function ( xAxis, yAxis, zAxis ) {
  6102. xAxis.setFromMatrixColumn( this, 0 );
  6103. yAxis.setFromMatrixColumn( this, 1 );
  6104. zAxis.setFromMatrixColumn( this, 2 );
  6105. return this;
  6106. },
  6107. makeBasis: function ( xAxis, yAxis, zAxis ) {
  6108. this.set(
  6109. xAxis.x, yAxis.x, zAxis.x, 0,
  6110. xAxis.y, yAxis.y, zAxis.y, 0,
  6111. xAxis.z, yAxis.z, zAxis.z, 0,
  6112. 0, 0, 0, 1
  6113. );
  6114. return this;
  6115. },
  6116. extractRotation: function () {
  6117. var v1;
  6118. return function extractRotation( m ) {
  6119. if ( v1 === undefined ) v1 = new Vector3();
  6120. var te = this.elements;
  6121. var me = m.elements;
  6122. var scaleX = 1 / v1.setFromMatrixColumn( m, 0 ).length();
  6123. var scaleY = 1 / v1.setFromMatrixColumn( m, 1 ).length();
  6124. var scaleZ = 1 / v1.setFromMatrixColumn( m, 2 ).length();
  6125. te[ 0 ] = me[ 0 ] * scaleX;
  6126. te[ 1 ] = me[ 1 ] * scaleX;
  6127. te[ 2 ] = me[ 2 ] * scaleX;
  6128. te[ 4 ] = me[ 4 ] * scaleY;
  6129. te[ 5 ] = me[ 5 ] * scaleY;
  6130. te[ 6 ] = me[ 6 ] * scaleY;
  6131. te[ 8 ] = me[ 8 ] * scaleZ;
  6132. te[ 9 ] = me[ 9 ] * scaleZ;
  6133. te[ 10 ] = me[ 10 ] * scaleZ;
  6134. return this;
  6135. };
  6136. }(),
  6137. makeRotationFromEuler: function ( euler ) {
  6138. if ( (euler && euler.isEuler) === false ) {
  6139. console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  6140. }
  6141. var te = this.elements;
  6142. var x = euler.x, y = euler.y, z = euler.z;
  6143. var a = Math.cos( x ), b = Math.sin( x );
  6144. var c = Math.cos( y ), d = Math.sin( y );
  6145. var e = Math.cos( z ), f = Math.sin( z );
  6146. if ( euler.order === 'XYZ' ) {
  6147. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  6148. te[ 0 ] = c * e;
  6149. te[ 4 ] = - c * f;
  6150. te[ 8 ] = d;
  6151. te[ 1 ] = af + be * d;
  6152. te[ 5 ] = ae - bf * d;
  6153. te[ 9 ] = - b * c;
  6154. te[ 2 ] = bf - ae * d;
  6155. te[ 6 ] = be + af * d;
  6156. te[ 10 ] = a * c;
  6157. } else if ( euler.order === 'YXZ' ) {
  6158. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  6159. te[ 0 ] = ce + df * b;
  6160. te[ 4 ] = de * b - cf;
  6161. te[ 8 ] = a * d;
  6162. te[ 1 ] = a * f;
  6163. te[ 5 ] = a * e;
  6164. te[ 9 ] = - b;
  6165. te[ 2 ] = cf * b - de;
  6166. te[ 6 ] = df + ce * b;
  6167. te[ 10 ] = a * c;
  6168. } else if ( euler.order === 'ZXY' ) {
  6169. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  6170. te[ 0 ] = ce - df * b;
  6171. te[ 4 ] = - a * f;
  6172. te[ 8 ] = de + cf * b;
  6173. te[ 1 ] = cf + de * b;
  6174. te[ 5 ] = a * e;
  6175. te[ 9 ] = df - ce * b;
  6176. te[ 2 ] = - a * d;
  6177. te[ 6 ] = b;
  6178. te[ 10 ] = a * c;
  6179. } else if ( euler.order === 'ZYX' ) {
  6180. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  6181. te[ 0 ] = c * e;
  6182. te[ 4 ] = be * d - af;
  6183. te[ 8 ] = ae * d + bf;
  6184. te[ 1 ] = c * f;
  6185. te[ 5 ] = bf * d + ae;
  6186. te[ 9 ] = af * d - be;
  6187. te[ 2 ] = - d;
  6188. te[ 6 ] = b * c;
  6189. te[ 10 ] = a * c;
  6190. } else if ( euler.order === 'YZX' ) {
  6191. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  6192. te[ 0 ] = c * e;
  6193. te[ 4 ] = bd - ac * f;
  6194. te[ 8 ] = bc * f + ad;
  6195. te[ 1 ] = f;
  6196. te[ 5 ] = a * e;
  6197. te[ 9 ] = - b * e;
  6198. te[ 2 ] = - d * e;
  6199. te[ 6 ] = ad * f + bc;
  6200. te[ 10 ] = ac - bd * f;
  6201. } else if ( euler.order === 'XZY' ) {
  6202. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  6203. te[ 0 ] = c * e;
  6204. te[ 4 ] = - f;
  6205. te[ 8 ] = d * e;
  6206. te[ 1 ] = ac * f + bd;
  6207. te[ 5 ] = a * e;
  6208. te[ 9 ] = ad * f - bc;
  6209. te[ 2 ] = bc * f - ad;
  6210. te[ 6 ] = b * e;
  6211. te[ 10 ] = bd * f + ac;
  6212. }
  6213. // last column
  6214. te[ 3 ] = 0;
  6215. te[ 7 ] = 0;
  6216. te[ 11 ] = 0;
  6217. // bottom row
  6218. te[ 12 ] = 0;
  6219. te[ 13 ] = 0;
  6220. te[ 14 ] = 0;
  6221. te[ 15 ] = 1;
  6222. return this;
  6223. },
  6224. makeRotationFromQuaternion: function ( q ) {
  6225. var te = this.elements;
  6226. var x = q.x, y = q.y, z = q.z, w = q.w;
  6227. var x2 = x + x, y2 = y + y, z2 = z + z;
  6228. var xx = x * x2, xy = x * y2, xz = x * z2;
  6229. var yy = y * y2, yz = y * z2, zz = z * z2;
  6230. var wx = w * x2, wy = w * y2, wz = w * z2;
  6231. te[ 0 ] = 1 - ( yy + zz );
  6232. te[ 4 ] = xy - wz;
  6233. te[ 8 ] = xz + wy;
  6234. te[ 1 ] = xy + wz;
  6235. te[ 5 ] = 1 - ( xx + zz );
  6236. te[ 9 ] = yz - wx;
  6237. te[ 2 ] = xz - wy;
  6238. te[ 6 ] = yz + wx;
  6239. te[ 10 ] = 1 - ( xx + yy );
  6240. // last column
  6241. te[ 3 ] = 0;
  6242. te[ 7 ] = 0;
  6243. te[ 11 ] = 0;
  6244. // bottom row
  6245. te[ 12 ] = 0;
  6246. te[ 13 ] = 0;
  6247. te[ 14 ] = 0;
  6248. te[ 15 ] = 1;
  6249. return this;
  6250. },
  6251. lookAt: function () {
  6252. var x, y, z;
  6253. return function lookAt( eye, target, up ) {
  6254. if ( x === undefined ) {
  6255. x = new Vector3();
  6256. y = new Vector3();
  6257. z = new Vector3();
  6258. }
  6259. var te = this.elements;
  6260. z.subVectors( eye, target ).normalize();
  6261. if ( z.lengthSq() === 0 ) {
  6262. z.z = 1;
  6263. }
  6264. x.crossVectors( up, z ).normalize();
  6265. if ( x.lengthSq() === 0 ) {
  6266. z.z += 0.0001;
  6267. x.crossVectors( up, z ).normalize();
  6268. }
  6269. y.crossVectors( z, x );
  6270. te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x;
  6271. te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y;
  6272. te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z;
  6273. return this;
  6274. };
  6275. }(),
  6276. multiply: function ( m, n ) {
  6277. if ( n !== undefined ) {
  6278. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  6279. return this.multiplyMatrices( m, n );
  6280. }
  6281. return this.multiplyMatrices( this, m );
  6282. },
  6283. premultiply: function ( m ) {
  6284. return this.multiplyMatrices( m, this );
  6285. },
  6286. multiplyMatrices: function ( a, b ) {
  6287. var ae = a.elements;
  6288. var be = b.elements;
  6289. var te = this.elements;
  6290. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  6291. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  6292. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  6293. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  6294. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  6295. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  6296. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  6297. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  6298. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  6299. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  6300. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  6301. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  6302. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  6303. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  6304. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  6305. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  6306. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  6307. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  6308. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  6309. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  6310. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  6311. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  6312. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  6313. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  6314. return this;
  6315. },
  6316. multiplyToArray: function ( a, b, r ) {
  6317. var te = this.elements;
  6318. this.multiplyMatrices( a, b );
  6319. r[ 0 ] = te[ 0 ]; r[ 1 ] = te[ 1 ]; r[ 2 ] = te[ 2 ]; r[ 3 ] = te[ 3 ];
  6320. r[ 4 ] = te[ 4 ]; r[ 5 ] = te[ 5 ]; r[ 6 ] = te[ 6 ]; r[ 7 ] = te[ 7 ];
  6321. r[ 8 ] = te[ 8 ]; r[ 9 ] = te[ 9 ]; r[ 10 ] = te[ 10 ]; r[ 11 ] = te[ 11 ];
  6322. r[ 12 ] = te[ 12 ]; r[ 13 ] = te[ 13 ]; r[ 14 ] = te[ 14 ]; r[ 15 ] = te[ 15 ];
  6323. return this;
  6324. },
  6325. multiplyScalar: function ( s ) {
  6326. var te = this.elements;
  6327. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  6328. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  6329. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  6330. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  6331. return this;
  6332. },
  6333. applyToBufferAttribute: function () {
  6334. var v1;
  6335. return function applyToBufferAttribute( attribute ) {
  6336. if ( v1 === undefined ) v1 = new Vector3();
  6337. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  6338. v1.x = attribute.getX( i );
  6339. v1.y = attribute.getY( i );
  6340. v1.z = attribute.getZ( i );
  6341. v1.applyMatrix4( this );
  6342. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  6343. }
  6344. return attribute;
  6345. };
  6346. }(),
  6347. determinant: function () {
  6348. var te = this.elements;
  6349. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  6350. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  6351. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  6352. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  6353. //TODO: make this more efficient
  6354. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  6355. return (
  6356. n41 * (
  6357. + n14 * n23 * n32
  6358. - n13 * n24 * n32
  6359. - n14 * n22 * n33
  6360. + n12 * n24 * n33
  6361. + n13 * n22 * n34
  6362. - n12 * n23 * n34
  6363. ) +
  6364. n42 * (
  6365. + n11 * n23 * n34
  6366. - n11 * n24 * n33
  6367. + n14 * n21 * n33
  6368. - n13 * n21 * n34
  6369. + n13 * n24 * n31
  6370. - n14 * n23 * n31
  6371. ) +
  6372. n43 * (
  6373. + n11 * n24 * n32
  6374. - n11 * n22 * n34
  6375. - n14 * n21 * n32
  6376. + n12 * n21 * n34
  6377. + n14 * n22 * n31
  6378. - n12 * n24 * n31
  6379. ) +
  6380. n44 * (
  6381. - n13 * n22 * n31
  6382. - n11 * n23 * n32
  6383. + n11 * n22 * n33
  6384. + n13 * n21 * n32
  6385. - n12 * n21 * n33
  6386. + n12 * n23 * n31
  6387. )
  6388. );
  6389. },
  6390. transpose: function () {
  6391. var te = this.elements;
  6392. var tmp;
  6393. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  6394. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  6395. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  6396. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  6397. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  6398. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  6399. return this;
  6400. },
  6401. setPosition: function ( v ) {
  6402. var te = this.elements;
  6403. te[ 12 ] = v.x;
  6404. te[ 13 ] = v.y;
  6405. te[ 14 ] = v.z;
  6406. return this;
  6407. },
  6408. getInverse: function ( m, throwOnDegenerate ) {
  6409. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  6410. var te = this.elements,
  6411. me = m.elements,
  6412. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ],
  6413. n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ],
  6414. n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ],
  6415. n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ],
  6416. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  6417. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  6418. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  6419. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  6420. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  6421. if ( det === 0 ) {
  6422. var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0";
  6423. if ( throwOnDegenerate === true ) {
  6424. throw new Error( msg );
  6425. } else {
  6426. console.warn( msg );
  6427. }
  6428. return this.identity();
  6429. }
  6430. var detInv = 1 / det;
  6431. te[ 0 ] = t11 * detInv;
  6432. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  6433. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  6434. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  6435. te[ 4 ] = t12 * detInv;
  6436. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  6437. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  6438. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  6439. te[ 8 ] = t13 * detInv;
  6440. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  6441. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  6442. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  6443. te[ 12 ] = t14 * detInv;
  6444. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  6445. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  6446. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  6447. return this;
  6448. },
  6449. scale: function ( v ) {
  6450. var te = this.elements;
  6451. var x = v.x, y = v.y, z = v.z;
  6452. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  6453. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  6454. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  6455. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  6456. return this;
  6457. },
  6458. getMaxScaleOnAxis: function () {
  6459. var te = this.elements;
  6460. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  6461. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  6462. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  6463. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  6464. },
  6465. makeTranslation: function ( x, y, z ) {
  6466. this.set(
  6467. 1, 0, 0, x,
  6468. 0, 1, 0, y,
  6469. 0, 0, 1, z,
  6470. 0, 0, 0, 1
  6471. );
  6472. return this;
  6473. },
  6474. makeRotationX: function ( theta ) {
  6475. var c = Math.cos( theta ), s = Math.sin( theta );
  6476. this.set(
  6477. 1, 0, 0, 0,
  6478. 0, c, - s, 0,
  6479. 0, s, c, 0,
  6480. 0, 0, 0, 1
  6481. );
  6482. return this;
  6483. },
  6484. makeRotationY: function ( theta ) {
  6485. var c = Math.cos( theta ), s = Math.sin( theta );
  6486. this.set(
  6487. c, 0, s, 0,
  6488. 0, 1, 0, 0,
  6489. - s, 0, c, 0,
  6490. 0, 0, 0, 1
  6491. );
  6492. return this;
  6493. },
  6494. makeRotationZ: function ( theta ) {
  6495. var c = Math.cos( theta ), s = Math.sin( theta );
  6496. this.set(
  6497. c, - s, 0, 0,
  6498. s, c, 0, 0,
  6499. 0, 0, 1, 0,
  6500. 0, 0, 0, 1
  6501. );
  6502. return this;
  6503. },
  6504. makeRotationAxis: function ( axis, angle ) {
  6505. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  6506. var c = Math.cos( angle );
  6507. var s = Math.sin( angle );
  6508. var t = 1 - c;
  6509. var x = axis.x, y = axis.y, z = axis.z;
  6510. var tx = t * x, ty = t * y;
  6511. this.set(
  6512. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  6513. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  6514. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  6515. 0, 0, 0, 1
  6516. );
  6517. return this;
  6518. },
  6519. makeScale: function ( x, y, z ) {
  6520. this.set(
  6521. x, 0, 0, 0,
  6522. 0, y, 0, 0,
  6523. 0, 0, z, 0,
  6524. 0, 0, 0, 1
  6525. );
  6526. return this;
  6527. },
  6528. makeShear: function ( x, y, z ) {
  6529. this.set(
  6530. 1, y, z, 0,
  6531. x, 1, z, 0,
  6532. x, y, 1, 0,
  6533. 0, 0, 0, 1
  6534. );
  6535. return this;
  6536. },
  6537. compose: function ( position, quaternion, scale ) {
  6538. this.makeRotationFromQuaternion( quaternion );
  6539. this.scale( scale );
  6540. this.setPosition( position );
  6541. return this;
  6542. },
  6543. decompose: function () {
  6544. var vector, matrix;
  6545. return function decompose( position, quaternion, scale ) {
  6546. if ( vector === undefined ) {
  6547. vector = new Vector3();
  6548. matrix = new Matrix4();
  6549. }
  6550. var te = this.elements;
  6551. var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  6552. var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  6553. var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  6554. // if determine is negative, we need to invert one scale
  6555. var det = this.determinant();
  6556. if ( det < 0 ) {
  6557. sx = - sx;
  6558. }
  6559. position.x = te[ 12 ];
  6560. position.y = te[ 13 ];
  6561. position.z = te[ 14 ];
  6562. // scale the rotation part
  6563. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  6564. var invSX = 1 / sx;
  6565. var invSY = 1 / sy;
  6566. var invSZ = 1 / sz;
  6567. matrix.elements[ 0 ] *= invSX;
  6568. matrix.elements[ 1 ] *= invSX;
  6569. matrix.elements[ 2 ] *= invSX;
  6570. matrix.elements[ 4 ] *= invSY;
  6571. matrix.elements[ 5 ] *= invSY;
  6572. matrix.elements[ 6 ] *= invSY;
  6573. matrix.elements[ 8 ] *= invSZ;
  6574. matrix.elements[ 9 ] *= invSZ;
  6575. matrix.elements[ 10 ] *= invSZ;
  6576. quaternion.setFromRotationMatrix( matrix );
  6577. scale.x = sx;
  6578. scale.y = sy;
  6579. scale.z = sz;
  6580. return this;
  6581. };
  6582. }(),
  6583. makePerspective: function ( left, right, top, bottom, near, far ) {
  6584. if ( far === undefined ) {
  6585. console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' );
  6586. }
  6587. var te = this.elements;
  6588. var x = 2 * near / ( right - left );
  6589. var y = 2 * near / ( top - bottom );
  6590. var a = ( right + left ) / ( right - left );
  6591. var b = ( top + bottom ) / ( top - bottom );
  6592. var c = - ( far + near ) / ( far - near );
  6593. var d = - 2 * far * near / ( far - near );
  6594. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  6595. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  6596. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  6597. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  6598. return this;
  6599. },
  6600. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  6601. var te = this.elements;
  6602. var w = 1.0 / ( right - left );
  6603. var h = 1.0 / ( top - bottom );
  6604. var p = 1.0 / ( far - near );
  6605. var x = ( right + left ) * w;
  6606. var y = ( top + bottom ) * h;
  6607. var z = ( far + near ) * p;
  6608. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  6609. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  6610. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  6611. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  6612. return this;
  6613. },
  6614. equals: function ( matrix ) {
  6615. var te = this.elements;
  6616. var me = matrix.elements;
  6617. for ( var i = 0; i < 16; i ++ ) {
  6618. if ( te[ i ] !== me[ i ] ) return false;
  6619. }
  6620. return true;
  6621. },
  6622. fromArray: function ( array, offset ) {
  6623. if ( offset === undefined ) offset = 0;
  6624. for( var i = 0; i < 16; i ++ ) {
  6625. this.elements[ i ] = array[ i + offset ];
  6626. }
  6627. return this;
  6628. },
  6629. toArray: function ( array, offset ) {
  6630. if ( array === undefined ) array = [];
  6631. if ( offset === undefined ) offset = 0;
  6632. var te = this.elements;
  6633. array[ offset ] = te[ 0 ];
  6634. array[ offset + 1 ] = te[ 1 ];
  6635. array[ offset + 2 ] = te[ 2 ];
  6636. array[ offset + 3 ] = te[ 3 ];
  6637. array[ offset + 4 ] = te[ 4 ];
  6638. array[ offset + 5 ] = te[ 5 ];
  6639. array[ offset + 6 ] = te[ 6 ];
  6640. array[ offset + 7 ] = te[ 7 ];
  6641. array[ offset + 8 ] = te[ 8 ];
  6642. array[ offset + 9 ] = te[ 9 ];
  6643. array[ offset + 10 ] = te[ 10 ];
  6644. array[ offset + 11 ] = te[ 11 ];
  6645. array[ offset + 12 ] = te[ 12 ];
  6646. array[ offset + 13 ] = te[ 13 ];
  6647. array[ offset + 14 ] = te[ 14 ];
  6648. array[ offset + 15 ] = te[ 15 ];
  6649. return array;
  6650. }
  6651. };
  6652. /**
  6653. * @author mrdoob / http://mrdoob.com/
  6654. */
  6655. function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  6656. images = images !== undefined ? images : [];
  6657. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  6658. Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  6659. this.flipY = false;
  6660. }
  6661. CubeTexture.prototype = Object.create( Texture.prototype );
  6662. CubeTexture.prototype.constructor = CubeTexture;
  6663. CubeTexture.prototype.isCubeTexture = true;
  6664. Object.defineProperty( CubeTexture.prototype, 'images', {
  6665. get: function () {
  6666. return this.image;
  6667. },
  6668. set: function ( value ) {
  6669. this.image = value;
  6670. }
  6671. } );
  6672. /**
  6673. * @author tschw
  6674. *
  6675. * Uniforms of a program.
  6676. * Those form a tree structure with a special top-level container for the root,
  6677. * which you get by calling 'new WebGLUniforms( gl, program, renderer )'.
  6678. *
  6679. *
  6680. * Properties of inner nodes including the top-level container:
  6681. *
  6682. * .seq - array of nested uniforms
  6683. * .map - nested uniforms by name
  6684. *
  6685. *
  6686. * Methods of all nodes except the top-level container:
  6687. *
  6688. * .setValue( gl, value, [renderer] )
  6689. *
  6690. * uploads a uniform value(s)
  6691. * the 'renderer' parameter is needed for sampler uniforms
  6692. *
  6693. *
  6694. * Static methods of the top-level container (renderer factorizations):
  6695. *
  6696. * .upload( gl, seq, values, renderer )
  6697. *
  6698. * sets uniforms in 'seq' to 'values[id].value'
  6699. *
  6700. * .seqWithValue( seq, values ) : filteredSeq
  6701. *
  6702. * filters 'seq' entries with corresponding entry in values
  6703. *
  6704. *
  6705. * Methods of the top-level container (renderer factorizations):
  6706. *
  6707. * .setValue( gl, name, value )
  6708. *
  6709. * sets uniform with name 'name' to 'value'
  6710. *
  6711. * .set( gl, obj, prop )
  6712. *
  6713. * sets uniform from object and property with same name than uniform
  6714. *
  6715. * .setOptional( gl, obj, prop )
  6716. *
  6717. * like .set for an optional property of the object
  6718. *
  6719. */
  6720. var emptyTexture = new Texture();
  6721. var emptyCubeTexture = new CubeTexture();
  6722. // --- Base for inner nodes (including the root) ---
  6723. function UniformContainer() {
  6724. this.seq = [];
  6725. this.map = {};
  6726. }
  6727. // --- Utilities ---
  6728. // Array Caches (provide typed arrays for temporary by size)
  6729. var arrayCacheF32 = [];
  6730. var arrayCacheI32 = [];
  6731. // Flattening for arrays of vectors and matrices
  6732. function flatten( array, nBlocks, blockSize ) {
  6733. var firstElem = array[ 0 ];
  6734. if ( firstElem <= 0 || firstElem > 0 ) return array;
  6735. // unoptimized: ! isNaN( firstElem )
  6736. // see http://jacksondunstan.com/articles/983
  6737. var n = nBlocks * blockSize,
  6738. r = arrayCacheF32[ n ];
  6739. if ( r === undefined ) {
  6740. r = new Float32Array( n );
  6741. arrayCacheF32[ n ] = r;
  6742. }
  6743. if ( nBlocks !== 0 ) {
  6744. firstElem.toArray( r, 0 );
  6745. for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) {
  6746. offset += blockSize;
  6747. array[ i ].toArray( r, offset );
  6748. }
  6749. }
  6750. return r;
  6751. }
  6752. // Texture unit allocation
  6753. function allocTexUnits( renderer, n ) {
  6754. var r = arrayCacheI32[ n ];
  6755. if ( r === undefined ) {
  6756. r = new Int32Array( n );
  6757. arrayCacheI32[ n ] = r;
  6758. }
  6759. for ( var i = 0; i !== n; ++ i )
  6760. r[ i ] = renderer.allocTextureUnit();
  6761. return r;
  6762. }
  6763. // --- Setters ---
  6764. // Note: Defining these methods externally, because they come in a bunch
  6765. // and this way their names minify.
  6766. // Single scalar
  6767. function setValue1f( gl, v ) { gl.uniform1f( this.addr, v ); }
  6768. function setValue1i( gl, v ) { gl.uniform1i( this.addr, v ); }
  6769. // Single float vector (from flat array or THREE.VectorN)
  6770. function setValue2fv( gl, v ) {
  6771. if ( v.x === undefined ) gl.uniform2fv( this.addr, v );
  6772. else gl.uniform2f( this.addr, v.x, v.y );
  6773. }
  6774. function setValue3fv( gl, v ) {
  6775. if ( v.x !== undefined )
  6776. gl.uniform3f( this.addr, v.x, v.y, v.z );
  6777. else if ( v.r !== undefined )
  6778. gl.uniform3f( this.addr, v.r, v.g, v.b );
  6779. else
  6780. gl.uniform3fv( this.addr, v );
  6781. }
  6782. function setValue4fv( gl, v ) {
  6783. if ( v.x === undefined ) gl.uniform4fv( this.addr, v );
  6784. else gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  6785. }
  6786. // Single matrix (from flat array or MatrixN)
  6787. function setValue2fm( gl, v ) {
  6788. gl.uniformMatrix2fv( this.addr, false, v.elements || v );
  6789. }
  6790. function setValue3fm( gl, v ) {
  6791. gl.uniformMatrix3fv( this.addr, false, v.elements || v );
  6792. }
  6793. function setValue4fm( gl, v ) {
  6794. gl.uniformMatrix4fv( this.addr, false, v.elements || v );
  6795. }
  6796. // Single texture (2D / Cube)
  6797. function setValueT1( gl, v, renderer ) {
  6798. var unit = renderer.allocTextureUnit();
  6799. gl.uniform1i( this.addr, unit );
  6800. renderer.setTexture2D( v || emptyTexture, unit );
  6801. }
  6802. function setValueT6( gl, v, renderer ) {
  6803. var unit = renderer.allocTextureUnit();
  6804. gl.uniform1i( this.addr, unit );
  6805. renderer.setTextureCube( v || emptyCubeTexture, unit );
  6806. }
  6807. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  6808. function setValue2iv( gl, v ) { gl.uniform2iv( this.addr, v ); }
  6809. function setValue3iv( gl, v ) { gl.uniform3iv( this.addr, v ); }
  6810. function setValue4iv( gl, v ) { gl.uniform4iv( this.addr, v ); }
  6811. // Helper to pick the right setter for the singular case
  6812. function getSingularSetter( type ) {
  6813. switch ( type ) {
  6814. case 0x1406: return setValue1f; // FLOAT
  6815. case 0x8b50: return setValue2fv; // _VEC2
  6816. case 0x8b51: return setValue3fv; // _VEC3
  6817. case 0x8b52: return setValue4fv; // _VEC4
  6818. case 0x8b5a: return setValue2fm; // _MAT2
  6819. case 0x8b5b: return setValue3fm; // _MAT3
  6820. case 0x8b5c: return setValue4fm; // _MAT4
  6821. case 0x8b5e: return setValueT1; // SAMPLER_2D
  6822. case 0x8b60: return setValueT6; // SAMPLER_CUBE
  6823. case 0x1404: case 0x8b56: return setValue1i; // INT, BOOL
  6824. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  6825. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  6826. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  6827. }
  6828. }
  6829. // Array of scalars
  6830. function setValue1fv( gl, v ) { gl.uniform1fv( this.addr, v ); }
  6831. function setValue1iv( gl, v ) { gl.uniform1iv( this.addr, v ); }
  6832. // Array of vectors (flat or from THREE classes)
  6833. function setValueV2a( gl, v ) {
  6834. gl.uniform2fv( this.addr, flatten( v, this.size, 2 ) );
  6835. }
  6836. function setValueV3a( gl, v ) {
  6837. gl.uniform3fv( this.addr, flatten( v, this.size, 3 ) );
  6838. }
  6839. function setValueV4a( gl, v ) {
  6840. gl.uniform4fv( this.addr, flatten( v, this.size, 4 ) );
  6841. }
  6842. // Array of matrices (flat or from THREE clases)
  6843. function setValueM2a( gl, v ) {
  6844. gl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) );
  6845. }
  6846. function setValueM3a( gl, v ) {
  6847. gl.uniformMatrix3fv( this.addr, false, flatten( v, this.size, 9 ) );
  6848. }
  6849. function setValueM4a( gl, v ) {
  6850. gl.uniformMatrix4fv( this.addr, false, flatten( v, this.size, 16 ) );
  6851. }
  6852. // Array of textures (2D / Cube)
  6853. function setValueT1a( gl, v, renderer ) {
  6854. var n = v.length,
  6855. units = allocTexUnits( renderer, n );
  6856. gl.uniform1iv( this.addr, units );
  6857. for ( var i = 0; i !== n; ++ i ) {
  6858. renderer.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  6859. }
  6860. }
  6861. function setValueT6a( gl, v, renderer ) {
  6862. var n = v.length,
  6863. units = allocTexUnits( renderer, n );
  6864. gl.uniform1iv( this.addr, units );
  6865. for ( var i = 0; i !== n; ++ i ) {
  6866. renderer.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  6867. }
  6868. }
  6869. // Helper to pick the right setter for a pure (bottom-level) array
  6870. function getPureArraySetter( type ) {
  6871. switch ( type ) {
  6872. case 0x1406: return setValue1fv; // FLOAT
  6873. case 0x8b50: return setValueV2a; // _VEC2
  6874. case 0x8b51: return setValueV3a; // _VEC3
  6875. case 0x8b52: return setValueV4a; // _VEC4
  6876. case 0x8b5a: return setValueM2a; // _MAT2
  6877. case 0x8b5b: return setValueM3a; // _MAT3
  6878. case 0x8b5c: return setValueM4a; // _MAT4
  6879. case 0x8b5e: return setValueT1a; // SAMPLER_2D
  6880. case 0x8b60: return setValueT6a; // SAMPLER_CUBE
  6881. case 0x1404: case 0x8b56: return setValue1iv; // INT, BOOL
  6882. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  6883. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  6884. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  6885. }
  6886. }
  6887. // --- Uniform Classes ---
  6888. function SingleUniform( id, activeInfo, addr ) {
  6889. this.id = id;
  6890. this.addr = addr;
  6891. this.setValue = getSingularSetter( activeInfo.type );
  6892. // this.path = activeInfo.name; // DEBUG
  6893. }
  6894. function PureArrayUniform( id, activeInfo, addr ) {
  6895. this.id = id;
  6896. this.addr = addr;
  6897. this.size = activeInfo.size;
  6898. this.setValue = getPureArraySetter( activeInfo.type );
  6899. // this.path = activeInfo.name; // DEBUG
  6900. }
  6901. function StructuredUniform( id ) {
  6902. this.id = id;
  6903. UniformContainer.call( this ); // mix-in
  6904. }
  6905. StructuredUniform.prototype.setValue = function( gl, value ) {
  6906. // Note: Don't need an extra 'renderer' parameter, since samplers
  6907. // are not allowed in structured uniforms.
  6908. var seq = this.seq;
  6909. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  6910. var u = seq[ i ];
  6911. u.setValue( gl, value[ u.id ] );
  6912. }
  6913. };
  6914. // --- Top-level ---
  6915. // Parser - builds up the property tree from the path strings
  6916. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g;
  6917. // extracts
  6918. // - the identifier (member name or array index)
  6919. // - followed by an optional right bracket (found when array index)
  6920. // - followed by an optional left bracket or dot (type of subscript)
  6921. //
  6922. // Note: These portions can be read in a non-overlapping fashion and
  6923. // allow straightforward parsing of the hierarchy that WebGL encodes
  6924. // in the uniform names.
  6925. function addUniform( container, uniformObject ) {
  6926. container.seq.push( uniformObject );
  6927. container.map[ uniformObject.id ] = uniformObject;
  6928. }
  6929. function parseUniform( activeInfo, addr, container ) {
  6930. var path = activeInfo.name,
  6931. pathLength = path.length;
  6932. // reset RegExp object, because of the early exit of a previous run
  6933. RePathPart.lastIndex = 0;
  6934. for (; ;) {
  6935. var match = RePathPart.exec( path ),
  6936. matchEnd = RePathPart.lastIndex,
  6937. id = match[ 1 ],
  6938. idIsIndex = match[ 2 ] === ']',
  6939. subscript = match[ 3 ];
  6940. if ( idIsIndex ) id = id | 0; // convert to integer
  6941. if ( subscript === undefined ||
  6942. subscript === '[' && matchEnd + 2 === pathLength ) {
  6943. // bare name or "pure" bottom-level array "[0]" suffix
  6944. addUniform( container, subscript === undefined ?
  6945. new SingleUniform( id, activeInfo, addr ) :
  6946. new PureArrayUniform( id, activeInfo, addr ) );
  6947. break;
  6948. } else {
  6949. // step into inner node / create it in case it doesn't exist
  6950. var map = container.map,
  6951. next = map[ id ];
  6952. if ( next === undefined ) {
  6953. next = new StructuredUniform( id );
  6954. addUniform( container, next );
  6955. }
  6956. container = next;
  6957. }
  6958. }
  6959. }
  6960. // Root Container
  6961. function WebGLUniforms( gl, program, renderer ) {
  6962. UniformContainer.call( this );
  6963. this.renderer = renderer;
  6964. var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  6965. for ( var i = 0; i < n; ++ i ) {
  6966. var info = gl.getActiveUniform( program, i ),
  6967. path = info.name,
  6968. addr = gl.getUniformLocation( program, path );
  6969. parseUniform( info, addr, this );
  6970. }
  6971. }
  6972. WebGLUniforms.prototype.setValue = function( gl, name, value ) {
  6973. var u = this.map[ name ];
  6974. if ( u !== undefined ) u.setValue( gl, value, this.renderer );
  6975. };
  6976. WebGLUniforms.prototype.set = function( gl, object, name ) {
  6977. var u = this.map[ name ];
  6978. if ( u !== undefined ) u.setValue( gl, object[ name ], this.renderer );
  6979. };
  6980. WebGLUniforms.prototype.setOptional = function( gl, object, name ) {
  6981. var v = object[ name ];
  6982. if ( v !== undefined ) this.setValue( gl, name, v );
  6983. };
  6984. // Static interface
  6985. WebGLUniforms.upload = function( gl, seq, values, renderer ) {
  6986. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  6987. var u = seq[ i ],
  6988. v = values[ u.id ];
  6989. if ( v.needsUpdate !== false ) {
  6990. // note: always updating when .needsUpdate is undefined
  6991. u.setValue( gl, v.value, renderer );
  6992. }
  6993. }
  6994. };
  6995. WebGLUniforms.seqWithValue = function( seq, values ) {
  6996. var r = [];
  6997. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  6998. var u = seq[ i ];
  6999. if ( u.id in values ) r.push( u );
  7000. }
  7001. return r;
  7002. };
  7003. /**
  7004. * Uniform Utilities
  7005. */
  7006. var UniformsUtils = {
  7007. merge: function ( uniforms ) {
  7008. var merged = {};
  7009. for ( var u = 0; u < uniforms.length; u ++ ) {
  7010. var tmp = this.clone( uniforms[ u ] );
  7011. for ( var p in tmp ) {
  7012. merged[ p ] = tmp[ p ];
  7013. }
  7014. }
  7015. return merged;
  7016. },
  7017. clone: function ( uniforms_src ) {
  7018. var uniforms_dst = {};
  7019. for ( var u in uniforms_src ) {
  7020. uniforms_dst[ u ] = {};
  7021. for ( var p in uniforms_src[ u ] ) {
  7022. var parameter_src = uniforms_src[ u ][ p ];
  7023. if ( parameter_src && ( parameter_src.isColor ||
  7024. parameter_src.isMatrix3 || parameter_src.isMatrix4 ||
  7025. parameter_src.isVector2 || parameter_src.isVector3 || parameter_src.isVector4 ||
  7026. parameter_src.isTexture ) ) {
  7027. uniforms_dst[ u ][ p ] = parameter_src.clone();
  7028. } else if ( Array.isArray( parameter_src ) ) {
  7029. uniforms_dst[ u ][ p ] = parameter_src.slice();
  7030. } else {
  7031. uniforms_dst[ u ][ p ] = parameter_src;
  7032. }
  7033. }
  7034. }
  7035. return uniforms_dst;
  7036. }
  7037. };
  7038. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n";
  7039. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif\n";
  7040. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n";
  7041. 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";
  7042. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7043. var begin_vertex = "\nvec3 transformed = vec3( position );\n";
  7044. var beginnormal_vertex = "\nvec3 objectNormal = vec3( normal );\n";
  7045. var bsdfs = "float punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t\tif( decayExponent > 0.0 ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\t\tfloat maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t\treturn distanceFalloff * maxDistanceCutoffFactor;\n#else\n\t\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n#endif\n\t\t}\n\t\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 ltcTextureCoords( const in GeometricContext geometry, 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\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 P = geometry.position;\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}\nvoid clipQuadToHorizon( inout vec3 L[5], out int n ) {\n\tint config = 0;\n\tif ( L[0].z > 0.0 ) config += 1;\n\tif ( L[1].z > 0.0 ) config += 2;\n\tif ( L[2].z > 0.0 ) config += 4;\n\tif ( L[3].z > 0.0 ) config += 8;\n\tn = 0;\n\tif ( config == 0 ) {\n\t} else if ( config == 1 ) {\n\t\tn = 3;\n\t\tL[1] = -L[1].z * L[0] + L[0].z * L[1];\n\t\tL[2] = -L[3].z * L[0] + L[0].z * L[3];\n\t} else if ( config == 2 ) {\n\t\tn = 3;\n\t\tL[0] = -L[0].z * L[1] + L[1].z * L[0];\n\t\tL[2] = -L[2].z * L[1] + L[1].z * L[2];\n\t} else if ( config == 3 ) {\n\t\tn = 4;\n\t\tL[2] = -L[2].z * L[1] + L[1].z * L[2];\n\t\tL[3] = -L[3].z * L[0] + L[0].z * L[3];\n\t} else if ( config == 4 ) {\n\t\tn = 3;\n\t\tL[0] = -L[3].z * L[2] + L[2].z * L[3];\n\t\tL[1] = -L[1].z * L[2] + L[2].z * L[1];\n\t} else if ( config == 5 ) {\n\t\tn = 0;\n\t} else if ( config == 6 ) {\n\t\tn = 4;\n\t\tL[0] = -L[0].z * L[1] + L[1].z * L[0];\n\t\tL[3] = -L[3].z * L[2] + L[2].z * L[3];\n\t} else if ( config == 7 ) {\n\t\tn = 5;\n\t\tL[4] = -L[3].z * L[0] + L[0].z * L[3];\n\t\tL[3] = -L[3].z * L[2] + L[2].z * L[3];\n\t} else if ( config == 8 ) {\n\t\tn = 3;\n\t\tL[0] = -L[0].z * L[3] + L[3].z * L[0];\n\t\tL[1] = -L[2].z * L[3] + L[3].z * L[2];\n\t\tL[2] = L[3];\n\t} else if ( config == 9 ) {\n\t\tn = 4;\n\t\tL[1] = -L[1].z * L[0] + L[0].z * L[1];\n\t\tL[2] = -L[2].z * L[3] + L[3].z * L[2];\n\t} else if ( config == 10 ) {\n\t\tn = 0;\n\t} else if ( config == 11 ) {\n\t\tn = 5;\n\t\tL[4] = L[3];\n\t\tL[3] = -L[2].z * L[3] + L[3].z * L[2];\n\t\tL[2] = -L[2].z * L[1] + L[1].z * L[2];\n\t} else if ( config == 12 ) {\n\t\tn = 4;\n\t\tL[1] = -L[1].z * L[2] + L[2].z * L[1];\n\t\tL[0] = -L[0].z * L[3] + L[3].z * L[0];\n\t} else if ( config == 13 ) {\n\t\tn = 5;\n\t\tL[4] = L[3];\n\t\tL[3] = L[2];\n\t\tL[2] = -L[1].z * L[2] + L[2].z * L[1];\n\t\tL[1] = -L[1].z * L[0] + L[0].z * L[1];\n\t} else if ( config == 14 ) {\n\t\tn = 5;\n\t\tL[4] = -L[0].z * L[3] + L[3].z * L[0];\n\t\tL[0] = -L[0].z * L[1] + L[1].z * L[0];\n\t} else if ( config == 15 ) {\n\t\tn = 4;\n\t}\n\tif ( n == 3 )\n\t\tL[3] = L[0];\n\tif ( n == 4 )\n\t\tL[4] = L[0];\n}\nfloat integrateLtcBrdfOverRectEdge( vec3 v1, vec3 v2 ) {\n\tfloat cosTheta = dot( v1, v2 );\n\tfloat theta = acos( cosTheta );\n\tfloat res = cross( v1, v2 ).z * ( ( theta > 0.001 ) ? theta / sin( theta ) : 1.0 );\n\treturn res;\n}\nvoid initRectPoints( const in vec3 pos, const in vec3 halfWidth, const in vec3 halfHeight, out vec3 rectPoints[4] ) {\n\trectPoints[0] = pos - halfWidth - halfHeight;\n\trectPoints[1] = pos + halfWidth - halfHeight;\n\trectPoints[2] = pos + halfWidth + halfHeight;\n\trectPoints[3] = pos - halfWidth + halfHeight;\n}\nvec3 integrateLtcBrdfOverRect( const in GeometricContext geometry, const in mat3 brdfMat, const in vec3 rectPoints[4] ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 P = geometry.position;\n\tvec3 T1, T2;\n\tT1 = normalize(V - N * dot( V, N ));\n\tT2 = - cross( N, T1 );\n\tmat3 brdfWrtSurface = brdfMat * transpose( mat3( T1, T2, N ) );\n\tvec3 clippedRect[5];\n\tclippedRect[0] = brdfWrtSurface * ( rectPoints[0] - P );\n\tclippedRect[1] = brdfWrtSurface * ( rectPoints[1] - P );\n\tclippedRect[2] = brdfWrtSurface * ( rectPoints[2] - P );\n\tclippedRect[3] = brdfWrtSurface * ( rectPoints[3] - P );\n\tint n;\n\tclipQuadToHorizon(clippedRect, n);\n\tif ( n == 0 )\n\t\treturn vec3( 0, 0, 0 );\n\tclippedRect[0] = normalize( clippedRect[0] );\n\tclippedRect[1] = normalize( clippedRect[1] );\n\tclippedRect[2] = normalize( clippedRect[2] );\n\tclippedRect[3] = normalize( clippedRect[3] );\n\tclippedRect[4] = normalize( clippedRect[4] );\n\tfloat sum = 0.0;\n\tsum += integrateLtcBrdfOverRectEdge( clippedRect[0], clippedRect[1] );\n\tsum += integrateLtcBrdfOverRectEdge( clippedRect[1], clippedRect[2] );\n\tsum += integrateLtcBrdfOverRectEdge( clippedRect[2], clippedRect[3] );\n\tif (n >= 4)\n\t\tsum += integrateLtcBrdfOverRectEdge( clippedRect[3], clippedRect[4] );\n\tif (n == 5)\n\t\tsum += integrateLtcBrdfOverRectEdge( clippedRect[4], clippedRect[0] );\n\tsum = max( 0.0, sum );\n\tvec3 Lo_i = vec3( sum, sum, sum );\n\treturn Lo_i;\n}\nvec3 Rect_Area_Light_Specular_Reflectance(\n\t\tconst in GeometricContext geometry,\n\t\tconst in vec3 lightPos, const in vec3 lightHalfWidth, const in vec3 lightHalfHeight,\n\t\tconst in float roughness,\n\t\tconst in sampler2D ltcMat, const in sampler2D ltcMag ) {\n\tvec3 rectPoints[4];\n\tinitRectPoints( lightPos, lightHalfWidth, lightHalfHeight, rectPoints );\n\tvec2 uv = ltcTextureCoords( geometry, roughness );\n\tvec4 brdfLtcApproxParams, t;\n\tbrdfLtcApproxParams = texture2D( ltcMat, uv );\n\tt = texture2D( ltcMat, uv );\n\tfloat brdfLtcScalar = texture2D( ltcMag, uv ).a;\n\tmat3 brdfLtcApproxMat = mat3(\n\t\tvec3( 1, 0, t.y ),\n\t\tvec3( 0, t.z, 0 ),\n\t\tvec3( t.w, 0, t.x )\n\t);\n\tvec3 specularReflectance = integrateLtcBrdfOverRect( geometry, brdfLtcApproxMat, rectPoints );\n\tspecularReflectance *= brdfLtcScalar;\n\treturn specularReflectance;\n}\nvec3 Rect_Area_Light_Diffuse_Reflectance(\n\t\tconst in GeometricContext geometry,\n\t\tconst in vec3 lightPos, const in vec3 lightHalfWidth, const in vec3 lightHalfHeight ) {\n\tvec3 rectPoints[4];\n\tinitRectPoints( lightPos, lightHalfWidth, lightHalfHeight, rectPoints );\n\tmat3 diffuseBrdfMat = mat3(1);\n\tvec3 diffuseReflectance = integrateLtcBrdfOverRect( geometry, diffuseBrdfMat, rectPoints );\n\treturn diffuseReflectance;\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";
  7046. 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 = dFdx( surf_pos );\n\t\tvec3 vSigmaY = dFdy( surf_pos );\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";
  7047. 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";
  7048. 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";
  7049. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n";
  7050. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n";
  7051. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7052. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif\n";
  7053. var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  7054. var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";
  7055. 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";
  7056. 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";
  7057. var defaultnormal_vertex = "#ifdef FLIP_SIDED\n\tobjectNormal = -objectNormal;\n#endif\nvec3 transformedNormal = normalMatrix * objectNormal;\n";
  7058. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif\n";
  7059. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normal * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n";
  7060. 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";
  7061. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif\n";
  7062. var encodings_fragment = " gl_FragColor = linearToOutputTexel( gl_FragColor );\n";
  7063. 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";
  7064. 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, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\tsampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n\t\tsampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\tvec3 reflectView = flipNormal * 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";
  7065. 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";
  7066. 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";
  7067. 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";
  7068. var fog_vertex = "\n#ifdef USE_FOG\nfogDepth = -mvPosition.z;\n#endif";
  7069. var fog_pars_vertex = "#ifdef USE_FOG\n varying float fogDepth;\n#endif\n";
  7070. 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";
  7071. 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";
  7072. 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";
  7073. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n";
  7074. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7075. 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";
  7076. 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};\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 = saturate( reflectVec.y * 0.5 + 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";
  7077. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n";
  7078. 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};\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_BlinnPhong( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 matDiffColor = material.diffuseColor;\n\t\tvec3 matSpecColor = material.specularColor;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = BlinnExponentToGGXRoughness( material.specularShininess );\n\t\tvec3 spec = Rect_Area_Light_Specular_Reflectance(\n\t\t\t\tgeometry,\n\t\t\t\trectAreaLight.position, rectAreaLight.halfWidth, rectAreaLight.halfHeight,\n\t\t\t\troughness,\n\t\t\t\tltcMat, ltcMag );\n\t\tvec3 diff = Rect_Area_Light_Diffuse_Reflectance(\n\t\t\t\tgeometry,\n\t\t\t\trectAreaLight.position, rectAreaLight.halfWidth, rectAreaLight.halfHeight );\n\t\treflectedLight.directSpecular += lightColor * matSpecColor * spec / PI2;\n\t\treflectedLight.directDiffuse += lightColor * matDiffColor * diff / PI2;\n\t}\n#endif\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_Direct_RectArea\t\tRE_Direct_RectArea_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)\n";
  7079. 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";
  7080. 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 matDiffColor = material.diffuseColor;\n\t\tvec3 matSpecColor = material.specularColor;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 spec = Rect_Area_Light_Specular_Reflectance(\n\t\t\t\tgeometry,\n\t\t\t\trectAreaLight.position, rectAreaLight.halfWidth, rectAreaLight.halfHeight,\n\t\t\t\troughness,\n\t\t\t\tltcMat, ltcMag );\n\t\tvec3 diff = Rect_Area_Light_Diffuse_Reflectance(\n\t\t\t\tgeometry,\n\t\t\t\trectAreaLight.position, rectAreaLight.halfWidth, rectAreaLight.halfHeight );\n\t\treflectedLight.directSpecular += lightColor * matSpecColor * spec;\n\t\treflectedLight.directDiffuse += lightColor * matDiffColor * diff;\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";
  7081. 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 ] ) : 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";
  7082. var logdepthbuf_fragment = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\tgl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n#endif";
  7083. 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";
  7084. 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";
  7085. 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";
  7086. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif\n";
  7087. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n";
  7088. 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";
  7089. var map_particle_pars_fragment = "#ifdef USE_MAP\n\tuniform vec4 offsetRepeat;\n\tuniform sampler2D map;\n#endif\n";
  7090. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.r;\n#endif\n";
  7091. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  7092. 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";
  7093. 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";
  7094. 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";
  7095. var normal_flip = "#ifdef DOUBLE_SIDED\n\tfloat flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n#else\n\tfloat flipNormal = 1.0;\n#endif\n";
  7096. 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 ) * flipNormal;\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";
  7097. 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 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\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";
  7098. 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";
  7099. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif\n";
  7100. var project_vertex = "#ifdef USE_SKINNING\n\tvec4 mvPosition = modelViewMatrix * skinned;\n#else\n\tvec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\n#endif\ngl_Position = projectionMatrix * mvPosition;\n";
  7101. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.r;\n#endif\n";
  7102. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  7103. 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\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\treturn (\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\treturn (\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\treturn texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn 1.0;\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 ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\tfloat dp = ( length( lightToPosition ) - shadowBias ) / 1000.0;\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";
  7104. 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";
  7105. 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";
  7106. 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 ] ) : 1.0;\n\t}\n\t#endif\n\t#endif\n\treturn shadow;\n}\n";
  7107. 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";
  7108. 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 boneTextureWidth;\n\t\tuniform int boneTextureHeight;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureWidth ) );\n\t\t\tfloat y = floor( j / float( boneTextureWidth ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureWidth );\n\t\t\tfloat dy = 1.0 / float( boneTextureHeight );\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";
  7109. 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\tskinned = bindMatrixInverse * skinned;\n#endif\n";
  7110. 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";
  7111. 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";
  7112. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  7113. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n";
  7114. 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";
  7115. 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";
  7116. 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";
  7117. 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";
  7118. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  7119. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif";
  7120. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif";
  7121. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( PHYSICAL ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\n\t#ifdef USE_SKINNING\n\t\tvec4 worldPosition = modelMatrix * skinned;\n\t#else\n\t\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n\t#endif\n#endif\n";
  7122. var cube_frag = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n\tgl_FragColor.a *= opacity;\n}\n";
  7123. 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";
  7124. 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";
  7125. 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#include <begin_vertex>\n\t#include <displacementmap_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n}\n";
  7126. var distanceRGBA_frag = "uniform vec3 lightPos;\nvarying vec4 vWorldPosition;\n#include <common>\n#include <packing>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tgl_FragColor = packDepthToRGBA( length( vWorldPosition.xyz - lightPos.xyz ) / 1000.0 );\n}\n";
  7127. var distanceRGBA_vert = "varying vec4 vWorldPosition;\n#include <common>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <skinbase_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition;\n}\n";
  7128. var equirect_frag = "uniform sampler2D tEquirect;\nuniform float tFlip;\nvarying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldPosition );\n\tvec2 sampleUV;\n\tsampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n}\n";
  7129. 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";
  7130. 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";
  7131. 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";
  7132. 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 <normal_flip>\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";
  7133. 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";
  7134. 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 <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 <normal_flip>\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";
  7135. 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";
  7136. 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 <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_flip>\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 <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  7137. 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 <displacementmap_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\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";
  7138. 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 <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 <specularmap_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_flip>\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 <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  7139. 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 <specularmap_pars_fragment>\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 <displacementmap_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\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n";
  7140. 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_flip>\n\t#include <normal_fragment>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}\n";
  7141. 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 <displacementmap_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_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";
  7142. 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";
  7143. 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";
  7144. var shadow_frag = "uniform 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( 0.0, 0.0, 0.0, opacity * ( 1.0 - getShadowMask() ) );\n}\n";
  7145. 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";
  7146. var ShaderChunk = {
  7147. alphamap_fragment: alphamap_fragment,
  7148. alphamap_pars_fragment: alphamap_pars_fragment,
  7149. alphatest_fragment: alphatest_fragment,
  7150. aomap_fragment: aomap_fragment,
  7151. aomap_pars_fragment: aomap_pars_fragment,
  7152. begin_vertex: begin_vertex,
  7153. beginnormal_vertex: beginnormal_vertex,
  7154. bsdfs: bsdfs,
  7155. bumpmap_pars_fragment: bumpmap_pars_fragment,
  7156. clipping_planes_fragment: clipping_planes_fragment,
  7157. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  7158. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  7159. clipping_planes_vertex: clipping_planes_vertex,
  7160. color_fragment: color_fragment,
  7161. color_pars_fragment: color_pars_fragment,
  7162. color_pars_vertex: color_pars_vertex,
  7163. color_vertex: color_vertex,
  7164. common: common,
  7165. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  7166. defaultnormal_vertex: defaultnormal_vertex,
  7167. displacementmap_pars_vertex: displacementmap_pars_vertex,
  7168. displacementmap_vertex: displacementmap_vertex,
  7169. emissivemap_fragment: emissivemap_fragment,
  7170. emissivemap_pars_fragment: emissivemap_pars_fragment,
  7171. encodings_fragment: encodings_fragment,
  7172. encodings_pars_fragment: encodings_pars_fragment,
  7173. envmap_fragment: envmap_fragment,
  7174. envmap_pars_fragment: envmap_pars_fragment,
  7175. envmap_pars_vertex: envmap_pars_vertex,
  7176. envmap_vertex: envmap_vertex,
  7177. fog_vertex: fog_vertex,
  7178. fog_pars_vertex: fog_pars_vertex,
  7179. fog_fragment: fog_fragment,
  7180. fog_pars_fragment: fog_pars_fragment,
  7181. gradientmap_pars_fragment: gradientmap_pars_fragment,
  7182. lightmap_fragment: lightmap_fragment,
  7183. lightmap_pars_fragment: lightmap_pars_fragment,
  7184. lights_lambert_vertex: lights_lambert_vertex,
  7185. lights_pars: lights_pars,
  7186. lights_phong_fragment: lights_phong_fragment,
  7187. lights_phong_pars_fragment: lights_phong_pars_fragment,
  7188. lights_physical_fragment: lights_physical_fragment,
  7189. lights_physical_pars_fragment: lights_physical_pars_fragment,
  7190. lights_template: lights_template,
  7191. logdepthbuf_fragment: logdepthbuf_fragment,
  7192. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  7193. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  7194. logdepthbuf_vertex: logdepthbuf_vertex,
  7195. map_fragment: map_fragment,
  7196. map_pars_fragment: map_pars_fragment,
  7197. map_particle_fragment: map_particle_fragment,
  7198. map_particle_pars_fragment: map_particle_pars_fragment,
  7199. metalnessmap_fragment: metalnessmap_fragment,
  7200. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  7201. morphnormal_vertex: morphnormal_vertex,
  7202. morphtarget_pars_vertex: morphtarget_pars_vertex,
  7203. morphtarget_vertex: morphtarget_vertex,
  7204. normal_flip: normal_flip,
  7205. normal_fragment: normal_fragment,
  7206. normalmap_pars_fragment: normalmap_pars_fragment,
  7207. packing: packing,
  7208. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  7209. project_vertex: project_vertex,
  7210. roughnessmap_fragment: roughnessmap_fragment,
  7211. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  7212. shadowmap_pars_fragment: shadowmap_pars_fragment,
  7213. shadowmap_pars_vertex: shadowmap_pars_vertex,
  7214. shadowmap_vertex: shadowmap_vertex,
  7215. shadowmask_pars_fragment: shadowmask_pars_fragment,
  7216. skinbase_vertex: skinbase_vertex,
  7217. skinning_pars_vertex: skinning_pars_vertex,
  7218. skinning_vertex: skinning_vertex,
  7219. skinnormal_vertex: skinnormal_vertex,
  7220. specularmap_fragment: specularmap_fragment,
  7221. specularmap_pars_fragment: specularmap_pars_fragment,
  7222. tonemapping_fragment: tonemapping_fragment,
  7223. tonemapping_pars_fragment: tonemapping_pars_fragment,
  7224. uv_pars_fragment: uv_pars_fragment,
  7225. uv_pars_vertex: uv_pars_vertex,
  7226. uv_vertex: uv_vertex,
  7227. uv2_pars_fragment: uv2_pars_fragment,
  7228. uv2_pars_vertex: uv2_pars_vertex,
  7229. uv2_vertex: uv2_vertex,
  7230. worldpos_vertex: worldpos_vertex,
  7231. cube_frag: cube_frag,
  7232. cube_vert: cube_vert,
  7233. depth_frag: depth_frag,
  7234. depth_vert: depth_vert,
  7235. distanceRGBA_frag: distanceRGBA_frag,
  7236. distanceRGBA_vert: distanceRGBA_vert,
  7237. equirect_frag: equirect_frag,
  7238. equirect_vert: equirect_vert,
  7239. linedashed_frag: linedashed_frag,
  7240. linedashed_vert: linedashed_vert,
  7241. meshbasic_frag: meshbasic_frag,
  7242. meshbasic_vert: meshbasic_vert,
  7243. meshlambert_frag: meshlambert_frag,
  7244. meshlambert_vert: meshlambert_vert,
  7245. meshphong_frag: meshphong_frag,
  7246. meshphong_vert: meshphong_vert,
  7247. meshphysical_frag: meshphysical_frag,
  7248. meshphysical_vert: meshphysical_vert,
  7249. normal_frag: normal_frag,
  7250. normal_vert: normal_vert,
  7251. points_frag: points_frag,
  7252. points_vert: points_vert,
  7253. shadow_frag: shadow_frag,
  7254. shadow_vert: shadow_vert
  7255. };
  7256. /**
  7257. * @author mrdoob / http://mrdoob.com/
  7258. */
  7259. function Color( r, g, b ) {
  7260. if ( g === undefined && b === undefined ) {
  7261. // r is THREE.Color, hex or string
  7262. return this.set( r );
  7263. }
  7264. return this.setRGB( r, g, b );
  7265. }
  7266. Color.prototype = {
  7267. constructor: Color,
  7268. isColor: true,
  7269. r: 1, g: 1, b: 1,
  7270. set: function ( value ) {
  7271. if ( value && value.isColor ) {
  7272. this.copy( value );
  7273. } else if ( typeof value === 'number' ) {
  7274. this.setHex( value );
  7275. } else if ( typeof value === 'string' ) {
  7276. this.setStyle( value );
  7277. }
  7278. return this;
  7279. },
  7280. setScalar: function ( scalar ) {
  7281. this.r = scalar;
  7282. this.g = scalar;
  7283. this.b = scalar;
  7284. return this;
  7285. },
  7286. setHex: function ( hex ) {
  7287. hex = Math.floor( hex );
  7288. this.r = ( hex >> 16 & 255 ) / 255;
  7289. this.g = ( hex >> 8 & 255 ) / 255;
  7290. this.b = ( hex & 255 ) / 255;
  7291. return this;
  7292. },
  7293. setRGB: function ( r, g, b ) {
  7294. this.r = r;
  7295. this.g = g;
  7296. this.b = b;
  7297. return this;
  7298. },
  7299. setHSL: function () {
  7300. function hue2rgb( p, q, t ) {
  7301. if ( t < 0 ) t += 1;
  7302. if ( t > 1 ) t -= 1;
  7303. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  7304. if ( t < 1 / 2 ) return q;
  7305. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  7306. return p;
  7307. }
  7308. return function setHSL( h, s, l ) {
  7309. // h,s,l ranges are in 0.0 - 1.0
  7310. h = _Math.euclideanModulo( h, 1 );
  7311. s = _Math.clamp( s, 0, 1 );
  7312. l = _Math.clamp( l, 0, 1 );
  7313. if ( s === 0 ) {
  7314. this.r = this.g = this.b = l;
  7315. } else {
  7316. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  7317. var q = ( 2 * l ) - p;
  7318. this.r = hue2rgb( q, p, h + 1 / 3 );
  7319. this.g = hue2rgb( q, p, h );
  7320. this.b = hue2rgb( q, p, h - 1 / 3 );
  7321. }
  7322. return this;
  7323. };
  7324. }(),
  7325. setStyle: function ( style ) {
  7326. function handleAlpha( string ) {
  7327. if ( string === undefined ) return;
  7328. if ( parseFloat( string ) < 1 ) {
  7329. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  7330. }
  7331. }
  7332. var m;
  7333. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  7334. // rgb / hsl
  7335. var color;
  7336. var name = m[ 1 ];
  7337. var components = m[ 2 ];
  7338. switch ( name ) {
  7339. case 'rgb':
  7340. case 'rgba':
  7341. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  7342. // rgb(255,0,0) rgba(255,0,0,0.5)
  7343. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  7344. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  7345. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  7346. handleAlpha( color[ 5 ] );
  7347. return this;
  7348. }
  7349. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  7350. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  7351. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  7352. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  7353. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  7354. handleAlpha( color[ 5 ] );
  7355. return this;
  7356. }
  7357. break;
  7358. case 'hsl':
  7359. case 'hsla':
  7360. if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  7361. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  7362. var h = parseFloat( color[ 1 ] ) / 360;
  7363. var s = parseInt( color[ 2 ], 10 ) / 100;
  7364. var l = parseInt( color[ 3 ], 10 ) / 100;
  7365. handleAlpha( color[ 5 ] );
  7366. return this.setHSL( h, s, l );
  7367. }
  7368. break;
  7369. }
  7370. } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {
  7371. // hex color
  7372. var hex = m[ 1 ];
  7373. var size = hex.length;
  7374. if ( size === 3 ) {
  7375. // #ff0
  7376. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  7377. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  7378. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  7379. return this;
  7380. } else if ( size === 6 ) {
  7381. // #ff0000
  7382. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  7383. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  7384. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  7385. return this;
  7386. }
  7387. }
  7388. if ( style && style.length > 0 ) {
  7389. // color keywords
  7390. var hex = ColorKeywords[ style ];
  7391. if ( hex !== undefined ) {
  7392. // red
  7393. this.setHex( hex );
  7394. } else {
  7395. // unknown color
  7396. console.warn( 'THREE.Color: Unknown color ' + style );
  7397. }
  7398. }
  7399. return this;
  7400. },
  7401. clone: function () {
  7402. return new this.constructor( this.r, this.g, this.b );
  7403. },
  7404. copy: function ( color ) {
  7405. this.r = color.r;
  7406. this.g = color.g;
  7407. this.b = color.b;
  7408. return this;
  7409. },
  7410. copyGammaToLinear: function ( color, gammaFactor ) {
  7411. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  7412. this.r = Math.pow( color.r, gammaFactor );
  7413. this.g = Math.pow( color.g, gammaFactor );
  7414. this.b = Math.pow( color.b, gammaFactor );
  7415. return this;
  7416. },
  7417. copyLinearToGamma: function ( color, gammaFactor ) {
  7418. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  7419. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  7420. this.r = Math.pow( color.r, safeInverse );
  7421. this.g = Math.pow( color.g, safeInverse );
  7422. this.b = Math.pow( color.b, safeInverse );
  7423. return this;
  7424. },
  7425. convertGammaToLinear: function () {
  7426. var r = this.r, g = this.g, b = this.b;
  7427. this.r = r * r;
  7428. this.g = g * g;
  7429. this.b = b * b;
  7430. return this;
  7431. },
  7432. convertLinearToGamma: function () {
  7433. this.r = Math.sqrt( this.r );
  7434. this.g = Math.sqrt( this.g );
  7435. this.b = Math.sqrt( this.b );
  7436. return this;
  7437. },
  7438. getHex: function () {
  7439. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  7440. },
  7441. getHexString: function () {
  7442. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  7443. },
  7444. getHSL: function ( optionalTarget ) {
  7445. // h,s,l ranges are in 0.0 - 1.0
  7446. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  7447. var r = this.r, g = this.g, b = this.b;
  7448. var max = Math.max( r, g, b );
  7449. var min = Math.min( r, g, b );
  7450. var hue, saturation;
  7451. var lightness = ( min + max ) / 2.0;
  7452. if ( min === max ) {
  7453. hue = 0;
  7454. saturation = 0;
  7455. } else {
  7456. var delta = max - min;
  7457. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  7458. switch ( max ) {
  7459. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  7460. case g: hue = ( b - r ) / delta + 2; break;
  7461. case b: hue = ( r - g ) / delta + 4; break;
  7462. }
  7463. hue /= 6;
  7464. }
  7465. hsl.h = hue;
  7466. hsl.s = saturation;
  7467. hsl.l = lightness;
  7468. return hsl;
  7469. },
  7470. getStyle: function () {
  7471. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  7472. },
  7473. offsetHSL: function ( h, s, l ) {
  7474. var hsl = this.getHSL();
  7475. hsl.h += h; hsl.s += s; hsl.l += l;
  7476. this.setHSL( hsl.h, hsl.s, hsl.l );
  7477. return this;
  7478. },
  7479. add: function ( color ) {
  7480. this.r += color.r;
  7481. this.g += color.g;
  7482. this.b += color.b;
  7483. return this;
  7484. },
  7485. addColors: function ( color1, color2 ) {
  7486. this.r = color1.r + color2.r;
  7487. this.g = color1.g + color2.g;
  7488. this.b = color1.b + color2.b;
  7489. return this;
  7490. },
  7491. addScalar: function ( s ) {
  7492. this.r += s;
  7493. this.g += s;
  7494. this.b += s;
  7495. return this;
  7496. },
  7497. sub: function( color ) {
  7498. this.r = Math.max( 0, this.r - color.r );
  7499. this.g = Math.max( 0, this.g - color.g );
  7500. this.b = Math.max( 0, this.b - color.b );
  7501. return this;
  7502. },
  7503. multiply: function ( color ) {
  7504. this.r *= color.r;
  7505. this.g *= color.g;
  7506. this.b *= color.b;
  7507. return this;
  7508. },
  7509. multiplyScalar: function ( s ) {
  7510. this.r *= s;
  7511. this.g *= s;
  7512. this.b *= s;
  7513. return this;
  7514. },
  7515. lerp: function ( color, alpha ) {
  7516. this.r += ( color.r - this.r ) * alpha;
  7517. this.g += ( color.g - this.g ) * alpha;
  7518. this.b += ( color.b - this.b ) * alpha;
  7519. return this;
  7520. },
  7521. equals: function ( c ) {
  7522. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  7523. },
  7524. fromArray: function ( array, offset ) {
  7525. if ( offset === undefined ) offset = 0;
  7526. this.r = array[ offset ];
  7527. this.g = array[ offset + 1 ];
  7528. this.b = array[ offset + 2 ];
  7529. return this;
  7530. },
  7531. toArray: function ( array, offset ) {
  7532. if ( array === undefined ) array = [];
  7533. if ( offset === undefined ) offset = 0;
  7534. array[ offset ] = this.r;
  7535. array[ offset + 1 ] = this.g;
  7536. array[ offset + 2 ] = this.b;
  7537. return array;
  7538. },
  7539. toJSON: function () {
  7540. return this.getHex();
  7541. }
  7542. };
  7543. var ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  7544. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  7545. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  7546. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  7547. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  7548. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  7549. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  7550. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  7551. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  7552. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  7553. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  7554. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  7555. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  7556. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  7557. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  7558. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  7559. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  7560. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  7561. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  7562. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  7563. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  7564. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  7565. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  7566. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  7567. /**
  7568. * @author alteredq / http://alteredqualia.com/
  7569. */
  7570. function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  7571. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  7572. this.image = { data: data, width: width, height: height };
  7573. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  7574. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  7575. this.generateMipmaps = false;
  7576. this.flipY = false;
  7577. this.unpackAlignment = 1;
  7578. }
  7579. DataTexture.prototype = Object.create( Texture.prototype );
  7580. DataTexture.prototype.constructor = DataTexture;
  7581. DataTexture.prototype.isDataTexture = true;
  7582. /**
  7583. * Uniforms library for shared webgl shaders
  7584. */
  7585. var UniformsLib = {
  7586. common: {
  7587. diffuse: { value: new Color( 0xeeeeee ) },
  7588. opacity: { value: 1.0 },
  7589. map: { value: null },
  7590. offsetRepeat: { value: new Vector4( 0, 0, 1, 1 ) },
  7591. specularMap: { value: null },
  7592. alphaMap: { value: null },
  7593. envMap: { value: null },
  7594. flipEnvMap: { value: - 1 },
  7595. reflectivity: { value: 1.0 },
  7596. refractionRatio: { value: 0.98 }
  7597. },
  7598. aomap: {
  7599. aoMap: { value: null },
  7600. aoMapIntensity: { value: 1 }
  7601. },
  7602. lightmap: {
  7603. lightMap: { value: null },
  7604. lightMapIntensity: { value: 1 }
  7605. },
  7606. emissivemap: {
  7607. emissiveMap: { value: null }
  7608. },
  7609. bumpmap: {
  7610. bumpMap: { value: null },
  7611. bumpScale: { value: 1 }
  7612. },
  7613. normalmap: {
  7614. normalMap: { value: null },
  7615. normalScale: { value: new Vector2( 1, 1 ) }
  7616. },
  7617. displacementmap: {
  7618. displacementMap: { value: null },
  7619. displacementScale: { value: 1 },
  7620. displacementBias: { value: 0 }
  7621. },
  7622. roughnessmap: {
  7623. roughnessMap: { value: null }
  7624. },
  7625. metalnessmap: {
  7626. metalnessMap: { value: null }
  7627. },
  7628. gradientmap: {
  7629. gradientMap: { value: null }
  7630. },
  7631. fog: {
  7632. fogDensity: { value: 0.00025 },
  7633. fogNear: { value: 1 },
  7634. fogFar: { value: 2000 },
  7635. fogColor: { value: new Color( 0xffffff ) }
  7636. },
  7637. lights: {
  7638. ambientLightColor: { value: [] },
  7639. directionalLights: { value: [], properties: {
  7640. direction: {},
  7641. color: {},
  7642. shadow: {},
  7643. shadowBias: {},
  7644. shadowRadius: {},
  7645. shadowMapSize: {}
  7646. } },
  7647. directionalShadowMap: { value: [] },
  7648. directionalShadowMatrix: { value: [] },
  7649. spotLights: { value: [], properties: {
  7650. color: {},
  7651. position: {},
  7652. direction: {},
  7653. distance: {},
  7654. coneCos: {},
  7655. penumbraCos: {},
  7656. decay: {},
  7657. shadow: {},
  7658. shadowBias: {},
  7659. shadowRadius: {},
  7660. shadowMapSize: {}
  7661. } },
  7662. spotShadowMap: { value: [] },
  7663. spotShadowMatrix: { value: [] },
  7664. pointLights: { value: [], properties: {
  7665. color: {},
  7666. position: {},
  7667. decay: {},
  7668. distance: {},
  7669. shadow: {},
  7670. shadowBias: {},
  7671. shadowRadius: {},
  7672. shadowMapSize: {}
  7673. } },
  7674. pointShadowMap: { value: [] },
  7675. pointShadowMatrix: { value: [] },
  7676. hemisphereLights: { value: [], properties: {
  7677. direction: {},
  7678. skyColor: {},
  7679. groundColor: {}
  7680. } },
  7681. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  7682. rectAreaLights: { value: [], properties: {
  7683. color: {},
  7684. position: {},
  7685. width: {},
  7686. height: {}
  7687. } }
  7688. },
  7689. points: {
  7690. diffuse: { value: new Color( 0xeeeeee ) },
  7691. opacity: { value: 1.0 },
  7692. size: { value: 1.0 },
  7693. scale: { value: 1.0 },
  7694. map: { value: null },
  7695. offsetRepeat: { value: new Vector4( 0, 0, 1, 1 ) }
  7696. }
  7697. };
  7698. /**
  7699. * @author alteredq / http://alteredqualia.com/
  7700. * @author mrdoob / http://mrdoob.com/
  7701. * @author mikael emtinger / http://gomo.se/
  7702. */
  7703. var ShaderLib = {
  7704. basic: {
  7705. uniforms: UniformsUtils.merge( [
  7706. UniformsLib.common,
  7707. UniformsLib.aomap,
  7708. UniformsLib.lightmap,
  7709. UniformsLib.fog
  7710. ] ),
  7711. vertexShader: ShaderChunk.meshbasic_vert,
  7712. fragmentShader: ShaderChunk.meshbasic_frag
  7713. },
  7714. lambert: {
  7715. uniforms: UniformsUtils.merge( [
  7716. UniformsLib.common,
  7717. UniformsLib.aomap,
  7718. UniformsLib.lightmap,
  7719. UniformsLib.emissivemap,
  7720. UniformsLib.fog,
  7721. UniformsLib.lights,
  7722. {
  7723. emissive: { value: new Color( 0x000000 ) }
  7724. }
  7725. ] ),
  7726. vertexShader: ShaderChunk.meshlambert_vert,
  7727. fragmentShader: ShaderChunk.meshlambert_frag
  7728. },
  7729. phong: {
  7730. uniforms: UniformsUtils.merge( [
  7731. UniformsLib.common,
  7732. UniformsLib.aomap,
  7733. UniformsLib.lightmap,
  7734. UniformsLib.emissivemap,
  7735. UniformsLib.bumpmap,
  7736. UniformsLib.normalmap,
  7737. UniformsLib.displacementmap,
  7738. UniformsLib.gradientmap,
  7739. UniformsLib.fog,
  7740. UniformsLib.lights,
  7741. {
  7742. emissive: { value: new Color( 0x000000 ) },
  7743. specular: { value: new Color( 0x111111 ) },
  7744. shininess: { value: 30 }
  7745. }
  7746. ] ),
  7747. vertexShader: ShaderChunk.meshphong_vert,
  7748. fragmentShader: ShaderChunk.meshphong_frag
  7749. },
  7750. standard: {
  7751. uniforms: UniformsUtils.merge( [
  7752. UniformsLib.common,
  7753. UniformsLib.aomap,
  7754. UniformsLib.lightmap,
  7755. UniformsLib.emissivemap,
  7756. UniformsLib.bumpmap,
  7757. UniformsLib.normalmap,
  7758. UniformsLib.displacementmap,
  7759. UniformsLib.roughnessmap,
  7760. UniformsLib.metalnessmap,
  7761. UniformsLib.fog,
  7762. UniformsLib.lights,
  7763. {
  7764. emissive: { value: new Color( 0x000000 ) },
  7765. roughness: { value: 0.5 },
  7766. metalness: { value: 0 },
  7767. envMapIntensity: { value: 1 } // temporary
  7768. }
  7769. ] ),
  7770. vertexShader: ShaderChunk.meshphysical_vert,
  7771. fragmentShader: ShaderChunk.meshphysical_frag
  7772. },
  7773. points: {
  7774. uniforms: UniformsUtils.merge( [
  7775. UniformsLib.points,
  7776. UniformsLib.fog
  7777. ] ),
  7778. vertexShader: ShaderChunk.points_vert,
  7779. fragmentShader: ShaderChunk.points_frag
  7780. },
  7781. dashed: {
  7782. uniforms: UniformsUtils.merge( [
  7783. UniformsLib.common,
  7784. UniformsLib.fog,
  7785. {
  7786. scale: { value: 1 },
  7787. dashSize: { value: 1 },
  7788. totalSize: { value: 2 }
  7789. }
  7790. ] ),
  7791. vertexShader: ShaderChunk.linedashed_vert,
  7792. fragmentShader: ShaderChunk.linedashed_frag
  7793. },
  7794. depth: {
  7795. uniforms: UniformsUtils.merge( [
  7796. UniformsLib.common,
  7797. UniformsLib.displacementmap
  7798. ] ),
  7799. vertexShader: ShaderChunk.depth_vert,
  7800. fragmentShader: ShaderChunk.depth_frag
  7801. },
  7802. normal: {
  7803. uniforms: UniformsUtils.merge( [
  7804. UniformsLib.common,
  7805. UniformsLib.bumpmap,
  7806. UniformsLib.normalmap,
  7807. UniformsLib.displacementmap,
  7808. {
  7809. opacity: { value: 1.0 }
  7810. }
  7811. ] ),
  7812. vertexShader: ShaderChunk.normal_vert,
  7813. fragmentShader: ShaderChunk.normal_frag
  7814. },
  7815. /* -------------------------------------------------------------------------
  7816. // Cube map shader
  7817. ------------------------------------------------------------------------- */
  7818. cube: {
  7819. uniforms: {
  7820. tCube: { value: null },
  7821. tFlip: { value: - 1 },
  7822. opacity: { value: 1.0 }
  7823. },
  7824. vertexShader: ShaderChunk.cube_vert,
  7825. fragmentShader: ShaderChunk.cube_frag
  7826. },
  7827. /* -------------------------------------------------------------------------
  7828. // Cube map shader
  7829. ------------------------------------------------------------------------- */
  7830. equirect: {
  7831. uniforms: {
  7832. tEquirect: { value: null },
  7833. tFlip: { value: - 1 }
  7834. },
  7835. vertexShader: ShaderChunk.equirect_vert,
  7836. fragmentShader: ShaderChunk.equirect_frag
  7837. },
  7838. distanceRGBA: {
  7839. uniforms: {
  7840. lightPos: { value: new Vector3() }
  7841. },
  7842. vertexShader: ShaderChunk.distanceRGBA_vert,
  7843. fragmentShader: ShaderChunk.distanceRGBA_frag
  7844. }
  7845. };
  7846. ShaderLib.physical = {
  7847. uniforms: UniformsUtils.merge( [
  7848. ShaderLib.standard.uniforms,
  7849. {
  7850. clearCoat: { value: 0 },
  7851. clearCoatRoughness: { value: 0 }
  7852. }
  7853. ] ),
  7854. vertexShader: ShaderChunk.meshphysical_vert,
  7855. fragmentShader: ShaderChunk.meshphysical_frag
  7856. };
  7857. /**
  7858. * @author bhouston / http://clara.io
  7859. */
  7860. function Box2( min, max ) {
  7861. this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity );
  7862. this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity );
  7863. }
  7864. Box2.prototype = {
  7865. constructor: Box2,
  7866. set: function ( min, max ) {
  7867. this.min.copy( min );
  7868. this.max.copy( max );
  7869. return this;
  7870. },
  7871. setFromPoints: function ( points ) {
  7872. this.makeEmpty();
  7873. for ( var i = 0, il = points.length; i < il; i ++ ) {
  7874. this.expandByPoint( points[ i ] );
  7875. }
  7876. return this;
  7877. },
  7878. setFromCenterAndSize: function () {
  7879. var v1 = new Vector2();
  7880. return function setFromCenterAndSize( center, size ) {
  7881. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  7882. this.min.copy( center ).sub( halfSize );
  7883. this.max.copy( center ).add( halfSize );
  7884. return this;
  7885. };
  7886. }(),
  7887. clone: function () {
  7888. return new this.constructor().copy( this );
  7889. },
  7890. copy: function ( box ) {
  7891. this.min.copy( box.min );
  7892. this.max.copy( box.max );
  7893. return this;
  7894. },
  7895. makeEmpty: function () {
  7896. this.min.x = this.min.y = + Infinity;
  7897. this.max.x = this.max.y = - Infinity;
  7898. return this;
  7899. },
  7900. isEmpty: function () {
  7901. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  7902. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  7903. },
  7904. getCenter: function ( optionalTarget ) {
  7905. var result = optionalTarget || new Vector2();
  7906. return this.isEmpty() ? result.set( 0, 0 ) : result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  7907. },
  7908. getSize: function ( optionalTarget ) {
  7909. var result = optionalTarget || new Vector2();
  7910. return this.isEmpty() ? result.set( 0, 0 ) : result.subVectors( this.max, this.min );
  7911. },
  7912. expandByPoint: function ( point ) {
  7913. this.min.min( point );
  7914. this.max.max( point );
  7915. return this;
  7916. },
  7917. expandByVector: function ( vector ) {
  7918. this.min.sub( vector );
  7919. this.max.add( vector );
  7920. return this;
  7921. },
  7922. expandByScalar: function ( scalar ) {
  7923. this.min.addScalar( - scalar );
  7924. this.max.addScalar( scalar );
  7925. return this;
  7926. },
  7927. containsPoint: function ( point ) {
  7928. return point.x < this.min.x || point.x > this.max.x ||
  7929. point.y < this.min.y || point.y > this.max.y ? false : true;
  7930. },
  7931. containsBox: function ( box ) {
  7932. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  7933. this.min.y <= box.min.y && box.max.y <= this.max.y;
  7934. },
  7935. getParameter: function ( point, optionalTarget ) {
  7936. // This can potentially have a divide by zero if the box
  7937. // has a size dimension of 0.
  7938. var result = optionalTarget || new Vector2();
  7939. return result.set(
  7940. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  7941. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  7942. );
  7943. },
  7944. intersectsBox: function ( box ) {
  7945. // using 6 splitting planes to rule out intersections.
  7946. return box.max.x < this.min.x || box.min.x > this.max.x ||
  7947. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  7948. },
  7949. clampPoint: function ( point, optionalTarget ) {
  7950. var result = optionalTarget || new Vector2();
  7951. return result.copy( point ).clamp( this.min, this.max );
  7952. },
  7953. distanceToPoint: function () {
  7954. var v1 = new Vector2();
  7955. return function distanceToPoint( point ) {
  7956. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  7957. return clampedPoint.sub( point ).length();
  7958. };
  7959. }(),
  7960. intersect: function ( box ) {
  7961. this.min.max( box.min );
  7962. this.max.min( box.max );
  7963. return this;
  7964. },
  7965. union: function ( box ) {
  7966. this.min.min( box.min );
  7967. this.max.max( box.max );
  7968. return this;
  7969. },
  7970. translate: function ( offset ) {
  7971. this.min.add( offset );
  7972. this.max.add( offset );
  7973. return this;
  7974. },
  7975. equals: function ( box ) {
  7976. return box.min.equals( this.min ) && box.max.equals( this.max );
  7977. }
  7978. };
  7979. /**
  7980. * @author mikael emtinger / http://gomo.se/
  7981. * @author alteredq / http://alteredqualia.com/
  7982. */
  7983. function LensFlarePlugin( renderer, flares ) {
  7984. var gl = renderer.context;
  7985. var state = renderer.state;
  7986. var vertexBuffer, elementBuffer;
  7987. var shader, program, attributes, uniforms;
  7988. var tempTexture, occlusionTexture;
  7989. function init() {
  7990. var vertices = new Float32Array( [
  7991. - 1, - 1, 0, 0,
  7992. 1, - 1, 1, 0,
  7993. 1, 1, 1, 1,
  7994. - 1, 1, 0, 1
  7995. ] );
  7996. var faces = new Uint16Array( [
  7997. 0, 1, 2,
  7998. 0, 2, 3
  7999. ] );
  8000. // buffers
  8001. vertexBuffer = gl.createBuffer();
  8002. elementBuffer = gl.createBuffer();
  8003. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  8004. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  8005. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  8006. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  8007. // textures
  8008. tempTexture = gl.createTexture();
  8009. occlusionTexture = gl.createTexture();
  8010. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  8011. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null );
  8012. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  8013. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  8014. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  8015. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  8016. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  8017. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null );
  8018. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  8019. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  8020. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  8021. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  8022. shader = {
  8023. vertexShader: [
  8024. "uniform lowp int renderType;",
  8025. "uniform vec3 screenPosition;",
  8026. "uniform vec2 scale;",
  8027. "uniform float rotation;",
  8028. "uniform sampler2D occlusionMap;",
  8029. "attribute vec2 position;",
  8030. "attribute vec2 uv;",
  8031. "varying vec2 vUV;",
  8032. "varying float vVisibility;",
  8033. "void main() {",
  8034. "vUV = uv;",
  8035. "vec2 pos = position;",
  8036. "if ( renderType == 2 ) {",
  8037. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  8038. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  8039. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  8040. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  8041. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  8042. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  8043. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  8044. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  8045. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  8046. "vVisibility = visibility.r / 9.0;",
  8047. "vVisibility *= 1.0 - visibility.g / 9.0;",
  8048. "vVisibility *= visibility.b / 9.0;",
  8049. "vVisibility *= 1.0 - visibility.a / 9.0;",
  8050. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  8051. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  8052. "}",
  8053. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  8054. "}"
  8055. ].join( "\n" ),
  8056. fragmentShader: [
  8057. "uniform lowp int renderType;",
  8058. "uniform sampler2D map;",
  8059. "uniform float opacity;",
  8060. "uniform vec3 color;",
  8061. "varying vec2 vUV;",
  8062. "varying float vVisibility;",
  8063. "void main() {",
  8064. // pink square
  8065. "if ( renderType == 0 ) {",
  8066. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  8067. // restore
  8068. "} else if ( renderType == 1 ) {",
  8069. "gl_FragColor = texture2D( map, vUV );",
  8070. // flare
  8071. "} else {",
  8072. "vec4 texture = texture2D( map, vUV );",
  8073. "texture.a *= opacity * vVisibility;",
  8074. "gl_FragColor = texture;",
  8075. "gl_FragColor.rgb *= color;",
  8076. "}",
  8077. "}"
  8078. ].join( "\n" )
  8079. };
  8080. program = createProgram( shader );
  8081. attributes = {
  8082. vertex: gl.getAttribLocation ( program, "position" ),
  8083. uv: gl.getAttribLocation ( program, "uv" )
  8084. };
  8085. uniforms = {
  8086. renderType: gl.getUniformLocation( program, "renderType" ),
  8087. map: gl.getUniformLocation( program, "map" ),
  8088. occlusionMap: gl.getUniformLocation( program, "occlusionMap" ),
  8089. opacity: gl.getUniformLocation( program, "opacity" ),
  8090. color: gl.getUniformLocation( program, "color" ),
  8091. scale: gl.getUniformLocation( program, "scale" ),
  8092. rotation: gl.getUniformLocation( program, "rotation" ),
  8093. screenPosition: gl.getUniformLocation( program, "screenPosition" )
  8094. };
  8095. }
  8096. /*
  8097. * Render lens flares
  8098. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  8099. * reads these back and calculates occlusion.
  8100. */
  8101. this.render = function ( scene, camera, viewport ) {
  8102. if ( flares.length === 0 ) return;
  8103. var tempPosition = new Vector3();
  8104. var invAspect = viewport.w / viewport.z,
  8105. halfViewportWidth = viewport.z * 0.5,
  8106. halfViewportHeight = viewport.w * 0.5;
  8107. var size = 16 / viewport.w,
  8108. scale = new Vector2( size * invAspect, size );
  8109. var screenPosition = new Vector3( 1, 1, 0 ),
  8110. screenPositionPixels = new Vector2( 1, 1 );
  8111. var validArea = new Box2();
  8112. validArea.min.set( viewport.x, viewport.y );
  8113. validArea.max.set( viewport.x + ( viewport.z - 16 ), viewport.y + ( viewport.w - 16 ) );
  8114. if ( program === undefined ) {
  8115. init();
  8116. }
  8117. gl.useProgram( program );
  8118. state.initAttributes();
  8119. state.enableAttribute( attributes.vertex );
  8120. state.enableAttribute( attributes.uv );
  8121. state.disableUnusedAttributes();
  8122. // loop through all lens flares to update their occlusion and positions
  8123. // setup gl and common used attribs/uniforms
  8124. gl.uniform1i( uniforms.occlusionMap, 0 );
  8125. gl.uniform1i( uniforms.map, 1 );
  8126. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  8127. gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 );
  8128. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  8129. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  8130. state.disable( gl.CULL_FACE );
  8131. state.setDepthWrite( false );
  8132. for ( var i = 0, l = flares.length; i < l; i ++ ) {
  8133. size = 16 / viewport.w;
  8134. scale.set( size * invAspect, size );
  8135. // calc object screen position
  8136. var flare = flares[ i ];
  8137. tempPosition.set( flare.matrixWorld.elements[ 12 ], flare.matrixWorld.elements[ 13 ], flare.matrixWorld.elements[ 14 ] );
  8138. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  8139. tempPosition.applyMatrix4( camera.projectionMatrix );
  8140. // setup arrays for gl programs
  8141. screenPosition.copy( tempPosition );
  8142. // horizontal and vertical coordinate of the lower left corner of the pixels to copy
  8143. screenPositionPixels.x = viewport.x + ( screenPosition.x * halfViewportWidth ) + halfViewportWidth - 8;
  8144. screenPositionPixels.y = viewport.y + ( screenPosition.y * halfViewportHeight ) + halfViewportHeight - 8;
  8145. // screen cull
  8146. if ( validArea.containsPoint( screenPositionPixels ) === true ) {
  8147. // save current RGB to temp texture
  8148. state.activeTexture( gl.TEXTURE0 );
  8149. state.bindTexture( gl.TEXTURE_2D, null );
  8150. state.activeTexture( gl.TEXTURE1 );
  8151. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  8152. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  8153. // render pink quad
  8154. gl.uniform1i( uniforms.renderType, 0 );
  8155. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  8156. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  8157. state.disable( gl.BLEND );
  8158. state.enable( gl.DEPTH_TEST );
  8159. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  8160. // copy result to occlusionMap
  8161. state.activeTexture( gl.TEXTURE0 );
  8162. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  8163. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  8164. // restore graphics
  8165. gl.uniform1i( uniforms.renderType, 1 );
  8166. state.disable( gl.DEPTH_TEST );
  8167. state.activeTexture( gl.TEXTURE1 );
  8168. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  8169. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  8170. // update object positions
  8171. flare.positionScreen.copy( screenPosition );
  8172. if ( flare.customUpdateCallback ) {
  8173. flare.customUpdateCallback( flare );
  8174. } else {
  8175. flare.updateLensFlares();
  8176. }
  8177. // render flares
  8178. gl.uniform1i( uniforms.renderType, 2 );
  8179. state.enable( gl.BLEND );
  8180. for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  8181. var sprite = flare.lensFlares[ j ];
  8182. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  8183. screenPosition.x = sprite.x;
  8184. screenPosition.y = sprite.y;
  8185. screenPosition.z = sprite.z;
  8186. size = sprite.size * sprite.scale / viewport.w;
  8187. scale.x = size * invAspect;
  8188. scale.y = size;
  8189. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  8190. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  8191. gl.uniform1f( uniforms.rotation, sprite.rotation );
  8192. gl.uniform1f( uniforms.opacity, sprite.opacity );
  8193. gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  8194. state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  8195. renderer.setTexture2D( sprite.texture, 1 );
  8196. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  8197. }
  8198. }
  8199. }
  8200. }
  8201. // restore gl
  8202. state.enable( gl.CULL_FACE );
  8203. state.enable( gl.DEPTH_TEST );
  8204. state.setDepthWrite( true );
  8205. renderer.resetGLState();
  8206. };
  8207. function createProgram( shader ) {
  8208. var program = gl.createProgram();
  8209. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  8210. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  8211. var prefix = "precision " + renderer.getPrecision() + " float;\n";
  8212. gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  8213. gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  8214. gl.compileShader( fragmentShader );
  8215. gl.compileShader( vertexShader );
  8216. gl.attachShader( program, fragmentShader );
  8217. gl.attachShader( program, vertexShader );
  8218. gl.linkProgram( program );
  8219. return program;
  8220. }
  8221. }
  8222. /**
  8223. * @author mikael emtinger / http://gomo.se/
  8224. * @author alteredq / http://alteredqualia.com/
  8225. */
  8226. function SpritePlugin( renderer, sprites ) {
  8227. var gl = renderer.context;
  8228. var state = renderer.state;
  8229. var vertexBuffer, elementBuffer;
  8230. var program, attributes, uniforms;
  8231. var texture;
  8232. // decompose matrixWorld
  8233. var spritePosition = new Vector3();
  8234. var spriteRotation = new Quaternion();
  8235. var spriteScale = new Vector3();
  8236. function init() {
  8237. var vertices = new Float32Array( [
  8238. - 0.5, - 0.5, 0, 0,
  8239. 0.5, - 0.5, 1, 0,
  8240. 0.5, 0.5, 1, 1,
  8241. - 0.5, 0.5, 0, 1
  8242. ] );
  8243. var faces = new Uint16Array( [
  8244. 0, 1, 2,
  8245. 0, 2, 3
  8246. ] );
  8247. vertexBuffer = gl.createBuffer();
  8248. elementBuffer = gl.createBuffer();
  8249. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  8250. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  8251. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  8252. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  8253. program = createProgram();
  8254. attributes = {
  8255. position: gl.getAttribLocation ( program, 'position' ),
  8256. uv: gl.getAttribLocation ( program, 'uv' )
  8257. };
  8258. uniforms = {
  8259. uvOffset: gl.getUniformLocation( program, 'uvOffset' ),
  8260. uvScale: gl.getUniformLocation( program, 'uvScale' ),
  8261. rotation: gl.getUniformLocation( program, 'rotation' ),
  8262. scale: gl.getUniformLocation( program, 'scale' ),
  8263. color: gl.getUniformLocation( program, 'color' ),
  8264. map: gl.getUniformLocation( program, 'map' ),
  8265. opacity: gl.getUniformLocation( program, 'opacity' ),
  8266. modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ),
  8267. projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ),
  8268. fogType: gl.getUniformLocation( program, 'fogType' ),
  8269. fogDensity: gl.getUniformLocation( program, 'fogDensity' ),
  8270. fogNear: gl.getUniformLocation( program, 'fogNear' ),
  8271. fogFar: gl.getUniformLocation( program, 'fogFar' ),
  8272. fogColor: gl.getUniformLocation( program, 'fogColor' ),
  8273. alphaTest: gl.getUniformLocation( program, 'alphaTest' )
  8274. };
  8275. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  8276. canvas.width = 8;
  8277. canvas.height = 8;
  8278. var context = canvas.getContext( '2d' );
  8279. context.fillStyle = 'white';
  8280. context.fillRect( 0, 0, 8, 8 );
  8281. texture = new Texture( canvas );
  8282. texture.needsUpdate = true;
  8283. }
  8284. this.render = function ( scene, camera ) {
  8285. if ( sprites.length === 0 ) return;
  8286. // setup gl
  8287. if ( program === undefined ) {
  8288. init();
  8289. }
  8290. gl.useProgram( program );
  8291. state.initAttributes();
  8292. state.enableAttribute( attributes.position );
  8293. state.enableAttribute( attributes.uv );
  8294. state.disableUnusedAttributes();
  8295. state.disable( gl.CULL_FACE );
  8296. state.enable( gl.BLEND );
  8297. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  8298. gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 );
  8299. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  8300. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  8301. gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  8302. state.activeTexture( gl.TEXTURE0 );
  8303. gl.uniform1i( uniforms.map, 0 );
  8304. var oldFogType = 0;
  8305. var sceneFogType = 0;
  8306. var fog = scene.fog;
  8307. if ( fog ) {
  8308. gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  8309. if ( fog.isFog ) {
  8310. gl.uniform1f( uniforms.fogNear, fog.near );
  8311. gl.uniform1f( uniforms.fogFar, fog.far );
  8312. gl.uniform1i( uniforms.fogType, 1 );
  8313. oldFogType = 1;
  8314. sceneFogType = 1;
  8315. } else if ( fog.isFogExp2 ) {
  8316. gl.uniform1f( uniforms.fogDensity, fog.density );
  8317. gl.uniform1i( uniforms.fogType, 2 );
  8318. oldFogType = 2;
  8319. sceneFogType = 2;
  8320. }
  8321. } else {
  8322. gl.uniform1i( uniforms.fogType, 0 );
  8323. oldFogType = 0;
  8324. sceneFogType = 0;
  8325. }
  8326. // update positions and sort
  8327. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  8328. var sprite = sprites[ i ];
  8329. sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  8330. sprite.z = - sprite.modelViewMatrix.elements[ 14 ];
  8331. }
  8332. sprites.sort( painterSortStable );
  8333. // render all sprites
  8334. var scale = [];
  8335. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  8336. var sprite = sprites[ i ];
  8337. var material = sprite.material;
  8338. if ( material.visible === false ) continue;
  8339. gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  8340. gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements );
  8341. sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale );
  8342. scale[ 0 ] = spriteScale.x;
  8343. scale[ 1 ] = spriteScale.y;
  8344. var fogType = 0;
  8345. if ( scene.fog && material.fog ) {
  8346. fogType = sceneFogType;
  8347. }
  8348. if ( oldFogType !== fogType ) {
  8349. gl.uniform1i( uniforms.fogType, fogType );
  8350. oldFogType = fogType;
  8351. }
  8352. if ( material.map !== null ) {
  8353. gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  8354. gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  8355. } else {
  8356. gl.uniform2f( uniforms.uvOffset, 0, 0 );
  8357. gl.uniform2f( uniforms.uvScale, 1, 1 );
  8358. }
  8359. gl.uniform1f( uniforms.opacity, material.opacity );
  8360. gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  8361. gl.uniform1f( uniforms.rotation, material.rotation );
  8362. gl.uniform2fv( uniforms.scale, scale );
  8363. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  8364. state.setDepthTest( material.depthTest );
  8365. state.setDepthWrite( material.depthWrite );
  8366. if ( material.map ) {
  8367. renderer.setTexture2D( material.map, 0 );
  8368. } else {
  8369. renderer.setTexture2D( texture, 0 );
  8370. }
  8371. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  8372. }
  8373. // restore gl
  8374. state.enable( gl.CULL_FACE );
  8375. renderer.resetGLState();
  8376. };
  8377. function createProgram() {
  8378. var program = gl.createProgram();
  8379. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  8380. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  8381. gl.shaderSource( vertexShader, [
  8382. 'precision ' + renderer.getPrecision() + ' float;',
  8383. 'uniform mat4 modelViewMatrix;',
  8384. 'uniform mat4 projectionMatrix;',
  8385. 'uniform float rotation;',
  8386. 'uniform vec2 scale;',
  8387. 'uniform vec2 uvOffset;',
  8388. 'uniform vec2 uvScale;',
  8389. 'attribute vec2 position;',
  8390. 'attribute vec2 uv;',
  8391. 'varying vec2 vUV;',
  8392. 'void main() {',
  8393. 'vUV = uvOffset + uv * uvScale;',
  8394. 'vec2 alignedPosition = position * scale;',
  8395. 'vec2 rotatedPosition;',
  8396. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  8397. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  8398. 'vec4 finalPosition;',
  8399. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  8400. 'finalPosition.xy += rotatedPosition;',
  8401. 'finalPosition = projectionMatrix * finalPosition;',
  8402. 'gl_Position = finalPosition;',
  8403. '}'
  8404. ].join( '\n' ) );
  8405. gl.shaderSource( fragmentShader, [
  8406. 'precision ' + renderer.getPrecision() + ' float;',
  8407. 'uniform vec3 color;',
  8408. 'uniform sampler2D map;',
  8409. 'uniform float opacity;',
  8410. 'uniform int fogType;',
  8411. 'uniform vec3 fogColor;',
  8412. 'uniform float fogDensity;',
  8413. 'uniform float fogNear;',
  8414. 'uniform float fogFar;',
  8415. 'uniform float alphaTest;',
  8416. 'varying vec2 vUV;',
  8417. 'void main() {',
  8418. 'vec4 texture = texture2D( map, vUV );',
  8419. 'if ( texture.a < alphaTest ) discard;',
  8420. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  8421. 'if ( fogType > 0 ) {',
  8422. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  8423. 'float fogFactor = 0.0;',
  8424. 'if ( fogType == 1 ) {',
  8425. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  8426. '} else {',
  8427. 'const float LOG2 = 1.442695;',
  8428. 'fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  8429. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  8430. '}',
  8431. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  8432. '}',
  8433. '}'
  8434. ].join( '\n' ) );
  8435. gl.compileShader( vertexShader );
  8436. gl.compileShader( fragmentShader );
  8437. gl.attachShader( program, vertexShader );
  8438. gl.attachShader( program, fragmentShader );
  8439. gl.linkProgram( program );
  8440. return program;
  8441. }
  8442. function painterSortStable( a, b ) {
  8443. if ( a.renderOrder !== b.renderOrder ) {
  8444. return a.renderOrder - b.renderOrder;
  8445. } else if ( a.z !== b.z ) {
  8446. return b.z - a.z;
  8447. } else {
  8448. return b.id - a.id;
  8449. }
  8450. }
  8451. }
  8452. /**
  8453. * @author mrdoob / http://mrdoob.com/
  8454. * @author alteredq / http://alteredqualia.com/
  8455. */
  8456. var materialId = 0;
  8457. function Material() {
  8458. Object.defineProperty( this, 'id', { value: materialId ++ } );
  8459. this.uuid = _Math.generateUUID();
  8460. this.name = '';
  8461. this.type = 'Material';
  8462. this.fog = true;
  8463. this.lights = true;
  8464. this.blending = NormalBlending;
  8465. this.side = FrontSide;
  8466. this.shading = SmoothShading; // THREE.FlatShading, THREE.SmoothShading
  8467. this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors
  8468. this.opacity = 1;
  8469. this.transparent = false;
  8470. this.blendSrc = SrcAlphaFactor;
  8471. this.blendDst = OneMinusSrcAlphaFactor;
  8472. this.blendEquation = AddEquation;
  8473. this.blendSrcAlpha = null;
  8474. this.blendDstAlpha = null;
  8475. this.blendEquationAlpha = null;
  8476. this.depthFunc = LessEqualDepth;
  8477. this.depthTest = true;
  8478. this.depthWrite = true;
  8479. this.clippingPlanes = null;
  8480. this.clipIntersection = false;
  8481. this.clipShadows = false;
  8482. this.colorWrite = true;
  8483. this.precision = null; // override the renderer's default precision for this material
  8484. this.polygonOffset = false;
  8485. this.polygonOffsetFactor = 0;
  8486. this.polygonOffsetUnits = 0;
  8487. this.alphaTest = 0;
  8488. this.premultipliedAlpha = false;
  8489. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  8490. this.visible = true;
  8491. this._needsUpdate = true;
  8492. }
  8493. Material.prototype = {
  8494. constructor: Material,
  8495. isMaterial: true,
  8496. get needsUpdate() {
  8497. return this._needsUpdate;
  8498. },
  8499. set needsUpdate( value ) {
  8500. if ( value === true ) this.update();
  8501. this._needsUpdate = value;
  8502. },
  8503. setValues: function ( values ) {
  8504. if ( values === undefined ) return;
  8505. for ( var key in values ) {
  8506. var newValue = values[ key ];
  8507. if ( newValue === undefined ) {
  8508. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  8509. continue;
  8510. }
  8511. var currentValue = this[ key ];
  8512. if ( currentValue === undefined ) {
  8513. console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
  8514. continue;
  8515. }
  8516. if ( currentValue && currentValue.isColor ) {
  8517. currentValue.set( newValue );
  8518. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  8519. currentValue.copy( newValue );
  8520. } else if ( key === 'overdraw' ) {
  8521. // ensure overdraw is backwards-compatible with legacy boolean type
  8522. this[ key ] = Number( newValue );
  8523. } else {
  8524. this[ key ] = newValue;
  8525. }
  8526. }
  8527. },
  8528. toJSON: function ( meta ) {
  8529. var isRoot = meta === undefined;
  8530. if ( isRoot ) {
  8531. meta = {
  8532. textures: {},
  8533. images: {}
  8534. };
  8535. }
  8536. var data = {
  8537. metadata: {
  8538. version: 4.4,
  8539. type: 'Material',
  8540. generator: 'Material.toJSON'
  8541. }
  8542. };
  8543. // standard Material serialization
  8544. data.uuid = this.uuid;
  8545. data.type = this.type;
  8546. if ( this.name !== '' ) data.name = this.name;
  8547. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  8548. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  8549. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  8550. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  8551. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  8552. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  8553. if ( this.clearCoat !== undefined ) data.clearCoat = this.clearCoat;
  8554. if ( this.clearCoatRoughness !== undefined ) data.clearCoatRoughness = this.clearCoatRoughness;
  8555. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  8556. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  8557. if ( this.lightMap && this.lightMap.isTexture ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  8558. if ( this.bumpMap && this.bumpMap.isTexture ) {
  8559. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  8560. data.bumpScale = this.bumpScale;
  8561. }
  8562. if ( this.normalMap && this.normalMap.isTexture ) {
  8563. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  8564. data.normalScale = this.normalScale.toArray();
  8565. }
  8566. if ( this.displacementMap && this.displacementMap.isTexture ) {
  8567. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  8568. data.displacementScale = this.displacementScale;
  8569. data.displacementBias = this.displacementBias;
  8570. }
  8571. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  8572. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  8573. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  8574. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  8575. if ( this.envMap && this.envMap.isTexture ) {
  8576. data.envMap = this.envMap.toJSON( meta ).uuid;
  8577. data.reflectivity = this.reflectivity; // Scale behind envMap
  8578. }
  8579. if ( this.gradientMap && this.gradientMap.isTexture ) {
  8580. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  8581. }
  8582. if ( this.size !== undefined ) data.size = this.size;
  8583. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  8584. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  8585. if ( this.shading !== SmoothShading ) data.shading = this.shading;
  8586. if ( this.side !== FrontSide ) data.side = this.side;
  8587. if ( this.vertexColors !== NoColors ) data.vertexColors = this.vertexColors;
  8588. if ( this.opacity < 1 ) data.opacity = this.opacity;
  8589. if ( this.transparent === true ) data.transparent = this.transparent;
  8590. data.depthFunc = this.depthFunc;
  8591. data.depthTest = this.depthTest;
  8592. data.depthWrite = this.depthWrite;
  8593. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  8594. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  8595. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  8596. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  8597. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  8598. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  8599. data.skinning = this.skinning;
  8600. data.morphTargets = this.morphTargets;
  8601. // TODO: Copied from Object3D.toJSON
  8602. function extractFromCache( cache ) {
  8603. var values = [];
  8604. for ( var key in cache ) {
  8605. var data = cache[ key ];
  8606. delete data.metadata;
  8607. values.push( data );
  8608. }
  8609. return values;
  8610. }
  8611. if ( isRoot ) {
  8612. var textures = extractFromCache( meta.textures );
  8613. var images = extractFromCache( meta.images );
  8614. if ( textures.length > 0 ) data.textures = textures;
  8615. if ( images.length > 0 ) data.images = images;
  8616. }
  8617. return data;
  8618. },
  8619. clone: function () {
  8620. return new this.constructor().copy( this );
  8621. },
  8622. copy: function ( source ) {
  8623. this.name = source.name;
  8624. this.fog = source.fog;
  8625. this.lights = source.lights;
  8626. this.blending = source.blending;
  8627. this.side = source.side;
  8628. this.shading = source.shading;
  8629. this.vertexColors = source.vertexColors;
  8630. this.opacity = source.opacity;
  8631. this.transparent = source.transparent;
  8632. this.blendSrc = source.blendSrc;
  8633. this.blendDst = source.blendDst;
  8634. this.blendEquation = source.blendEquation;
  8635. this.blendSrcAlpha = source.blendSrcAlpha;
  8636. this.blendDstAlpha = source.blendDstAlpha;
  8637. this.blendEquationAlpha = source.blendEquationAlpha;
  8638. this.depthFunc = source.depthFunc;
  8639. this.depthTest = source.depthTest;
  8640. this.depthWrite = source.depthWrite;
  8641. this.colorWrite = source.colorWrite;
  8642. this.precision = source.precision;
  8643. this.polygonOffset = source.polygonOffset;
  8644. this.polygonOffsetFactor = source.polygonOffsetFactor;
  8645. this.polygonOffsetUnits = source.polygonOffsetUnits;
  8646. this.alphaTest = source.alphaTest;
  8647. this.premultipliedAlpha = source.premultipliedAlpha;
  8648. this.overdraw = source.overdraw;
  8649. this.visible = source.visible;
  8650. this.clipShadows = source.clipShadows;
  8651. this.clipIntersection = source.clipIntersection;
  8652. var srcPlanes = source.clippingPlanes,
  8653. dstPlanes = null;
  8654. if ( srcPlanes !== null ) {
  8655. var n = srcPlanes.length;
  8656. dstPlanes = new Array( n );
  8657. for ( var i = 0; i !== n; ++ i )
  8658. dstPlanes[ i ] = srcPlanes[ i ].clone();
  8659. }
  8660. this.clippingPlanes = dstPlanes;
  8661. return this;
  8662. },
  8663. update: function () {
  8664. this.dispatchEvent( { type: 'update' } );
  8665. },
  8666. dispose: function () {
  8667. this.dispatchEvent( { type: 'dispose' } );
  8668. }
  8669. };
  8670. Object.assign( Material.prototype, EventDispatcher.prototype );
  8671. /**
  8672. * @author alteredq / http://alteredqualia.com/
  8673. *
  8674. * parameters = {
  8675. * defines: { "label" : "value" },
  8676. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  8677. *
  8678. * fragmentShader: <string>,
  8679. * vertexShader: <string>,
  8680. *
  8681. * wireframe: <boolean>,
  8682. * wireframeLinewidth: <float>,
  8683. *
  8684. * lights: <bool>,
  8685. *
  8686. * skinning: <bool>,
  8687. * morphTargets: <bool>,
  8688. * morphNormals: <bool>
  8689. * }
  8690. */
  8691. function ShaderMaterial( parameters ) {
  8692. Material.call( this );
  8693. this.type = 'ShaderMaterial';
  8694. this.defines = {};
  8695. this.uniforms = {};
  8696. this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
  8697. this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
  8698. this.linewidth = 1;
  8699. this.wireframe = false;
  8700. this.wireframeLinewidth = 1;
  8701. this.fog = false; // set to use scene fog
  8702. this.lights = false; // set to use scene lights
  8703. this.clipping = false; // set to use user-defined clipping planes
  8704. this.skinning = false; // set to use skinning attribute streams
  8705. this.morphTargets = false; // set to use morph targets
  8706. this.morphNormals = false; // set to use morph normals
  8707. this.extensions = {
  8708. derivatives: false, // set to use derivatives
  8709. fragDepth: false, // set to use fragment depth values
  8710. drawBuffers: false, // set to use draw buffers
  8711. shaderTextureLOD: false // set to use shader texture LOD
  8712. };
  8713. // When rendered geometry doesn't include these attributes but the material does,
  8714. // use these default values in WebGL. This avoids errors when buffer data is missing.
  8715. this.defaultAttributeValues = {
  8716. 'color': [ 1, 1, 1 ],
  8717. 'uv': [ 0, 0 ],
  8718. 'uv2': [ 0, 0 ]
  8719. };
  8720. this.index0AttributeName = undefined;
  8721. if ( parameters !== undefined ) {
  8722. if ( parameters.attributes !== undefined ) {
  8723. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  8724. }
  8725. this.setValues( parameters );
  8726. }
  8727. }
  8728. ShaderMaterial.prototype = Object.create( Material.prototype );
  8729. ShaderMaterial.prototype.constructor = ShaderMaterial;
  8730. ShaderMaterial.prototype.isShaderMaterial = true;
  8731. ShaderMaterial.prototype.copy = function ( source ) {
  8732. Material.prototype.copy.call( this, source );
  8733. this.fragmentShader = source.fragmentShader;
  8734. this.vertexShader = source.vertexShader;
  8735. this.uniforms = UniformsUtils.clone( source.uniforms );
  8736. this.defines = source.defines;
  8737. this.wireframe = source.wireframe;
  8738. this.wireframeLinewidth = source.wireframeLinewidth;
  8739. this.lights = source.lights;
  8740. this.clipping = source.clipping;
  8741. this.skinning = source.skinning;
  8742. this.morphTargets = source.morphTargets;
  8743. this.morphNormals = source.morphNormals;
  8744. this.extensions = source.extensions;
  8745. return this;
  8746. };
  8747. ShaderMaterial.prototype.toJSON = function ( meta ) {
  8748. var data = Material.prototype.toJSON.call( this, meta );
  8749. data.uniforms = this.uniforms;
  8750. data.vertexShader = this.vertexShader;
  8751. data.fragmentShader = this.fragmentShader;
  8752. return data;
  8753. };
  8754. /**
  8755. * @author mrdoob / http://mrdoob.com/
  8756. * @author alteredq / http://alteredqualia.com/
  8757. * @author bhouston / https://clara.io
  8758. * @author WestLangley / http://github.com/WestLangley
  8759. *
  8760. * parameters = {
  8761. *
  8762. * opacity: <float>,
  8763. *
  8764. * map: new THREE.Texture( <Image> ),
  8765. *
  8766. * alphaMap: new THREE.Texture( <Image> ),
  8767. *
  8768. * displacementMap: new THREE.Texture( <Image> ),
  8769. * displacementScale: <float>,
  8770. * displacementBias: <float>,
  8771. *
  8772. * wireframe: <boolean>,
  8773. * wireframeLinewidth: <float>
  8774. * }
  8775. */
  8776. function MeshDepthMaterial( parameters ) {
  8777. Material.call( this );
  8778. this.type = 'MeshDepthMaterial';
  8779. this.depthPacking = BasicDepthPacking;
  8780. this.skinning = false;
  8781. this.morphTargets = false;
  8782. this.map = null;
  8783. this.alphaMap = null;
  8784. this.displacementMap = null;
  8785. this.displacementScale = 1;
  8786. this.displacementBias = 0;
  8787. this.wireframe = false;
  8788. this.wireframeLinewidth = 1;
  8789. this.fog = false;
  8790. this.lights = false;
  8791. this.setValues( parameters );
  8792. }
  8793. MeshDepthMaterial.prototype = Object.create( Material.prototype );
  8794. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  8795. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  8796. MeshDepthMaterial.prototype.copy = function ( source ) {
  8797. Material.prototype.copy.call( this, source );
  8798. this.depthPacking = source.depthPacking;
  8799. this.skinning = source.skinning;
  8800. this.morphTargets = source.morphTargets;
  8801. this.map = source.map;
  8802. this.alphaMap = source.alphaMap;
  8803. this.displacementMap = source.displacementMap;
  8804. this.displacementScale = source.displacementScale;
  8805. this.displacementBias = source.displacementBias;
  8806. this.wireframe = source.wireframe;
  8807. this.wireframeLinewidth = source.wireframeLinewidth;
  8808. return this;
  8809. };
  8810. /**
  8811. * @author bhouston / http://clara.io
  8812. * @author WestLangley / http://github.com/WestLangley
  8813. */
  8814. function Box3( min, max ) {
  8815. this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity );
  8816. this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity );
  8817. }
  8818. Box3.prototype = {
  8819. constructor: Box3,
  8820. isBox3: true,
  8821. set: function ( min, max ) {
  8822. this.min.copy( min );
  8823. this.max.copy( max );
  8824. return this;
  8825. },
  8826. setFromArray: function ( array ) {
  8827. var minX = + Infinity;
  8828. var minY = + Infinity;
  8829. var minZ = + Infinity;
  8830. var maxX = - Infinity;
  8831. var maxY = - Infinity;
  8832. var maxZ = - Infinity;
  8833. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  8834. var x = array[ i ];
  8835. var y = array[ i + 1 ];
  8836. var z = array[ i + 2 ];
  8837. if ( x < minX ) minX = x;
  8838. if ( y < minY ) minY = y;
  8839. if ( z < minZ ) minZ = z;
  8840. if ( x > maxX ) maxX = x;
  8841. if ( y > maxY ) maxY = y;
  8842. if ( z > maxZ ) maxZ = z;
  8843. }
  8844. this.min.set( minX, minY, minZ );
  8845. this.max.set( maxX, maxY, maxZ );
  8846. return this;
  8847. },
  8848. setFromBufferAttribute: function ( attribute ) {
  8849. var minX = + Infinity;
  8850. var minY = + Infinity;
  8851. var minZ = + Infinity;
  8852. var maxX = - Infinity;
  8853. var maxY = - Infinity;
  8854. var maxZ = - Infinity;
  8855. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  8856. var x = attribute.getX( i );
  8857. var y = attribute.getY( i );
  8858. var z = attribute.getZ( i );
  8859. if ( x < minX ) minX = x;
  8860. if ( y < minY ) minY = y;
  8861. if ( z < minZ ) minZ = z;
  8862. if ( x > maxX ) maxX = x;
  8863. if ( y > maxY ) maxY = y;
  8864. if ( z > maxZ ) maxZ = z;
  8865. }
  8866. this.min.set( minX, minY, minZ );
  8867. this.max.set( maxX, maxY, maxZ );
  8868. return this;
  8869. },
  8870. setFromPoints: function ( points ) {
  8871. this.makeEmpty();
  8872. for ( var i = 0, il = points.length; i < il; i ++ ) {
  8873. this.expandByPoint( points[ i ] );
  8874. }
  8875. return this;
  8876. },
  8877. setFromCenterAndSize: function () {
  8878. var v1 = new Vector3();
  8879. return function setFromCenterAndSize( center, size ) {
  8880. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  8881. this.min.copy( center ).sub( halfSize );
  8882. this.max.copy( center ).add( halfSize );
  8883. return this;
  8884. };
  8885. }(),
  8886. setFromObject: function ( object ) {
  8887. this.makeEmpty();
  8888. return this.expandByObject( object );
  8889. },
  8890. clone: function () {
  8891. return new this.constructor().copy( this );
  8892. },
  8893. copy: function ( box ) {
  8894. this.min.copy( box.min );
  8895. this.max.copy( box.max );
  8896. return this;
  8897. },
  8898. makeEmpty: function () {
  8899. this.min.x = this.min.y = this.min.z = + Infinity;
  8900. this.max.x = this.max.y = this.max.z = - Infinity;
  8901. return this;
  8902. },
  8903. isEmpty: function () {
  8904. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  8905. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  8906. },
  8907. getCenter: function ( optionalTarget ) {
  8908. var result = optionalTarget || new Vector3();
  8909. return this.isEmpty() ? result.set( 0, 0, 0 ) : result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  8910. },
  8911. getSize: function ( optionalTarget ) {
  8912. var result = optionalTarget || new Vector3();
  8913. return this.isEmpty() ? result.set( 0, 0, 0 ) : result.subVectors( this.max, this.min );
  8914. },
  8915. expandByPoint: function ( point ) {
  8916. this.min.min( point );
  8917. this.max.max( point );
  8918. return this;
  8919. },
  8920. expandByVector: function ( vector ) {
  8921. this.min.sub( vector );
  8922. this.max.add( vector );
  8923. return this;
  8924. },
  8925. expandByScalar: function ( scalar ) {
  8926. this.min.addScalar( - scalar );
  8927. this.max.addScalar( scalar );
  8928. return this;
  8929. },
  8930. expandByObject: function () {
  8931. // Computes the world-axis-aligned bounding box of an object (including its children),
  8932. // accounting for both the object's, and children's, world transforms
  8933. var v1 = new Vector3();
  8934. return function expandByObject( object ) {
  8935. var scope = this;
  8936. object.updateMatrixWorld( true );
  8937. object.traverse( function ( node ) {
  8938. var i, l;
  8939. var geometry = node.geometry;
  8940. if ( geometry !== undefined ) {
  8941. if ( geometry.isGeometry ) {
  8942. var vertices = geometry.vertices;
  8943. for ( i = 0, l = vertices.length; i < l; i ++ ) {
  8944. v1.copy( vertices[ i ] );
  8945. v1.applyMatrix4( node.matrixWorld );
  8946. scope.expandByPoint( v1 );
  8947. }
  8948. } else if ( geometry.isBufferGeometry ) {
  8949. var attribute = geometry.attributes.position;
  8950. if ( attribute !== undefined ) {
  8951. for ( i = 0, l = attribute.count; i < l; i ++ ) {
  8952. v1.fromBufferAttribute( attribute, i ).applyMatrix4( node.matrixWorld );
  8953. scope.expandByPoint( v1 );
  8954. }
  8955. }
  8956. }
  8957. }
  8958. } );
  8959. return this;
  8960. };
  8961. }(),
  8962. containsPoint: function ( point ) {
  8963. return point.x < this.min.x || point.x > this.max.x ||
  8964. point.y < this.min.y || point.y > this.max.y ||
  8965. point.z < this.min.z || point.z > this.max.z ? false : true;
  8966. },
  8967. containsBox: function ( box ) {
  8968. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  8969. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  8970. this.min.z <= box.min.z && box.max.z <= this.max.z;
  8971. },
  8972. getParameter: function ( point, optionalTarget ) {
  8973. // This can potentially have a divide by zero if the box
  8974. // has a size dimension of 0.
  8975. var result = optionalTarget || new Vector3();
  8976. return result.set(
  8977. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  8978. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  8979. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  8980. );
  8981. },
  8982. intersectsBox: function ( box ) {
  8983. // using 6 splitting planes to rule out intersections.
  8984. return box.max.x < this.min.x || box.min.x > this.max.x ||
  8985. box.max.y < this.min.y || box.min.y > this.max.y ||
  8986. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  8987. },
  8988. intersectsSphere: ( function () {
  8989. var closestPoint;
  8990. return function intersectsSphere( sphere ) {
  8991. if ( closestPoint === undefined ) closestPoint = new Vector3();
  8992. // Find the point on the AABB closest to the sphere center.
  8993. this.clampPoint( sphere.center, closestPoint );
  8994. // If that point is inside the sphere, the AABB and sphere intersect.
  8995. return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  8996. };
  8997. } )(),
  8998. intersectsPlane: function ( plane ) {
  8999. // We compute the minimum and maximum dot product values. If those values
  9000. // are on the same side (back or front) of the plane, then there is no intersection.
  9001. var min, max;
  9002. if ( plane.normal.x > 0 ) {
  9003. min = plane.normal.x * this.min.x;
  9004. max = plane.normal.x * this.max.x;
  9005. } else {
  9006. min = plane.normal.x * this.max.x;
  9007. max = plane.normal.x * this.min.x;
  9008. }
  9009. if ( plane.normal.y > 0 ) {
  9010. min += plane.normal.y * this.min.y;
  9011. max += plane.normal.y * this.max.y;
  9012. } else {
  9013. min += plane.normal.y * this.max.y;
  9014. max += plane.normal.y * this.min.y;
  9015. }
  9016. if ( plane.normal.z > 0 ) {
  9017. min += plane.normal.z * this.min.z;
  9018. max += plane.normal.z * this.max.z;
  9019. } else {
  9020. min += plane.normal.z * this.max.z;
  9021. max += plane.normal.z * this.min.z;
  9022. }
  9023. return ( min <= plane.constant && max >= plane.constant );
  9024. },
  9025. clampPoint: function ( point, optionalTarget ) {
  9026. var result = optionalTarget || new Vector3();
  9027. return result.copy( point ).clamp( this.min, this.max );
  9028. },
  9029. distanceToPoint: function () {
  9030. var v1 = new Vector3();
  9031. return function distanceToPoint( point ) {
  9032. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  9033. return clampedPoint.sub( point ).length();
  9034. };
  9035. }(),
  9036. getBoundingSphere: function () {
  9037. var v1 = new Vector3();
  9038. return function getBoundingSphere( optionalTarget ) {
  9039. var result = optionalTarget || new Sphere();
  9040. this.getCenter( result.center );
  9041. result.radius = this.getSize( v1 ).length() * 0.5;
  9042. return result;
  9043. };
  9044. }(),
  9045. intersect: function ( box ) {
  9046. this.min.max( box.min );
  9047. this.max.min( box.max );
  9048. // 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.
  9049. if( this.isEmpty() ) this.makeEmpty();
  9050. return this;
  9051. },
  9052. union: function ( box ) {
  9053. this.min.min( box.min );
  9054. this.max.max( box.max );
  9055. return this;
  9056. },
  9057. applyMatrix4: function () {
  9058. var points = [
  9059. new Vector3(),
  9060. new Vector3(),
  9061. new Vector3(),
  9062. new Vector3(),
  9063. new Vector3(),
  9064. new Vector3(),
  9065. new Vector3(),
  9066. new Vector3()
  9067. ];
  9068. return function applyMatrix4( matrix ) {
  9069. // transform of empty box is an empty box.
  9070. if( this.isEmpty() ) return this;
  9071. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  9072. points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  9073. points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  9074. points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  9075. points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  9076. points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  9077. points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  9078. points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  9079. points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  9080. this.setFromPoints( points );
  9081. return this;
  9082. };
  9083. }(),
  9084. translate: function ( offset ) {
  9085. this.min.add( offset );
  9086. this.max.add( offset );
  9087. return this;
  9088. },
  9089. equals: function ( box ) {
  9090. return box.min.equals( this.min ) && box.max.equals( this.max );
  9091. }
  9092. };
  9093. /**
  9094. * @author bhouston / http://clara.io
  9095. * @author mrdoob / http://mrdoob.com/
  9096. */
  9097. function Sphere( center, radius ) {
  9098. this.center = ( center !== undefined ) ? center : new Vector3();
  9099. this.radius = ( radius !== undefined ) ? radius : 0;
  9100. }
  9101. Sphere.prototype = {
  9102. constructor: Sphere,
  9103. set: function ( center, radius ) {
  9104. this.center.copy( center );
  9105. this.radius = radius;
  9106. return this;
  9107. },
  9108. setFromPoints: function () {
  9109. var box;
  9110. return function setFromPoints( points, optionalCenter ) {
  9111. if ( box === undefined ) box = new Box3(); // see #10547
  9112. var center = this.center;
  9113. if ( optionalCenter !== undefined ) {
  9114. center.copy( optionalCenter );
  9115. } else {
  9116. box.setFromPoints( points ).getCenter( center );
  9117. }
  9118. var maxRadiusSq = 0;
  9119. for ( var i = 0, il = points.length; i < il; i ++ ) {
  9120. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  9121. }
  9122. this.radius = Math.sqrt( maxRadiusSq );
  9123. return this;
  9124. };
  9125. }(),
  9126. clone: function () {
  9127. return new this.constructor().copy( this );
  9128. },
  9129. copy: function ( sphere ) {
  9130. this.center.copy( sphere.center );
  9131. this.radius = sphere.radius;
  9132. return this;
  9133. },
  9134. empty: function () {
  9135. return ( this.radius <= 0 );
  9136. },
  9137. containsPoint: function ( point ) {
  9138. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  9139. },
  9140. distanceToPoint: function ( point ) {
  9141. return ( point.distanceTo( this.center ) - this.radius );
  9142. },
  9143. intersectsSphere: function ( sphere ) {
  9144. var radiusSum = this.radius + sphere.radius;
  9145. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  9146. },
  9147. intersectsBox: function ( box ) {
  9148. return box.intersectsSphere( this );
  9149. },
  9150. intersectsPlane: function ( plane ) {
  9151. // We use the following equation to compute the signed distance from
  9152. // the center of the sphere to the plane.
  9153. //
  9154. // distance = q * n - d
  9155. //
  9156. // If this distance is greater than the radius of the sphere,
  9157. // then there is no intersection.
  9158. return Math.abs( this.center.dot( plane.normal ) - plane.constant ) <= this.radius;
  9159. },
  9160. clampPoint: function ( point, optionalTarget ) {
  9161. var deltaLengthSq = this.center.distanceToSquared( point );
  9162. var result = optionalTarget || new Vector3();
  9163. result.copy( point );
  9164. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  9165. result.sub( this.center ).normalize();
  9166. result.multiplyScalar( this.radius ).add( this.center );
  9167. }
  9168. return result;
  9169. },
  9170. getBoundingBox: function ( optionalTarget ) {
  9171. var box = optionalTarget || new Box3();
  9172. box.set( this.center, this.center );
  9173. box.expandByScalar( this.radius );
  9174. return box;
  9175. },
  9176. applyMatrix4: function ( matrix ) {
  9177. this.center.applyMatrix4( matrix );
  9178. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  9179. return this;
  9180. },
  9181. translate: function ( offset ) {
  9182. this.center.add( offset );
  9183. return this;
  9184. },
  9185. equals: function ( sphere ) {
  9186. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  9187. }
  9188. };
  9189. /**
  9190. * @author alteredq / http://alteredqualia.com/
  9191. * @author WestLangley / http://github.com/WestLangley
  9192. * @author bhouston / http://clara.io
  9193. * @author tschw
  9194. */
  9195. function Matrix3() {
  9196. this.elements = new Float32Array( [
  9197. 1, 0, 0,
  9198. 0, 1, 0,
  9199. 0, 0, 1
  9200. ] );
  9201. if ( arguments.length > 0 ) {
  9202. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  9203. }
  9204. }
  9205. Matrix3.prototype = {
  9206. constructor: Matrix3,
  9207. isMatrix3: true,
  9208. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  9209. var te = this.elements;
  9210. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  9211. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  9212. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  9213. return this;
  9214. },
  9215. identity: function () {
  9216. this.set(
  9217. 1, 0, 0,
  9218. 0, 1, 0,
  9219. 0, 0, 1
  9220. );
  9221. return this;
  9222. },
  9223. clone: function () {
  9224. return new this.constructor().fromArray( this.elements );
  9225. },
  9226. copy: function ( m ) {
  9227. var me = m.elements;
  9228. this.set(
  9229. me[ 0 ], me[ 3 ], me[ 6 ],
  9230. me[ 1 ], me[ 4 ], me[ 7 ],
  9231. me[ 2 ], me[ 5 ], me[ 8 ]
  9232. );
  9233. return this;
  9234. },
  9235. setFromMatrix4: function( m ) {
  9236. var me = m.elements;
  9237. this.set(
  9238. me[ 0 ], me[ 4 ], me[ 8 ],
  9239. me[ 1 ], me[ 5 ], me[ 9 ],
  9240. me[ 2 ], me[ 6 ], me[ 10 ]
  9241. );
  9242. return this;
  9243. },
  9244. applyToBufferAttribute: function () {
  9245. var v1;
  9246. return function applyToBufferAttribute( attribute ) {
  9247. if ( v1 === undefined ) v1 = new Vector3();
  9248. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  9249. v1.x = attribute.getX( i );
  9250. v1.y = attribute.getY( i );
  9251. v1.z = attribute.getZ( i );
  9252. v1.applyMatrix3( this );
  9253. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  9254. }
  9255. return attribute;
  9256. };
  9257. }(),
  9258. multiplyScalar: function ( s ) {
  9259. var te = this.elements;
  9260. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  9261. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  9262. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  9263. return this;
  9264. },
  9265. determinant: function () {
  9266. var te = this.elements;
  9267. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  9268. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  9269. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  9270. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  9271. },
  9272. getInverse: function ( matrix, throwOnDegenerate ) {
  9273. if ( matrix && matrix.isMatrix4 ) {
  9274. console.error( "THREE.Matrix3.getInverse no longer takes a Matrix4 argument." );
  9275. }
  9276. var me = matrix.elements,
  9277. te = this.elements,
  9278. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ],
  9279. n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ],
  9280. n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ],
  9281. t11 = n33 * n22 - n32 * n23,
  9282. t12 = n32 * n13 - n33 * n12,
  9283. t13 = n23 * n12 - n22 * n13,
  9284. det = n11 * t11 + n21 * t12 + n31 * t13;
  9285. if ( det === 0 ) {
  9286. var msg = "THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0";
  9287. if ( throwOnDegenerate === true ) {
  9288. throw new Error( msg );
  9289. } else {
  9290. console.warn( msg );
  9291. }
  9292. return this.identity();
  9293. }
  9294. var detInv = 1 / det;
  9295. te[ 0 ] = t11 * detInv;
  9296. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  9297. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  9298. te[ 3 ] = t12 * detInv;
  9299. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  9300. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  9301. te[ 6 ] = t13 * detInv;
  9302. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  9303. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  9304. return this;
  9305. },
  9306. transpose: function () {
  9307. var tmp, m = this.elements;
  9308. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  9309. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  9310. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  9311. return this;
  9312. },
  9313. getNormalMatrix: function ( matrix4 ) {
  9314. return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose();
  9315. },
  9316. transposeIntoArray: function ( r ) {
  9317. var m = this.elements;
  9318. r[ 0 ] = m[ 0 ];
  9319. r[ 1 ] = m[ 3 ];
  9320. r[ 2 ] = m[ 6 ];
  9321. r[ 3 ] = m[ 1 ];
  9322. r[ 4 ] = m[ 4 ];
  9323. r[ 5 ] = m[ 7 ];
  9324. r[ 6 ] = m[ 2 ];
  9325. r[ 7 ] = m[ 5 ];
  9326. r[ 8 ] = m[ 8 ];
  9327. return this;
  9328. },
  9329. fromArray: function ( array, offset ) {
  9330. if ( offset === undefined ) offset = 0;
  9331. for( var i = 0; i < 9; i ++ ) {
  9332. this.elements[ i ] = array[ i + offset ];
  9333. }
  9334. return this;
  9335. },
  9336. toArray: function ( array, offset ) {
  9337. if ( array === undefined ) array = [];
  9338. if ( offset === undefined ) offset = 0;
  9339. var te = this.elements;
  9340. array[ offset ] = te[ 0 ];
  9341. array[ offset + 1 ] = te[ 1 ];
  9342. array[ offset + 2 ] = te[ 2 ];
  9343. array[ offset + 3 ] = te[ 3 ];
  9344. array[ offset + 4 ] = te[ 4 ];
  9345. array[ offset + 5 ] = te[ 5 ];
  9346. array[ offset + 6 ] = te[ 6 ];
  9347. array[ offset + 7 ] = te[ 7 ];
  9348. array[ offset + 8 ] = te[ 8 ];
  9349. return array;
  9350. }
  9351. };
  9352. /**
  9353. * @author bhouston / http://clara.io
  9354. */
  9355. function Plane( normal, constant ) {
  9356. this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 );
  9357. this.constant = ( constant !== undefined ) ? constant : 0;
  9358. }
  9359. Plane.prototype = {
  9360. constructor: Plane,
  9361. set: function ( normal, constant ) {
  9362. this.normal.copy( normal );
  9363. this.constant = constant;
  9364. return this;
  9365. },
  9366. setComponents: function ( x, y, z, w ) {
  9367. this.normal.set( x, y, z );
  9368. this.constant = w;
  9369. return this;
  9370. },
  9371. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  9372. this.normal.copy( normal );
  9373. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  9374. return this;
  9375. },
  9376. setFromCoplanarPoints: function () {
  9377. var v1 = new Vector3();
  9378. var v2 = new Vector3();
  9379. return function setFromCoplanarPoints( a, b, c ) {
  9380. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  9381. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  9382. this.setFromNormalAndCoplanarPoint( normal, a );
  9383. return this;
  9384. };
  9385. }(),
  9386. clone: function () {
  9387. return new this.constructor().copy( this );
  9388. },
  9389. copy: function ( plane ) {
  9390. this.normal.copy( plane.normal );
  9391. this.constant = plane.constant;
  9392. return this;
  9393. },
  9394. normalize: function () {
  9395. // Note: will lead to a divide by zero if the plane is invalid.
  9396. var inverseNormalLength = 1.0 / this.normal.length();
  9397. this.normal.multiplyScalar( inverseNormalLength );
  9398. this.constant *= inverseNormalLength;
  9399. return this;
  9400. },
  9401. negate: function () {
  9402. this.constant *= - 1;
  9403. this.normal.negate();
  9404. return this;
  9405. },
  9406. distanceToPoint: function ( point ) {
  9407. return this.normal.dot( point ) + this.constant;
  9408. },
  9409. distanceToSphere: function ( sphere ) {
  9410. return this.distanceToPoint( sphere.center ) - sphere.radius;
  9411. },
  9412. projectPoint: function ( point, optionalTarget ) {
  9413. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  9414. },
  9415. orthoPoint: function ( point, optionalTarget ) {
  9416. var perpendicularMagnitude = this.distanceToPoint( point );
  9417. var result = optionalTarget || new Vector3();
  9418. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  9419. },
  9420. intersectLine: function () {
  9421. var v1 = new Vector3();
  9422. return function intersectLine( line, optionalTarget ) {
  9423. var result = optionalTarget || new Vector3();
  9424. var direction = line.delta( v1 );
  9425. var denominator = this.normal.dot( direction );
  9426. if ( denominator === 0 ) {
  9427. // line is coplanar, return origin
  9428. if ( this.distanceToPoint( line.start ) === 0 ) {
  9429. return result.copy( line.start );
  9430. }
  9431. // Unsure if this is the correct method to handle this case.
  9432. return undefined;
  9433. }
  9434. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  9435. if ( t < 0 || t > 1 ) {
  9436. return undefined;
  9437. }
  9438. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  9439. };
  9440. }(),
  9441. intersectsLine: function ( line ) {
  9442. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  9443. var startSign = this.distanceToPoint( line.start );
  9444. var endSign = this.distanceToPoint( line.end );
  9445. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  9446. },
  9447. intersectsBox: function ( box ) {
  9448. return box.intersectsPlane( this );
  9449. },
  9450. intersectsSphere: function ( sphere ) {
  9451. return sphere.intersectsPlane( this );
  9452. },
  9453. coplanarPoint: function ( optionalTarget ) {
  9454. var result = optionalTarget || new Vector3();
  9455. return result.copy( this.normal ).multiplyScalar( - this.constant );
  9456. },
  9457. applyMatrix4: function () {
  9458. var v1 = new Vector3();
  9459. var m1 = new Matrix3();
  9460. return function applyMatrix4( matrix, optionalNormalMatrix ) {
  9461. var referencePoint = this.coplanarPoint( v1 ).applyMatrix4( matrix );
  9462. // transform normal based on theory here:
  9463. // http://www.songho.ca/opengl/gl_normaltransform.html
  9464. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  9465. var normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  9466. // recalculate constant (like in setFromNormalAndCoplanarPoint)
  9467. this.constant = - referencePoint.dot( normal );
  9468. return this;
  9469. };
  9470. }(),
  9471. translate: function ( offset ) {
  9472. this.constant = this.constant - offset.dot( this.normal );
  9473. return this;
  9474. },
  9475. equals: function ( plane ) {
  9476. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  9477. }
  9478. };
  9479. /**
  9480. * @author mrdoob / http://mrdoob.com/
  9481. * @author alteredq / http://alteredqualia.com/
  9482. * @author bhouston / http://clara.io
  9483. */
  9484. function Frustum( p0, p1, p2, p3, p4, p5 ) {
  9485. this.planes = [
  9486. ( p0 !== undefined ) ? p0 : new Plane(),
  9487. ( p1 !== undefined ) ? p1 : new Plane(),
  9488. ( p2 !== undefined ) ? p2 : new Plane(),
  9489. ( p3 !== undefined ) ? p3 : new Plane(),
  9490. ( p4 !== undefined ) ? p4 : new Plane(),
  9491. ( p5 !== undefined ) ? p5 : new Plane()
  9492. ];
  9493. }
  9494. Frustum.prototype = {
  9495. constructor: Frustum,
  9496. set: function ( p0, p1, p2, p3, p4, p5 ) {
  9497. var planes = this.planes;
  9498. planes[ 0 ].copy( p0 );
  9499. planes[ 1 ].copy( p1 );
  9500. planes[ 2 ].copy( p2 );
  9501. planes[ 3 ].copy( p3 );
  9502. planes[ 4 ].copy( p4 );
  9503. planes[ 5 ].copy( p5 );
  9504. return this;
  9505. },
  9506. clone: function () {
  9507. return new this.constructor().copy( this );
  9508. },
  9509. copy: function ( frustum ) {
  9510. var planes = this.planes;
  9511. for ( var i = 0; i < 6; i ++ ) {
  9512. planes[ i ].copy( frustum.planes[ i ] );
  9513. }
  9514. return this;
  9515. },
  9516. setFromMatrix: function ( m ) {
  9517. var planes = this.planes;
  9518. var me = m.elements;
  9519. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  9520. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  9521. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  9522. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  9523. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  9524. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  9525. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  9526. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  9527. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  9528. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  9529. return this;
  9530. },
  9531. intersectsObject: function () {
  9532. var sphere = new Sphere();
  9533. return function intersectsObject( object ) {
  9534. var geometry = object.geometry;
  9535. if ( geometry.boundingSphere === null )
  9536. geometry.computeBoundingSphere();
  9537. sphere.copy( geometry.boundingSphere )
  9538. .applyMatrix4( object.matrixWorld );
  9539. return this.intersectsSphere( sphere );
  9540. };
  9541. }(),
  9542. intersectsSprite: function () {
  9543. var sphere = new Sphere();
  9544. return function intersectsSprite( sprite ) {
  9545. sphere.center.set( 0, 0, 0 );
  9546. sphere.radius = 0.7071067811865476;
  9547. sphere.applyMatrix4( sprite.matrixWorld );
  9548. return this.intersectsSphere( sphere );
  9549. };
  9550. }(),
  9551. intersectsSphere: function ( sphere ) {
  9552. var planes = this.planes;
  9553. var center = sphere.center;
  9554. var negRadius = - sphere.radius;
  9555. for ( var i = 0; i < 6; i ++ ) {
  9556. var distance = planes[ i ].distanceToPoint( center );
  9557. if ( distance < negRadius ) {
  9558. return false;
  9559. }
  9560. }
  9561. return true;
  9562. },
  9563. intersectsBox: function () {
  9564. var p1 = new Vector3(),
  9565. p2 = new Vector3();
  9566. return function intersectsBox( box ) {
  9567. var planes = this.planes;
  9568. for ( var i = 0; i < 6 ; i ++ ) {
  9569. var plane = planes[ i ];
  9570. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  9571. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  9572. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  9573. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  9574. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  9575. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  9576. var d1 = plane.distanceToPoint( p1 );
  9577. var d2 = plane.distanceToPoint( p2 );
  9578. // if both outside plane, no intersection
  9579. if ( d1 < 0 && d2 < 0 ) {
  9580. return false;
  9581. }
  9582. }
  9583. return true;
  9584. };
  9585. }(),
  9586. containsPoint: function ( point ) {
  9587. var planes = this.planes;
  9588. for ( var i = 0; i < 6; i ++ ) {
  9589. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  9590. return false;
  9591. }
  9592. }
  9593. return true;
  9594. }
  9595. };
  9596. /**
  9597. * @author alteredq / http://alteredqualia.com/
  9598. * @author mrdoob / http://mrdoob.com/
  9599. */
  9600. function WebGLShadowMap( _renderer, _lights, _objects, capabilities ) {
  9601. var _gl = _renderer.context,
  9602. _state = _renderer.state,
  9603. _frustum = new Frustum(),
  9604. _projScreenMatrix = new Matrix4(),
  9605. _lightShadows = _lights.shadows,
  9606. _shadowMapSize = new Vector2(),
  9607. _maxShadowMapSize = new Vector2( capabilities.maxTextureSize, capabilities.maxTextureSize ),
  9608. _lookTarget = new Vector3(),
  9609. _lightPositionWorld = new Vector3(),
  9610. _renderList = [],
  9611. _MorphingFlag = 1,
  9612. _SkinningFlag = 2,
  9613. _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1,
  9614. _depthMaterials = new Array( _NumberOfMaterialVariants ),
  9615. _distanceMaterials = new Array( _NumberOfMaterialVariants ),
  9616. _materialCache = {};
  9617. var cubeDirections = [
  9618. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  9619. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  9620. ];
  9621. var cubeUps = [
  9622. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  9623. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  9624. ];
  9625. var cube2DViewPorts = [
  9626. new Vector4(), new Vector4(), new Vector4(),
  9627. new Vector4(), new Vector4(), new Vector4()
  9628. ];
  9629. // init
  9630. var depthMaterialTemplate = new MeshDepthMaterial();
  9631. depthMaterialTemplate.depthPacking = RGBADepthPacking;
  9632. depthMaterialTemplate.clipping = true;
  9633. var distanceShader = ShaderLib[ "distanceRGBA" ];
  9634. var distanceUniforms = UniformsUtils.clone( distanceShader.uniforms );
  9635. for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) {
  9636. var useMorphing = ( i & _MorphingFlag ) !== 0;
  9637. var useSkinning = ( i & _SkinningFlag ) !== 0;
  9638. var depthMaterial = depthMaterialTemplate.clone();
  9639. depthMaterial.morphTargets = useMorphing;
  9640. depthMaterial.skinning = useSkinning;
  9641. _depthMaterials[ i ] = depthMaterial;
  9642. var distanceMaterial = new ShaderMaterial( {
  9643. defines: {
  9644. 'USE_SHADOWMAP': ''
  9645. },
  9646. uniforms: distanceUniforms,
  9647. vertexShader: distanceShader.vertexShader,
  9648. fragmentShader: distanceShader.fragmentShader,
  9649. morphTargets: useMorphing,
  9650. skinning: useSkinning,
  9651. clipping: true
  9652. } );
  9653. _distanceMaterials[ i ] = distanceMaterial;
  9654. }
  9655. //
  9656. var scope = this;
  9657. this.enabled = false;
  9658. this.autoUpdate = true;
  9659. this.needsUpdate = false;
  9660. this.type = PCFShadowMap;
  9661. this.renderReverseSided = true;
  9662. this.renderSingleSided = true;
  9663. this.render = function ( scene, camera ) {
  9664. if ( scope.enabled === false ) return;
  9665. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  9666. if ( _lightShadows.length === 0 ) return;
  9667. // Set GL state for depth map.
  9668. _state.buffers.color.setClear( 1, 1, 1, 1 );
  9669. _state.disable( _gl.BLEND );
  9670. _state.setDepthTest( true );
  9671. _state.setScissorTest( false );
  9672. // render depth map
  9673. var faceCount, isPointLight;
  9674. for ( var i = 0, il = _lightShadows.length; i < il; i ++ ) {
  9675. var light = _lightShadows[ i ];
  9676. var shadow = light.shadow;
  9677. if ( shadow === undefined ) {
  9678. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  9679. continue;
  9680. }
  9681. var shadowCamera = shadow.camera;
  9682. _shadowMapSize.copy( shadow.mapSize );
  9683. _shadowMapSize.min( _maxShadowMapSize );
  9684. if ( light && light.isPointLight ) {
  9685. faceCount = 6;
  9686. isPointLight = true;
  9687. var vpWidth = _shadowMapSize.x;
  9688. var vpHeight = _shadowMapSize.y;
  9689. // These viewports map a cube-map onto a 2D texture with the
  9690. // following orientation:
  9691. //
  9692. // xzXZ
  9693. // y Y
  9694. //
  9695. // X - Positive x direction
  9696. // x - Negative x direction
  9697. // Y - Positive y direction
  9698. // y - Negative y direction
  9699. // Z - Positive z direction
  9700. // z - Negative z direction
  9701. // positive X
  9702. cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight );
  9703. // negative X
  9704. cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight );
  9705. // positive Z
  9706. cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight );
  9707. // negative Z
  9708. cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight );
  9709. // positive Y
  9710. cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight );
  9711. // negative Y
  9712. cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight );
  9713. _shadowMapSize.x *= 4.0;
  9714. _shadowMapSize.y *= 2.0;
  9715. } else {
  9716. faceCount = 1;
  9717. isPointLight = false;
  9718. }
  9719. if ( shadow.map === null ) {
  9720. var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  9721. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  9722. shadowCamera.updateProjectionMatrix();
  9723. }
  9724. if ( shadow.isSpotLightShadow ) {
  9725. shadow.update( light );
  9726. }
  9727. // TODO (abelnation / sam-g-steel): is this needed?
  9728. if (shadow && shadow.isRectAreaLightShadow ) {
  9729. shadow.update( light );
  9730. }
  9731. var shadowMap = shadow.map;
  9732. var shadowMatrix = shadow.matrix;
  9733. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  9734. shadowCamera.position.copy( _lightPositionWorld );
  9735. _renderer.setRenderTarget( shadowMap );
  9736. _renderer.clear();
  9737. // render shadow map for each cube face (if omni-directional) or
  9738. // run a single pass if not
  9739. for ( var face = 0; face < faceCount; face ++ ) {
  9740. if ( isPointLight ) {
  9741. _lookTarget.copy( shadowCamera.position );
  9742. _lookTarget.add( cubeDirections[ face ] );
  9743. shadowCamera.up.copy( cubeUps[ face ] );
  9744. shadowCamera.lookAt( _lookTarget );
  9745. var vpDimensions = cube2DViewPorts[ face ];
  9746. _state.viewport( vpDimensions );
  9747. } else {
  9748. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  9749. shadowCamera.lookAt( _lookTarget );
  9750. }
  9751. shadowCamera.updateMatrixWorld();
  9752. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  9753. // compute shadow matrix
  9754. shadowMatrix.set(
  9755. 0.5, 0.0, 0.0, 0.5,
  9756. 0.0, 0.5, 0.0, 0.5,
  9757. 0.0, 0.0, 0.5, 0.5,
  9758. 0.0, 0.0, 0.0, 1.0
  9759. );
  9760. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  9761. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  9762. // update camera matrices and frustum
  9763. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  9764. _frustum.setFromMatrix( _projScreenMatrix );
  9765. // set object matrices & frustum culling
  9766. _renderList.length = 0;
  9767. projectObject( scene, camera, shadowCamera );
  9768. // render shadow map
  9769. // render regular objects
  9770. for ( var j = 0, jl = _renderList.length; j < jl; j ++ ) {
  9771. var object = _renderList[ j ];
  9772. var geometry = _objects.update( object );
  9773. var material = object.material;
  9774. if ( material && material.isMultiMaterial ) {
  9775. var groups = geometry.groups;
  9776. var materials = material.materials;
  9777. for ( var k = 0, kl = groups.length; k < kl; k ++ ) {
  9778. var group = groups[ k ];
  9779. var groupMaterial = materials[ group.materialIndex ];
  9780. if ( groupMaterial.visible === true ) {
  9781. var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld );
  9782. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  9783. }
  9784. }
  9785. } else {
  9786. var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld );
  9787. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  9788. }
  9789. }
  9790. }
  9791. }
  9792. // Restore GL state.
  9793. var clearColor = _renderer.getClearColor(),
  9794. clearAlpha = _renderer.getClearAlpha();
  9795. _renderer.setClearColor( clearColor, clearAlpha );
  9796. scope.needsUpdate = false;
  9797. };
  9798. function getDepthMaterial( object, material, isPointLight, lightPositionWorld ) {
  9799. var geometry = object.geometry;
  9800. var result = null;
  9801. var materialVariants = _depthMaterials;
  9802. var customMaterial = object.customDepthMaterial;
  9803. if ( isPointLight ) {
  9804. materialVariants = _distanceMaterials;
  9805. customMaterial = object.customDistanceMaterial;
  9806. }
  9807. if ( ! customMaterial ) {
  9808. var useMorphing = false;
  9809. if ( material.morphTargets ) {
  9810. if ( geometry && geometry.isBufferGeometry ) {
  9811. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  9812. } else if ( geometry && geometry.isGeometry ) {
  9813. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  9814. }
  9815. }
  9816. var useSkinning = object.isSkinnedMesh && material.skinning;
  9817. var variantIndex = 0;
  9818. if ( useMorphing ) variantIndex |= _MorphingFlag;
  9819. if ( useSkinning ) variantIndex |= _SkinningFlag;
  9820. result = materialVariants[ variantIndex ];
  9821. } else {
  9822. result = customMaterial;
  9823. }
  9824. if ( _renderer.localClippingEnabled &&
  9825. material.clipShadows === true &&
  9826. material.clippingPlanes.length !== 0 ) {
  9827. // in this case we need a unique material instance reflecting the
  9828. // appropriate state
  9829. var keyA = result.uuid, keyB = material.uuid;
  9830. var materialsForVariant = _materialCache[ keyA ];
  9831. if ( materialsForVariant === undefined ) {
  9832. materialsForVariant = {};
  9833. _materialCache[ keyA ] = materialsForVariant;
  9834. }
  9835. var cachedMaterial = materialsForVariant[ keyB ];
  9836. if ( cachedMaterial === undefined ) {
  9837. cachedMaterial = result.clone();
  9838. materialsForVariant[ keyB ] = cachedMaterial;
  9839. }
  9840. result = cachedMaterial;
  9841. }
  9842. result.visible = material.visible;
  9843. result.wireframe = material.wireframe;
  9844. var side = material.side;
  9845. if ( scope.renderSingleSided && side == DoubleSide ) {
  9846. side = FrontSide;
  9847. }
  9848. if ( scope.renderReverseSided ) {
  9849. if ( side === FrontSide ) side = BackSide;
  9850. else if ( side === BackSide ) side = FrontSide;
  9851. }
  9852. result.side = side;
  9853. result.clipShadows = material.clipShadows;
  9854. result.clippingPlanes = material.clippingPlanes;
  9855. result.wireframeLinewidth = material.wireframeLinewidth;
  9856. result.linewidth = material.linewidth;
  9857. if ( isPointLight && result.uniforms.lightPos !== undefined ) {
  9858. result.uniforms.lightPos.value.copy( lightPositionWorld );
  9859. }
  9860. return result;
  9861. }
  9862. function projectObject( object, camera, shadowCamera ) {
  9863. if ( object.visible === false ) return;
  9864. var visible = ( object.layers.mask & camera.layers.mask ) !== 0;
  9865. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  9866. if ( object.castShadow && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) {
  9867. var material = object.material;
  9868. if ( material.visible === true ) {
  9869. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  9870. _renderList.push( object );
  9871. }
  9872. }
  9873. }
  9874. var children = object.children;
  9875. for ( var i = 0, l = children.length; i < l; i ++ ) {
  9876. projectObject( children[ i ], camera, shadowCamera );
  9877. }
  9878. }
  9879. }
  9880. /**
  9881. * @author bhouston / http://clara.io
  9882. */
  9883. function Ray( origin, direction ) {
  9884. this.origin = ( origin !== undefined ) ? origin : new Vector3();
  9885. this.direction = ( direction !== undefined ) ? direction : new Vector3();
  9886. }
  9887. Ray.prototype = {
  9888. constructor: Ray,
  9889. set: function ( origin, direction ) {
  9890. this.origin.copy( origin );
  9891. this.direction.copy( direction );
  9892. return this;
  9893. },
  9894. clone: function () {
  9895. return new this.constructor().copy( this );
  9896. },
  9897. copy: function ( ray ) {
  9898. this.origin.copy( ray.origin );
  9899. this.direction.copy( ray.direction );
  9900. return this;
  9901. },
  9902. at: function ( t, optionalTarget ) {
  9903. var result = optionalTarget || new Vector3();
  9904. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  9905. },
  9906. lookAt: function ( v ) {
  9907. this.direction.copy( v ).sub( this.origin ).normalize();
  9908. return this;
  9909. },
  9910. recast: function () {
  9911. var v1 = new Vector3();
  9912. return function recast( t ) {
  9913. this.origin.copy( this.at( t, v1 ) );
  9914. return this;
  9915. };
  9916. }(),
  9917. closestPointToPoint: function ( point, optionalTarget ) {
  9918. var result = optionalTarget || new Vector3();
  9919. result.subVectors( point, this.origin );
  9920. var directionDistance = result.dot( this.direction );
  9921. if ( directionDistance < 0 ) {
  9922. return result.copy( this.origin );
  9923. }
  9924. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  9925. },
  9926. distanceToPoint: function ( point ) {
  9927. return Math.sqrt( this.distanceSqToPoint( point ) );
  9928. },
  9929. distanceSqToPoint: function () {
  9930. var v1 = new Vector3();
  9931. return function distanceSqToPoint( point ) {
  9932. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  9933. // point behind the ray
  9934. if ( directionDistance < 0 ) {
  9935. return this.origin.distanceToSquared( point );
  9936. }
  9937. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  9938. return v1.distanceToSquared( point );
  9939. };
  9940. }(),
  9941. distanceSqToSegment: function () {
  9942. var segCenter = new Vector3();
  9943. var segDir = new Vector3();
  9944. var diff = new Vector3();
  9945. return function distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  9946. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  9947. // It returns the min distance between the ray and the segment
  9948. // defined by v0 and v1
  9949. // It can also set two optional targets :
  9950. // - The closest point on the ray
  9951. // - The closest point on the segment
  9952. segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  9953. segDir.copy( v1 ).sub( v0 ).normalize();
  9954. diff.copy( this.origin ).sub( segCenter );
  9955. var segExtent = v0.distanceTo( v1 ) * 0.5;
  9956. var a01 = - this.direction.dot( segDir );
  9957. var b0 = diff.dot( this.direction );
  9958. var b1 = - diff.dot( segDir );
  9959. var c = diff.lengthSq();
  9960. var det = Math.abs( 1 - a01 * a01 );
  9961. var s0, s1, sqrDist, extDet;
  9962. if ( det > 0 ) {
  9963. // The ray and segment are not parallel.
  9964. s0 = a01 * b1 - b0;
  9965. s1 = a01 * b0 - b1;
  9966. extDet = segExtent * det;
  9967. if ( s0 >= 0 ) {
  9968. if ( s1 >= - extDet ) {
  9969. if ( s1 <= extDet ) {
  9970. // region 0
  9971. // Minimum at interior points of ray and segment.
  9972. var invDet = 1 / det;
  9973. s0 *= invDet;
  9974. s1 *= invDet;
  9975. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  9976. } else {
  9977. // region 1
  9978. s1 = segExtent;
  9979. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  9980. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9981. }
  9982. } else {
  9983. // region 5
  9984. s1 = - segExtent;
  9985. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  9986. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9987. }
  9988. } else {
  9989. if ( s1 <= - extDet ) {
  9990. // region 4
  9991. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  9992. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  9993. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9994. } else if ( s1 <= extDet ) {
  9995. // region 3
  9996. s0 = 0;
  9997. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  9998. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  9999. } else {
  10000. // region 2
  10001. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  10002. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  10003. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  10004. }
  10005. }
  10006. } else {
  10007. // Ray and segment are parallel.
  10008. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  10009. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  10010. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  10011. }
  10012. if ( optionalPointOnRay ) {
  10013. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  10014. }
  10015. if ( optionalPointOnSegment ) {
  10016. optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter );
  10017. }
  10018. return sqrDist;
  10019. };
  10020. }(),
  10021. intersectSphere: function () {
  10022. var v1 = new Vector3();
  10023. return function intersectSphere( sphere, optionalTarget ) {
  10024. v1.subVectors( sphere.center, this.origin );
  10025. var tca = v1.dot( this.direction );
  10026. var d2 = v1.dot( v1 ) - tca * tca;
  10027. var radius2 = sphere.radius * sphere.radius;
  10028. if ( d2 > radius2 ) return null;
  10029. var thc = Math.sqrt( radius2 - d2 );
  10030. // t0 = first intersect point - entrance on front of sphere
  10031. var t0 = tca - thc;
  10032. // t1 = second intersect point - exit point on back of sphere
  10033. var t1 = tca + thc;
  10034. // test to see if both t0 and t1 are behind the ray - if so, return null
  10035. if ( t0 < 0 && t1 < 0 ) return null;
  10036. // test to see if t0 is behind the ray:
  10037. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  10038. // in order to always return an intersect point that is in front of the ray.
  10039. if ( t0 < 0 ) return this.at( t1, optionalTarget );
  10040. // else t0 is in front of the ray, so return the first collision point scaled by t0
  10041. return this.at( t0, optionalTarget );
  10042. };
  10043. }(),
  10044. intersectsSphere: function ( sphere ) {
  10045. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  10046. },
  10047. distanceToPlane: function ( plane ) {
  10048. var denominator = plane.normal.dot( this.direction );
  10049. if ( denominator === 0 ) {
  10050. // line is coplanar, return origin
  10051. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  10052. return 0;
  10053. }
  10054. // Null is preferable to undefined since undefined means.... it is undefined
  10055. return null;
  10056. }
  10057. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  10058. // Return if the ray never intersects the plane
  10059. return t >= 0 ? t : null;
  10060. },
  10061. intersectPlane: function ( plane, optionalTarget ) {
  10062. var t = this.distanceToPlane( plane );
  10063. if ( t === null ) {
  10064. return null;
  10065. }
  10066. return this.at( t, optionalTarget );
  10067. },
  10068. intersectsPlane: function ( plane ) {
  10069. // check if the ray lies on the plane first
  10070. var distToPoint = plane.distanceToPoint( this.origin );
  10071. if ( distToPoint === 0 ) {
  10072. return true;
  10073. }
  10074. var denominator = plane.normal.dot( this.direction );
  10075. if ( denominator * distToPoint < 0 ) {
  10076. return true;
  10077. }
  10078. // ray origin is behind the plane (and is pointing behind it)
  10079. return false;
  10080. },
  10081. intersectBox: function ( box, optionalTarget ) {
  10082. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  10083. var invdirx = 1 / this.direction.x,
  10084. invdiry = 1 / this.direction.y,
  10085. invdirz = 1 / this.direction.z;
  10086. var origin = this.origin;
  10087. if ( invdirx >= 0 ) {
  10088. tmin = ( box.min.x - origin.x ) * invdirx;
  10089. tmax = ( box.max.x - origin.x ) * invdirx;
  10090. } else {
  10091. tmin = ( box.max.x - origin.x ) * invdirx;
  10092. tmax = ( box.min.x - origin.x ) * invdirx;
  10093. }
  10094. if ( invdiry >= 0 ) {
  10095. tymin = ( box.min.y - origin.y ) * invdiry;
  10096. tymax = ( box.max.y - origin.y ) * invdiry;
  10097. } else {
  10098. tymin = ( box.max.y - origin.y ) * invdiry;
  10099. tymax = ( box.min.y - origin.y ) * invdiry;
  10100. }
  10101. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  10102. // These lines also handle the case where tmin or tmax is NaN
  10103. // (result of 0 * Infinity). x !== x returns true if x is NaN
  10104. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  10105. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  10106. if ( invdirz >= 0 ) {
  10107. tzmin = ( box.min.z - origin.z ) * invdirz;
  10108. tzmax = ( box.max.z - origin.z ) * invdirz;
  10109. } else {
  10110. tzmin = ( box.max.z - origin.z ) * invdirz;
  10111. tzmax = ( box.min.z - origin.z ) * invdirz;
  10112. }
  10113. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  10114. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  10115. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  10116. //return point closest to the ray (positive side)
  10117. if ( tmax < 0 ) return null;
  10118. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  10119. },
  10120. intersectsBox: ( function () {
  10121. var v = new Vector3();
  10122. return function intersectsBox( box ) {
  10123. return this.intersectBox( box, v ) !== null;
  10124. };
  10125. } )(),
  10126. intersectTriangle: function () {
  10127. // Compute the offset origin, edges, and normal.
  10128. var diff = new Vector3();
  10129. var edge1 = new Vector3();
  10130. var edge2 = new Vector3();
  10131. var normal = new Vector3();
  10132. return function intersectTriangle( a, b, c, backfaceCulling, optionalTarget ) {
  10133. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  10134. edge1.subVectors( b, a );
  10135. edge2.subVectors( c, a );
  10136. normal.crossVectors( edge1, edge2 );
  10137. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  10138. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  10139. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  10140. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  10141. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  10142. var DdN = this.direction.dot( normal );
  10143. var sign;
  10144. if ( DdN > 0 ) {
  10145. if ( backfaceCulling ) return null;
  10146. sign = 1;
  10147. } else if ( DdN < 0 ) {
  10148. sign = - 1;
  10149. DdN = - DdN;
  10150. } else {
  10151. return null;
  10152. }
  10153. diff.subVectors( this.origin, a );
  10154. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  10155. // b1 < 0, no intersection
  10156. if ( DdQxE2 < 0 ) {
  10157. return null;
  10158. }
  10159. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  10160. // b2 < 0, no intersection
  10161. if ( DdE1xQ < 0 ) {
  10162. return null;
  10163. }
  10164. // b1+b2 > 1, no intersection
  10165. if ( DdQxE2 + DdE1xQ > DdN ) {
  10166. return null;
  10167. }
  10168. // Line intersects triangle, check if ray does.
  10169. var QdN = - sign * diff.dot( normal );
  10170. // t < 0, no intersection
  10171. if ( QdN < 0 ) {
  10172. return null;
  10173. }
  10174. // Ray intersects triangle.
  10175. return this.at( QdN / DdN, optionalTarget );
  10176. };
  10177. }(),
  10178. applyMatrix4: function ( matrix4 ) {
  10179. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  10180. this.origin.applyMatrix4( matrix4 );
  10181. this.direction.sub( this.origin );
  10182. this.direction.normalize();
  10183. return this;
  10184. },
  10185. equals: function ( ray ) {
  10186. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  10187. }
  10188. };
  10189. /**
  10190. * @author mrdoob / http://mrdoob.com/
  10191. * @author WestLangley / http://github.com/WestLangley
  10192. * @author bhouston / http://clara.io
  10193. */
  10194. function Euler( x, y, z, order ) {
  10195. this._x = x || 0;
  10196. this._y = y || 0;
  10197. this._z = z || 0;
  10198. this._order = order || Euler.DefaultOrder;
  10199. }
  10200. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  10201. Euler.DefaultOrder = 'XYZ';
  10202. Euler.prototype = {
  10203. constructor: Euler,
  10204. isEuler: true,
  10205. get x () {
  10206. return this._x;
  10207. },
  10208. set x ( value ) {
  10209. this._x = value;
  10210. this.onChangeCallback();
  10211. },
  10212. get y () {
  10213. return this._y;
  10214. },
  10215. set y ( value ) {
  10216. this._y = value;
  10217. this.onChangeCallback();
  10218. },
  10219. get z () {
  10220. return this._z;
  10221. },
  10222. set z ( value ) {
  10223. this._z = value;
  10224. this.onChangeCallback();
  10225. },
  10226. get order () {
  10227. return this._order;
  10228. },
  10229. set order ( value ) {
  10230. this._order = value;
  10231. this.onChangeCallback();
  10232. },
  10233. set: function ( x, y, z, order ) {
  10234. this._x = x;
  10235. this._y = y;
  10236. this._z = z;
  10237. this._order = order || this._order;
  10238. this.onChangeCallback();
  10239. return this;
  10240. },
  10241. clone: function () {
  10242. return new this.constructor( this._x, this._y, this._z, this._order );
  10243. },
  10244. copy: function ( euler ) {
  10245. this._x = euler._x;
  10246. this._y = euler._y;
  10247. this._z = euler._z;
  10248. this._order = euler._order;
  10249. this.onChangeCallback();
  10250. return this;
  10251. },
  10252. setFromRotationMatrix: function ( m, order, update ) {
  10253. var clamp = _Math.clamp;
  10254. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  10255. var te = m.elements;
  10256. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  10257. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  10258. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  10259. order = order || this._order;
  10260. if ( order === 'XYZ' ) {
  10261. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  10262. if ( Math.abs( m13 ) < 0.99999 ) {
  10263. this._x = Math.atan2( - m23, m33 );
  10264. this._z = Math.atan2( - m12, m11 );
  10265. } else {
  10266. this._x = Math.atan2( m32, m22 );
  10267. this._z = 0;
  10268. }
  10269. } else if ( order === 'YXZ' ) {
  10270. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  10271. if ( Math.abs( m23 ) < 0.99999 ) {
  10272. this._y = Math.atan2( m13, m33 );
  10273. this._z = Math.atan2( m21, m22 );
  10274. } else {
  10275. this._y = Math.atan2( - m31, m11 );
  10276. this._z = 0;
  10277. }
  10278. } else if ( order === 'ZXY' ) {
  10279. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  10280. if ( Math.abs( m32 ) < 0.99999 ) {
  10281. this._y = Math.atan2( - m31, m33 );
  10282. this._z = Math.atan2( - m12, m22 );
  10283. } else {
  10284. this._y = 0;
  10285. this._z = Math.atan2( m21, m11 );
  10286. }
  10287. } else if ( order === 'ZYX' ) {
  10288. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  10289. if ( Math.abs( m31 ) < 0.99999 ) {
  10290. this._x = Math.atan2( m32, m33 );
  10291. this._z = Math.atan2( m21, m11 );
  10292. } else {
  10293. this._x = 0;
  10294. this._z = Math.atan2( - m12, m22 );
  10295. }
  10296. } else if ( order === 'YZX' ) {
  10297. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  10298. if ( Math.abs( m21 ) < 0.99999 ) {
  10299. this._x = Math.atan2( - m23, m22 );
  10300. this._y = Math.atan2( - m31, m11 );
  10301. } else {
  10302. this._x = 0;
  10303. this._y = Math.atan2( m13, m33 );
  10304. }
  10305. } else if ( order === 'XZY' ) {
  10306. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  10307. if ( Math.abs( m12 ) < 0.99999 ) {
  10308. this._x = Math.atan2( m32, m22 );
  10309. this._y = Math.atan2( m13, m11 );
  10310. } else {
  10311. this._x = Math.atan2( - m23, m33 );
  10312. this._y = 0;
  10313. }
  10314. } else {
  10315. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order );
  10316. }
  10317. this._order = order;
  10318. if ( update !== false ) this.onChangeCallback();
  10319. return this;
  10320. },
  10321. setFromQuaternion: function () {
  10322. var matrix;
  10323. return function setFromQuaternion( q, order, update ) {
  10324. if ( matrix === undefined ) matrix = new Matrix4();
  10325. matrix.makeRotationFromQuaternion( q );
  10326. return this.setFromRotationMatrix( matrix, order, update );
  10327. };
  10328. }(),
  10329. setFromVector3: function ( v, order ) {
  10330. return this.set( v.x, v.y, v.z, order || this._order );
  10331. },
  10332. reorder: function () {
  10333. // WARNING: this discards revolution information -bhouston
  10334. var q = new Quaternion();
  10335. return function reorder( newOrder ) {
  10336. q.setFromEuler( this );
  10337. return this.setFromQuaternion( q, newOrder );
  10338. };
  10339. }(),
  10340. equals: function ( euler ) {
  10341. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  10342. },
  10343. fromArray: function ( array ) {
  10344. this._x = array[ 0 ];
  10345. this._y = array[ 1 ];
  10346. this._z = array[ 2 ];
  10347. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  10348. this.onChangeCallback();
  10349. return this;
  10350. },
  10351. toArray: function ( array, offset ) {
  10352. if ( array === undefined ) array = [];
  10353. if ( offset === undefined ) offset = 0;
  10354. array[ offset ] = this._x;
  10355. array[ offset + 1 ] = this._y;
  10356. array[ offset + 2 ] = this._z;
  10357. array[ offset + 3 ] = this._order;
  10358. return array;
  10359. },
  10360. toVector3: function ( optionalResult ) {
  10361. if ( optionalResult ) {
  10362. return optionalResult.set( this._x, this._y, this._z );
  10363. } else {
  10364. return new Vector3( this._x, this._y, this._z );
  10365. }
  10366. },
  10367. onChange: function ( callback ) {
  10368. this.onChangeCallback = callback;
  10369. return this;
  10370. },
  10371. onChangeCallback: function () {}
  10372. };
  10373. /**
  10374. * @author mrdoob / http://mrdoob.com/
  10375. */
  10376. function Layers() {
  10377. this.mask = 1;
  10378. }
  10379. Layers.prototype = {
  10380. constructor: Layers,
  10381. set: function ( channel ) {
  10382. this.mask = 1 << channel;
  10383. },
  10384. enable: function ( channel ) {
  10385. this.mask |= 1 << channel;
  10386. },
  10387. toggle: function ( channel ) {
  10388. this.mask ^= 1 << channel;
  10389. },
  10390. disable: function ( channel ) {
  10391. this.mask &= ~ ( 1 << channel );
  10392. },
  10393. test: function ( layers ) {
  10394. return ( this.mask & layers.mask ) !== 0;
  10395. }
  10396. };
  10397. /**
  10398. * @author mrdoob / http://mrdoob.com/
  10399. * @author mikael emtinger / http://gomo.se/
  10400. * @author alteredq / http://alteredqualia.com/
  10401. * @author WestLangley / http://github.com/WestLangley
  10402. * @author elephantatwork / www.elephantatwork.ch
  10403. */
  10404. var object3DId = 0;
  10405. function Object3D() {
  10406. Object.defineProperty( this, 'id', { value: object3DId ++ } );
  10407. this.uuid = _Math.generateUUID();
  10408. this.name = '';
  10409. this.type = 'Object3D';
  10410. this.parent = null;
  10411. this.children = [];
  10412. this.up = Object3D.DefaultUp.clone();
  10413. var position = new Vector3();
  10414. var rotation = new Euler();
  10415. var quaternion = new Quaternion();
  10416. var scale = new Vector3( 1, 1, 1 );
  10417. function onRotationChange() {
  10418. quaternion.setFromEuler( rotation, false );
  10419. }
  10420. function onQuaternionChange() {
  10421. rotation.setFromQuaternion( quaternion, undefined, false );
  10422. }
  10423. rotation.onChange( onRotationChange );
  10424. quaternion.onChange( onQuaternionChange );
  10425. Object.defineProperties( this, {
  10426. position: {
  10427. enumerable: true,
  10428. value: position
  10429. },
  10430. rotation: {
  10431. enumerable: true,
  10432. value: rotation
  10433. },
  10434. quaternion: {
  10435. enumerable: true,
  10436. value: quaternion
  10437. },
  10438. scale: {
  10439. enumerable: true,
  10440. value: scale
  10441. },
  10442. modelViewMatrix: {
  10443. value: new Matrix4()
  10444. },
  10445. normalMatrix: {
  10446. value: new Matrix3()
  10447. }
  10448. } );
  10449. this.matrix = new Matrix4();
  10450. this.matrixWorld = new Matrix4();
  10451. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  10452. this.matrixWorldNeedsUpdate = false;
  10453. this.layers = new Layers();
  10454. this.visible = true;
  10455. this.castShadow = false;
  10456. this.receiveShadow = false;
  10457. this.frustumCulled = true;
  10458. this.renderOrder = 0;
  10459. this.userData = {};
  10460. this.onBeforeRender = function () {};
  10461. this.onAfterRender = function () {};
  10462. }
  10463. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  10464. Object3D.DefaultMatrixAutoUpdate = true;
  10465. Object3D.prototype = {
  10466. constructor: Object3D,
  10467. isObject3D: true,
  10468. applyMatrix: function ( matrix ) {
  10469. this.matrix.multiplyMatrices( matrix, this.matrix );
  10470. this.matrix.decompose( this.position, this.quaternion, this.scale );
  10471. },
  10472. setRotationFromAxisAngle: function ( axis, angle ) {
  10473. // assumes axis is normalized
  10474. this.quaternion.setFromAxisAngle( axis, angle );
  10475. },
  10476. setRotationFromEuler: function ( euler ) {
  10477. this.quaternion.setFromEuler( euler, true );
  10478. },
  10479. setRotationFromMatrix: function ( m ) {
  10480. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  10481. this.quaternion.setFromRotationMatrix( m );
  10482. },
  10483. setRotationFromQuaternion: function ( q ) {
  10484. // assumes q is normalized
  10485. this.quaternion.copy( q );
  10486. },
  10487. rotateOnAxis: function () {
  10488. // rotate object on axis in object space
  10489. // axis is assumed to be normalized
  10490. var q1 = new Quaternion();
  10491. return function rotateOnAxis( axis, angle ) {
  10492. q1.setFromAxisAngle( axis, angle );
  10493. this.quaternion.multiply( q1 );
  10494. return this;
  10495. };
  10496. }(),
  10497. rotateX: function () {
  10498. var v1 = new Vector3( 1, 0, 0 );
  10499. return function rotateX( angle ) {
  10500. return this.rotateOnAxis( v1, angle );
  10501. };
  10502. }(),
  10503. rotateY: function () {
  10504. var v1 = new Vector3( 0, 1, 0 );
  10505. return function rotateY( angle ) {
  10506. return this.rotateOnAxis( v1, angle );
  10507. };
  10508. }(),
  10509. rotateZ: function () {
  10510. var v1 = new Vector3( 0, 0, 1 );
  10511. return function rotateZ( angle ) {
  10512. return this.rotateOnAxis( v1, angle );
  10513. };
  10514. }(),
  10515. translateOnAxis: function () {
  10516. // translate object by distance along axis in object space
  10517. // axis is assumed to be normalized
  10518. var v1 = new Vector3();
  10519. return function translateOnAxis( axis, distance ) {
  10520. v1.copy( axis ).applyQuaternion( this.quaternion );
  10521. this.position.add( v1.multiplyScalar( distance ) );
  10522. return this;
  10523. };
  10524. }(),
  10525. translateX: function () {
  10526. var v1 = new Vector3( 1, 0, 0 );
  10527. return function translateX( distance ) {
  10528. return this.translateOnAxis( v1, distance );
  10529. };
  10530. }(),
  10531. translateY: function () {
  10532. var v1 = new Vector3( 0, 1, 0 );
  10533. return function translateY( distance ) {
  10534. return this.translateOnAxis( v1, distance );
  10535. };
  10536. }(),
  10537. translateZ: function () {
  10538. var v1 = new Vector3( 0, 0, 1 );
  10539. return function translateZ( distance ) {
  10540. return this.translateOnAxis( v1, distance );
  10541. };
  10542. }(),
  10543. localToWorld: function ( vector ) {
  10544. return vector.applyMatrix4( this.matrixWorld );
  10545. },
  10546. worldToLocal: function () {
  10547. var m1 = new Matrix4();
  10548. return function worldToLocal( vector ) {
  10549. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  10550. };
  10551. }(),
  10552. lookAt: function () {
  10553. // This routine does not support objects with rotated and/or translated parent(s)
  10554. var m1 = new Matrix4();
  10555. return function lookAt( vector ) {
  10556. m1.lookAt( vector, this.position, this.up );
  10557. this.quaternion.setFromRotationMatrix( m1 );
  10558. };
  10559. }(),
  10560. add: function ( object ) {
  10561. if ( arguments.length > 1 ) {
  10562. for ( var i = 0; i < arguments.length; i ++ ) {
  10563. this.add( arguments[ i ] );
  10564. }
  10565. return this;
  10566. }
  10567. if ( object === this ) {
  10568. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  10569. return this;
  10570. }
  10571. if ( ( object && object.isObject3D ) ) {
  10572. if ( object.parent !== null ) {
  10573. object.parent.remove( object );
  10574. }
  10575. object.parent = this;
  10576. object.dispatchEvent( { type: 'added' } );
  10577. this.children.push( object );
  10578. } else {
  10579. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  10580. }
  10581. return this;
  10582. },
  10583. remove: function ( object ) {
  10584. if ( arguments.length > 1 ) {
  10585. for ( var i = 0; i < arguments.length; i ++ ) {
  10586. this.remove( arguments[ i ] );
  10587. }
  10588. }
  10589. var index = this.children.indexOf( object );
  10590. if ( index !== - 1 ) {
  10591. object.parent = null;
  10592. object.dispatchEvent( { type: 'removed' } );
  10593. this.children.splice( index, 1 );
  10594. }
  10595. },
  10596. getObjectById: function ( id ) {
  10597. return this.getObjectByProperty( 'id', id );
  10598. },
  10599. getObjectByName: function ( name ) {
  10600. return this.getObjectByProperty( 'name', name );
  10601. },
  10602. getObjectByProperty: function ( name, value ) {
  10603. if ( this[ name ] === value ) return this;
  10604. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  10605. var child = this.children[ i ];
  10606. var object = child.getObjectByProperty( name, value );
  10607. if ( object !== undefined ) {
  10608. return object;
  10609. }
  10610. }
  10611. return undefined;
  10612. },
  10613. getWorldPosition: function ( optionalTarget ) {
  10614. var result = optionalTarget || new Vector3();
  10615. this.updateMatrixWorld( true );
  10616. return result.setFromMatrixPosition( this.matrixWorld );
  10617. },
  10618. getWorldQuaternion: function () {
  10619. var position = new Vector3();
  10620. var scale = new Vector3();
  10621. return function getWorldQuaternion( optionalTarget ) {
  10622. var result = optionalTarget || new Quaternion();
  10623. this.updateMatrixWorld( true );
  10624. this.matrixWorld.decompose( position, result, scale );
  10625. return result;
  10626. };
  10627. }(),
  10628. getWorldRotation: function () {
  10629. var quaternion = new Quaternion();
  10630. return function getWorldRotation( optionalTarget ) {
  10631. var result = optionalTarget || new Euler();
  10632. this.getWorldQuaternion( quaternion );
  10633. return result.setFromQuaternion( quaternion, this.rotation.order, false );
  10634. };
  10635. }(),
  10636. getWorldScale: function () {
  10637. var position = new Vector3();
  10638. var quaternion = new Quaternion();
  10639. return function getWorldScale( optionalTarget ) {
  10640. var result = optionalTarget || new Vector3();
  10641. this.updateMatrixWorld( true );
  10642. this.matrixWorld.decompose( position, quaternion, result );
  10643. return result;
  10644. };
  10645. }(),
  10646. getWorldDirection: function () {
  10647. var quaternion = new Quaternion();
  10648. return function getWorldDirection( optionalTarget ) {
  10649. var result = optionalTarget || new Vector3();
  10650. this.getWorldQuaternion( quaternion );
  10651. return result.set( 0, 0, 1 ).applyQuaternion( quaternion );
  10652. };
  10653. }(),
  10654. raycast: function () {},
  10655. traverse: function ( callback ) {
  10656. callback( this );
  10657. var children = this.children;
  10658. for ( var i = 0, l = children.length; i < l; i ++ ) {
  10659. children[ i ].traverse( callback );
  10660. }
  10661. },
  10662. traverseVisible: function ( callback ) {
  10663. if ( this.visible === false ) return;
  10664. callback( this );
  10665. var children = this.children;
  10666. for ( var i = 0, l = children.length; i < l; i ++ ) {
  10667. children[ i ].traverseVisible( callback );
  10668. }
  10669. },
  10670. traverseAncestors: function ( callback ) {
  10671. var parent = this.parent;
  10672. if ( parent !== null ) {
  10673. callback( parent );
  10674. parent.traverseAncestors( callback );
  10675. }
  10676. },
  10677. updateMatrix: function () {
  10678. this.matrix.compose( this.position, this.quaternion, this.scale );
  10679. this.matrixWorldNeedsUpdate = true;
  10680. },
  10681. updateMatrixWorld: function ( force ) {
  10682. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  10683. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  10684. if ( this.parent === null ) {
  10685. this.matrixWorld.copy( this.matrix );
  10686. } else {
  10687. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10688. }
  10689. this.matrixWorldNeedsUpdate = false;
  10690. force = true;
  10691. }
  10692. // update children
  10693. var children = this.children;
  10694. for ( var i = 0, l = children.length; i < l; i ++ ) {
  10695. children[ i ].updateMatrixWorld( force );
  10696. }
  10697. },
  10698. toJSON: function ( meta ) {
  10699. // meta is '' when called from JSON.stringify
  10700. var isRootObject = ( meta === undefined || meta === '' );
  10701. var output = {};
  10702. // meta is a hash used to collect geometries, materials.
  10703. // not providing it implies that this is the root object
  10704. // being serialized.
  10705. if ( isRootObject ) {
  10706. // initialize meta obj
  10707. meta = {
  10708. geometries: {},
  10709. materials: {},
  10710. textures: {},
  10711. images: {}
  10712. };
  10713. output.metadata = {
  10714. version: 4.4,
  10715. type: 'Object',
  10716. generator: 'Object3D.toJSON'
  10717. };
  10718. }
  10719. // standard Object3D serialization
  10720. var object = {};
  10721. object.uuid = this.uuid;
  10722. object.type = this.type;
  10723. if ( this.name !== '' ) object.name = this.name;
  10724. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  10725. if ( this.castShadow === true ) object.castShadow = true;
  10726. if ( this.receiveShadow === true ) object.receiveShadow = true;
  10727. if ( this.visible === false ) object.visible = false;
  10728. object.matrix = this.matrix.toArray();
  10729. //
  10730. if ( this.geometry !== undefined ) {
  10731. if ( meta.geometries[ this.geometry.uuid ] === undefined ) {
  10732. meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON( meta );
  10733. }
  10734. object.geometry = this.geometry.uuid;
  10735. }
  10736. if ( this.material !== undefined ) {
  10737. if ( meta.materials[ this.material.uuid ] === undefined ) {
  10738. meta.materials[ this.material.uuid ] = this.material.toJSON( meta );
  10739. }
  10740. object.material = this.material.uuid;
  10741. }
  10742. //
  10743. if ( this.children.length > 0 ) {
  10744. object.children = [];
  10745. for ( var i = 0; i < this.children.length; i ++ ) {
  10746. object.children.push( this.children[ i ].toJSON( meta ).object );
  10747. }
  10748. }
  10749. if ( isRootObject ) {
  10750. var geometries = extractFromCache( meta.geometries );
  10751. var materials = extractFromCache( meta.materials );
  10752. var textures = extractFromCache( meta.textures );
  10753. var images = extractFromCache( meta.images );
  10754. if ( geometries.length > 0 ) output.geometries = geometries;
  10755. if ( materials.length > 0 ) output.materials = materials;
  10756. if ( textures.length > 0 ) output.textures = textures;
  10757. if ( images.length > 0 ) output.images = images;
  10758. }
  10759. output.object = object;
  10760. return output;
  10761. // extract data from the cache hash
  10762. // remove metadata on each item
  10763. // and return as array
  10764. function extractFromCache( cache ) {
  10765. var values = [];
  10766. for ( var key in cache ) {
  10767. var data = cache[ key ];
  10768. delete data.metadata;
  10769. values.push( data );
  10770. }
  10771. return values;
  10772. }
  10773. },
  10774. clone: function ( recursive ) {
  10775. return new this.constructor().copy( this, recursive );
  10776. },
  10777. copy: function ( source, recursive ) {
  10778. if ( recursive === undefined ) recursive = true;
  10779. this.name = source.name;
  10780. this.up.copy( source.up );
  10781. this.position.copy( source.position );
  10782. this.quaternion.copy( source.quaternion );
  10783. this.scale.copy( source.scale );
  10784. this.matrix.copy( source.matrix );
  10785. this.matrixWorld.copy( source.matrixWorld );
  10786. this.matrixAutoUpdate = source.matrixAutoUpdate;
  10787. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  10788. this.layers.mask = source.layers.mask;
  10789. this.visible = source.visible;
  10790. this.castShadow = source.castShadow;
  10791. this.receiveShadow = source.receiveShadow;
  10792. this.frustumCulled = source.frustumCulled;
  10793. this.renderOrder = source.renderOrder;
  10794. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  10795. if ( recursive === true ) {
  10796. for ( var i = 0; i < source.children.length; i ++ ) {
  10797. var child = source.children[ i ];
  10798. this.add( child.clone() );
  10799. }
  10800. }
  10801. return this;
  10802. }
  10803. };
  10804. Object.assign( Object3D.prototype, EventDispatcher.prototype );
  10805. /**
  10806. * @author bhouston / http://clara.io
  10807. */
  10808. function Line3( start, end ) {
  10809. this.start = ( start !== undefined ) ? start : new Vector3();
  10810. this.end = ( end !== undefined ) ? end : new Vector3();
  10811. }
  10812. Line3.prototype = {
  10813. constructor: Line3,
  10814. set: function ( start, end ) {
  10815. this.start.copy( start );
  10816. this.end.copy( end );
  10817. return this;
  10818. },
  10819. clone: function () {
  10820. return new this.constructor().copy( this );
  10821. },
  10822. copy: function ( line ) {
  10823. this.start.copy( line.start );
  10824. this.end.copy( line.end );
  10825. return this;
  10826. },
  10827. getCenter: function ( optionalTarget ) {
  10828. var result = optionalTarget || new Vector3();
  10829. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  10830. },
  10831. delta: function ( optionalTarget ) {
  10832. var result = optionalTarget || new Vector3();
  10833. return result.subVectors( this.end, this.start );
  10834. },
  10835. distanceSq: function () {
  10836. return this.start.distanceToSquared( this.end );
  10837. },
  10838. distance: function () {
  10839. return this.start.distanceTo( this.end );
  10840. },
  10841. at: function ( t, optionalTarget ) {
  10842. var result = optionalTarget || new Vector3();
  10843. return this.delta( result ).multiplyScalar( t ).add( this.start );
  10844. },
  10845. closestPointToPointParameter: function () {
  10846. var startP = new Vector3();
  10847. var startEnd = new Vector3();
  10848. return function closestPointToPointParameter( point, clampToLine ) {
  10849. startP.subVectors( point, this.start );
  10850. startEnd.subVectors( this.end, this.start );
  10851. var startEnd2 = startEnd.dot( startEnd );
  10852. var startEnd_startP = startEnd.dot( startP );
  10853. var t = startEnd_startP / startEnd2;
  10854. if ( clampToLine ) {
  10855. t = _Math.clamp( t, 0, 1 );
  10856. }
  10857. return t;
  10858. };
  10859. }(),
  10860. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  10861. var t = this.closestPointToPointParameter( point, clampToLine );
  10862. var result = optionalTarget || new Vector3();
  10863. return this.delta( result ).multiplyScalar( t ).add( this.start );
  10864. },
  10865. applyMatrix4: function ( matrix ) {
  10866. this.start.applyMatrix4( matrix );
  10867. this.end.applyMatrix4( matrix );
  10868. return this;
  10869. },
  10870. equals: function ( line ) {
  10871. return line.start.equals( this.start ) && line.end.equals( this.end );
  10872. }
  10873. };
  10874. /**
  10875. * @author bhouston / http://clara.io
  10876. * @author mrdoob / http://mrdoob.com/
  10877. */
  10878. function Triangle( a, b, c ) {
  10879. this.a = ( a !== undefined ) ? a : new Vector3();
  10880. this.b = ( b !== undefined ) ? b : new Vector3();
  10881. this.c = ( c !== undefined ) ? c : new Vector3();
  10882. }
  10883. Triangle.normal = function () {
  10884. var v0 = new Vector3();
  10885. return function normal( a, b, c, optionalTarget ) {
  10886. var result = optionalTarget || new Vector3();
  10887. result.subVectors( c, b );
  10888. v0.subVectors( a, b );
  10889. result.cross( v0 );
  10890. var resultLengthSq = result.lengthSq();
  10891. if ( resultLengthSq > 0 ) {
  10892. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  10893. }
  10894. return result.set( 0, 0, 0 );
  10895. };
  10896. }();
  10897. // static/instance method to calculate barycentric coordinates
  10898. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  10899. Triangle.barycoordFromPoint = function () {
  10900. var v0 = new Vector3();
  10901. var v1 = new Vector3();
  10902. var v2 = new Vector3();
  10903. return function barycoordFromPoint( point, a, b, c, optionalTarget ) {
  10904. v0.subVectors( c, a );
  10905. v1.subVectors( b, a );
  10906. v2.subVectors( point, a );
  10907. var dot00 = v0.dot( v0 );
  10908. var dot01 = v0.dot( v1 );
  10909. var dot02 = v0.dot( v2 );
  10910. var dot11 = v1.dot( v1 );
  10911. var dot12 = v1.dot( v2 );
  10912. var denom = ( dot00 * dot11 - dot01 * dot01 );
  10913. var result = optionalTarget || new Vector3();
  10914. // collinear or singular triangle
  10915. if ( denom === 0 ) {
  10916. // arbitrary location outside of triangle?
  10917. // not sure if this is the best idea, maybe should be returning undefined
  10918. return result.set( - 2, - 1, - 1 );
  10919. }
  10920. var invDenom = 1 / denom;
  10921. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  10922. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  10923. // barycentric coordinates must always sum to 1
  10924. return result.set( 1 - u - v, v, u );
  10925. };
  10926. }();
  10927. Triangle.containsPoint = function () {
  10928. var v1 = new Vector3();
  10929. return function containsPoint( point, a, b, c ) {
  10930. var result = Triangle.barycoordFromPoint( point, a, b, c, v1 );
  10931. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  10932. };
  10933. }();
  10934. Triangle.prototype = {
  10935. constructor: Triangle,
  10936. set: function ( a, b, c ) {
  10937. this.a.copy( a );
  10938. this.b.copy( b );
  10939. this.c.copy( c );
  10940. return this;
  10941. },
  10942. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  10943. this.a.copy( points[ i0 ] );
  10944. this.b.copy( points[ i1 ] );
  10945. this.c.copy( points[ i2 ] );
  10946. return this;
  10947. },
  10948. clone: function () {
  10949. return new this.constructor().copy( this );
  10950. },
  10951. copy: function ( triangle ) {
  10952. this.a.copy( triangle.a );
  10953. this.b.copy( triangle.b );
  10954. this.c.copy( triangle.c );
  10955. return this;
  10956. },
  10957. area: function () {
  10958. var v0 = new Vector3();
  10959. var v1 = new Vector3();
  10960. return function area() {
  10961. v0.subVectors( this.c, this.b );
  10962. v1.subVectors( this.a, this.b );
  10963. return v0.cross( v1 ).length() * 0.5;
  10964. };
  10965. }(),
  10966. midpoint: function ( optionalTarget ) {
  10967. var result = optionalTarget || new Vector3();
  10968. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  10969. },
  10970. normal: function ( optionalTarget ) {
  10971. return Triangle.normal( this.a, this.b, this.c, optionalTarget );
  10972. },
  10973. plane: function ( optionalTarget ) {
  10974. var result = optionalTarget || new Plane();
  10975. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  10976. },
  10977. barycoordFromPoint: function ( point, optionalTarget ) {
  10978. return Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  10979. },
  10980. containsPoint: function ( point ) {
  10981. return Triangle.containsPoint( point, this.a, this.b, this.c );
  10982. },
  10983. closestPointToPoint: function () {
  10984. var plane, edgeList, projectedPoint, closestPoint;
  10985. return function closestPointToPoint( point, optionalTarget ) {
  10986. if ( plane === undefined ) {
  10987. plane = new Plane();
  10988. edgeList = [ new Line3(), new Line3(), new Line3() ];
  10989. projectedPoint = new Vector3();
  10990. closestPoint = new Vector3();
  10991. }
  10992. var result = optionalTarget || new Vector3();
  10993. var minDistance = Infinity;
  10994. // project the point onto the plane of the triangle
  10995. plane.setFromCoplanarPoints( this.a, this.b, this.c );
  10996. plane.projectPoint( point, projectedPoint );
  10997. // check if the projection lies within the triangle
  10998. if( this.containsPoint( projectedPoint ) === true ) {
  10999. // if so, this is the closest point
  11000. result.copy( projectedPoint );
  11001. } else {
  11002. // if not, the point falls outside the triangle. the result is the closest point to the triangle's edges or vertices
  11003. edgeList[ 0 ].set( this.a, this.b );
  11004. edgeList[ 1 ].set( this.b, this.c );
  11005. edgeList[ 2 ].set( this.c, this.a );
  11006. for( var i = 0; i < edgeList.length; i ++ ) {
  11007. edgeList[ i ].closestPointToPoint( projectedPoint, true, closestPoint );
  11008. var distance = projectedPoint.distanceToSquared( closestPoint );
  11009. if( distance < minDistance ) {
  11010. minDistance = distance;
  11011. result.copy( closestPoint );
  11012. }
  11013. }
  11014. }
  11015. return result;
  11016. };
  11017. }(),
  11018. equals: function ( triangle ) {
  11019. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  11020. }
  11021. };
  11022. /**
  11023. * @author mrdoob / http://mrdoob.com/
  11024. * @author alteredq / http://alteredqualia.com/
  11025. */
  11026. function Face3( a, b, c, normal, color, materialIndex ) {
  11027. this.a = a;
  11028. this.b = b;
  11029. this.c = c;
  11030. this.normal = (normal && normal.isVector3) ? normal : new Vector3();
  11031. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  11032. this.color = (color && color.isColor) ? color : new Color();
  11033. this.vertexColors = Array.isArray( color ) ? color : [];
  11034. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  11035. }
  11036. Face3.prototype = {
  11037. constructor: Face3,
  11038. clone: function () {
  11039. return new this.constructor().copy( this );
  11040. },
  11041. copy: function ( source ) {
  11042. this.a = source.a;
  11043. this.b = source.b;
  11044. this.c = source.c;
  11045. this.normal.copy( source.normal );
  11046. this.color.copy( source.color );
  11047. this.materialIndex = source.materialIndex;
  11048. for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  11049. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  11050. }
  11051. for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  11052. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  11053. }
  11054. return this;
  11055. }
  11056. };
  11057. /**
  11058. * @author mrdoob / http://mrdoob.com/
  11059. * @author alteredq / http://alteredqualia.com/
  11060. *
  11061. * parameters = {
  11062. * color: <hex>,
  11063. * opacity: <float>,
  11064. * map: new THREE.Texture( <Image> ),
  11065. *
  11066. * lightMap: new THREE.Texture( <Image> ),
  11067. * lightMapIntensity: <float>
  11068. *
  11069. * aoMap: new THREE.Texture( <Image> ),
  11070. * aoMapIntensity: <float>
  11071. *
  11072. * specularMap: new THREE.Texture( <Image> ),
  11073. *
  11074. * alphaMap: new THREE.Texture( <Image> ),
  11075. *
  11076. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  11077. * combine: THREE.Multiply,
  11078. * reflectivity: <float>,
  11079. * refractionRatio: <float>,
  11080. *
  11081. * shading: THREE.SmoothShading,
  11082. * depthTest: <bool>,
  11083. * depthWrite: <bool>,
  11084. *
  11085. * wireframe: <boolean>,
  11086. * wireframeLinewidth: <float>,
  11087. *
  11088. * skinning: <bool>,
  11089. * morphTargets: <bool>
  11090. * }
  11091. */
  11092. function MeshBasicMaterial( parameters ) {
  11093. Material.call( this );
  11094. this.type = 'MeshBasicMaterial';
  11095. this.color = new Color( 0xffffff ); // emissive
  11096. this.map = null;
  11097. this.lightMap = null;
  11098. this.lightMapIntensity = 1.0;
  11099. this.aoMap = null;
  11100. this.aoMapIntensity = 1.0;
  11101. this.specularMap = null;
  11102. this.alphaMap = null;
  11103. this.envMap = null;
  11104. this.combine = MultiplyOperation;
  11105. this.reflectivity = 1;
  11106. this.refractionRatio = 0.98;
  11107. this.wireframe = false;
  11108. this.wireframeLinewidth = 1;
  11109. this.wireframeLinecap = 'round';
  11110. this.wireframeLinejoin = 'round';
  11111. this.skinning = false;
  11112. this.morphTargets = false;
  11113. this.lights = false;
  11114. this.setValues( parameters );
  11115. }
  11116. MeshBasicMaterial.prototype = Object.create( Material.prototype );
  11117. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  11118. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  11119. MeshBasicMaterial.prototype.copy = function ( source ) {
  11120. Material.prototype.copy.call( this, source );
  11121. this.color.copy( source.color );
  11122. this.map = source.map;
  11123. this.lightMap = source.lightMap;
  11124. this.lightMapIntensity = source.lightMapIntensity;
  11125. this.aoMap = source.aoMap;
  11126. this.aoMapIntensity = source.aoMapIntensity;
  11127. this.specularMap = source.specularMap;
  11128. this.alphaMap = source.alphaMap;
  11129. this.envMap = source.envMap;
  11130. this.combine = source.combine;
  11131. this.reflectivity = source.reflectivity;
  11132. this.refractionRatio = source.refractionRatio;
  11133. this.wireframe = source.wireframe;
  11134. this.wireframeLinewidth = source.wireframeLinewidth;
  11135. this.wireframeLinecap = source.wireframeLinecap;
  11136. this.wireframeLinejoin = source.wireframeLinejoin;
  11137. this.skinning = source.skinning;
  11138. this.morphTargets = source.morphTargets;
  11139. return this;
  11140. };
  11141. /**
  11142. * @author mrdoob / http://mrdoob.com/
  11143. */
  11144. function BufferAttribute( array, itemSize, normalized ) {
  11145. if ( Array.isArray( array ) ) {
  11146. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  11147. }
  11148. this.uuid = _Math.generateUUID();
  11149. this.array = array;
  11150. this.itemSize = itemSize;
  11151. this.count = array !== undefined ? array.length / itemSize : 0;
  11152. this.normalized = normalized === true;
  11153. this.dynamic = false;
  11154. this.updateRange = { offset: 0, count: - 1 };
  11155. this.onUploadCallback = function () {};
  11156. this.version = 0;
  11157. }
  11158. BufferAttribute.prototype = {
  11159. constructor: BufferAttribute,
  11160. isBufferAttribute: true,
  11161. set needsUpdate( value ) {
  11162. if ( value === true ) this.version ++;
  11163. },
  11164. setArray: function ( array ) {
  11165. if ( Array.isArray( array ) ) {
  11166. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  11167. }
  11168. this.count = array !== undefined ? array.length / this.itemSize : 0;
  11169. this.array = array;
  11170. },
  11171. setDynamic: function ( value ) {
  11172. this.dynamic = value;
  11173. return this;
  11174. },
  11175. copy: function ( source ) {
  11176. this.array = new source.array.constructor( source.array );
  11177. this.itemSize = source.itemSize;
  11178. this.count = source.count;
  11179. this.normalized = source.normalized;
  11180. this.dynamic = source.dynamic;
  11181. return this;
  11182. },
  11183. copyAt: function ( index1, attribute, index2 ) {
  11184. index1 *= this.itemSize;
  11185. index2 *= attribute.itemSize;
  11186. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  11187. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  11188. }
  11189. return this;
  11190. },
  11191. copyArray: function ( array ) {
  11192. this.array.set( array );
  11193. return this;
  11194. },
  11195. copyColorsArray: function ( colors ) {
  11196. var array = this.array, offset = 0;
  11197. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  11198. var color = colors[ i ];
  11199. if ( color === undefined ) {
  11200. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  11201. color = new Color();
  11202. }
  11203. array[ offset ++ ] = color.r;
  11204. array[ offset ++ ] = color.g;
  11205. array[ offset ++ ] = color.b;
  11206. }
  11207. return this;
  11208. },
  11209. copyIndicesArray: function ( indices ) {
  11210. var array = this.array, offset = 0;
  11211. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  11212. var index = indices[ i ];
  11213. array[ offset ++ ] = index.a;
  11214. array[ offset ++ ] = index.b;
  11215. array[ offset ++ ] = index.c;
  11216. }
  11217. return this;
  11218. },
  11219. copyVector2sArray: function ( vectors ) {
  11220. var array = this.array, offset = 0;
  11221. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  11222. var vector = vectors[ i ];
  11223. if ( vector === undefined ) {
  11224. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  11225. vector = new Vector2();
  11226. }
  11227. array[ offset ++ ] = vector.x;
  11228. array[ offset ++ ] = vector.y;
  11229. }
  11230. return this;
  11231. },
  11232. copyVector3sArray: function ( vectors ) {
  11233. var array = this.array, offset = 0;
  11234. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  11235. var vector = vectors[ i ];
  11236. if ( vector === undefined ) {
  11237. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  11238. vector = new Vector3();
  11239. }
  11240. array[ offset ++ ] = vector.x;
  11241. array[ offset ++ ] = vector.y;
  11242. array[ offset ++ ] = vector.z;
  11243. }
  11244. return this;
  11245. },
  11246. copyVector4sArray: function ( vectors ) {
  11247. var array = this.array, offset = 0;
  11248. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  11249. var vector = vectors[ i ];
  11250. if ( vector === undefined ) {
  11251. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  11252. vector = new Vector4();
  11253. }
  11254. array[ offset ++ ] = vector.x;
  11255. array[ offset ++ ] = vector.y;
  11256. array[ offset ++ ] = vector.z;
  11257. array[ offset ++ ] = vector.w;
  11258. }
  11259. return this;
  11260. },
  11261. set: function ( value, offset ) {
  11262. if ( offset === undefined ) offset = 0;
  11263. this.array.set( value, offset );
  11264. return this;
  11265. },
  11266. getX: function ( index ) {
  11267. return this.array[ index * this.itemSize ];
  11268. },
  11269. setX: function ( index, x ) {
  11270. this.array[ index * this.itemSize ] = x;
  11271. return this;
  11272. },
  11273. getY: function ( index ) {
  11274. return this.array[ index * this.itemSize + 1 ];
  11275. },
  11276. setY: function ( index, y ) {
  11277. this.array[ index * this.itemSize + 1 ] = y;
  11278. return this;
  11279. },
  11280. getZ: function ( index ) {
  11281. return this.array[ index * this.itemSize + 2 ];
  11282. },
  11283. setZ: function ( index, z ) {
  11284. this.array[ index * this.itemSize + 2 ] = z;
  11285. return this;
  11286. },
  11287. getW: function ( index ) {
  11288. return this.array[ index * this.itemSize + 3 ];
  11289. },
  11290. setW: function ( index, w ) {
  11291. this.array[ index * this.itemSize + 3 ] = w;
  11292. return this;
  11293. },
  11294. setXY: function ( index, x, y ) {
  11295. index *= this.itemSize;
  11296. this.array[ index + 0 ] = x;
  11297. this.array[ index + 1 ] = y;
  11298. return this;
  11299. },
  11300. setXYZ: function ( index, x, y, z ) {
  11301. index *= this.itemSize;
  11302. this.array[ index + 0 ] = x;
  11303. this.array[ index + 1 ] = y;
  11304. this.array[ index + 2 ] = z;
  11305. return this;
  11306. },
  11307. setXYZW: function ( index, x, y, z, w ) {
  11308. index *= this.itemSize;
  11309. this.array[ index + 0 ] = x;
  11310. this.array[ index + 1 ] = y;
  11311. this.array[ index + 2 ] = z;
  11312. this.array[ index + 3 ] = w;
  11313. return this;
  11314. },
  11315. onUpload: function ( callback ) {
  11316. this.onUploadCallback = callback;
  11317. return this;
  11318. },
  11319. clone: function () {
  11320. return new this.constructor( this.array, this.itemSize ).copy( this );
  11321. }
  11322. };
  11323. //
  11324. function Int8BufferAttribute( array, itemSize ) {
  11325. BufferAttribute.call( this, new Int8Array( array ), itemSize );
  11326. }
  11327. Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11328. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  11329. function Uint8BufferAttribute( array, itemSize ) {
  11330. BufferAttribute.call( this, new Uint8Array( array ), itemSize );
  11331. }
  11332. Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11333. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  11334. function Uint8ClampedBufferAttribute( array, itemSize ) {
  11335. BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize );
  11336. }
  11337. Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11338. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  11339. function Int16BufferAttribute( array, itemSize ) {
  11340. BufferAttribute.call( this, new Int16Array( array ), itemSize );
  11341. }
  11342. Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11343. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  11344. function Uint16BufferAttribute( array, itemSize ) {
  11345. BufferAttribute.call( this, new Uint16Array( array ), itemSize );
  11346. }
  11347. Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11348. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  11349. function Int32BufferAttribute( array, itemSize ) {
  11350. BufferAttribute.call( this, new Int32Array( array ), itemSize );
  11351. }
  11352. Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11353. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  11354. function Uint32BufferAttribute( array, itemSize ) {
  11355. BufferAttribute.call( this, new Uint32Array( array ), itemSize );
  11356. }
  11357. Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11358. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  11359. function Float32BufferAttribute( array, itemSize ) {
  11360. BufferAttribute.call( this, new Float32Array( array ), itemSize );
  11361. }
  11362. Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11363. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  11364. function Float64BufferAttribute( array, itemSize ) {
  11365. BufferAttribute.call( this, new Float64Array( array ), itemSize );
  11366. }
  11367. Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11368. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  11369. /**
  11370. * @author mrdoob / http://mrdoob.com/
  11371. */
  11372. function DirectGeometry() {
  11373. this.indices = [];
  11374. this.vertices = [];
  11375. this.normals = [];
  11376. this.colors = [];
  11377. this.uvs = [];
  11378. this.uvs2 = [];
  11379. this.groups = [];
  11380. this.morphTargets = {};
  11381. this.skinWeights = [];
  11382. this.skinIndices = [];
  11383. // this.lineDistances = [];
  11384. this.boundingBox = null;
  11385. this.boundingSphere = null;
  11386. // update flags
  11387. this.verticesNeedUpdate = false;
  11388. this.normalsNeedUpdate = false;
  11389. this.colorsNeedUpdate = false;
  11390. this.uvsNeedUpdate = false;
  11391. this.groupsNeedUpdate = false;
  11392. }
  11393. Object.assign( DirectGeometry.prototype, {
  11394. computeGroups: function ( geometry ) {
  11395. var group;
  11396. var groups = [];
  11397. var materialIndex = undefined;
  11398. var faces = geometry.faces;
  11399. for ( var i = 0; i < faces.length; i ++ ) {
  11400. var face = faces[ i ];
  11401. // materials
  11402. if ( face.materialIndex !== materialIndex ) {
  11403. materialIndex = face.materialIndex;
  11404. if ( group !== undefined ) {
  11405. group.count = ( i * 3 ) - group.start;
  11406. groups.push( group );
  11407. }
  11408. group = {
  11409. start: i * 3,
  11410. materialIndex: materialIndex
  11411. };
  11412. }
  11413. }
  11414. if ( group !== undefined ) {
  11415. group.count = ( i * 3 ) - group.start;
  11416. groups.push( group );
  11417. }
  11418. this.groups = groups;
  11419. },
  11420. fromGeometry: function ( geometry ) {
  11421. var faces = geometry.faces;
  11422. var vertices = geometry.vertices;
  11423. var faceVertexUvs = geometry.faceVertexUvs;
  11424. var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  11425. var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  11426. // morphs
  11427. var morphTargets = geometry.morphTargets;
  11428. var morphTargetsLength = morphTargets.length;
  11429. var morphTargetsPosition;
  11430. if ( morphTargetsLength > 0 ) {
  11431. morphTargetsPosition = [];
  11432. for ( var i = 0; i < morphTargetsLength; i ++ ) {
  11433. morphTargetsPosition[ i ] = [];
  11434. }
  11435. this.morphTargets.position = morphTargetsPosition;
  11436. }
  11437. var morphNormals = geometry.morphNormals;
  11438. var morphNormalsLength = morphNormals.length;
  11439. var morphTargetsNormal;
  11440. if ( morphNormalsLength > 0 ) {
  11441. morphTargetsNormal = [];
  11442. for ( var i = 0; i < morphNormalsLength; i ++ ) {
  11443. morphTargetsNormal[ i ] = [];
  11444. }
  11445. this.morphTargets.normal = morphTargetsNormal;
  11446. }
  11447. // skins
  11448. var skinIndices = geometry.skinIndices;
  11449. var skinWeights = geometry.skinWeights;
  11450. var hasSkinIndices = skinIndices.length === vertices.length;
  11451. var hasSkinWeights = skinWeights.length === vertices.length;
  11452. //
  11453. for ( var i = 0; i < faces.length; i ++ ) {
  11454. var face = faces[ i ];
  11455. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  11456. var vertexNormals = face.vertexNormals;
  11457. if ( vertexNormals.length === 3 ) {
  11458. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  11459. } else {
  11460. var normal = face.normal;
  11461. this.normals.push( normal, normal, normal );
  11462. }
  11463. var vertexColors = face.vertexColors;
  11464. if ( vertexColors.length === 3 ) {
  11465. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  11466. } else {
  11467. var color = face.color;
  11468. this.colors.push( color, color, color );
  11469. }
  11470. if ( hasFaceVertexUv === true ) {
  11471. var vertexUvs = faceVertexUvs[ 0 ][ i ];
  11472. if ( vertexUvs !== undefined ) {
  11473. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  11474. } else {
  11475. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  11476. this.uvs.push( new Vector2(), new Vector2(), new Vector2() );
  11477. }
  11478. }
  11479. if ( hasFaceVertexUv2 === true ) {
  11480. var vertexUvs = faceVertexUvs[ 1 ][ i ];
  11481. if ( vertexUvs !== undefined ) {
  11482. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  11483. } else {
  11484. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  11485. this.uvs2.push( new Vector2(), new Vector2(), new Vector2() );
  11486. }
  11487. }
  11488. // morphs
  11489. for ( var j = 0; j < morphTargetsLength; j ++ ) {
  11490. var morphTarget = morphTargets[ j ].vertices;
  11491. morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  11492. }
  11493. for ( var j = 0; j < morphNormalsLength; j ++ ) {
  11494. var morphNormal = morphNormals[ j ].vertexNormals[ i ];
  11495. morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c );
  11496. }
  11497. // skins
  11498. if ( hasSkinIndices ) {
  11499. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  11500. }
  11501. if ( hasSkinWeights ) {
  11502. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  11503. }
  11504. }
  11505. this.computeGroups( geometry );
  11506. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  11507. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  11508. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  11509. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  11510. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  11511. return this;
  11512. }
  11513. } );
  11514. // http://stackoverflow.com/questions/1669190/javascript-min-max-array-values/13440842#13440842
  11515. function arrayMax( array ) {
  11516. var length = array.length, max = - Infinity;
  11517. while ( length -- ) {
  11518. if ( array[ length ] > max ) {
  11519. max = array[ length ];
  11520. }
  11521. }
  11522. return max;
  11523. }
  11524. /**
  11525. * @author mrdoob / http://mrdoob.com/
  11526. * @author kile / http://kile.stravaganza.org/
  11527. * @author alteredq / http://alteredqualia.com/
  11528. * @author mikael emtinger / http://gomo.se/
  11529. * @author zz85 / http://www.lab4games.net/zz85/blog
  11530. * @author bhouston / http://clara.io
  11531. */
  11532. var count = 0;
  11533. function GeometryIdCount() { return count++; }
  11534. function Geometry() {
  11535. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  11536. this.uuid = _Math.generateUUID();
  11537. this.name = '';
  11538. this.type = 'Geometry';
  11539. this.vertices = [];
  11540. this.colors = [];
  11541. this.faces = [];
  11542. this.faceVertexUvs = [[]];
  11543. this.morphTargets = [];
  11544. this.morphNormals = [];
  11545. this.skinWeights = [];
  11546. this.skinIndices = [];
  11547. this.lineDistances = [];
  11548. this.boundingBox = null;
  11549. this.boundingSphere = null;
  11550. // update flags
  11551. this.elementsNeedUpdate = false;
  11552. this.verticesNeedUpdate = false;
  11553. this.uvsNeedUpdate = false;
  11554. this.normalsNeedUpdate = false;
  11555. this.colorsNeedUpdate = false;
  11556. this.lineDistancesNeedUpdate = false;
  11557. this.groupsNeedUpdate = false;
  11558. }
  11559. Geometry.prototype = {
  11560. constructor: Geometry,
  11561. isGeometry: true,
  11562. applyMatrix: function ( matrix ) {
  11563. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  11564. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  11565. var vertex = this.vertices[ i ];
  11566. vertex.applyMatrix4( matrix );
  11567. }
  11568. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  11569. var face = this.faces[ i ];
  11570. face.normal.applyMatrix3( normalMatrix ).normalize();
  11571. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  11572. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  11573. }
  11574. }
  11575. if ( this.boundingBox !== null ) {
  11576. this.computeBoundingBox();
  11577. }
  11578. if ( this.boundingSphere !== null ) {
  11579. this.computeBoundingSphere();
  11580. }
  11581. this.verticesNeedUpdate = true;
  11582. this.normalsNeedUpdate = true;
  11583. return this;
  11584. },
  11585. rotateX: function () {
  11586. // rotate geometry around world x-axis
  11587. var m1;
  11588. return function rotateX( angle ) {
  11589. if ( m1 === undefined ) m1 = new Matrix4();
  11590. m1.makeRotationX( angle );
  11591. this.applyMatrix( m1 );
  11592. return this;
  11593. };
  11594. }(),
  11595. rotateY: function () {
  11596. // rotate geometry around world y-axis
  11597. var m1;
  11598. return function rotateY( angle ) {
  11599. if ( m1 === undefined ) m1 = new Matrix4();
  11600. m1.makeRotationY( angle );
  11601. this.applyMatrix( m1 );
  11602. return this;
  11603. };
  11604. }(),
  11605. rotateZ: function () {
  11606. // rotate geometry around world z-axis
  11607. var m1;
  11608. return function rotateZ( angle ) {
  11609. if ( m1 === undefined ) m1 = new Matrix4();
  11610. m1.makeRotationZ( angle );
  11611. this.applyMatrix( m1 );
  11612. return this;
  11613. };
  11614. }(),
  11615. translate: function () {
  11616. // translate geometry
  11617. var m1;
  11618. return function translate( x, y, z ) {
  11619. if ( m1 === undefined ) m1 = new Matrix4();
  11620. m1.makeTranslation( x, y, z );
  11621. this.applyMatrix( m1 );
  11622. return this;
  11623. };
  11624. }(),
  11625. scale: function () {
  11626. // scale geometry
  11627. var m1;
  11628. return function scale( x, y, z ) {
  11629. if ( m1 === undefined ) m1 = new Matrix4();
  11630. m1.makeScale( x, y, z );
  11631. this.applyMatrix( m1 );
  11632. return this;
  11633. };
  11634. }(),
  11635. lookAt: function () {
  11636. var obj;
  11637. return function lookAt( vector ) {
  11638. if ( obj === undefined ) obj = new Object3D();
  11639. obj.lookAt( vector );
  11640. obj.updateMatrix();
  11641. this.applyMatrix( obj.matrix );
  11642. };
  11643. }(),
  11644. fromBufferGeometry: function ( geometry ) {
  11645. var scope = this;
  11646. var indices = geometry.index !== null ? geometry.index.array : undefined;
  11647. var attributes = geometry.attributes;
  11648. var positions = attributes.position.array;
  11649. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  11650. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  11651. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  11652. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  11653. if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
  11654. var tempNormals = [];
  11655. var tempUVs = [];
  11656. var tempUVs2 = [];
  11657. for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) {
  11658. scope.vertices.push( new Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) );
  11659. if ( normals !== undefined ) {
  11660. tempNormals.push( new Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) );
  11661. }
  11662. if ( colors !== undefined ) {
  11663. scope.colors.push( new Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) );
  11664. }
  11665. if ( uvs !== undefined ) {
  11666. tempUVs.push( new Vector2( uvs[ j ], uvs[ j + 1 ] ) );
  11667. }
  11668. if ( uvs2 !== undefined ) {
  11669. tempUVs2.push( new Vector2( uvs2[ j ], uvs2[ j + 1 ] ) );
  11670. }
  11671. }
  11672. function addFace( a, b, c, materialIndex ) {
  11673. var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : [];
  11674. var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : [];
  11675. var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex );
  11676. scope.faces.push( face );
  11677. if ( uvs !== undefined ) {
  11678. scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] );
  11679. }
  11680. if ( uvs2 !== undefined ) {
  11681. scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] );
  11682. }
  11683. }
  11684. if ( indices !== undefined ) {
  11685. var groups = geometry.groups;
  11686. if ( groups.length > 0 ) {
  11687. for ( var i = 0; i < groups.length; i ++ ) {
  11688. var group = groups[ i ];
  11689. var start = group.start;
  11690. var count = group.count;
  11691. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  11692. addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex );
  11693. }
  11694. }
  11695. } else {
  11696. for ( var i = 0; i < indices.length; i += 3 ) {
  11697. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  11698. }
  11699. }
  11700. } else {
  11701. for ( var i = 0; i < positions.length / 3; i += 3 ) {
  11702. addFace( i, i + 1, i + 2 );
  11703. }
  11704. }
  11705. this.computeFaceNormals();
  11706. if ( geometry.boundingBox !== null ) {
  11707. this.boundingBox = geometry.boundingBox.clone();
  11708. }
  11709. if ( geometry.boundingSphere !== null ) {
  11710. this.boundingSphere = geometry.boundingSphere.clone();
  11711. }
  11712. return this;
  11713. },
  11714. center: function () {
  11715. this.computeBoundingBox();
  11716. var offset = this.boundingBox.getCenter().negate();
  11717. this.translate( offset.x, offset.y, offset.z );
  11718. return offset;
  11719. },
  11720. normalize: function () {
  11721. this.computeBoundingSphere();
  11722. var center = this.boundingSphere.center;
  11723. var radius = this.boundingSphere.radius;
  11724. var s = radius === 0 ? 1 : 1.0 / radius;
  11725. var matrix = new Matrix4();
  11726. matrix.set(
  11727. s, 0, 0, - s * center.x,
  11728. 0, s, 0, - s * center.y,
  11729. 0, 0, s, - s * center.z,
  11730. 0, 0, 0, 1
  11731. );
  11732. this.applyMatrix( matrix );
  11733. return this;
  11734. },
  11735. computeFaceNormals: function () {
  11736. var cb = new Vector3(), ab = new Vector3();
  11737. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  11738. var face = this.faces[ f ];
  11739. var vA = this.vertices[ face.a ];
  11740. var vB = this.vertices[ face.b ];
  11741. var vC = this.vertices[ face.c ];
  11742. cb.subVectors( vC, vB );
  11743. ab.subVectors( vA, vB );
  11744. cb.cross( ab );
  11745. cb.normalize();
  11746. face.normal.copy( cb );
  11747. }
  11748. },
  11749. computeVertexNormals: function ( areaWeighted ) {
  11750. if ( areaWeighted === undefined ) areaWeighted = true;
  11751. var v, vl, f, fl, face, vertices;
  11752. vertices = new Array( this.vertices.length );
  11753. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  11754. vertices[ v ] = new Vector3();
  11755. }
  11756. if ( areaWeighted ) {
  11757. // vertex normals weighted by triangle areas
  11758. // http://www.iquilezles.org/www/articles/normals/normals.htm
  11759. var vA, vB, vC;
  11760. var cb = new Vector3(), ab = new Vector3();
  11761. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  11762. face = this.faces[ f ];
  11763. vA = this.vertices[ face.a ];
  11764. vB = this.vertices[ face.b ];
  11765. vC = this.vertices[ face.c ];
  11766. cb.subVectors( vC, vB );
  11767. ab.subVectors( vA, vB );
  11768. cb.cross( ab );
  11769. vertices[ face.a ].add( cb );
  11770. vertices[ face.b ].add( cb );
  11771. vertices[ face.c ].add( cb );
  11772. }
  11773. } else {
  11774. this.computeFaceNormals();
  11775. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  11776. face = this.faces[ f ];
  11777. vertices[ face.a ].add( face.normal );
  11778. vertices[ face.b ].add( face.normal );
  11779. vertices[ face.c ].add( face.normal );
  11780. }
  11781. }
  11782. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  11783. vertices[ v ].normalize();
  11784. }
  11785. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  11786. face = this.faces[ f ];
  11787. var vertexNormals = face.vertexNormals;
  11788. if ( vertexNormals.length === 3 ) {
  11789. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  11790. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  11791. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  11792. } else {
  11793. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  11794. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  11795. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  11796. }
  11797. }
  11798. if ( this.faces.length > 0 ) {
  11799. this.normalsNeedUpdate = true;
  11800. }
  11801. },
  11802. computeFlatVertexNormals: function () {
  11803. var f, fl, face;
  11804. this.computeFaceNormals();
  11805. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  11806. face = this.faces[ f ];
  11807. var vertexNormals = face.vertexNormals;
  11808. if ( vertexNormals.length === 3 ) {
  11809. vertexNormals[ 0 ].copy( face.normal );
  11810. vertexNormals[ 1 ].copy( face.normal );
  11811. vertexNormals[ 2 ].copy( face.normal );
  11812. } else {
  11813. vertexNormals[ 0 ] = face.normal.clone();
  11814. vertexNormals[ 1 ] = face.normal.clone();
  11815. vertexNormals[ 2 ] = face.normal.clone();
  11816. }
  11817. }
  11818. if ( this.faces.length > 0 ) {
  11819. this.normalsNeedUpdate = true;
  11820. }
  11821. },
  11822. computeMorphNormals: function () {
  11823. var i, il, f, fl, face;
  11824. // save original normals
  11825. // - create temp variables on first access
  11826. // otherwise just copy (for faster repeated calls)
  11827. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  11828. face = this.faces[ f ];
  11829. if ( ! face.__originalFaceNormal ) {
  11830. face.__originalFaceNormal = face.normal.clone();
  11831. } else {
  11832. face.__originalFaceNormal.copy( face.normal );
  11833. }
  11834. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  11835. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  11836. if ( ! face.__originalVertexNormals[ i ] ) {
  11837. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  11838. } else {
  11839. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  11840. }
  11841. }
  11842. }
  11843. // use temp geometry to compute face and vertex normals for each morph
  11844. var tmpGeo = new Geometry();
  11845. tmpGeo.faces = this.faces;
  11846. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  11847. // create on first access
  11848. if ( ! this.morphNormals[ i ] ) {
  11849. this.morphNormals[ i ] = {};
  11850. this.morphNormals[ i ].faceNormals = [];
  11851. this.morphNormals[ i ].vertexNormals = [];
  11852. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  11853. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  11854. var faceNormal, vertexNormals;
  11855. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  11856. faceNormal = new Vector3();
  11857. vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() };
  11858. dstNormalsFace.push( faceNormal );
  11859. dstNormalsVertex.push( vertexNormals );
  11860. }
  11861. }
  11862. var morphNormals = this.morphNormals[ i ];
  11863. // set vertices to morph target
  11864. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  11865. // compute morph normals
  11866. tmpGeo.computeFaceNormals();
  11867. tmpGeo.computeVertexNormals();
  11868. // store morph normals
  11869. var faceNormal, vertexNormals;
  11870. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  11871. face = this.faces[ f ];
  11872. faceNormal = morphNormals.faceNormals[ f ];
  11873. vertexNormals = morphNormals.vertexNormals[ f ];
  11874. faceNormal.copy( face.normal );
  11875. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  11876. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  11877. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  11878. }
  11879. }
  11880. // restore original normals
  11881. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  11882. face = this.faces[ f ];
  11883. face.normal = face.__originalFaceNormal;
  11884. face.vertexNormals = face.__originalVertexNormals;
  11885. }
  11886. },
  11887. computeLineDistances: function () {
  11888. var d = 0;
  11889. var vertices = this.vertices;
  11890. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  11891. if ( i > 0 ) {
  11892. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  11893. }
  11894. this.lineDistances[ i ] = d;
  11895. }
  11896. },
  11897. computeBoundingBox: function () {
  11898. if ( this.boundingBox === null ) {
  11899. this.boundingBox = new Box3();
  11900. }
  11901. this.boundingBox.setFromPoints( this.vertices );
  11902. },
  11903. computeBoundingSphere: function () {
  11904. if ( this.boundingSphere === null ) {
  11905. this.boundingSphere = new Sphere();
  11906. }
  11907. this.boundingSphere.setFromPoints( this.vertices );
  11908. },
  11909. merge: function ( geometry, matrix, materialIndexOffset ) {
  11910. if ( ( geometry && geometry.isGeometry ) === false ) {
  11911. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  11912. return;
  11913. }
  11914. var normalMatrix,
  11915. vertexOffset = this.vertices.length,
  11916. vertices1 = this.vertices,
  11917. vertices2 = geometry.vertices,
  11918. faces1 = this.faces,
  11919. faces2 = geometry.faces,
  11920. uvs1 = this.faceVertexUvs[ 0 ],
  11921. uvs2 = geometry.faceVertexUvs[ 0 ],
  11922. colors1 = this.colors,
  11923. colors2 = geometry.colors;
  11924. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  11925. if ( matrix !== undefined ) {
  11926. normalMatrix = new Matrix3().getNormalMatrix( matrix );
  11927. }
  11928. // vertices
  11929. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  11930. var vertex = vertices2[ i ];
  11931. var vertexCopy = vertex.clone();
  11932. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  11933. vertices1.push( vertexCopy );
  11934. }
  11935. // colors
  11936. for ( var i = 0, il = colors2.length; i < il; i ++ ) {
  11937. colors1.push( colors2[ i ].clone() );
  11938. }
  11939. // faces
  11940. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  11941. var face = faces2[ i ], faceCopy, normal, color,
  11942. faceVertexNormals = face.vertexNormals,
  11943. faceVertexColors = face.vertexColors;
  11944. faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  11945. faceCopy.normal.copy( face.normal );
  11946. if ( normalMatrix !== undefined ) {
  11947. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  11948. }
  11949. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  11950. normal = faceVertexNormals[ j ].clone();
  11951. if ( normalMatrix !== undefined ) {
  11952. normal.applyMatrix3( normalMatrix ).normalize();
  11953. }
  11954. faceCopy.vertexNormals.push( normal );
  11955. }
  11956. faceCopy.color.copy( face.color );
  11957. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  11958. color = faceVertexColors[ j ];
  11959. faceCopy.vertexColors.push( color.clone() );
  11960. }
  11961. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  11962. faces1.push( faceCopy );
  11963. }
  11964. // uvs
  11965. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  11966. var uv = uvs2[ i ], uvCopy = [];
  11967. if ( uv === undefined ) {
  11968. continue;
  11969. }
  11970. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  11971. uvCopy.push( uv[ j ].clone() );
  11972. }
  11973. uvs1.push( uvCopy );
  11974. }
  11975. },
  11976. mergeMesh: function ( mesh ) {
  11977. if ( ( mesh && mesh.isMesh ) === false ) {
  11978. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  11979. return;
  11980. }
  11981. mesh.matrixAutoUpdate && mesh.updateMatrix();
  11982. this.merge( mesh.geometry, mesh.matrix );
  11983. },
  11984. /*
  11985. * Checks for duplicate vertices with hashmap.
  11986. * Duplicated vertices are removed
  11987. * and faces' vertices are updated.
  11988. */
  11989. mergeVertices: function () {
  11990. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  11991. var unique = [], changes = [];
  11992. var v, key;
  11993. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  11994. var precision = Math.pow( 10, precisionPoints );
  11995. var i, il, face;
  11996. var indices, j, jl;
  11997. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  11998. v = this.vertices[ i ];
  11999. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  12000. if ( verticesMap[ key ] === undefined ) {
  12001. verticesMap[ key ] = i;
  12002. unique.push( this.vertices[ i ] );
  12003. changes[ i ] = unique.length - 1;
  12004. } else {
  12005. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  12006. changes[ i ] = changes[ verticesMap[ key ] ];
  12007. }
  12008. }
  12009. // if faces are completely degenerate after merging vertices, we
  12010. // have to remove them from the geometry.
  12011. var faceIndicesToRemove = [];
  12012. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  12013. face = this.faces[ i ];
  12014. face.a = changes[ face.a ];
  12015. face.b = changes[ face.b ];
  12016. face.c = changes[ face.c ];
  12017. indices = [ face.a, face.b, face.c ];
  12018. // if any duplicate vertices are found in a Face3
  12019. // we have to remove the face as nothing can be saved
  12020. for ( var n = 0; n < 3; n ++ ) {
  12021. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  12022. faceIndicesToRemove.push( i );
  12023. break;
  12024. }
  12025. }
  12026. }
  12027. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  12028. var idx = faceIndicesToRemove[ i ];
  12029. this.faces.splice( idx, 1 );
  12030. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  12031. this.faceVertexUvs[ j ].splice( idx, 1 );
  12032. }
  12033. }
  12034. // Use unique set of vertices
  12035. var diff = this.vertices.length - unique.length;
  12036. this.vertices = unique;
  12037. return diff;
  12038. },
  12039. sortFacesByMaterialIndex: function () {
  12040. var faces = this.faces;
  12041. var length = faces.length;
  12042. // tag faces
  12043. for ( var i = 0; i < length; i ++ ) {
  12044. faces[ i ]._id = i;
  12045. }
  12046. // sort faces
  12047. function materialIndexSort( a, b ) {
  12048. return a.materialIndex - b.materialIndex;
  12049. }
  12050. faces.sort( materialIndexSort );
  12051. // sort uvs
  12052. var uvs1 = this.faceVertexUvs[ 0 ];
  12053. var uvs2 = this.faceVertexUvs[ 1 ];
  12054. var newUvs1, newUvs2;
  12055. if ( uvs1 && uvs1.length === length ) newUvs1 = [];
  12056. if ( uvs2 && uvs2.length === length ) newUvs2 = [];
  12057. for ( var i = 0; i < length; i ++ ) {
  12058. var id = faces[ i ]._id;
  12059. if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
  12060. if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
  12061. }
  12062. if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
  12063. if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
  12064. },
  12065. toJSON: function () {
  12066. var data = {
  12067. metadata: {
  12068. version: 4.4,
  12069. type: 'Geometry',
  12070. generator: 'Geometry.toJSON'
  12071. }
  12072. };
  12073. // standard Geometry serialization
  12074. data.uuid = this.uuid;
  12075. data.type = this.type;
  12076. if ( this.name !== '' ) data.name = this.name;
  12077. if ( this.parameters !== undefined ) {
  12078. var parameters = this.parameters;
  12079. for ( var key in parameters ) {
  12080. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  12081. }
  12082. return data;
  12083. }
  12084. var vertices = [];
  12085. for ( var i = 0; i < this.vertices.length; i ++ ) {
  12086. var vertex = this.vertices[ i ];
  12087. vertices.push( vertex.x, vertex.y, vertex.z );
  12088. }
  12089. var faces = [];
  12090. var normals = [];
  12091. var normalsHash = {};
  12092. var colors = [];
  12093. var colorsHash = {};
  12094. var uvs = [];
  12095. var uvsHash = {};
  12096. for ( var i = 0; i < this.faces.length; i ++ ) {
  12097. var face = this.faces[ i ];
  12098. var hasMaterial = true;
  12099. var hasFaceUv = false; // deprecated
  12100. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  12101. var hasFaceNormal = face.normal.length() > 0;
  12102. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  12103. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  12104. var hasFaceVertexColor = face.vertexColors.length > 0;
  12105. var faceType = 0;
  12106. faceType = setBit( faceType, 0, 0 ); // isQuad
  12107. faceType = setBit( faceType, 1, hasMaterial );
  12108. faceType = setBit( faceType, 2, hasFaceUv );
  12109. faceType = setBit( faceType, 3, hasFaceVertexUv );
  12110. faceType = setBit( faceType, 4, hasFaceNormal );
  12111. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  12112. faceType = setBit( faceType, 6, hasFaceColor );
  12113. faceType = setBit( faceType, 7, hasFaceVertexColor );
  12114. faces.push( faceType );
  12115. faces.push( face.a, face.b, face.c );
  12116. faces.push( face.materialIndex );
  12117. if ( hasFaceVertexUv ) {
  12118. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  12119. faces.push(
  12120. getUvIndex( faceVertexUvs[ 0 ] ),
  12121. getUvIndex( faceVertexUvs[ 1 ] ),
  12122. getUvIndex( faceVertexUvs[ 2 ] )
  12123. );
  12124. }
  12125. if ( hasFaceNormal ) {
  12126. faces.push( getNormalIndex( face.normal ) );
  12127. }
  12128. if ( hasFaceVertexNormal ) {
  12129. var vertexNormals = face.vertexNormals;
  12130. faces.push(
  12131. getNormalIndex( vertexNormals[ 0 ] ),
  12132. getNormalIndex( vertexNormals[ 1 ] ),
  12133. getNormalIndex( vertexNormals[ 2 ] )
  12134. );
  12135. }
  12136. if ( hasFaceColor ) {
  12137. faces.push( getColorIndex( face.color ) );
  12138. }
  12139. if ( hasFaceVertexColor ) {
  12140. var vertexColors = face.vertexColors;
  12141. faces.push(
  12142. getColorIndex( vertexColors[ 0 ] ),
  12143. getColorIndex( vertexColors[ 1 ] ),
  12144. getColorIndex( vertexColors[ 2 ] )
  12145. );
  12146. }
  12147. }
  12148. function setBit( value, position, enabled ) {
  12149. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  12150. }
  12151. function getNormalIndex( normal ) {
  12152. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  12153. if ( normalsHash[ hash ] !== undefined ) {
  12154. return normalsHash[ hash ];
  12155. }
  12156. normalsHash[ hash ] = normals.length / 3;
  12157. normals.push( normal.x, normal.y, normal.z );
  12158. return normalsHash[ hash ];
  12159. }
  12160. function getColorIndex( color ) {
  12161. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  12162. if ( colorsHash[ hash ] !== undefined ) {
  12163. return colorsHash[ hash ];
  12164. }
  12165. colorsHash[ hash ] = colors.length;
  12166. colors.push( color.getHex() );
  12167. return colorsHash[ hash ];
  12168. }
  12169. function getUvIndex( uv ) {
  12170. var hash = uv.x.toString() + uv.y.toString();
  12171. if ( uvsHash[ hash ] !== undefined ) {
  12172. return uvsHash[ hash ];
  12173. }
  12174. uvsHash[ hash ] = uvs.length / 2;
  12175. uvs.push( uv.x, uv.y );
  12176. return uvsHash[ hash ];
  12177. }
  12178. data.data = {};
  12179. data.data.vertices = vertices;
  12180. data.data.normals = normals;
  12181. if ( colors.length > 0 ) data.data.colors = colors;
  12182. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  12183. data.data.faces = faces;
  12184. return data;
  12185. },
  12186. clone: function () {
  12187. /*
  12188. // Handle primitives
  12189. var parameters = this.parameters;
  12190. if ( parameters !== undefined ) {
  12191. var values = [];
  12192. for ( var key in parameters ) {
  12193. values.push( parameters[ key ] );
  12194. }
  12195. var geometry = Object.create( this.constructor.prototype );
  12196. this.constructor.apply( geometry, values );
  12197. return geometry;
  12198. }
  12199. return new this.constructor().copy( this );
  12200. */
  12201. return new Geometry().copy( this );
  12202. },
  12203. copy: function ( source ) {
  12204. var i, il, j, jl, k, kl;
  12205. // reset
  12206. this.vertices = [];
  12207. this.colors = [];
  12208. this.faces = [];
  12209. this.faceVertexUvs = [[]];
  12210. this.morphTargets = [];
  12211. this.morphNormals = [];
  12212. this.skinWeights = [];
  12213. this.skinIndices = [];
  12214. this.lineDistances = [];
  12215. this.boundingBox = null;
  12216. this.boundingSphere = null;
  12217. // name
  12218. this.name = source.name;
  12219. // vertices
  12220. var vertices = source.vertices;
  12221. for ( i = 0, il = vertices.length; i < il; i ++ ) {
  12222. this.vertices.push( vertices[ i ].clone() );
  12223. }
  12224. // colors
  12225. var colors = source.colors;
  12226. for ( i = 0, il = colors.length; i < il; i ++ ) {
  12227. this.colors.push( colors[ i ].clone() );
  12228. }
  12229. // faces
  12230. var faces = source.faces;
  12231. for ( i = 0, il = faces.length; i < il; i ++ ) {
  12232. this.faces.push( faces[ i ].clone() );
  12233. }
  12234. // face vertex uvs
  12235. for ( i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  12236. var faceVertexUvs = source.faceVertexUvs[ i ];
  12237. if ( this.faceVertexUvs[ i ] === undefined ) {
  12238. this.faceVertexUvs[ i ] = [];
  12239. }
  12240. for ( j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  12241. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  12242. for ( k = 0, kl = uvs.length; k < kl; k ++ ) {
  12243. var uv = uvs[ k ];
  12244. uvsCopy.push( uv.clone() );
  12245. }
  12246. this.faceVertexUvs[ i ].push( uvsCopy );
  12247. }
  12248. }
  12249. // morph targets
  12250. var morphTargets = source.morphTargets;
  12251. for ( i = 0, il = morphTargets.length; i < il; i ++ ) {
  12252. var morphTarget = {};
  12253. morphTarget.name = morphTargets[ i ].name;
  12254. // vertices
  12255. if ( morphTargets[ i ].vertices !== undefined ) {
  12256. morphTarget.vertices = [];
  12257. for ( j = 0, jl = morphTargets[ i ].vertices.length; j < jl; j ++ ) {
  12258. morphTarget.vertices.push( morphTargets[ i ].vertices[ j ].clone() );
  12259. }
  12260. }
  12261. // normals
  12262. if ( morphTargets[ i ].normals !== undefined ) {
  12263. morphTarget.normals = [];
  12264. for ( j = 0, jl = morphTargets[ i ].normals.length; j < jl; j ++ ) {
  12265. morphTarget.normals.push( morphTargets[ i ].normals[ j ].clone() );
  12266. }
  12267. }
  12268. this.morphTargets.push( morphTarget );
  12269. }
  12270. // morph normals
  12271. var morphNormals = source.morphNormals;
  12272. for ( i = 0, il = morphNormals.length; i < il; i ++ ) {
  12273. var morphNormal = {};
  12274. // vertex normals
  12275. if ( morphNormals[ i ].vertexNormals !== undefined ) {
  12276. morphNormal.vertexNormals = [];
  12277. for ( j = 0, jl = morphNormals[ i ].vertexNormals.length; j < jl; j ++ ) {
  12278. var srcVertexNormal = morphNormals[ i ].vertexNormals[ j ];
  12279. var destVertexNormal = {};
  12280. destVertexNormal.a = srcVertexNormal.a.clone();
  12281. destVertexNormal.b = srcVertexNormal.b.clone();
  12282. destVertexNormal.c = srcVertexNormal.c.clone();
  12283. morphNormal.vertexNormals.push( destVertexNormal );
  12284. }
  12285. }
  12286. // face normals
  12287. if ( morphNormals[ i ].faceNormals !== undefined ) {
  12288. morphNormal.faceNormals = [];
  12289. for ( j = 0, jl = morphNormals[ i ].faceNormals.length; j < jl; j ++ ) {
  12290. morphNormal.faceNormals.push( morphNormals[ i ].faceNormals[ j ].clone() );
  12291. }
  12292. }
  12293. this.morphNormals.push( morphNormal );
  12294. }
  12295. // skin weights
  12296. var skinWeights = source.skinWeights;
  12297. for ( i = 0, il = skinWeights.length; i < il; i ++ ) {
  12298. this.skinWeights.push( skinWeights[ i ].clone() );
  12299. }
  12300. // skin indices
  12301. var skinIndices = source.skinIndices;
  12302. for ( i = 0, il = skinIndices.length; i < il; i ++ ) {
  12303. this.skinIndices.push( skinIndices[ i ].clone() );
  12304. }
  12305. // line distances
  12306. var lineDistances = source.lineDistances;
  12307. for ( i = 0, il = lineDistances.length; i < il; i ++ ) {
  12308. this.lineDistances.push( lineDistances[ i ] );
  12309. }
  12310. // bounding box
  12311. var boundingBox = source.boundingBox;
  12312. if ( boundingBox !== null ) {
  12313. this.boundingBox = boundingBox.clone();
  12314. }
  12315. // bounding sphere
  12316. var boundingSphere = source.boundingSphere;
  12317. if ( boundingSphere !== null ) {
  12318. this.boundingSphere = boundingSphere.clone();
  12319. }
  12320. // update flags
  12321. this.elementsNeedUpdate = source.elementsNeedUpdate;
  12322. this.verticesNeedUpdate = source.verticesNeedUpdate;
  12323. this.uvsNeedUpdate = source.uvsNeedUpdate;
  12324. this.normalsNeedUpdate = source.normalsNeedUpdate;
  12325. this.colorsNeedUpdate = source.colorsNeedUpdate;
  12326. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  12327. this.groupsNeedUpdate = source.groupsNeedUpdate;
  12328. return this;
  12329. },
  12330. dispose: function () {
  12331. this.dispatchEvent( { type: 'dispose' } );
  12332. }
  12333. };
  12334. Object.assign( Geometry.prototype, EventDispatcher.prototype );
  12335. /**
  12336. * @author alteredq / http://alteredqualia.com/
  12337. * @author mrdoob / http://mrdoob.com/
  12338. */
  12339. function BufferGeometry() {
  12340. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  12341. this.uuid = _Math.generateUUID();
  12342. this.name = '';
  12343. this.type = 'BufferGeometry';
  12344. this.index = null;
  12345. this.attributes = {};
  12346. this.morphAttributes = {};
  12347. this.groups = [];
  12348. this.boundingBox = null;
  12349. this.boundingSphere = null;
  12350. this.drawRange = { start: 0, count: Infinity };
  12351. }
  12352. BufferGeometry.prototype = {
  12353. constructor: BufferGeometry,
  12354. isBufferGeometry: true,
  12355. getIndex: function () {
  12356. return this.index;
  12357. },
  12358. setIndex: function ( index ) {
  12359. if ( Array.isArray( index ) ) {
  12360. this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  12361. } else {
  12362. this.index = index;
  12363. }
  12364. },
  12365. addAttribute: function ( name, attribute ) {
  12366. if ( ( attribute && attribute.isBufferAttribute ) === false && ( attribute && attribute.isInterleavedBufferAttribute ) === false ) {
  12367. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  12368. this.addAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  12369. return;
  12370. }
  12371. if ( name === 'index' ) {
  12372. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  12373. this.setIndex( attribute );
  12374. return;
  12375. }
  12376. this.attributes[ name ] = attribute;
  12377. return this;
  12378. },
  12379. getAttribute: function ( name ) {
  12380. return this.attributes[ name ];
  12381. },
  12382. removeAttribute: function ( name ) {
  12383. delete this.attributes[ name ];
  12384. return this;
  12385. },
  12386. addGroup: function ( start, count, materialIndex ) {
  12387. this.groups.push( {
  12388. start: start,
  12389. count: count,
  12390. materialIndex: materialIndex !== undefined ? materialIndex : 0
  12391. } );
  12392. },
  12393. clearGroups: function () {
  12394. this.groups = [];
  12395. },
  12396. setDrawRange: function ( start, count ) {
  12397. this.drawRange.start = start;
  12398. this.drawRange.count = count;
  12399. },
  12400. applyMatrix: function ( matrix ) {
  12401. var position = this.attributes.position;
  12402. if ( position !== undefined ) {
  12403. matrix.applyToBufferAttribute( position );
  12404. position.needsUpdate = true;
  12405. }
  12406. var normal = this.attributes.normal;
  12407. if ( normal !== undefined ) {
  12408. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  12409. normalMatrix.applyToBufferAttribute( normal );
  12410. normal.needsUpdate = true;
  12411. }
  12412. if ( this.boundingBox !== null ) {
  12413. this.computeBoundingBox();
  12414. }
  12415. if ( this.boundingSphere !== null ) {
  12416. this.computeBoundingSphere();
  12417. }
  12418. return this;
  12419. },
  12420. rotateX: function () {
  12421. // rotate geometry around world x-axis
  12422. var m1;
  12423. return function rotateX( angle ) {
  12424. if ( m1 === undefined ) m1 = new Matrix4();
  12425. m1.makeRotationX( angle );
  12426. this.applyMatrix( m1 );
  12427. return this;
  12428. };
  12429. }(),
  12430. rotateY: function () {
  12431. // rotate geometry around world y-axis
  12432. var m1;
  12433. return function rotateY( angle ) {
  12434. if ( m1 === undefined ) m1 = new Matrix4();
  12435. m1.makeRotationY( angle );
  12436. this.applyMatrix( m1 );
  12437. return this;
  12438. };
  12439. }(),
  12440. rotateZ: function () {
  12441. // rotate geometry around world z-axis
  12442. var m1;
  12443. return function rotateZ( angle ) {
  12444. if ( m1 === undefined ) m1 = new Matrix4();
  12445. m1.makeRotationZ( angle );
  12446. this.applyMatrix( m1 );
  12447. return this;
  12448. };
  12449. }(),
  12450. translate: function () {
  12451. // translate geometry
  12452. var m1;
  12453. return function translate( x, y, z ) {
  12454. if ( m1 === undefined ) m1 = new Matrix4();
  12455. m1.makeTranslation( x, y, z );
  12456. this.applyMatrix( m1 );
  12457. return this;
  12458. };
  12459. }(),
  12460. scale: function () {
  12461. // scale geometry
  12462. var m1;
  12463. return function scale( x, y, z ) {
  12464. if ( m1 === undefined ) m1 = new Matrix4();
  12465. m1.makeScale( x, y, z );
  12466. this.applyMatrix( m1 );
  12467. return this;
  12468. };
  12469. }(),
  12470. lookAt: function () {
  12471. var obj;
  12472. return function lookAt( vector ) {
  12473. if ( obj === undefined ) obj = new Object3D();
  12474. obj.lookAt( vector );
  12475. obj.updateMatrix();
  12476. this.applyMatrix( obj.matrix );
  12477. };
  12478. }(),
  12479. center: function () {
  12480. this.computeBoundingBox();
  12481. var offset = this.boundingBox.getCenter().negate();
  12482. this.translate( offset.x, offset.y, offset.z );
  12483. return offset;
  12484. },
  12485. setFromObject: function ( object ) {
  12486. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  12487. var geometry = object.geometry;
  12488. if ( object.isPoints || object.isLine ) {
  12489. var positions = new Float32BufferAttribute( geometry.vertices.length * 3, 3 );
  12490. var colors = new Float32BufferAttribute( geometry.colors.length * 3, 3 );
  12491. this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  12492. this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  12493. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  12494. var lineDistances = new Float32BufferAttribute( geometry.lineDistances.length, 1 );
  12495. this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  12496. }
  12497. if ( geometry.boundingSphere !== null ) {
  12498. this.boundingSphere = geometry.boundingSphere.clone();
  12499. }
  12500. if ( geometry.boundingBox !== null ) {
  12501. this.boundingBox = geometry.boundingBox.clone();
  12502. }
  12503. } else if ( object.isMesh ) {
  12504. if ( geometry && geometry.isGeometry ) {
  12505. this.fromGeometry( geometry );
  12506. }
  12507. }
  12508. return this;
  12509. },
  12510. updateFromObject: function ( object ) {
  12511. var geometry = object.geometry;
  12512. if ( object.isMesh ) {
  12513. var direct = geometry.__directGeometry;
  12514. if ( geometry.elementsNeedUpdate === true ) {
  12515. direct = undefined;
  12516. geometry.elementsNeedUpdate = false;
  12517. }
  12518. if ( direct === undefined ) {
  12519. return this.fromGeometry( geometry );
  12520. }
  12521. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  12522. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  12523. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  12524. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  12525. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  12526. geometry.verticesNeedUpdate = false;
  12527. geometry.normalsNeedUpdate = false;
  12528. geometry.colorsNeedUpdate = false;
  12529. geometry.uvsNeedUpdate = false;
  12530. geometry.groupsNeedUpdate = false;
  12531. geometry = direct;
  12532. }
  12533. var attribute;
  12534. if ( geometry.verticesNeedUpdate === true ) {
  12535. attribute = this.attributes.position;
  12536. if ( attribute !== undefined ) {
  12537. attribute.copyVector3sArray( geometry.vertices );
  12538. attribute.needsUpdate = true;
  12539. }
  12540. geometry.verticesNeedUpdate = false;
  12541. }
  12542. if ( geometry.normalsNeedUpdate === true ) {
  12543. attribute = this.attributes.normal;
  12544. if ( attribute !== undefined ) {
  12545. attribute.copyVector3sArray( geometry.normals );
  12546. attribute.needsUpdate = true;
  12547. }
  12548. geometry.normalsNeedUpdate = false;
  12549. }
  12550. if ( geometry.colorsNeedUpdate === true ) {
  12551. attribute = this.attributes.color;
  12552. if ( attribute !== undefined ) {
  12553. attribute.copyColorsArray( geometry.colors );
  12554. attribute.needsUpdate = true;
  12555. }
  12556. geometry.colorsNeedUpdate = false;
  12557. }
  12558. if ( geometry.uvsNeedUpdate ) {
  12559. attribute = this.attributes.uv;
  12560. if ( attribute !== undefined ) {
  12561. attribute.copyVector2sArray( geometry.uvs );
  12562. attribute.needsUpdate = true;
  12563. }
  12564. geometry.uvsNeedUpdate = false;
  12565. }
  12566. if ( geometry.lineDistancesNeedUpdate ) {
  12567. attribute = this.attributes.lineDistance;
  12568. if ( attribute !== undefined ) {
  12569. attribute.copyArray( geometry.lineDistances );
  12570. attribute.needsUpdate = true;
  12571. }
  12572. geometry.lineDistancesNeedUpdate = false;
  12573. }
  12574. if ( geometry.groupsNeedUpdate ) {
  12575. geometry.computeGroups( object.geometry );
  12576. this.groups = geometry.groups;
  12577. geometry.groupsNeedUpdate = false;
  12578. }
  12579. return this;
  12580. },
  12581. fromGeometry: function ( geometry ) {
  12582. geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry );
  12583. return this.fromDirectGeometry( geometry.__directGeometry );
  12584. },
  12585. fromDirectGeometry: function ( geometry ) {
  12586. var positions = new Float32Array( geometry.vertices.length * 3 );
  12587. this.addAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  12588. if ( geometry.normals.length > 0 ) {
  12589. var normals = new Float32Array( geometry.normals.length * 3 );
  12590. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  12591. }
  12592. if ( geometry.colors.length > 0 ) {
  12593. var colors = new Float32Array( geometry.colors.length * 3 );
  12594. this.addAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  12595. }
  12596. if ( geometry.uvs.length > 0 ) {
  12597. var uvs = new Float32Array( geometry.uvs.length * 2 );
  12598. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  12599. }
  12600. if ( geometry.uvs2.length > 0 ) {
  12601. var uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  12602. this.addAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  12603. }
  12604. if ( geometry.indices.length > 0 ) {
  12605. var TypeArray = arrayMax( geometry.indices ) > 65535 ? Uint32Array : Uint16Array;
  12606. var indices = new TypeArray( geometry.indices.length * 3 );
  12607. this.setIndex( new BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) );
  12608. }
  12609. // groups
  12610. this.groups = geometry.groups;
  12611. // morphs
  12612. for ( var name in geometry.morphTargets ) {
  12613. var array = [];
  12614. var morphTargets = geometry.morphTargets[ name ];
  12615. for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {
  12616. var morphTarget = morphTargets[ i ];
  12617. var attribute = new Float32BufferAttribute( morphTarget.length * 3, 3 );
  12618. array.push( attribute.copyVector3sArray( morphTarget ) );
  12619. }
  12620. this.morphAttributes[ name ] = array;
  12621. }
  12622. // skinning
  12623. if ( geometry.skinIndices.length > 0 ) {
  12624. var skinIndices = new Float32BufferAttribute( geometry.skinIndices.length * 4, 4 );
  12625. this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  12626. }
  12627. if ( geometry.skinWeights.length > 0 ) {
  12628. var skinWeights = new Float32BufferAttribute( geometry.skinWeights.length * 4, 4 );
  12629. this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  12630. }
  12631. //
  12632. if ( geometry.boundingSphere !== null ) {
  12633. this.boundingSphere = geometry.boundingSphere.clone();
  12634. }
  12635. if ( geometry.boundingBox !== null ) {
  12636. this.boundingBox = geometry.boundingBox.clone();
  12637. }
  12638. return this;
  12639. },
  12640. computeBoundingBox: function () {
  12641. if ( this.boundingBox === null ) {
  12642. this.boundingBox = new Box3();
  12643. }
  12644. var position = this.attributes.position;
  12645. if ( position !== undefined ) {
  12646. this.boundingBox.setFromBufferAttribute( position );
  12647. } else {
  12648. this.boundingBox.makeEmpty();
  12649. }
  12650. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  12651. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  12652. }
  12653. },
  12654. computeBoundingSphere: function () {
  12655. var box = new Box3();
  12656. var vector = new Vector3();
  12657. return function computeBoundingSphere() {
  12658. if ( this.boundingSphere === null ) {
  12659. this.boundingSphere = new Sphere();
  12660. }
  12661. var position = this.attributes.position;
  12662. if ( position ) {
  12663. var center = this.boundingSphere.center;
  12664. box.setFromBufferAttribute( position );
  12665. box.getCenter( center );
  12666. // hoping to find a boundingSphere with a radius smaller than the
  12667. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  12668. var maxRadiusSq = 0;
  12669. for ( var i = 0, il = position.count; i < il; i ++ ) {
  12670. vector.x = position.getX( i );
  12671. vector.y = position.getY( i );
  12672. vector.z = position.getZ( i );
  12673. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  12674. }
  12675. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  12676. if ( isNaN( this.boundingSphere.radius ) ) {
  12677. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  12678. }
  12679. }
  12680. };
  12681. }(),
  12682. computeFaceNormals: function () {
  12683. // backwards compatibility
  12684. },
  12685. computeVertexNormals: function () {
  12686. var index = this.index;
  12687. var attributes = this.attributes;
  12688. var groups = this.groups;
  12689. if ( attributes.position ) {
  12690. var positions = attributes.position.array;
  12691. if ( attributes.normal === undefined ) {
  12692. this.addAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) );
  12693. } else {
  12694. // reset existing normals to zero
  12695. var array = attributes.normal.array;
  12696. for ( var i = 0, il = array.length; i < il; i ++ ) {
  12697. array[ i ] = 0;
  12698. }
  12699. }
  12700. var normals = attributes.normal.array;
  12701. var vA, vB, vC;
  12702. var pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  12703. var cb = new Vector3(), ab = new Vector3();
  12704. // indexed elements
  12705. if ( index ) {
  12706. var indices = index.array;
  12707. if ( groups.length === 0 ) {
  12708. this.addGroup( 0, indices.length );
  12709. }
  12710. for ( var j = 0, jl = groups.length; j < jl; ++ j ) {
  12711. var group = groups[ j ];
  12712. var start = group.start;
  12713. var count = group.count;
  12714. for ( var i = start, il = start + count; i < il; i += 3 ) {
  12715. vA = indices[ i + 0 ] * 3;
  12716. vB = indices[ i + 1 ] * 3;
  12717. vC = indices[ i + 2 ] * 3;
  12718. pA.fromArray( positions, vA );
  12719. pB.fromArray( positions, vB );
  12720. pC.fromArray( positions, vC );
  12721. cb.subVectors( pC, pB );
  12722. ab.subVectors( pA, pB );
  12723. cb.cross( ab );
  12724. normals[ vA ] += cb.x;
  12725. normals[ vA + 1 ] += cb.y;
  12726. normals[ vA + 2 ] += cb.z;
  12727. normals[ vB ] += cb.x;
  12728. normals[ vB + 1 ] += cb.y;
  12729. normals[ vB + 2 ] += cb.z;
  12730. normals[ vC ] += cb.x;
  12731. normals[ vC + 1 ] += cb.y;
  12732. normals[ vC + 2 ] += cb.z;
  12733. }
  12734. }
  12735. } else {
  12736. // non-indexed elements (unconnected triangle soup)
  12737. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  12738. pA.fromArray( positions, i );
  12739. pB.fromArray( positions, i + 3 );
  12740. pC.fromArray( positions, i + 6 );
  12741. cb.subVectors( pC, pB );
  12742. ab.subVectors( pA, pB );
  12743. cb.cross( ab );
  12744. normals[ i ] = cb.x;
  12745. normals[ i + 1 ] = cb.y;
  12746. normals[ i + 2 ] = cb.z;
  12747. normals[ i + 3 ] = cb.x;
  12748. normals[ i + 4 ] = cb.y;
  12749. normals[ i + 5 ] = cb.z;
  12750. normals[ i + 6 ] = cb.x;
  12751. normals[ i + 7 ] = cb.y;
  12752. normals[ i + 8 ] = cb.z;
  12753. }
  12754. }
  12755. this.normalizeNormals();
  12756. attributes.normal.needsUpdate = true;
  12757. }
  12758. },
  12759. merge: function ( geometry, offset ) {
  12760. if ( ( geometry && geometry.isBufferGeometry ) === false ) {
  12761. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  12762. return;
  12763. }
  12764. if ( offset === undefined ) offset = 0;
  12765. var attributes = this.attributes;
  12766. for ( var key in attributes ) {
  12767. if ( geometry.attributes[ key ] === undefined ) continue;
  12768. var attribute1 = attributes[ key ];
  12769. var attributeArray1 = attribute1.array;
  12770. var attribute2 = geometry.attributes[ key ];
  12771. var attributeArray2 = attribute2.array;
  12772. var attributeSize = attribute2.itemSize;
  12773. for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) {
  12774. attributeArray1[ j ] = attributeArray2[ i ];
  12775. }
  12776. }
  12777. return this;
  12778. },
  12779. normalizeNormals: function () {
  12780. var normals = this.attributes.normal.array;
  12781. var x, y, z, n;
  12782. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  12783. x = normals[ i ];
  12784. y = normals[ i + 1 ];
  12785. z = normals[ i + 2 ];
  12786. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  12787. normals[ i ] *= n;
  12788. normals[ i + 1 ] *= n;
  12789. normals[ i + 2 ] *= n;
  12790. }
  12791. },
  12792. toNonIndexed: function () {
  12793. if ( this.index === null ) {
  12794. console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' );
  12795. return this;
  12796. }
  12797. var geometry2 = new BufferGeometry();
  12798. var indices = this.index.array;
  12799. var attributes = this.attributes;
  12800. for ( var name in attributes ) {
  12801. var attribute = attributes[ name ];
  12802. var array = attribute.array;
  12803. var itemSize = attribute.itemSize;
  12804. var array2 = new array.constructor( indices.length * itemSize );
  12805. var index = 0, index2 = 0;
  12806. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  12807. index = indices[ i ] * itemSize;
  12808. for ( var j = 0; j < itemSize; j ++ ) {
  12809. array2[ index2 ++ ] = array[ index ++ ];
  12810. }
  12811. }
  12812. geometry2.addAttribute( name, new BufferAttribute( array2, itemSize ) );
  12813. }
  12814. return geometry2;
  12815. },
  12816. toJSON: function () {
  12817. var data = {
  12818. metadata: {
  12819. version: 4.4,
  12820. type: 'BufferGeometry',
  12821. generator: 'BufferGeometry.toJSON'
  12822. }
  12823. };
  12824. // standard BufferGeometry serialization
  12825. data.uuid = this.uuid;
  12826. data.type = this.type;
  12827. if ( this.name !== '' ) data.name = this.name;
  12828. if ( this.parameters !== undefined ) {
  12829. var parameters = this.parameters;
  12830. for ( var key in parameters ) {
  12831. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  12832. }
  12833. return data;
  12834. }
  12835. data.data = { attributes: {} };
  12836. var index = this.index;
  12837. if ( index !== null ) {
  12838. var array = Array.prototype.slice.call( index.array );
  12839. data.data.index = {
  12840. type: index.array.constructor.name,
  12841. array: array
  12842. };
  12843. }
  12844. var attributes = this.attributes;
  12845. for ( var key in attributes ) {
  12846. var attribute = attributes[ key ];
  12847. var array = Array.prototype.slice.call( attribute.array );
  12848. data.data.attributes[ key ] = {
  12849. itemSize: attribute.itemSize,
  12850. type: attribute.array.constructor.name,
  12851. array: array,
  12852. normalized: attribute.normalized
  12853. };
  12854. }
  12855. var groups = this.groups;
  12856. if ( groups.length > 0 ) {
  12857. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  12858. }
  12859. var boundingSphere = this.boundingSphere;
  12860. if ( boundingSphere !== null ) {
  12861. data.data.boundingSphere = {
  12862. center: boundingSphere.center.toArray(),
  12863. radius: boundingSphere.radius
  12864. };
  12865. }
  12866. return data;
  12867. },
  12868. clone: function () {
  12869. /*
  12870. // Handle primitives
  12871. var parameters = this.parameters;
  12872. if ( parameters !== undefined ) {
  12873. var values = [];
  12874. for ( var key in parameters ) {
  12875. values.push( parameters[ key ] );
  12876. }
  12877. var geometry = Object.create( this.constructor.prototype );
  12878. this.constructor.apply( geometry, values );
  12879. return geometry;
  12880. }
  12881. return new this.constructor().copy( this );
  12882. */
  12883. return new BufferGeometry().copy( this );
  12884. },
  12885. copy: function ( source ) {
  12886. var name, i, l;
  12887. // reset
  12888. this.index = null;
  12889. this.attributes = {};
  12890. this.morphAttributes = {};
  12891. this.groups = [];
  12892. this.boundingBox = null;
  12893. this.boundingSphere = null;
  12894. // name
  12895. this.name = source.name;
  12896. // index
  12897. var index = source.index;
  12898. if ( index !== null ) {
  12899. this.setIndex( index.clone() );
  12900. }
  12901. // attributes
  12902. var attributes = source.attributes;
  12903. for ( name in attributes ) {
  12904. var attribute = attributes[ name ];
  12905. this.addAttribute( name, attribute.clone() );
  12906. }
  12907. // morph attributes
  12908. var morphAttributes = source.morphAttributes;
  12909. for ( name in morphAttributes ) {
  12910. var array = [];
  12911. var morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  12912. for ( i = 0, l = morphAttribute.length; i < l; i ++ ) {
  12913. array.push( morphAttribute[ i ].clone() );
  12914. }
  12915. this.morphAttributes[ name ] = array;
  12916. }
  12917. // groups
  12918. var groups = source.groups;
  12919. for ( i = 0, l = groups.length; i < l; i ++ ) {
  12920. var group = groups[ i ];
  12921. this.addGroup( group.start, group.count, group.materialIndex );
  12922. }
  12923. // bounding box
  12924. var boundingBox = source.boundingBox;
  12925. if ( boundingBox !== null ) {
  12926. this.boundingBox = boundingBox.clone();
  12927. }
  12928. // bounding sphere
  12929. var boundingSphere = source.boundingSphere;
  12930. if ( boundingSphere !== null ) {
  12931. this.boundingSphere = boundingSphere.clone();
  12932. }
  12933. // draw range
  12934. this.drawRange.start = source.drawRange.start;
  12935. this.drawRange.count = source.drawRange.count;
  12936. return this;
  12937. },
  12938. dispose: function () {
  12939. this.dispatchEvent( { type: 'dispose' } );
  12940. }
  12941. };
  12942. BufferGeometry.MaxIndex = 65535;
  12943. Object.assign( BufferGeometry.prototype, EventDispatcher.prototype );
  12944. /**
  12945. * @author mrdoob / http://mrdoob.com/
  12946. * @author alteredq / http://alteredqualia.com/
  12947. * @author mikael emtinger / http://gomo.se/
  12948. * @author jonobr1 / http://jonobr1.com/
  12949. */
  12950. function Mesh( geometry, material ) {
  12951. Object3D.call( this );
  12952. this.type = 'Mesh';
  12953. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  12954. this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  12955. this.drawMode = TrianglesDrawMode;
  12956. this.updateMorphTargets();
  12957. }
  12958. Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
  12959. constructor: Mesh,
  12960. isMesh: true,
  12961. setDrawMode: function ( value ) {
  12962. this.drawMode = value;
  12963. },
  12964. copy: function ( source ) {
  12965. Object3D.prototype.copy.call( this, source );
  12966. this.drawMode = source.drawMode;
  12967. return this;
  12968. },
  12969. updateMorphTargets: function () {
  12970. var morphTargets = this.geometry.morphTargets;
  12971. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  12972. this.morphTargetInfluences = [];
  12973. this.morphTargetDictionary = {};
  12974. for ( var m = 0, ml = morphTargets.length; m < ml; m ++ ) {
  12975. this.morphTargetInfluences.push( 0 );
  12976. this.morphTargetDictionary[ morphTargets[ m ].name ] = m;
  12977. }
  12978. }
  12979. },
  12980. raycast: ( function () {
  12981. var inverseMatrix = new Matrix4();
  12982. var ray = new Ray();
  12983. var sphere = new Sphere();
  12984. var vA = new Vector3();
  12985. var vB = new Vector3();
  12986. var vC = new Vector3();
  12987. var tempA = new Vector3();
  12988. var tempB = new Vector3();
  12989. var tempC = new Vector3();
  12990. var uvA = new Vector2();
  12991. var uvB = new Vector2();
  12992. var uvC = new Vector2();
  12993. var barycoord = new Vector3();
  12994. var intersectionPoint = new Vector3();
  12995. var intersectionPointWorld = new Vector3();
  12996. function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) {
  12997. Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord );
  12998. uv1.multiplyScalar( barycoord.x );
  12999. uv2.multiplyScalar( barycoord.y );
  13000. uv3.multiplyScalar( barycoord.z );
  13001. uv1.add( uv2 ).add( uv3 );
  13002. return uv1.clone();
  13003. }
  13004. function checkIntersection( object, raycaster, ray, pA, pB, pC, point ) {
  13005. var intersect;
  13006. var material = object.material;
  13007. if ( material.side === BackSide ) {
  13008. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  13009. } else {
  13010. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  13011. }
  13012. if ( intersect === null ) return null;
  13013. intersectionPointWorld.copy( point );
  13014. intersectionPointWorld.applyMatrix4( object.matrixWorld );
  13015. var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld );
  13016. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  13017. return {
  13018. distance: distance,
  13019. point: intersectionPointWorld.clone(),
  13020. object: object
  13021. };
  13022. }
  13023. function checkBufferGeometryIntersection( object, raycaster, ray, position, uv, a, b, c ) {
  13024. vA.fromBufferAttribute( position, a );
  13025. vB.fromBufferAttribute( position, b );
  13026. vC.fromBufferAttribute( position, c );
  13027. var intersection = checkIntersection( object, raycaster, ray, vA, vB, vC, intersectionPoint );
  13028. if ( intersection ) {
  13029. if ( uv ) {
  13030. uvA.fromBufferAttribute( uv, a );
  13031. uvB.fromBufferAttribute( uv, b );
  13032. uvC.fromBufferAttribute( uv, c );
  13033. intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC );
  13034. }
  13035. intersection.face = new Face3( a, b, c, Triangle.normal( vA, vB, vC ) );
  13036. intersection.faceIndex = a;
  13037. }
  13038. return intersection;
  13039. }
  13040. return function raycast( raycaster, intersects ) {
  13041. var geometry = this.geometry;
  13042. var material = this.material;
  13043. var matrixWorld = this.matrixWorld;
  13044. if ( material === undefined ) return;
  13045. // Checking boundingSphere distance to ray
  13046. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  13047. sphere.copy( geometry.boundingSphere );
  13048. sphere.applyMatrix4( matrixWorld );
  13049. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  13050. //
  13051. inverseMatrix.getInverse( matrixWorld );
  13052. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  13053. // Check boundingBox before continuing
  13054. if ( geometry.boundingBox !== null ) {
  13055. if ( ray.intersectsBox( geometry.boundingBox ) === false ) return;
  13056. }
  13057. var intersection;
  13058. if ( geometry.isBufferGeometry ) {
  13059. var a, b, c;
  13060. var index = geometry.index;
  13061. var position = geometry.attributes.position;
  13062. var uv = geometry.attributes.uv;
  13063. var i, l;
  13064. if ( index !== null ) {
  13065. // indexed buffer geometry
  13066. for ( i = 0, l = index.count; i < l; i += 3 ) {
  13067. a = index.getX( i );
  13068. b = index.getX( i + 1 );
  13069. c = index.getX( i + 2 );
  13070. intersection = checkBufferGeometryIntersection( this, raycaster, ray, position, uv, a, b, c );
  13071. if ( intersection ) {
  13072. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics
  13073. intersects.push( intersection );
  13074. }
  13075. }
  13076. } else {
  13077. // non-indexed buffer geometry
  13078. for ( i = 0, l = position.count; i < l; i += 3 ) {
  13079. a = i;
  13080. b = i + 1;
  13081. c = i + 2;
  13082. intersection = checkBufferGeometryIntersection( this, raycaster, ray, position, uv, a, b, c );
  13083. if ( intersection ) {
  13084. intersection.index = a; // triangle number in positions buffer semantics
  13085. intersects.push( intersection );
  13086. }
  13087. }
  13088. }
  13089. } else if ( geometry.isGeometry ) {
  13090. var fvA, fvB, fvC;
  13091. var isFaceMaterial = ( material && material.isMultiMaterial );
  13092. var materials = isFaceMaterial === true ? material.materials : null;
  13093. var vertices = geometry.vertices;
  13094. var faces = geometry.faces;
  13095. var uvs;
  13096. var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  13097. if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;
  13098. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  13099. var face = faces[ f ];
  13100. var faceMaterial = isFaceMaterial === true ? materials[ face.materialIndex ] : material;
  13101. if ( faceMaterial === undefined ) continue;
  13102. fvA = vertices[ face.a ];
  13103. fvB = vertices[ face.b ];
  13104. fvC = vertices[ face.c ];
  13105. if ( faceMaterial.morphTargets === true ) {
  13106. var morphTargets = geometry.morphTargets;
  13107. var morphInfluences = this.morphTargetInfluences;
  13108. vA.set( 0, 0, 0 );
  13109. vB.set( 0, 0, 0 );
  13110. vC.set( 0, 0, 0 );
  13111. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  13112. var influence = morphInfluences[ t ];
  13113. if ( influence === 0 ) continue;
  13114. var targets = morphTargets[ t ].vertices;
  13115. vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence );
  13116. vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence );
  13117. vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence );
  13118. }
  13119. vA.add( fvA );
  13120. vB.add( fvB );
  13121. vC.add( fvC );
  13122. fvA = vA;
  13123. fvB = vB;
  13124. fvC = vC;
  13125. }
  13126. intersection = checkIntersection( this, raycaster, ray, fvA, fvB, fvC, intersectionPoint );
  13127. if ( intersection ) {
  13128. if ( uvs ) {
  13129. var uvs_f = uvs[ f ];
  13130. uvA.copy( uvs_f[ 0 ] );
  13131. uvB.copy( uvs_f[ 1 ] );
  13132. uvC.copy( uvs_f[ 2 ] );
  13133. intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC );
  13134. }
  13135. intersection.face = face;
  13136. intersection.faceIndex = f;
  13137. intersects.push( intersection );
  13138. }
  13139. }
  13140. }
  13141. };
  13142. }() ),
  13143. clone: function () {
  13144. return new this.constructor( this.geometry, this.material ).copy( this );
  13145. }
  13146. } );
  13147. /**
  13148. * @author mrdoob / http://mrdoob.com/
  13149. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  13150. */
  13151. function BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  13152. Geometry.call( this );
  13153. this.type = 'BoxGeometry';
  13154. this.parameters = {
  13155. width: width,
  13156. height: height,
  13157. depth: depth,
  13158. widthSegments: widthSegments,
  13159. heightSegments: heightSegments,
  13160. depthSegments: depthSegments
  13161. };
  13162. this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
  13163. this.mergeVertices();
  13164. }
  13165. BoxGeometry.prototype = Object.create( Geometry.prototype );
  13166. BoxGeometry.prototype.constructor = BoxGeometry;
  13167. /**
  13168. * @author Mugen87 / https://github.com/Mugen87
  13169. */
  13170. function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  13171. BufferGeometry.call( this );
  13172. this.type = 'BoxBufferGeometry';
  13173. this.parameters = {
  13174. width: width,
  13175. height: height,
  13176. depth: depth,
  13177. widthSegments: widthSegments,
  13178. heightSegments: heightSegments,
  13179. depthSegments: depthSegments
  13180. };
  13181. var scope = this;
  13182. // segments
  13183. widthSegments = Math.floor( widthSegments ) || 1;
  13184. heightSegments = Math.floor( heightSegments ) || 1;
  13185. depthSegments = Math.floor( depthSegments ) || 1;
  13186. // buffers
  13187. var indices = [];
  13188. var vertices = [];
  13189. var normals = [];
  13190. var uvs = [];
  13191. // helper variables
  13192. var numberOfVertices = 0;
  13193. var groupStart = 0;
  13194. // build each side of the box geometry
  13195. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  13196. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  13197. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  13198. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  13199. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  13200. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  13201. // build geometry
  13202. this.setIndex( indices );
  13203. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13204. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13205. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13206. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  13207. var segmentWidth = width / gridX;
  13208. var segmentHeight = height / gridY;
  13209. var widthHalf = width / 2;
  13210. var heightHalf = height / 2;
  13211. var depthHalf = depth / 2;
  13212. var gridX1 = gridX + 1;
  13213. var gridY1 = gridY + 1;
  13214. var vertexCounter = 0;
  13215. var groupCount = 0;
  13216. var ix, iy;
  13217. var vector = new Vector3();
  13218. // generate vertices, normals and uvs
  13219. for ( iy = 0; iy < gridY1; iy ++ ) {
  13220. var y = iy * segmentHeight - heightHalf;
  13221. for ( ix = 0; ix < gridX1; ix ++ ) {
  13222. var x = ix * segmentWidth - widthHalf;
  13223. // set values to correct vector component
  13224. vector[ u ] = x * udir;
  13225. vector[ v ] = y * vdir;
  13226. vector[ w ] = depthHalf;
  13227. // now apply vector to vertex buffer
  13228. vertices.push( vector.x, vector.y, vector.z );
  13229. // set values to correct vector component
  13230. vector[ u ] = 0;
  13231. vector[ v ] = 0;
  13232. vector[ w ] = depth > 0 ? 1 : - 1;
  13233. // now apply vector to normal buffer
  13234. normals.push( vector.x, vector.y, vector.z );
  13235. // uvs
  13236. uvs.push( ix / gridX );
  13237. uvs.push( 1 - ( iy / gridY ) );
  13238. // counters
  13239. vertexCounter += 1;
  13240. }
  13241. }
  13242. // indices
  13243. // 1. you need three indices to draw a single face
  13244. // 2. a single segment consists of two faces
  13245. // 3. so we need to generate six (2*3) indices per segment
  13246. for ( iy = 0; iy < gridY; iy ++ ) {
  13247. for ( ix = 0; ix < gridX; ix ++ ) {
  13248. var a = numberOfVertices + ix + gridX1 * iy;
  13249. var b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  13250. var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  13251. var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  13252. // faces
  13253. indices.push( a, b, d );
  13254. indices.push( b, c, d );
  13255. // increase counter
  13256. groupCount += 6;
  13257. }
  13258. }
  13259. // add a group to the geometry. this will ensure multi material support
  13260. scope.addGroup( groupStart, groupCount, materialIndex );
  13261. // calculate new start value for groups
  13262. groupStart += groupCount;
  13263. // update total number of vertices
  13264. numberOfVertices += vertexCounter;
  13265. }
  13266. }
  13267. BoxBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  13268. BoxBufferGeometry.prototype.constructor = BoxBufferGeometry;
  13269. /**
  13270. * @author mrdoob / http://mrdoob.com/
  13271. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  13272. */
  13273. function PlaneGeometry( width, height, widthSegments, heightSegments ) {
  13274. Geometry.call( this );
  13275. this.type = 'PlaneGeometry';
  13276. this.parameters = {
  13277. width: width,
  13278. height: height,
  13279. widthSegments: widthSegments,
  13280. heightSegments: heightSegments
  13281. };
  13282. this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  13283. }
  13284. PlaneGeometry.prototype = Object.create( Geometry.prototype );
  13285. PlaneGeometry.prototype.constructor = PlaneGeometry;
  13286. /**
  13287. * @author mrdoob / http://mrdoob.com/
  13288. * @author Mugen87 / https://github.com/Mugen87
  13289. *
  13290. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  13291. */
  13292. function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) {
  13293. BufferGeometry.call( this );
  13294. this.type = 'PlaneBufferGeometry';
  13295. this.parameters = {
  13296. width: width,
  13297. height: height,
  13298. widthSegments: widthSegments,
  13299. heightSegments: heightSegments
  13300. };
  13301. var width_half = width / 2;
  13302. var height_half = height / 2;
  13303. var gridX = Math.floor( widthSegments ) || 1;
  13304. var gridY = Math.floor( heightSegments ) || 1;
  13305. var gridX1 = gridX + 1;
  13306. var gridY1 = gridY + 1;
  13307. var segment_width = width / gridX;
  13308. var segment_height = height / gridY;
  13309. var ix, iy;
  13310. // buffers
  13311. var indices = [];
  13312. var vertices = [];
  13313. var normals = [];
  13314. var uvs = [];
  13315. // generate vertices, normals and uvs
  13316. for ( iy = 0; iy < gridY1; iy ++ ) {
  13317. var y = iy * segment_height - height_half;
  13318. for ( ix = 0; ix < gridX1; ix ++ ) {
  13319. var x = ix * segment_width - width_half;
  13320. vertices.push( x, - y, 0 );
  13321. normals.push( 0, 0, 1 );
  13322. uvs.push( ix / gridX );
  13323. uvs.push( 1 - ( iy / gridY ) );
  13324. }
  13325. }
  13326. // indices
  13327. for ( iy = 0; iy < gridY; iy ++ ) {
  13328. for ( ix = 0; ix < gridX; ix ++ ) {
  13329. var a = ix + gridX1 * iy;
  13330. var b = ix + gridX1 * ( iy + 1 );
  13331. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  13332. var d = ( ix + 1 ) + gridX1 * iy;
  13333. // faces
  13334. indices.push( a, b, d );
  13335. indices.push( b, c, d );
  13336. }
  13337. }
  13338. // build geometry
  13339. this.setIndex( indices );
  13340. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13341. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13342. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13343. }
  13344. PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  13345. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  13346. /**
  13347. * @author mrdoob / http://mrdoob.com/
  13348. * @author mikael emtinger / http://gomo.se/
  13349. * @author WestLangley / http://github.com/WestLangley
  13350. */
  13351. function Camera() {
  13352. Object3D.call( this );
  13353. this.type = 'Camera';
  13354. this.matrixWorldInverse = new Matrix4();
  13355. this.projectionMatrix = new Matrix4();
  13356. }
  13357. Camera.prototype = Object.create( Object3D.prototype );
  13358. Camera.prototype.constructor = Camera;
  13359. Camera.prototype.isCamera = true;
  13360. Camera.prototype.getWorldDirection = function () {
  13361. var quaternion = new Quaternion();
  13362. return function getWorldDirection( optionalTarget ) {
  13363. var result = optionalTarget || new Vector3();
  13364. this.getWorldQuaternion( quaternion );
  13365. return result.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  13366. };
  13367. }();
  13368. Camera.prototype.lookAt = function () {
  13369. // This routine does not support cameras with rotated and/or translated parent(s)
  13370. var m1 = new Matrix4();
  13371. return function lookAt( vector ) {
  13372. m1.lookAt( this.position, vector, this.up );
  13373. this.quaternion.setFromRotationMatrix( m1 );
  13374. };
  13375. }();
  13376. Camera.prototype.clone = function () {
  13377. return new this.constructor().copy( this );
  13378. };
  13379. Camera.prototype.copy = function ( source ) {
  13380. Object3D.prototype.copy.call( this, source );
  13381. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  13382. this.projectionMatrix.copy( source.projectionMatrix );
  13383. return this;
  13384. };
  13385. /**
  13386. * @author mrdoob / http://mrdoob.com/
  13387. * @author greggman / http://games.greggman.com/
  13388. * @author zz85 / http://www.lab4games.net/zz85/blog
  13389. * @author tschw
  13390. */
  13391. function PerspectiveCamera( fov, aspect, near, far ) {
  13392. Camera.call( this );
  13393. this.type = 'PerspectiveCamera';
  13394. this.fov = fov !== undefined ? fov : 50;
  13395. this.zoom = 1;
  13396. this.near = near !== undefined ? near : 0.1;
  13397. this.far = far !== undefined ? far : 2000;
  13398. this.focus = 10;
  13399. this.aspect = aspect !== undefined ? aspect : 1;
  13400. this.view = null;
  13401. this.filmGauge = 35; // width of the film (default in millimeters)
  13402. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  13403. this.updateProjectionMatrix();
  13404. }
  13405. PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  13406. constructor: PerspectiveCamera,
  13407. isPerspectiveCamera: true,
  13408. copy: function ( source ) {
  13409. Camera.prototype.copy.call( this, source );
  13410. this.fov = source.fov;
  13411. this.zoom = source.zoom;
  13412. this.near = source.near;
  13413. this.far = source.far;
  13414. this.focus = source.focus;
  13415. this.aspect = source.aspect;
  13416. this.view = source.view === null ? null : Object.assign( {}, source.view );
  13417. this.filmGauge = source.filmGauge;
  13418. this.filmOffset = source.filmOffset;
  13419. return this;
  13420. },
  13421. /**
  13422. * Sets the FOV by focal length in respect to the current .filmGauge.
  13423. *
  13424. * The default film gauge is 35, so that the focal length can be specified for
  13425. * a 35mm (full frame) camera.
  13426. *
  13427. * Values for focal length and film gauge must have the same unit.
  13428. */
  13429. setFocalLength: function ( focalLength ) {
  13430. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  13431. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  13432. this.fov = _Math.RAD2DEG * 2 * Math.atan( vExtentSlope );
  13433. this.updateProjectionMatrix();
  13434. },
  13435. /**
  13436. * Calculates the focal length from the current .fov and .filmGauge.
  13437. */
  13438. getFocalLength: function () {
  13439. var vExtentSlope = Math.tan( _Math.DEG2RAD * 0.5 * this.fov );
  13440. return 0.5 * this.getFilmHeight() / vExtentSlope;
  13441. },
  13442. getEffectiveFOV: function () {
  13443. return _Math.RAD2DEG * 2 * Math.atan(
  13444. Math.tan( _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom );
  13445. },
  13446. getFilmWidth: function () {
  13447. // film not completely covered in portrait format (aspect < 1)
  13448. return this.filmGauge * Math.min( this.aspect, 1 );
  13449. },
  13450. getFilmHeight: function () {
  13451. // film not completely covered in landscape format (aspect > 1)
  13452. return this.filmGauge / Math.max( this.aspect, 1 );
  13453. },
  13454. /**
  13455. * Sets an offset in a larger frustum. This is useful for multi-window or
  13456. * multi-monitor/multi-machine setups.
  13457. *
  13458. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  13459. * the monitors are in grid like this
  13460. *
  13461. * +---+---+---+
  13462. * | A | B | C |
  13463. * +---+---+---+
  13464. * | D | E | F |
  13465. * +---+---+---+
  13466. *
  13467. * then for each monitor you would call it like this
  13468. *
  13469. * var w = 1920;
  13470. * var h = 1080;
  13471. * var fullWidth = w * 3;
  13472. * var fullHeight = h * 2;
  13473. *
  13474. * --A--
  13475. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  13476. * --B--
  13477. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  13478. * --C--
  13479. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  13480. * --D--
  13481. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  13482. * --E--
  13483. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  13484. * --F--
  13485. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  13486. *
  13487. * Note there is no reason monitors have to be the same size or in a grid.
  13488. */
  13489. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  13490. this.aspect = fullWidth / fullHeight;
  13491. this.view = {
  13492. fullWidth: fullWidth,
  13493. fullHeight: fullHeight,
  13494. offsetX: x,
  13495. offsetY: y,
  13496. width: width,
  13497. height: height
  13498. };
  13499. this.updateProjectionMatrix();
  13500. },
  13501. clearViewOffset: function() {
  13502. this.view = null;
  13503. this.updateProjectionMatrix();
  13504. },
  13505. updateProjectionMatrix: function () {
  13506. var near = this.near,
  13507. top = near * Math.tan(
  13508. _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom,
  13509. height = 2 * top,
  13510. width = this.aspect * height,
  13511. left = - 0.5 * width,
  13512. view = this.view;
  13513. if ( view !== null ) {
  13514. var fullWidth = view.fullWidth,
  13515. fullHeight = view.fullHeight;
  13516. left += view.offsetX * width / fullWidth;
  13517. top -= view.offsetY * height / fullHeight;
  13518. width *= view.width / fullWidth;
  13519. height *= view.height / fullHeight;
  13520. }
  13521. var skew = this.filmOffset;
  13522. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  13523. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  13524. },
  13525. toJSON: function ( meta ) {
  13526. var data = Object3D.prototype.toJSON.call( this, meta );
  13527. data.object.fov = this.fov;
  13528. data.object.zoom = this.zoom;
  13529. data.object.near = this.near;
  13530. data.object.far = this.far;
  13531. data.object.focus = this.focus;
  13532. data.object.aspect = this.aspect;
  13533. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  13534. data.object.filmGauge = this.filmGauge;
  13535. data.object.filmOffset = this.filmOffset;
  13536. return data;
  13537. }
  13538. } );
  13539. /**
  13540. * @author alteredq / http://alteredqualia.com/
  13541. * @author arose / http://github.com/arose
  13542. */
  13543. function OrthographicCamera( left, right, top, bottom, near, far ) {
  13544. Camera.call( this );
  13545. this.type = 'OrthographicCamera';
  13546. this.zoom = 1;
  13547. this.view = null;
  13548. this.left = left;
  13549. this.right = right;
  13550. this.top = top;
  13551. this.bottom = bottom;
  13552. this.near = ( near !== undefined ) ? near : 0.1;
  13553. this.far = ( far !== undefined ) ? far : 2000;
  13554. this.updateProjectionMatrix();
  13555. }
  13556. OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  13557. constructor: OrthographicCamera,
  13558. isOrthographicCamera: true,
  13559. copy: function ( source ) {
  13560. Camera.prototype.copy.call( this, source );
  13561. this.left = source.left;
  13562. this.right = source.right;
  13563. this.top = source.top;
  13564. this.bottom = source.bottom;
  13565. this.near = source.near;
  13566. this.far = source.far;
  13567. this.zoom = source.zoom;
  13568. this.view = source.view === null ? null : Object.assign( {}, source.view );
  13569. return this;
  13570. },
  13571. setViewOffset: function( fullWidth, fullHeight, x, y, width, height ) {
  13572. this.view = {
  13573. fullWidth: fullWidth,
  13574. fullHeight: fullHeight,
  13575. offsetX: x,
  13576. offsetY: y,
  13577. width: width,
  13578. height: height
  13579. };
  13580. this.updateProjectionMatrix();
  13581. },
  13582. clearViewOffset: function() {
  13583. this.view = null;
  13584. this.updateProjectionMatrix();
  13585. },
  13586. updateProjectionMatrix: function () {
  13587. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  13588. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  13589. var cx = ( this.right + this.left ) / 2;
  13590. var cy = ( this.top + this.bottom ) / 2;
  13591. var left = cx - dx;
  13592. var right = cx + dx;
  13593. var top = cy + dy;
  13594. var bottom = cy - dy;
  13595. if ( this.view !== null ) {
  13596. var zoomW = this.zoom / ( this.view.width / this.view.fullWidth );
  13597. var zoomH = this.zoom / ( this.view.height / this.view.fullHeight );
  13598. var scaleW = ( this.right - this.left ) / this.view.width;
  13599. var scaleH = ( this.top - this.bottom ) / this.view.height;
  13600. left += scaleW * ( this.view.offsetX / zoomW );
  13601. right = left + scaleW * ( this.view.width / zoomW );
  13602. top -= scaleH * ( this.view.offsetY / zoomH );
  13603. bottom = top - scaleH * ( this.view.height / zoomH );
  13604. }
  13605. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  13606. },
  13607. toJSON: function ( meta ) {
  13608. var data = Object3D.prototype.toJSON.call( this, meta );
  13609. data.object.zoom = this.zoom;
  13610. data.object.left = this.left;
  13611. data.object.right = this.right;
  13612. data.object.top = this.top;
  13613. data.object.bottom = this.bottom;
  13614. data.object.near = this.near;
  13615. data.object.far = this.far;
  13616. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  13617. return data;
  13618. }
  13619. } );
  13620. /**
  13621. * @author mrdoob / http://mrdoob.com/
  13622. */
  13623. function WebGLIndexedBufferRenderer( gl, extensions, infoRender ) {
  13624. var mode;
  13625. function setMode( value ) {
  13626. mode = value;
  13627. }
  13628. var type, size;
  13629. function setIndex( index ) {
  13630. if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) {
  13631. type = gl.UNSIGNED_INT;
  13632. size = 4;
  13633. } else if ( index.array instanceof Uint16Array ) {
  13634. type = gl.UNSIGNED_SHORT;
  13635. size = 2;
  13636. } else {
  13637. type = gl.UNSIGNED_BYTE;
  13638. size = 1;
  13639. }
  13640. }
  13641. function render( start, count ) {
  13642. gl.drawElements( mode, count, type, start * size );
  13643. infoRender.calls ++;
  13644. infoRender.vertices += count;
  13645. if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3;
  13646. }
  13647. function renderInstances( geometry, start, count ) {
  13648. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  13649. if ( extension === null ) {
  13650. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  13651. return;
  13652. }
  13653. extension.drawElementsInstancedANGLE( mode, count, type, start * size, geometry.maxInstancedCount );
  13654. infoRender.calls ++;
  13655. infoRender.vertices += count * geometry.maxInstancedCount;
  13656. if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3;
  13657. }
  13658. return {
  13659. setMode: setMode,
  13660. setIndex: setIndex,
  13661. render: render,
  13662. renderInstances: renderInstances
  13663. };
  13664. }
  13665. /**
  13666. * @author mrdoob / http://mrdoob.com/
  13667. */
  13668. function WebGLBufferRenderer( gl, extensions, infoRender ) {
  13669. var mode;
  13670. function setMode( value ) {
  13671. mode = value;
  13672. }
  13673. function render( start, count ) {
  13674. gl.drawArrays( mode, start, count );
  13675. infoRender.calls ++;
  13676. infoRender.vertices += count;
  13677. if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3;
  13678. }
  13679. function renderInstances( geometry ) {
  13680. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  13681. if ( extension === null ) {
  13682. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  13683. return;
  13684. }
  13685. var position = geometry.attributes.position;
  13686. var count = 0;
  13687. if ( position.isInterleavedBufferAttribute ) {
  13688. count = position.data.count;
  13689. extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
  13690. } else {
  13691. count = position.count;
  13692. extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
  13693. }
  13694. infoRender.calls ++;
  13695. infoRender.vertices += count * geometry.maxInstancedCount;
  13696. if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3;
  13697. }
  13698. return {
  13699. setMode: setMode,
  13700. render: render,
  13701. renderInstances: renderInstances
  13702. };
  13703. }
  13704. /**
  13705. * @author mrdoob / http://mrdoob.com/
  13706. */
  13707. function WebGLLights() {
  13708. var lights = {};
  13709. return {
  13710. get: function ( light ) {
  13711. if ( lights[ light.id ] !== undefined ) {
  13712. return lights[ light.id ];
  13713. }
  13714. var uniforms;
  13715. switch ( light.type ) {
  13716. case 'DirectionalLight':
  13717. uniforms = {
  13718. direction: new Vector3(),
  13719. color: new Color(),
  13720. shadow: false,
  13721. shadowBias: 0,
  13722. shadowRadius: 1,
  13723. shadowMapSize: new Vector2()
  13724. };
  13725. break;
  13726. case 'SpotLight':
  13727. uniforms = {
  13728. position: new Vector3(),
  13729. direction: new Vector3(),
  13730. color: new Color(),
  13731. distance: 0,
  13732. coneCos: 0,
  13733. penumbraCos: 0,
  13734. decay: 0,
  13735. shadow: false,
  13736. shadowBias: 0,
  13737. shadowRadius: 1,
  13738. shadowMapSize: new Vector2()
  13739. };
  13740. break;
  13741. case 'PointLight':
  13742. uniforms = {
  13743. position: new Vector3(),
  13744. color: new Color(),
  13745. distance: 0,
  13746. decay: 0,
  13747. shadow: false,
  13748. shadowBias: 0,
  13749. shadowRadius: 1,
  13750. shadowMapSize: new Vector2()
  13751. };
  13752. break;
  13753. case 'HemisphereLight':
  13754. uniforms = {
  13755. direction: new Vector3(),
  13756. skyColor: new Color(),
  13757. groundColor: new Color()
  13758. };
  13759. break;
  13760. case 'RectAreaLight':
  13761. uniforms = {
  13762. color: new Color(),
  13763. position: new Vector3(),
  13764. halfWidth: new Vector3(),
  13765. halfHeight: new Vector3()
  13766. // TODO (abelnation): set RectAreaLight shadow uniforms
  13767. };
  13768. break;
  13769. }
  13770. lights[ light.id ] = uniforms;
  13771. return uniforms;
  13772. }
  13773. };
  13774. }
  13775. /**
  13776. * @author mrdoob / http://mrdoob.com/
  13777. */
  13778. function addLineNumbers( string ) {
  13779. var lines = string.split( '\n' );
  13780. for ( var i = 0; i < lines.length; i ++ ) {
  13781. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  13782. }
  13783. return lines.join( '\n' );
  13784. }
  13785. function WebGLShader( gl, type, string ) {
  13786. var shader = gl.createShader( type );
  13787. gl.shaderSource( shader, string );
  13788. gl.compileShader( shader );
  13789. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  13790. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  13791. }
  13792. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  13793. console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) );
  13794. }
  13795. // --enable-privileged-webgl-extension
  13796. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  13797. return shader;
  13798. }
  13799. /**
  13800. * @author mrdoob / http://mrdoob.com/
  13801. */
  13802. var programIdCount = 0;
  13803. function getEncodingComponents( encoding ) {
  13804. switch ( encoding ) {
  13805. case LinearEncoding:
  13806. return [ 'Linear','( value )' ];
  13807. case sRGBEncoding:
  13808. return [ 'sRGB','( value )' ];
  13809. case RGBEEncoding:
  13810. return [ 'RGBE','( value )' ];
  13811. case RGBM7Encoding:
  13812. return [ 'RGBM','( value, 7.0 )' ];
  13813. case RGBM16Encoding:
  13814. return [ 'RGBM','( value, 16.0 )' ];
  13815. case RGBDEncoding:
  13816. return [ 'RGBD','( value, 256.0 )' ];
  13817. case GammaEncoding:
  13818. return [ 'Gamma','( value, float( GAMMA_FACTOR ) )' ];
  13819. default:
  13820. throw new Error( 'unsupported encoding: ' + encoding );
  13821. }
  13822. }
  13823. function getTexelDecodingFunction( functionName, encoding ) {
  13824. var components = getEncodingComponents( encoding );
  13825. return "vec4 " + functionName + "( vec4 value ) { return " + components[ 0 ] + "ToLinear" + components[ 1 ] + "; }";
  13826. }
  13827. function getTexelEncodingFunction( functionName, encoding ) {
  13828. var components = getEncodingComponents( encoding );
  13829. return "vec4 " + functionName + "( vec4 value ) { return LinearTo" + components[ 0 ] + components[ 1 ] + "; }";
  13830. }
  13831. function getToneMappingFunction( functionName, toneMapping ) {
  13832. var toneMappingName;
  13833. switch ( toneMapping ) {
  13834. case LinearToneMapping:
  13835. toneMappingName = "Linear";
  13836. break;
  13837. case ReinhardToneMapping:
  13838. toneMappingName = "Reinhard";
  13839. break;
  13840. case Uncharted2ToneMapping:
  13841. toneMappingName = "Uncharted2";
  13842. break;
  13843. case CineonToneMapping:
  13844. toneMappingName = "OptimizedCineon";
  13845. break;
  13846. default:
  13847. throw new Error( 'unsupported toneMapping: ' + toneMapping );
  13848. }
  13849. return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }";
  13850. }
  13851. function generateExtensions( extensions, parameters, rendererExtensions ) {
  13852. extensions = extensions || {};
  13853. var chunks = [
  13854. ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  13855. ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '',
  13856. ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '',
  13857. ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  13858. ];
  13859. return chunks.filter( filterEmptyLine ).join( '\n' );
  13860. }
  13861. function generateDefines( defines ) {
  13862. var chunks = [];
  13863. for ( var name in defines ) {
  13864. var value = defines[ name ];
  13865. if ( value === false ) continue;
  13866. chunks.push( '#define ' + name + ' ' + value );
  13867. }
  13868. return chunks.join( '\n' );
  13869. }
  13870. function fetchAttributeLocations( gl, program, identifiers ) {
  13871. var attributes = {};
  13872. var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  13873. for ( var i = 0; i < n; i ++ ) {
  13874. var info = gl.getActiveAttrib( program, i );
  13875. var name = info.name;
  13876. // console.log("THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:", name, i );
  13877. attributes[ name ] = gl.getAttribLocation( program, name );
  13878. }
  13879. return attributes;
  13880. }
  13881. function filterEmptyLine( string ) {
  13882. return string !== '';
  13883. }
  13884. function replaceLightNums( string, parameters ) {
  13885. return string
  13886. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  13887. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  13888. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  13889. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  13890. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights );
  13891. }
  13892. function parseIncludes( string ) {
  13893. var pattern = /#include +<([\w\d.]+)>/g;
  13894. function replace( match, include ) {
  13895. var replace = ShaderChunk[ include ];
  13896. if ( replace === undefined ) {
  13897. throw new Error( 'Can not resolve #include <' + include + '>' );
  13898. }
  13899. return parseIncludes( replace );
  13900. }
  13901. return string.replace( pattern, replace );
  13902. }
  13903. function unrollLoops( string ) {
  13904. var pattern = /for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  13905. function replace( match, start, end, snippet ) {
  13906. var unroll = '';
  13907. for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) {
  13908. unroll += snippet.replace( /\[ i \]/g, '[ ' + i + ' ]' );
  13909. }
  13910. return unroll;
  13911. }
  13912. return string.replace( pattern, replace );
  13913. }
  13914. function WebGLProgram( renderer, code, material, parameters ) {
  13915. var gl = renderer.context;
  13916. var extensions = material.extensions;
  13917. var defines = material.defines;
  13918. var vertexShader = material.__webglShader.vertexShader;
  13919. var fragmentShader = material.__webglShader.fragmentShader;
  13920. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  13921. if ( parameters.shadowMapType === PCFShadowMap ) {
  13922. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  13923. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  13924. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  13925. }
  13926. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  13927. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  13928. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  13929. if ( parameters.envMap ) {
  13930. switch ( material.envMap.mapping ) {
  13931. case CubeReflectionMapping:
  13932. case CubeRefractionMapping:
  13933. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  13934. break;
  13935. case CubeUVReflectionMapping:
  13936. case CubeUVRefractionMapping:
  13937. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  13938. break;
  13939. case EquirectangularReflectionMapping:
  13940. case EquirectangularRefractionMapping:
  13941. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  13942. break;
  13943. case SphericalReflectionMapping:
  13944. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  13945. break;
  13946. }
  13947. switch ( material.envMap.mapping ) {
  13948. case CubeRefractionMapping:
  13949. case EquirectangularRefractionMapping:
  13950. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  13951. break;
  13952. }
  13953. switch ( material.combine ) {
  13954. case MultiplyOperation:
  13955. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  13956. break;
  13957. case MixOperation:
  13958. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  13959. break;
  13960. case AddOperation:
  13961. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  13962. break;
  13963. }
  13964. }
  13965. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  13966. // console.log( 'building new program ' );
  13967. //
  13968. var customExtensions = generateExtensions( extensions, parameters, renderer.extensions );
  13969. var customDefines = generateDefines( defines );
  13970. //
  13971. var program = gl.createProgram();
  13972. var prefixVertex, prefixFragment;
  13973. if ( material.isRawShaderMaterial ) {
  13974. prefixVertex = [
  13975. customDefines,
  13976. '\n'
  13977. ].filter( filterEmptyLine ).join( '\n' );
  13978. prefixFragment = [
  13979. customExtensions,
  13980. customDefines,
  13981. '\n'
  13982. ].filter( filterEmptyLine ).join( '\n' );
  13983. } else {
  13984. prefixVertex = [
  13985. 'precision ' + parameters.precision + ' float;',
  13986. 'precision ' + parameters.precision + ' int;',
  13987. '#define SHADER_NAME ' + material.__webglShader.name,
  13988. customDefines,
  13989. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  13990. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  13991. '#define MAX_BONES ' + parameters.maxBones,
  13992. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  13993. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  13994. parameters.map ? '#define USE_MAP' : '',
  13995. parameters.envMap ? '#define USE_ENVMAP' : '',
  13996. parameters.envMap ? '#define ' + envMapModeDefine : '',
  13997. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  13998. parameters.aoMap ? '#define USE_AOMAP' : '',
  13999. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  14000. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  14001. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  14002. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  14003. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  14004. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  14005. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  14006. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  14007. parameters.vertexColors ? '#define USE_COLOR' : '',
  14008. parameters.flatShading ? '#define FLAT_SHADED' : '',
  14009. parameters.skinning ? '#define USE_SKINNING' : '',
  14010. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  14011. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  14012. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  14013. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  14014. parameters.flipSided ? '#define FLIP_SIDED' : '',
  14015. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  14016. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  14017. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  14018. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  14019. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  14020. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  14021. 'uniform mat4 modelMatrix;',
  14022. 'uniform mat4 modelViewMatrix;',
  14023. 'uniform mat4 projectionMatrix;',
  14024. 'uniform mat4 viewMatrix;',
  14025. 'uniform mat3 normalMatrix;',
  14026. 'uniform vec3 cameraPosition;',
  14027. 'attribute vec3 position;',
  14028. 'attribute vec3 normal;',
  14029. 'attribute vec2 uv;',
  14030. '#ifdef USE_COLOR',
  14031. ' attribute vec3 color;',
  14032. '#endif',
  14033. '#ifdef USE_MORPHTARGETS',
  14034. ' attribute vec3 morphTarget0;',
  14035. ' attribute vec3 morphTarget1;',
  14036. ' attribute vec3 morphTarget2;',
  14037. ' attribute vec3 morphTarget3;',
  14038. ' #ifdef USE_MORPHNORMALS',
  14039. ' attribute vec3 morphNormal0;',
  14040. ' attribute vec3 morphNormal1;',
  14041. ' attribute vec3 morphNormal2;',
  14042. ' attribute vec3 morphNormal3;',
  14043. ' #else',
  14044. ' attribute vec3 morphTarget4;',
  14045. ' attribute vec3 morphTarget5;',
  14046. ' attribute vec3 morphTarget6;',
  14047. ' attribute vec3 morphTarget7;',
  14048. ' #endif',
  14049. '#endif',
  14050. '#ifdef USE_SKINNING',
  14051. ' attribute vec4 skinIndex;',
  14052. ' attribute vec4 skinWeight;',
  14053. '#endif',
  14054. '\n'
  14055. ].filter( filterEmptyLine ).join( '\n' );
  14056. prefixFragment = [
  14057. customExtensions,
  14058. 'precision ' + parameters.precision + ' float;',
  14059. 'precision ' + parameters.precision + ' int;',
  14060. '#define SHADER_NAME ' + material.__webglShader.name,
  14061. customDefines,
  14062. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '',
  14063. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  14064. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  14065. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  14066. parameters.map ? '#define USE_MAP' : '',
  14067. parameters.envMap ? '#define USE_ENVMAP' : '',
  14068. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  14069. parameters.envMap ? '#define ' + envMapModeDefine : '',
  14070. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  14071. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  14072. parameters.aoMap ? '#define USE_AOMAP' : '',
  14073. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  14074. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  14075. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  14076. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  14077. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  14078. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  14079. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  14080. parameters.vertexColors ? '#define USE_COLOR' : '',
  14081. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  14082. parameters.flatShading ? '#define FLAT_SHADED' : '',
  14083. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  14084. parameters.flipSided ? '#define FLIP_SIDED' : '',
  14085. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  14086. '#define UNION_CLIPPING_PLANES ' + (parameters.numClippingPlanes - parameters.numClipIntersection),
  14087. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  14088. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  14089. parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : '',
  14090. parameters.physicallyCorrectLights ? "#define PHYSICALLY_CORRECT_LIGHTS" : '',
  14091. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  14092. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  14093. parameters.envMap && renderer.extensions.get( 'EXT_shader_texture_lod' ) ? '#define TEXTURE_LOD_EXT' : '',
  14094. 'uniform mat4 viewMatrix;',
  14095. 'uniform vec3 cameraPosition;',
  14096. ( parameters.toneMapping !== NoToneMapping ) ? "#define TONE_MAPPING" : '',
  14097. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  14098. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( "toneMapping", parameters.toneMapping ) : '',
  14099. ( 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
  14100. parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  14101. parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  14102. parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  14103. parameters.outputEncoding ? getTexelEncodingFunction( "linearToOutputTexel", parameters.outputEncoding ) : '',
  14104. parameters.depthPacking ? "#define DEPTH_PACKING " + material.depthPacking : '',
  14105. '\n'
  14106. ].filter( filterEmptyLine ).join( '\n' );
  14107. }
  14108. vertexShader = parseIncludes( vertexShader, parameters );
  14109. vertexShader = replaceLightNums( vertexShader, parameters );
  14110. fragmentShader = parseIncludes( fragmentShader, parameters );
  14111. fragmentShader = replaceLightNums( fragmentShader, parameters );
  14112. if ( ! material.isShaderMaterial ) {
  14113. vertexShader = unrollLoops( vertexShader );
  14114. fragmentShader = unrollLoops( fragmentShader );
  14115. }
  14116. var vertexGlsl = prefixVertex + vertexShader;
  14117. var fragmentGlsl = prefixFragment + fragmentShader;
  14118. // console.log( '*VERTEX*', vertexGlsl );
  14119. // console.log( '*FRAGMENT*', fragmentGlsl );
  14120. var glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  14121. var glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  14122. gl.attachShader( program, glVertexShader );
  14123. gl.attachShader( program, glFragmentShader );
  14124. // Force a particular attribute to index 0.
  14125. if ( material.index0AttributeName !== undefined ) {
  14126. gl.bindAttribLocation( program, 0, material.index0AttributeName );
  14127. } else if ( parameters.morphTargets === true ) {
  14128. // programs with morphTargets displace position out of attribute 0
  14129. gl.bindAttribLocation( program, 0, 'position' );
  14130. }
  14131. gl.linkProgram( program );
  14132. var programLog = gl.getProgramInfoLog( program );
  14133. var vertexLog = gl.getShaderInfoLog( glVertexShader );
  14134. var fragmentLog = gl.getShaderInfoLog( glFragmentShader );
  14135. var runnable = true;
  14136. var haveDiagnostics = true;
  14137. // console.log( '**VERTEX**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) );
  14138. // console.log( '**FRAGMENT**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) );
  14139. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  14140. runnable = false;
  14141. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog );
  14142. } else if ( programLog !== '' ) {
  14143. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  14144. } else if ( vertexLog === '' || fragmentLog === '' ) {
  14145. haveDiagnostics = false;
  14146. }
  14147. if ( haveDiagnostics ) {
  14148. this.diagnostics = {
  14149. runnable: runnable,
  14150. material: material,
  14151. programLog: programLog,
  14152. vertexShader: {
  14153. log: vertexLog,
  14154. prefix: prefixVertex
  14155. },
  14156. fragmentShader: {
  14157. log: fragmentLog,
  14158. prefix: prefixFragment
  14159. }
  14160. };
  14161. }
  14162. // clean up
  14163. gl.deleteShader( glVertexShader );
  14164. gl.deleteShader( glFragmentShader );
  14165. // set up caching for uniform locations
  14166. var cachedUniforms;
  14167. this.getUniforms = function() {
  14168. if ( cachedUniforms === undefined ) {
  14169. cachedUniforms =
  14170. new WebGLUniforms( gl, program, renderer );
  14171. }
  14172. return cachedUniforms;
  14173. };
  14174. // set up caching for attribute locations
  14175. var cachedAttributes;
  14176. this.getAttributes = function() {
  14177. if ( cachedAttributes === undefined ) {
  14178. cachedAttributes = fetchAttributeLocations( gl, program );
  14179. }
  14180. return cachedAttributes;
  14181. };
  14182. // free resource
  14183. this.destroy = function() {
  14184. gl.deleteProgram( program );
  14185. this.program = undefined;
  14186. };
  14187. // DEPRECATED
  14188. Object.defineProperties( this, {
  14189. uniforms: {
  14190. get: function() {
  14191. console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' );
  14192. return this.getUniforms();
  14193. }
  14194. },
  14195. attributes: {
  14196. get: function() {
  14197. console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' );
  14198. return this.getAttributes();
  14199. }
  14200. }
  14201. } );
  14202. //
  14203. this.id = programIdCount ++;
  14204. this.code = code;
  14205. this.usedTimes = 1;
  14206. this.program = program;
  14207. this.vertexShader = glVertexShader;
  14208. this.fragmentShader = glFragmentShader;
  14209. return this;
  14210. }
  14211. /**
  14212. * @author mrdoob / http://mrdoob.com/
  14213. */
  14214. function WebGLPrograms( renderer, capabilities ) {
  14215. var programs = [];
  14216. var shaderIDs = {
  14217. MeshDepthMaterial: 'depth',
  14218. MeshNormalMaterial: 'normal',
  14219. MeshBasicMaterial: 'basic',
  14220. MeshLambertMaterial: 'lambert',
  14221. MeshPhongMaterial: 'phong',
  14222. MeshToonMaterial: 'phong',
  14223. MeshStandardMaterial: 'physical',
  14224. MeshPhysicalMaterial: 'physical',
  14225. LineBasicMaterial: 'basic',
  14226. LineDashedMaterial: 'dashed',
  14227. PointsMaterial: 'points'
  14228. };
  14229. var parameterNames = [
  14230. "precision", "supportsVertexTextures", "map", "mapEncoding", "envMap", "envMapMode", "envMapEncoding",
  14231. "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "displacementMap", "specularMap",
  14232. "roughnessMap", "metalnessMap", "gradientMap",
  14233. "alphaMap", "combine", "vertexColors", "fog", "useFog", "fogExp",
  14234. "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
  14235. "maxBones", "useVertexTexture", "morphTargets", "morphNormals",
  14236. "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha",
  14237. "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights",
  14238. "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights',
  14239. "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking"
  14240. ];
  14241. function allocateBones( object ) {
  14242. if ( capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture ) {
  14243. return 1024;
  14244. } else {
  14245. // default for when object is not specified
  14246. // ( for example when prebuilding shader to be used with multiple objects )
  14247. //
  14248. // - leave some extra space for other uniforms
  14249. // - limit here is ANGLE's 254 max uniform vectors
  14250. // (up to 54 should be safe)
  14251. var nVertexUniforms = capabilities.maxVertexUniforms;
  14252. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  14253. var maxBones = nVertexMatrices;
  14254. if ( object !== undefined && (object && object.isSkinnedMesh) ) {
  14255. maxBones = Math.min( object.skeleton.bones.length, maxBones );
  14256. if ( maxBones < object.skeleton.bones.length ) {
  14257. console.warn( 'WebGLRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' );
  14258. }
  14259. }
  14260. return maxBones;
  14261. }
  14262. }
  14263. function getTextureEncodingFromMap( map, gammaOverrideLinear ) {
  14264. var encoding;
  14265. if ( ! map ) {
  14266. encoding = LinearEncoding;
  14267. } else if ( map.isTexture ) {
  14268. encoding = map.encoding;
  14269. } else if ( map.isWebGLRenderTarget ) {
  14270. console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." );
  14271. encoding = map.texture.encoding;
  14272. }
  14273. // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  14274. if ( encoding === LinearEncoding && gammaOverrideLinear ) {
  14275. encoding = GammaEncoding;
  14276. }
  14277. return encoding;
  14278. }
  14279. this.getParameters = function ( material, lights, fog, nClipPlanes, nClipIntersection, object ) {
  14280. var shaderID = shaderIDs[ material.type ];
  14281. // heuristics to create shader parameters according to lights in the scene
  14282. // (not to blow over maxLights budget)
  14283. var maxBones = allocateBones( object );
  14284. var precision = renderer.getPrecision();
  14285. if ( material.precision !== null ) {
  14286. precision = capabilities.getMaxPrecision( material.precision );
  14287. if ( precision !== material.precision ) {
  14288. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  14289. }
  14290. }
  14291. var currentRenderTarget = renderer.getCurrentRenderTarget();
  14292. var parameters = {
  14293. shaderID: shaderID,
  14294. precision: precision,
  14295. supportsVertexTextures: capabilities.vertexTextures,
  14296. outputEncoding: getTextureEncodingFromMap( ( ! currentRenderTarget ) ? null : currentRenderTarget.texture, renderer.gammaOutput ),
  14297. map: !! material.map,
  14298. mapEncoding: getTextureEncodingFromMap( material.map, renderer.gammaInput ),
  14299. envMap: !! material.envMap,
  14300. envMapMode: material.envMap && material.envMap.mapping,
  14301. envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ),
  14302. envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === CubeUVReflectionMapping ) || ( material.envMap.mapping === CubeUVRefractionMapping ) ),
  14303. lightMap: !! material.lightMap,
  14304. aoMap: !! material.aoMap,
  14305. emissiveMap: !! material.emissiveMap,
  14306. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap, renderer.gammaInput ),
  14307. bumpMap: !! material.bumpMap,
  14308. normalMap: !! material.normalMap,
  14309. displacementMap: !! material.displacementMap,
  14310. roughnessMap: !! material.roughnessMap,
  14311. metalnessMap: !! material.metalnessMap,
  14312. specularMap: !! material.specularMap,
  14313. alphaMap: !! material.alphaMap,
  14314. gradientMap: !! material.gradientMap,
  14315. combine: material.combine,
  14316. vertexColors: material.vertexColors,
  14317. fog: !! fog,
  14318. useFog: material.fog,
  14319. fogExp: (fog && fog.isFogExp2),
  14320. flatShading: material.shading === FlatShading,
  14321. sizeAttenuation: material.sizeAttenuation,
  14322. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  14323. skinning: material.skinning,
  14324. maxBones: maxBones,
  14325. useVertexTexture: capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture,
  14326. morphTargets: material.morphTargets,
  14327. morphNormals: material.morphNormals,
  14328. maxMorphTargets: renderer.maxMorphTargets,
  14329. maxMorphNormals: renderer.maxMorphNormals,
  14330. numDirLights: lights.directional.length,
  14331. numPointLights: lights.point.length,
  14332. numSpotLights: lights.spot.length,
  14333. numRectAreaLights: lights.rectArea.length,
  14334. numHemiLights: lights.hemi.length,
  14335. numClippingPlanes: nClipPlanes,
  14336. numClipIntersection: nClipIntersection,
  14337. shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && lights.shadows.length > 0,
  14338. shadowMapType: renderer.shadowMap.type,
  14339. toneMapping: renderer.toneMapping,
  14340. physicallyCorrectLights: renderer.physicallyCorrectLights,
  14341. premultipliedAlpha: material.premultipliedAlpha,
  14342. alphaTest: material.alphaTest,
  14343. doubleSided: material.side === DoubleSide,
  14344. flipSided: material.side === BackSide,
  14345. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false
  14346. };
  14347. return parameters;
  14348. };
  14349. this.getProgramCode = function ( material, parameters ) {
  14350. var array = [];
  14351. if ( parameters.shaderID ) {
  14352. array.push( parameters.shaderID );
  14353. } else {
  14354. array.push( material.fragmentShader );
  14355. array.push( material.vertexShader );
  14356. }
  14357. if ( material.defines !== undefined ) {
  14358. for ( var name in material.defines ) {
  14359. array.push( name );
  14360. array.push( material.defines[ name ] );
  14361. }
  14362. }
  14363. for ( var i = 0; i < parameterNames.length; i ++ ) {
  14364. array.push( parameters[ parameterNames[ i ] ] );
  14365. }
  14366. return array.join();
  14367. };
  14368. this.acquireProgram = function ( material, parameters, code ) {
  14369. var program;
  14370. // Check if code has been already compiled
  14371. for ( var p = 0, pl = programs.length; p < pl; p ++ ) {
  14372. var programInfo = programs[ p ];
  14373. if ( programInfo.code === code ) {
  14374. program = programInfo;
  14375. ++ program.usedTimes;
  14376. break;
  14377. }
  14378. }
  14379. if ( program === undefined ) {
  14380. program = new WebGLProgram( renderer, code, material, parameters );
  14381. programs.push( program );
  14382. }
  14383. return program;
  14384. };
  14385. this.releaseProgram = function( program ) {
  14386. if ( -- program.usedTimes === 0 ) {
  14387. // Remove from unordered set
  14388. var i = programs.indexOf( program );
  14389. programs[ i ] = programs[ programs.length - 1 ];
  14390. programs.pop();
  14391. // Free WebGL resources
  14392. program.destroy();
  14393. }
  14394. };
  14395. // Exposed for resource monitoring & error feedback via renderer.info:
  14396. this.programs = programs;
  14397. }
  14398. /**
  14399. * @author mrdoob / http://mrdoob.com/
  14400. */
  14401. function WebGLGeometries( gl, properties, info ) {
  14402. var geometries = {};
  14403. function onGeometryDispose( event ) {
  14404. var geometry = event.target;
  14405. var buffergeometry = geometries[ geometry.id ];
  14406. if ( buffergeometry.index !== null ) {
  14407. deleteAttribute( buffergeometry.index );
  14408. }
  14409. deleteAttributes( buffergeometry.attributes );
  14410. geometry.removeEventListener( 'dispose', onGeometryDispose );
  14411. delete geometries[ geometry.id ];
  14412. // TODO
  14413. var property = properties.get( geometry );
  14414. if ( property.wireframe ) {
  14415. deleteAttribute( property.wireframe );
  14416. }
  14417. properties.delete( geometry );
  14418. var bufferproperty = properties.get( buffergeometry );
  14419. if ( bufferproperty.wireframe ) {
  14420. deleteAttribute( bufferproperty.wireframe );
  14421. }
  14422. properties.delete( buffergeometry );
  14423. //
  14424. info.memory.geometries --;
  14425. }
  14426. function getAttributeBuffer( attribute ) {
  14427. if ( attribute.isInterleavedBufferAttribute ) {
  14428. return properties.get( attribute.data ).__webglBuffer;
  14429. }
  14430. return properties.get( attribute ).__webglBuffer;
  14431. }
  14432. function deleteAttribute( attribute ) {
  14433. var buffer = getAttributeBuffer( attribute );
  14434. if ( buffer !== undefined ) {
  14435. gl.deleteBuffer( buffer );
  14436. removeAttributeBuffer( attribute );
  14437. }
  14438. }
  14439. function deleteAttributes( attributes ) {
  14440. for ( var name in attributes ) {
  14441. deleteAttribute( attributes[ name ] );
  14442. }
  14443. }
  14444. function removeAttributeBuffer( attribute ) {
  14445. if ( attribute.isInterleavedBufferAttribute ) {
  14446. properties.delete( attribute.data );
  14447. } else {
  14448. properties.delete( attribute );
  14449. }
  14450. }
  14451. return {
  14452. get: function ( object ) {
  14453. var geometry = object.geometry;
  14454. if ( geometries[ geometry.id ] !== undefined ) {
  14455. return geometries[ geometry.id ];
  14456. }
  14457. geometry.addEventListener( 'dispose', onGeometryDispose );
  14458. var buffergeometry;
  14459. if ( geometry.isBufferGeometry ) {
  14460. buffergeometry = geometry;
  14461. } else if ( geometry.isGeometry ) {
  14462. if ( geometry._bufferGeometry === undefined ) {
  14463. geometry._bufferGeometry = new BufferGeometry().setFromObject( object );
  14464. }
  14465. buffergeometry = geometry._bufferGeometry;
  14466. }
  14467. geometries[ geometry.id ] = buffergeometry;
  14468. info.memory.geometries ++;
  14469. return buffergeometry;
  14470. }
  14471. };
  14472. }
  14473. /**
  14474. * @author mrdoob / http://mrdoob.com/
  14475. */
  14476. function WebGLObjects( gl, properties, info ) {
  14477. var geometries = new WebGLGeometries( gl, properties, info );
  14478. //
  14479. function update( object ) {
  14480. // TODO: Avoid updating twice (when using shadowMap). Maybe add frame counter.
  14481. var geometry = geometries.get( object );
  14482. if ( object.geometry.isGeometry ) {
  14483. geometry.updateFromObject( object );
  14484. }
  14485. var index = geometry.index;
  14486. var attributes = geometry.attributes;
  14487. if ( index !== null ) {
  14488. updateAttribute( index, gl.ELEMENT_ARRAY_BUFFER );
  14489. }
  14490. for ( var name in attributes ) {
  14491. updateAttribute( attributes[ name ], gl.ARRAY_BUFFER );
  14492. }
  14493. // morph targets
  14494. var morphAttributes = geometry.morphAttributes;
  14495. for ( var name in morphAttributes ) {
  14496. var array = morphAttributes[ name ];
  14497. for ( var i = 0, l = array.length; i < l; i ++ ) {
  14498. updateAttribute( array[ i ], gl.ARRAY_BUFFER );
  14499. }
  14500. }
  14501. return geometry;
  14502. }
  14503. function updateAttribute( attribute, bufferType ) {
  14504. var data = ( attribute.isInterleavedBufferAttribute ) ? attribute.data : attribute;
  14505. var attributeProperties = properties.get( data );
  14506. if ( attributeProperties.__webglBuffer === undefined ) {
  14507. createBuffer( attributeProperties, data, bufferType );
  14508. } else if ( attributeProperties.version !== data.version ) {
  14509. updateBuffer( attributeProperties, data, bufferType );
  14510. }
  14511. }
  14512. function createBuffer( attributeProperties, data, bufferType ) {
  14513. attributeProperties.__webglBuffer = gl.createBuffer();
  14514. gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
  14515. var usage = data.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;
  14516. gl.bufferData( bufferType, data.array, usage );
  14517. var type = gl.FLOAT;
  14518. var array = data.array;
  14519. if ( array instanceof Float32Array ) {
  14520. type = gl.FLOAT;
  14521. } else if ( array instanceof Float64Array ) {
  14522. console.warn( "Unsupported data buffer format: Float64Array" );
  14523. } else if ( array instanceof Uint16Array ) {
  14524. type = gl.UNSIGNED_SHORT;
  14525. } else if ( array instanceof Int16Array ) {
  14526. type = gl.SHORT;
  14527. } else if ( array instanceof Uint32Array ) {
  14528. type = gl.UNSIGNED_INT;
  14529. } else if ( array instanceof Int32Array ) {
  14530. type = gl.INT;
  14531. } else if ( array instanceof Int8Array ) {
  14532. type = gl.BYTE;
  14533. } else if ( array instanceof Uint8Array ) {
  14534. type = gl.UNSIGNED_BYTE;
  14535. }
  14536. attributeProperties.bytesPerElement = array.BYTES_PER_ELEMENT;
  14537. attributeProperties.type = type;
  14538. attributeProperties.version = data.version;
  14539. data.onUploadCallback();
  14540. }
  14541. function updateBuffer( attributeProperties, data, bufferType ) {
  14542. gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
  14543. if ( data.dynamic === false ) {
  14544. gl.bufferData( bufferType, data.array, gl.STATIC_DRAW );
  14545. } else if ( data.updateRange.count === - 1 ) {
  14546. // Not using update ranges
  14547. gl.bufferSubData( bufferType, 0, data.array );
  14548. } else if ( data.updateRange.count === 0 ) {
  14549. 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.' );
  14550. } else {
  14551. gl.bufferSubData( bufferType, data.updateRange.offset * data.array.BYTES_PER_ELEMENT,
  14552. data.array.subarray( data.updateRange.offset, data.updateRange.offset + data.updateRange.count ) );
  14553. data.updateRange.count = 0; // reset range
  14554. }
  14555. attributeProperties.version = data.version;
  14556. }
  14557. function getAttributeBuffer( attribute ) {
  14558. if ( attribute.isInterleavedBufferAttribute ) {
  14559. return properties.get( attribute.data ).__webglBuffer;
  14560. }
  14561. return properties.get( attribute ).__webglBuffer;
  14562. }
  14563. function getAttributeProperties( attribute ) {
  14564. if ( attribute.isInterleavedBufferAttribute ) {
  14565. return properties.get( attribute.data );
  14566. }
  14567. return properties.get( attribute );
  14568. }
  14569. function getWireframeAttribute( geometry ) {
  14570. var property = properties.get( geometry );
  14571. if ( property.wireframe !== undefined ) {
  14572. return property.wireframe;
  14573. }
  14574. var indices = [];
  14575. var index = geometry.index;
  14576. var attributes = geometry.attributes;
  14577. // console.time( 'wireframe' );
  14578. if ( index !== null ) {
  14579. var array = index.array;
  14580. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  14581. var a = array[ i + 0 ];
  14582. var b = array[ i + 1 ];
  14583. var c = array[ i + 2 ];
  14584. indices.push( a, b, b, c, c, a );
  14585. }
  14586. } else {
  14587. var array = attributes.position.array;
  14588. for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  14589. var a = i + 0;
  14590. var b = i + 1;
  14591. var c = i + 2;
  14592. indices.push( a, b, b, c, c, a );
  14593. }
  14594. }
  14595. // console.timeEnd( 'wireframe' );
  14596. var attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  14597. updateAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  14598. property.wireframe = attribute;
  14599. return attribute;
  14600. }
  14601. return {
  14602. getAttributeBuffer: getAttributeBuffer,
  14603. getAttributeProperties: getAttributeProperties,
  14604. getWireframeAttribute: getWireframeAttribute,
  14605. update: update
  14606. };
  14607. }
  14608. /**
  14609. * @author mrdoob / http://mrdoob.com/
  14610. */
  14611. function WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, info ) {
  14612. var _infoMemory = info.memory;
  14613. var _isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof WebGL2RenderingContext );
  14614. //
  14615. function clampToMaxSize( image, maxSize ) {
  14616. if ( image.width > maxSize || image.height > maxSize ) {
  14617. // Warning: Scaling through the canvas will only work with images that use
  14618. // premultiplied alpha.
  14619. var scale = maxSize / Math.max( image.width, image.height );
  14620. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  14621. canvas.width = Math.floor( image.width * scale );
  14622. canvas.height = Math.floor( image.height * scale );
  14623. var context = canvas.getContext( '2d' );
  14624. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  14625. console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  14626. return canvas;
  14627. }
  14628. return image;
  14629. }
  14630. function isPowerOfTwo( image ) {
  14631. return _Math.isPowerOfTwo( image.width ) && _Math.isPowerOfTwo( image.height );
  14632. }
  14633. function makePowerOfTwo( image ) {
  14634. if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) {
  14635. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  14636. canvas.width = _Math.nearestPowerOfTwo( image.width );
  14637. canvas.height = _Math.nearestPowerOfTwo( image.height );
  14638. var context = canvas.getContext( '2d' );
  14639. context.drawImage( image, 0, 0, canvas.width, canvas.height );
  14640. console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  14641. return canvas;
  14642. }
  14643. return image;
  14644. }
  14645. function textureNeedsPowerOfTwo( texture ) {
  14646. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  14647. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  14648. }
  14649. // Fallback filters for non-power-of-2 textures
  14650. function filterFallback( f ) {
  14651. if ( f === NearestFilter || f === NearestMipMapNearestFilter || f === NearestMipMapLinearFilter ) {
  14652. return _gl.NEAREST;
  14653. }
  14654. return _gl.LINEAR;
  14655. }
  14656. //
  14657. function onTextureDispose( event ) {
  14658. var texture = event.target;
  14659. texture.removeEventListener( 'dispose', onTextureDispose );
  14660. deallocateTexture( texture );
  14661. _infoMemory.textures --;
  14662. }
  14663. function onRenderTargetDispose( event ) {
  14664. var renderTarget = event.target;
  14665. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  14666. deallocateRenderTarget( renderTarget );
  14667. _infoMemory.textures --;
  14668. }
  14669. //
  14670. function deallocateTexture( texture ) {
  14671. var textureProperties = properties.get( texture );
  14672. if ( texture.image && textureProperties.__image__webglTextureCube ) {
  14673. // cube texture
  14674. _gl.deleteTexture( textureProperties.__image__webglTextureCube );
  14675. } else {
  14676. // 2D texture
  14677. if ( textureProperties.__webglInit === undefined ) return;
  14678. _gl.deleteTexture( textureProperties.__webglTexture );
  14679. }
  14680. // remove all webgl properties
  14681. properties.delete( texture );
  14682. }
  14683. function deallocateRenderTarget( renderTarget ) {
  14684. var renderTargetProperties = properties.get( renderTarget );
  14685. var textureProperties = properties.get( renderTarget.texture );
  14686. if ( ! renderTarget ) return;
  14687. if ( textureProperties.__webglTexture !== undefined ) {
  14688. _gl.deleteTexture( textureProperties.__webglTexture );
  14689. }
  14690. if ( renderTarget.depthTexture ) {
  14691. renderTarget.depthTexture.dispose();
  14692. }
  14693. if ( renderTarget.isWebGLRenderTargetCube ) {
  14694. for ( var i = 0; i < 6; i ++ ) {
  14695. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  14696. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  14697. }
  14698. } else {
  14699. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  14700. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  14701. }
  14702. properties.delete( renderTarget.texture );
  14703. properties.delete( renderTarget );
  14704. }
  14705. //
  14706. function setTexture2D( texture, slot ) {
  14707. var textureProperties = properties.get( texture );
  14708. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14709. var image = texture.image;
  14710. if ( image === undefined ) {
  14711. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture );
  14712. } else if ( image.complete === false ) {
  14713. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
  14714. } else {
  14715. uploadTexture( textureProperties, texture, slot );
  14716. return;
  14717. }
  14718. }
  14719. state.activeTexture( _gl.TEXTURE0 + slot );
  14720. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  14721. }
  14722. function setTextureCube( texture, slot ) {
  14723. var textureProperties = properties.get( texture );
  14724. if ( texture.image.length === 6 ) {
  14725. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14726. if ( ! textureProperties.__image__webglTextureCube ) {
  14727. texture.addEventListener( 'dispose', onTextureDispose );
  14728. textureProperties.__image__webglTextureCube = _gl.createTexture();
  14729. _infoMemory.textures ++;
  14730. }
  14731. state.activeTexture( _gl.TEXTURE0 + slot );
  14732. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  14733. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14734. var isCompressed = ( texture && texture.isCompressedTexture );
  14735. var isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  14736. var cubeImage = [];
  14737. for ( var i = 0; i < 6; i ++ ) {
  14738. if ( ! isCompressed && ! isDataTexture ) {
  14739. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize );
  14740. } else {
  14741. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  14742. }
  14743. }
  14744. var image = cubeImage[ 0 ],
  14745. isPowerOfTwoImage = isPowerOfTwo( image ),
  14746. glFormat = paramThreeToGL( texture.format ),
  14747. glType = paramThreeToGL( texture.type );
  14748. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage );
  14749. for ( var i = 0; i < 6; i ++ ) {
  14750. if ( ! isCompressed ) {
  14751. if ( isDataTexture ) {
  14752. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  14753. } else {
  14754. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  14755. }
  14756. } else {
  14757. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  14758. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  14759. mipmap = mipmaps[ j ];
  14760. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  14761. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  14762. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14763. } else {
  14764. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()" );
  14765. }
  14766. } else {
  14767. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14768. }
  14769. }
  14770. }
  14771. }
  14772. if ( texture.generateMipmaps && isPowerOfTwoImage ) {
  14773. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14774. }
  14775. textureProperties.__version = texture.version;
  14776. if ( texture.onUpdate ) texture.onUpdate( texture );
  14777. } else {
  14778. state.activeTexture( _gl.TEXTURE0 + slot );
  14779. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  14780. }
  14781. }
  14782. }
  14783. function setTextureCubeDynamic( texture, slot ) {
  14784. state.activeTexture( _gl.TEXTURE0 + slot );
  14785. state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture );
  14786. }
  14787. function setTextureParameters( textureType, texture, isPowerOfTwoImage ) {
  14788. var extension;
  14789. if ( isPowerOfTwoImage ) {
  14790. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  14791. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  14792. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  14793. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  14794. } else {
  14795. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  14796. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  14797. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  14798. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture );
  14799. }
  14800. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  14801. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  14802. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  14803. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture );
  14804. }
  14805. }
  14806. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  14807. if ( extension ) {
  14808. if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  14809. if ( texture.type === HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return;
  14810. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  14811. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  14812. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  14813. }
  14814. }
  14815. }
  14816. function uploadTexture( textureProperties, texture, slot ) {
  14817. if ( textureProperties.__webglInit === undefined ) {
  14818. textureProperties.__webglInit = true;
  14819. texture.addEventListener( 'dispose', onTextureDispose );
  14820. textureProperties.__webglTexture = _gl.createTexture();
  14821. _infoMemory.textures ++;
  14822. }
  14823. state.activeTexture( _gl.TEXTURE0 + slot );
  14824. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  14825. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14826. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14827. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14828. var image = clampToMaxSize( texture.image, capabilities.maxTextureSize );
  14829. if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) {
  14830. image = makePowerOfTwo( image );
  14831. }
  14832. var isPowerOfTwoImage = isPowerOfTwo( image ),
  14833. glFormat = paramThreeToGL( texture.format ),
  14834. glType = paramThreeToGL( texture.type );
  14835. setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage );
  14836. var mipmap, mipmaps = texture.mipmaps;
  14837. if ( texture.isDepthTexture ) {
  14838. // populate depth texture with dummy data
  14839. var internalFormat = _gl.DEPTH_COMPONENT;
  14840. if ( texture.type === FloatType ) {
  14841. if ( !_isWebGL2 ) throw new Error('Float Depth Texture only supported in WebGL2.0');
  14842. internalFormat = _gl.DEPTH_COMPONENT32F;
  14843. } else if ( _isWebGL2 ) {
  14844. // WebGL 2.0 requires signed internalformat for glTexImage2D
  14845. internalFormat = _gl.DEPTH_COMPONENT16;
  14846. }
  14847. if ( texture.format === DepthFormat && internalFormat === _gl.DEPTH_COMPONENT ) {
  14848. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14849. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  14850. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14851. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  14852. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  14853. texture.type = UnsignedShortType;
  14854. glType = paramThreeToGL( texture.type );
  14855. }
  14856. }
  14857. // Depth stencil textures need the DEPTH_STENCIL internal format
  14858. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14859. if ( texture.format === DepthStencilFormat ) {
  14860. internalFormat = _gl.DEPTH_STENCIL;
  14861. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14862. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  14863. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14864. if ( texture.type !== UnsignedInt248Type ) {
  14865. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  14866. texture.type = UnsignedInt248Type;
  14867. glType = paramThreeToGL( texture.type );
  14868. }
  14869. }
  14870. state.texImage2D( _gl.TEXTURE_2D, 0, internalFormat, image.width, image.height, 0, glFormat, glType, null );
  14871. } else if ( texture.isDataTexture ) {
  14872. // use manually created mipmaps if available
  14873. // if there are no manual mipmaps
  14874. // set 0 level mipmap and then use GL to generate other mipmap levels
  14875. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  14876. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14877. mipmap = mipmaps[ i ];
  14878. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14879. }
  14880. texture.generateMipmaps = false;
  14881. } else {
  14882. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14883. }
  14884. } else if ( texture.isCompressedTexture ) {
  14885. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14886. mipmap = mipmaps[ i ];
  14887. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  14888. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  14889. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14890. } else {
  14891. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" );
  14892. }
  14893. } else {
  14894. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14895. }
  14896. }
  14897. } else {
  14898. // regular Texture (image, video, canvas)
  14899. // use manually created mipmaps if available
  14900. // if there are no manual mipmaps
  14901. // set 0 level mipmap and then use GL to generate other mipmap levels
  14902. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  14903. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14904. mipmap = mipmaps[ i ];
  14905. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  14906. }
  14907. texture.generateMipmaps = false;
  14908. } else {
  14909. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image );
  14910. }
  14911. }
  14912. if ( texture.generateMipmaps && isPowerOfTwoImage ) _gl.generateMipmap( _gl.TEXTURE_2D );
  14913. textureProperties.__version = texture.version;
  14914. if ( texture.onUpdate ) texture.onUpdate( texture );
  14915. }
  14916. // Render targets
  14917. // Setup storage for target texture and bind it to correct framebuffer
  14918. function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {
  14919. var glFormat = paramThreeToGL( renderTarget.texture.format );
  14920. var glType = paramThreeToGL( renderTarget.texture.type );
  14921. state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14922. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14923. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  14924. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  14925. }
  14926. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  14927. function setupRenderBufferStorage( renderbuffer, renderTarget ) {
  14928. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  14929. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14930. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  14931. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14932. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14933. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  14934. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14935. } else {
  14936. // FIXME: We don't support !depth !stencil
  14937. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  14938. }
  14939. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  14940. }
  14941. // Setup resources for a Depth Texture for a FBO (needs an extension)
  14942. function setupDepthTexture( framebuffer, renderTarget ) {
  14943. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  14944. if ( isCube ) throw new Error('Depth Texture with cube render targets is not supported!');
  14945. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14946. if ( !( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  14947. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  14948. }
  14949. // upload an empty depth texture with framebuffer size
  14950. if ( !properties.get( renderTarget.depthTexture ).__webglTexture ||
  14951. renderTarget.depthTexture.image.width !== renderTarget.width ||
  14952. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  14953. renderTarget.depthTexture.image.width = renderTarget.width;
  14954. renderTarget.depthTexture.image.height = renderTarget.height;
  14955. renderTarget.depthTexture.needsUpdate = true;
  14956. }
  14957. setTexture2D( renderTarget.depthTexture, 0 );
  14958. var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  14959. if ( renderTarget.depthTexture.format === DepthFormat ) {
  14960. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  14961. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  14962. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  14963. } else {
  14964. throw new Error('Unknown depthTexture format')
  14965. }
  14966. }
  14967. // Setup GL resources for a non-texture depth buffer
  14968. function setupDepthRenderbuffer( renderTarget ) {
  14969. var renderTargetProperties = properties.get( renderTarget );
  14970. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  14971. if ( renderTarget.depthTexture ) {
  14972. if ( isCube ) throw new Error('target.depthTexture not supported in Cube render targets');
  14973. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  14974. } else {
  14975. if ( isCube ) {
  14976. renderTargetProperties.__webglDepthbuffer = [];
  14977. for ( var i = 0; i < 6; i ++ ) {
  14978. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  14979. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  14980. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );
  14981. }
  14982. } else {
  14983. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  14984. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  14985. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );
  14986. }
  14987. }
  14988. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  14989. }
  14990. // Set up GL resources for the render target
  14991. function setupRenderTarget( renderTarget ) {
  14992. var renderTargetProperties = properties.get( renderTarget );
  14993. var textureProperties = properties.get( renderTarget.texture );
  14994. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  14995. textureProperties.__webglTexture = _gl.createTexture();
  14996. _infoMemory.textures ++;
  14997. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  14998. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget );
  14999. // Setup framebuffer
  15000. if ( isCube ) {
  15001. renderTargetProperties.__webglFramebuffer = [];
  15002. for ( var i = 0; i < 6; i ++ ) {
  15003. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15004. }
  15005. } else {
  15006. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  15007. }
  15008. // Setup color buffer
  15009. if ( isCube ) {
  15010. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  15011. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo );
  15012. for ( var i = 0; i < 6; i ++ ) {
  15013. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  15014. }
  15015. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15016. state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15017. } else {
  15018. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  15019. setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo );
  15020. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
  15021. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15022. state.bindTexture( _gl.TEXTURE_2D, null );
  15023. }
  15024. // Setup depth and stencil buffers
  15025. if ( renderTarget.depthBuffer ) {
  15026. setupDepthRenderbuffer( renderTarget );
  15027. }
  15028. }
  15029. function updateRenderTargetMipmap( renderTarget ) {
  15030. var texture = renderTarget.texture;
  15031. if ( texture.generateMipmaps && isPowerOfTwo( renderTarget ) &&
  15032. texture.minFilter !== NearestFilter &&
  15033. texture.minFilter !== LinearFilter ) {
  15034. var target = (renderTarget && renderTarget.isWebGLRenderTargetCube) ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  15035. var webglTexture = properties.get( texture ).__webglTexture;
  15036. state.bindTexture( target, webglTexture );
  15037. _gl.generateMipmap( target );
  15038. state.bindTexture( target, null );
  15039. }
  15040. }
  15041. this.setTexture2D = setTexture2D;
  15042. this.setTextureCube = setTextureCube;
  15043. this.setTextureCubeDynamic = setTextureCubeDynamic;
  15044. this.setupRenderTarget = setupRenderTarget;
  15045. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  15046. }
  15047. /**
  15048. * @author fordacious / fordacious.github.io
  15049. */
  15050. function WebGLProperties() {
  15051. var properties = {};
  15052. return {
  15053. get: function ( object ) {
  15054. var uuid = object.uuid;
  15055. var map = properties[ uuid ];
  15056. if ( map === undefined ) {
  15057. map = {};
  15058. properties[ uuid ] = map;
  15059. }
  15060. return map;
  15061. },
  15062. delete: function ( object ) {
  15063. delete properties[ object.uuid ];
  15064. },
  15065. clear: function () {
  15066. properties = {};
  15067. }
  15068. };
  15069. }
  15070. /**
  15071. * @author mrdoob / http://mrdoob.com/
  15072. */
  15073. function WebGLState( gl, extensions, paramThreeToGL ) {
  15074. function ColorBuffer() {
  15075. var locked = false;
  15076. var color = new Vector4();
  15077. var currentColorMask = null;
  15078. var currentColorClear = new Vector4();
  15079. return {
  15080. setMask: function ( colorMask ) {
  15081. if ( currentColorMask !== colorMask && ! locked ) {
  15082. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  15083. currentColorMask = colorMask;
  15084. }
  15085. },
  15086. setLocked: function ( lock ) {
  15087. locked = lock;
  15088. },
  15089. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  15090. if ( premultipliedAlpha === true ) {
  15091. r *= a; g *= a; b *= a;
  15092. }
  15093. color.set( r, g, b, a );
  15094. if ( currentColorClear.equals( color ) === false ) {
  15095. gl.clearColor( r, g, b, a );
  15096. currentColorClear.copy( color );
  15097. }
  15098. },
  15099. reset: function () {
  15100. locked = false;
  15101. currentColorMask = null;
  15102. currentColorClear.set( 0, 0, 0, 1 );
  15103. }
  15104. };
  15105. }
  15106. function DepthBuffer() {
  15107. var locked = false;
  15108. var currentDepthMask = null;
  15109. var currentDepthFunc = null;
  15110. var currentDepthClear = null;
  15111. return {
  15112. setTest: function ( depthTest ) {
  15113. if ( depthTest ) {
  15114. enable( gl.DEPTH_TEST );
  15115. } else {
  15116. disable( gl.DEPTH_TEST );
  15117. }
  15118. },
  15119. setMask: function ( depthMask ) {
  15120. if ( currentDepthMask !== depthMask && ! locked ) {
  15121. gl.depthMask( depthMask );
  15122. currentDepthMask = depthMask;
  15123. }
  15124. },
  15125. setFunc: function ( depthFunc ) {
  15126. if ( currentDepthFunc !== depthFunc ) {
  15127. if ( depthFunc ) {
  15128. switch ( depthFunc ) {
  15129. case NeverDepth:
  15130. gl.depthFunc( gl.NEVER );
  15131. break;
  15132. case AlwaysDepth:
  15133. gl.depthFunc( gl.ALWAYS );
  15134. break;
  15135. case LessDepth:
  15136. gl.depthFunc( gl.LESS );
  15137. break;
  15138. case LessEqualDepth:
  15139. gl.depthFunc( gl.LEQUAL );
  15140. break;
  15141. case EqualDepth:
  15142. gl.depthFunc( gl.EQUAL );
  15143. break;
  15144. case GreaterEqualDepth:
  15145. gl.depthFunc( gl.GEQUAL );
  15146. break;
  15147. case GreaterDepth:
  15148. gl.depthFunc( gl.GREATER );
  15149. break;
  15150. case NotEqualDepth:
  15151. gl.depthFunc( gl.NOTEQUAL );
  15152. break;
  15153. default:
  15154. gl.depthFunc( gl.LEQUAL );
  15155. }
  15156. } else {
  15157. gl.depthFunc( gl.LEQUAL );
  15158. }
  15159. currentDepthFunc = depthFunc;
  15160. }
  15161. },
  15162. setLocked: function ( lock ) {
  15163. locked = lock;
  15164. },
  15165. setClear: function ( depth ) {
  15166. if ( currentDepthClear !== depth ) {
  15167. gl.clearDepth( depth );
  15168. currentDepthClear = depth;
  15169. }
  15170. },
  15171. reset: function () {
  15172. locked = false;
  15173. currentDepthMask = null;
  15174. currentDepthFunc = null;
  15175. currentDepthClear = null;
  15176. }
  15177. };
  15178. }
  15179. function StencilBuffer() {
  15180. var locked = false;
  15181. var currentStencilMask = null;
  15182. var currentStencilFunc = null;
  15183. var currentStencilRef = null;
  15184. var currentStencilFuncMask = null;
  15185. var currentStencilFail = null;
  15186. var currentStencilZFail = null;
  15187. var currentStencilZPass = null;
  15188. var currentStencilClear = null;
  15189. return {
  15190. setTest: function ( stencilTest ) {
  15191. if ( stencilTest ) {
  15192. enable( gl.STENCIL_TEST );
  15193. } else {
  15194. disable( gl.STENCIL_TEST );
  15195. }
  15196. },
  15197. setMask: function ( stencilMask ) {
  15198. if ( currentStencilMask !== stencilMask && ! locked ) {
  15199. gl.stencilMask( stencilMask );
  15200. currentStencilMask = stencilMask;
  15201. }
  15202. },
  15203. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  15204. if ( currentStencilFunc !== stencilFunc ||
  15205. currentStencilRef !== stencilRef ||
  15206. currentStencilFuncMask !== stencilMask ) {
  15207. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  15208. currentStencilFunc = stencilFunc;
  15209. currentStencilRef = stencilRef;
  15210. currentStencilFuncMask = stencilMask;
  15211. }
  15212. },
  15213. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  15214. if ( currentStencilFail !== stencilFail ||
  15215. currentStencilZFail !== stencilZFail ||
  15216. currentStencilZPass !== stencilZPass ) {
  15217. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  15218. currentStencilFail = stencilFail;
  15219. currentStencilZFail = stencilZFail;
  15220. currentStencilZPass = stencilZPass;
  15221. }
  15222. },
  15223. setLocked: function ( lock ) {
  15224. locked = lock;
  15225. },
  15226. setClear: function ( stencil ) {
  15227. if ( currentStencilClear !== stencil ) {
  15228. gl.clearStencil( stencil );
  15229. currentStencilClear = stencil;
  15230. }
  15231. },
  15232. reset: function () {
  15233. locked = false;
  15234. currentStencilMask = null;
  15235. currentStencilFunc = null;
  15236. currentStencilRef = null;
  15237. currentStencilFuncMask = null;
  15238. currentStencilFail = null;
  15239. currentStencilZFail = null;
  15240. currentStencilZPass = null;
  15241. currentStencilClear = null;
  15242. }
  15243. };
  15244. }
  15245. //
  15246. var colorBuffer = new ColorBuffer();
  15247. var depthBuffer = new DepthBuffer();
  15248. var stencilBuffer = new StencilBuffer();
  15249. var maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  15250. var newAttributes = new Uint8Array( maxVertexAttributes );
  15251. var enabledAttributes = new Uint8Array( maxVertexAttributes );
  15252. var attributeDivisors = new Uint8Array( maxVertexAttributes );
  15253. var capabilities = {};
  15254. var compressedTextureFormats = null;
  15255. var currentBlending = null;
  15256. var currentBlendEquation = null;
  15257. var currentBlendSrc = null;
  15258. var currentBlendDst = null;
  15259. var currentBlendEquationAlpha = null;
  15260. var currentBlendSrcAlpha = null;
  15261. var currentBlendDstAlpha = null;
  15262. var currentPremultipledAlpha = false;
  15263. var currentFlipSided = null;
  15264. var currentCullFace = null;
  15265. var currentLineWidth = null;
  15266. var currentPolygonOffsetFactor = null;
  15267. var currentPolygonOffsetUnits = null;
  15268. var currentScissorTest = null;
  15269. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  15270. var version = parseFloat( /^WebGL\ ([0-9])/.exec( gl.getParameter( gl.VERSION ) )[ 1 ] );
  15271. var lineWidthAvailable = parseFloat( version ) >= 1.0;
  15272. var currentTextureSlot = null;
  15273. var currentBoundTextures = {};
  15274. var currentScissor = new Vector4();
  15275. var currentViewport = new Vector4();
  15276. function createTexture( type, target, count ) {
  15277. var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  15278. var texture = gl.createTexture();
  15279. gl.bindTexture( type, texture );
  15280. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  15281. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  15282. for ( var i = 0; i < count; i ++ ) {
  15283. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  15284. }
  15285. return texture;
  15286. }
  15287. var emptyTextures = {};
  15288. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  15289. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  15290. //
  15291. function init() {
  15292. colorBuffer.setClear( 0, 0, 0, 1 );
  15293. depthBuffer.setClear( 1 );
  15294. stencilBuffer.setClear( 0 );
  15295. enable( gl.DEPTH_TEST );
  15296. setDepthFunc( LessEqualDepth );
  15297. setFlipSided( false );
  15298. setCullFace( CullFaceBack );
  15299. enable( gl.CULL_FACE );
  15300. enable( gl.BLEND );
  15301. setBlending( NormalBlending );
  15302. }
  15303. function initAttributes() {
  15304. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  15305. newAttributes[ i ] = 0;
  15306. }
  15307. }
  15308. function enableAttribute( attribute ) {
  15309. newAttributes[ attribute ] = 1;
  15310. if ( enabledAttributes[ attribute ] === 0 ) {
  15311. gl.enableVertexAttribArray( attribute );
  15312. enabledAttributes[ attribute ] = 1;
  15313. }
  15314. if ( attributeDivisors[ attribute ] !== 0 ) {
  15315. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  15316. extension.vertexAttribDivisorANGLE( attribute, 0 );
  15317. attributeDivisors[ attribute ] = 0;
  15318. }
  15319. }
  15320. function enableAttributeAndDivisor( attribute, meshPerAttribute, extension ) {
  15321. newAttributes[ attribute ] = 1;
  15322. if ( enabledAttributes[ attribute ] === 0 ) {
  15323. gl.enableVertexAttribArray( attribute );
  15324. enabledAttributes[ attribute ] = 1;
  15325. }
  15326. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  15327. extension.vertexAttribDivisorANGLE( attribute, meshPerAttribute );
  15328. attributeDivisors[ attribute ] = meshPerAttribute;
  15329. }
  15330. }
  15331. function disableUnusedAttributes() {
  15332. for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) {
  15333. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  15334. gl.disableVertexAttribArray( i );
  15335. enabledAttributes[ i ] = 0;
  15336. }
  15337. }
  15338. }
  15339. function enable( id ) {
  15340. if ( capabilities[ id ] !== true ) {
  15341. gl.enable( id );
  15342. capabilities[ id ] = true;
  15343. }
  15344. }
  15345. function disable( id ) {
  15346. if ( capabilities[ id ] !== false ) {
  15347. gl.disable( id );
  15348. capabilities[ id ] = false;
  15349. }
  15350. }
  15351. function getCompressedTextureFormats() {
  15352. if ( compressedTextureFormats === null ) {
  15353. compressedTextureFormats = [];
  15354. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) ||
  15355. extensions.get( 'WEBGL_compressed_texture_s3tc' ) ||
  15356. extensions.get( 'WEBGL_compressed_texture_etc1' ) ) {
  15357. var formats = gl.getParameter( gl.COMPRESSED_TEXTURE_FORMATS );
  15358. for ( var i = 0; i < formats.length; i ++ ) {
  15359. compressedTextureFormats.push( formats[ i ] );
  15360. }
  15361. }
  15362. }
  15363. return compressedTextureFormats;
  15364. }
  15365. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  15366. if ( blending !== NoBlending ) {
  15367. enable( gl.BLEND );
  15368. } else {
  15369. disable( gl.BLEND );
  15370. }
  15371. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  15372. if ( blending === AdditiveBlending ) {
  15373. if ( premultipliedAlpha ) {
  15374. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  15375. gl.blendFuncSeparate( gl.ONE, gl.ONE, gl.ONE, gl.ONE );
  15376. } else {
  15377. gl.blendEquation( gl.FUNC_ADD );
  15378. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  15379. }
  15380. } else if ( blending === SubtractiveBlending ) {
  15381. if ( premultipliedAlpha ) {
  15382. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  15383. gl.blendFuncSeparate( gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA );
  15384. } else {
  15385. gl.blendEquation( gl.FUNC_ADD );
  15386. gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR );
  15387. }
  15388. } else if ( blending === MultiplyBlending ) {
  15389. if ( premultipliedAlpha ) {
  15390. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  15391. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  15392. } else {
  15393. gl.blendEquation( gl.FUNC_ADD );
  15394. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  15395. }
  15396. } else {
  15397. if ( premultipliedAlpha ) {
  15398. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  15399. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  15400. } else {
  15401. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  15402. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  15403. }
  15404. }
  15405. currentBlending = blending;
  15406. currentPremultipledAlpha = premultipliedAlpha;
  15407. }
  15408. if ( blending === CustomBlending ) {
  15409. blendEquationAlpha = blendEquationAlpha || blendEquation;
  15410. blendSrcAlpha = blendSrcAlpha || blendSrc;
  15411. blendDstAlpha = blendDstAlpha || blendDst;
  15412. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  15413. gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) );
  15414. currentBlendEquation = blendEquation;
  15415. currentBlendEquationAlpha = blendEquationAlpha;
  15416. }
  15417. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  15418. gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) );
  15419. currentBlendSrc = blendSrc;
  15420. currentBlendDst = blendDst;
  15421. currentBlendSrcAlpha = blendSrcAlpha;
  15422. currentBlendDstAlpha = blendDstAlpha;
  15423. }
  15424. } else {
  15425. currentBlendEquation = null;
  15426. currentBlendSrc = null;
  15427. currentBlendDst = null;
  15428. currentBlendEquationAlpha = null;
  15429. currentBlendSrcAlpha = null;
  15430. currentBlendDstAlpha = null;
  15431. }
  15432. }
  15433. // TODO Deprecate
  15434. function setColorWrite( colorWrite ) {
  15435. colorBuffer.setMask( colorWrite );
  15436. }
  15437. function setDepthTest( depthTest ) {
  15438. depthBuffer.setTest( depthTest );
  15439. }
  15440. function setDepthWrite( depthWrite ) {
  15441. depthBuffer.setMask( depthWrite );
  15442. }
  15443. function setDepthFunc( depthFunc ) {
  15444. depthBuffer.setFunc( depthFunc );
  15445. }
  15446. function setStencilTest( stencilTest ) {
  15447. stencilBuffer.setTest( stencilTest );
  15448. }
  15449. function setStencilWrite( stencilWrite ) {
  15450. stencilBuffer.setMask( stencilWrite );
  15451. }
  15452. function setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  15453. stencilBuffer.setFunc( stencilFunc, stencilRef, stencilMask );
  15454. }
  15455. function setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  15456. stencilBuffer.setOp( stencilFail, stencilZFail, stencilZPass );
  15457. }
  15458. //
  15459. function setFlipSided( flipSided ) {
  15460. if ( currentFlipSided !== flipSided ) {
  15461. if ( flipSided ) {
  15462. gl.frontFace( gl.CW );
  15463. } else {
  15464. gl.frontFace( gl.CCW );
  15465. }
  15466. currentFlipSided = flipSided;
  15467. }
  15468. }
  15469. function setCullFace( cullFace ) {
  15470. if ( cullFace !== CullFaceNone ) {
  15471. enable( gl.CULL_FACE );
  15472. if ( cullFace !== currentCullFace ) {
  15473. if ( cullFace === CullFaceBack ) {
  15474. gl.cullFace( gl.BACK );
  15475. } else if ( cullFace === CullFaceFront ) {
  15476. gl.cullFace( gl.FRONT );
  15477. } else {
  15478. gl.cullFace( gl.FRONT_AND_BACK );
  15479. }
  15480. }
  15481. } else {
  15482. disable( gl.CULL_FACE );
  15483. }
  15484. currentCullFace = cullFace;
  15485. }
  15486. function setLineWidth( width ) {
  15487. if ( width !== currentLineWidth ) {
  15488. if ( lineWidthAvailable ) gl.lineWidth( width );
  15489. currentLineWidth = width;
  15490. }
  15491. }
  15492. function setPolygonOffset( polygonOffset, factor, units ) {
  15493. if ( polygonOffset ) {
  15494. enable( gl.POLYGON_OFFSET_FILL );
  15495. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  15496. gl.polygonOffset( factor, units );
  15497. currentPolygonOffsetFactor = factor;
  15498. currentPolygonOffsetUnits = units;
  15499. }
  15500. } else {
  15501. disable( gl.POLYGON_OFFSET_FILL );
  15502. }
  15503. }
  15504. function getScissorTest() {
  15505. return currentScissorTest;
  15506. }
  15507. function setScissorTest( scissorTest ) {
  15508. currentScissorTest = scissorTest;
  15509. if ( scissorTest ) {
  15510. enable( gl.SCISSOR_TEST );
  15511. } else {
  15512. disable( gl.SCISSOR_TEST );
  15513. }
  15514. }
  15515. // texture
  15516. function activeTexture( webglSlot ) {
  15517. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  15518. if ( currentTextureSlot !== webglSlot ) {
  15519. gl.activeTexture( webglSlot );
  15520. currentTextureSlot = webglSlot;
  15521. }
  15522. }
  15523. function bindTexture( webglType, webglTexture ) {
  15524. if ( currentTextureSlot === null ) {
  15525. activeTexture();
  15526. }
  15527. var boundTexture = currentBoundTextures[ currentTextureSlot ];
  15528. if ( boundTexture === undefined ) {
  15529. boundTexture = { type: undefined, texture: undefined };
  15530. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  15531. }
  15532. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  15533. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  15534. boundTexture.type = webglType;
  15535. boundTexture.texture = webglTexture;
  15536. }
  15537. }
  15538. function compressedTexImage2D() {
  15539. try {
  15540. gl.compressedTexImage2D.apply( gl, arguments );
  15541. } catch ( error ) {
  15542. console.error( error );
  15543. }
  15544. }
  15545. function texImage2D() {
  15546. try {
  15547. gl.texImage2D.apply( gl, arguments );
  15548. } catch ( error ) {
  15549. console.error( error );
  15550. }
  15551. }
  15552. //
  15553. function scissor( scissor ) {
  15554. if ( currentScissor.equals( scissor ) === false ) {
  15555. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  15556. currentScissor.copy( scissor );
  15557. }
  15558. }
  15559. function viewport( viewport ) {
  15560. if ( currentViewport.equals( viewport ) === false ) {
  15561. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  15562. currentViewport.copy( viewport );
  15563. }
  15564. }
  15565. //
  15566. function reset() {
  15567. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  15568. if ( enabledAttributes[ i ] === 1 ) {
  15569. gl.disableVertexAttribArray( i );
  15570. enabledAttributes[ i ] = 0;
  15571. }
  15572. }
  15573. capabilities = {};
  15574. compressedTextureFormats = null;
  15575. currentTextureSlot = null;
  15576. currentBoundTextures = {};
  15577. currentBlending = null;
  15578. currentFlipSided = null;
  15579. currentCullFace = null;
  15580. colorBuffer.reset();
  15581. depthBuffer.reset();
  15582. stencilBuffer.reset();
  15583. }
  15584. return {
  15585. buffers: {
  15586. color: colorBuffer,
  15587. depth: depthBuffer,
  15588. stencil: stencilBuffer
  15589. },
  15590. init: init,
  15591. initAttributes: initAttributes,
  15592. enableAttribute: enableAttribute,
  15593. enableAttributeAndDivisor: enableAttributeAndDivisor,
  15594. disableUnusedAttributes: disableUnusedAttributes,
  15595. enable: enable,
  15596. disable: disable,
  15597. getCompressedTextureFormats: getCompressedTextureFormats,
  15598. setBlending: setBlending,
  15599. setColorWrite: setColorWrite,
  15600. setDepthTest: setDepthTest,
  15601. setDepthWrite: setDepthWrite,
  15602. setDepthFunc: setDepthFunc,
  15603. setStencilTest: setStencilTest,
  15604. setStencilWrite: setStencilWrite,
  15605. setStencilFunc: setStencilFunc,
  15606. setStencilOp: setStencilOp,
  15607. setFlipSided: setFlipSided,
  15608. setCullFace: setCullFace,
  15609. setLineWidth: setLineWidth,
  15610. setPolygonOffset: setPolygonOffset,
  15611. getScissorTest: getScissorTest,
  15612. setScissorTest: setScissorTest,
  15613. activeTexture: activeTexture,
  15614. bindTexture: bindTexture,
  15615. compressedTexImage2D: compressedTexImage2D,
  15616. texImage2D: texImage2D,
  15617. scissor: scissor,
  15618. viewport: viewport,
  15619. reset: reset
  15620. };
  15621. }
  15622. /**
  15623. * @author mrdoob / http://mrdoob.com/
  15624. */
  15625. function WebGLCapabilities( gl, extensions, parameters ) {
  15626. var maxAnisotropy;
  15627. function getMaxAnisotropy() {
  15628. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  15629. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  15630. if ( extension !== null ) {
  15631. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  15632. } else {
  15633. maxAnisotropy = 0;
  15634. }
  15635. return maxAnisotropy;
  15636. }
  15637. function getMaxPrecision( precision ) {
  15638. if ( precision === 'highp' ) {
  15639. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  15640. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  15641. return 'highp';
  15642. }
  15643. precision = 'mediump';
  15644. }
  15645. if ( precision === 'mediump' ) {
  15646. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  15647. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  15648. return 'mediump';
  15649. }
  15650. }
  15651. return 'lowp';
  15652. }
  15653. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  15654. var maxPrecision = getMaxPrecision( precision );
  15655. if ( maxPrecision !== precision ) {
  15656. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  15657. precision = maxPrecision;
  15658. }
  15659. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true && !! extensions.get( 'EXT_frag_depth' );
  15660. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  15661. var maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  15662. var maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  15663. var maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  15664. var maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  15665. var maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  15666. var maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  15667. var maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  15668. var vertexTextures = maxVertexTextures > 0;
  15669. var floatFragmentTextures = !! extensions.get( 'OES_texture_float' );
  15670. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  15671. return {
  15672. getMaxAnisotropy: getMaxAnisotropy,
  15673. getMaxPrecision: getMaxPrecision,
  15674. precision: precision,
  15675. logarithmicDepthBuffer: logarithmicDepthBuffer,
  15676. maxTextures: maxTextures,
  15677. maxVertexTextures: maxVertexTextures,
  15678. maxTextureSize: maxTextureSize,
  15679. maxCubemapSize: maxCubemapSize,
  15680. maxAttributes: maxAttributes,
  15681. maxVertexUniforms: maxVertexUniforms,
  15682. maxVaryings: maxVaryings,
  15683. maxFragmentUniforms: maxFragmentUniforms,
  15684. vertexTextures: vertexTextures,
  15685. floatFragmentTextures: floatFragmentTextures,
  15686. floatVertexTextures: floatVertexTextures
  15687. };
  15688. }
  15689. /**
  15690. * @author mrdoob / http://mrdoob.com/
  15691. */
  15692. function WebGLExtensions( gl ) {
  15693. var extensions = {};
  15694. return {
  15695. get: function ( name ) {
  15696. if ( extensions[ name ] !== undefined ) {
  15697. return extensions[ name ];
  15698. }
  15699. var extension;
  15700. switch ( name ) {
  15701. case 'WEBGL_depth_texture':
  15702. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  15703. break;
  15704. case 'EXT_texture_filter_anisotropic':
  15705. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  15706. break;
  15707. case 'WEBGL_compressed_texture_s3tc':
  15708. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  15709. break;
  15710. case 'WEBGL_compressed_texture_pvrtc':
  15711. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  15712. break;
  15713. case 'WEBGL_compressed_texture_etc1':
  15714. extension = gl.getExtension( 'WEBGL_compressed_texture_etc1' );
  15715. break;
  15716. default:
  15717. extension = gl.getExtension( name );
  15718. }
  15719. if ( extension === null ) {
  15720. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  15721. }
  15722. extensions[ name ] = extension;
  15723. return extension;
  15724. }
  15725. };
  15726. }
  15727. /**
  15728. * @author tschw
  15729. */
  15730. function WebGLClipping() {
  15731. var scope = this,
  15732. globalState = null,
  15733. numGlobalPlanes = 0,
  15734. localClippingEnabled = false,
  15735. renderingShadows = false,
  15736. plane = new Plane(),
  15737. viewNormalMatrix = new Matrix3(),
  15738. uniform = { value: null, needsUpdate: false };
  15739. this.uniform = uniform;
  15740. this.numPlanes = 0;
  15741. this.numIntersection = 0;
  15742. this.init = function( planes, enableLocalClipping, camera ) {
  15743. var enabled =
  15744. planes.length !== 0 ||
  15745. enableLocalClipping ||
  15746. // enable state of previous frame - the clipping code has to
  15747. // run another frame in order to reset the state:
  15748. numGlobalPlanes !== 0 ||
  15749. localClippingEnabled;
  15750. localClippingEnabled = enableLocalClipping;
  15751. globalState = projectPlanes( planes, camera, 0 );
  15752. numGlobalPlanes = planes.length;
  15753. return enabled;
  15754. };
  15755. this.beginShadows = function() {
  15756. renderingShadows = true;
  15757. projectPlanes( null );
  15758. };
  15759. this.endShadows = function() {
  15760. renderingShadows = false;
  15761. resetGlobalState();
  15762. };
  15763. this.setState = function( planes, clipIntersection, clipShadows, camera, cache, fromCache ) {
  15764. if ( ! localClippingEnabled ||
  15765. planes === null || planes.length === 0 ||
  15766. renderingShadows && ! clipShadows ) {
  15767. // there's no local clipping
  15768. if ( renderingShadows ) {
  15769. // there's no global clipping
  15770. projectPlanes( null );
  15771. } else {
  15772. resetGlobalState();
  15773. }
  15774. } else {
  15775. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  15776. lGlobal = nGlobal * 4,
  15777. dstArray = cache.clippingState || null;
  15778. uniform.value = dstArray; // ensure unique state
  15779. dstArray = projectPlanes( planes, camera, lGlobal, fromCache );
  15780. for ( var i = 0; i !== lGlobal; ++ i ) {
  15781. dstArray[ i ] = globalState[ i ];
  15782. }
  15783. cache.clippingState = dstArray;
  15784. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  15785. this.numPlanes += nGlobal;
  15786. }
  15787. };
  15788. function resetGlobalState() {
  15789. if ( uniform.value !== globalState ) {
  15790. uniform.value = globalState;
  15791. uniform.needsUpdate = numGlobalPlanes > 0;
  15792. }
  15793. scope.numPlanes = numGlobalPlanes;
  15794. scope.numIntersection = 0;
  15795. }
  15796. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  15797. var nPlanes = planes !== null ? planes.length : 0,
  15798. dstArray = null;
  15799. if ( nPlanes !== 0 ) {
  15800. dstArray = uniform.value;
  15801. if ( skipTransform !== true || dstArray === null ) {
  15802. var flatSize = dstOffset + nPlanes * 4,
  15803. viewMatrix = camera.matrixWorldInverse;
  15804. viewNormalMatrix.getNormalMatrix( viewMatrix );
  15805. if ( dstArray === null || dstArray.length < flatSize ) {
  15806. dstArray = new Float32Array( flatSize );
  15807. }
  15808. for ( var i = 0, i4 = dstOffset;
  15809. i !== nPlanes; ++ i, i4 += 4 ) {
  15810. plane.copy( planes[ i ] ).
  15811. applyMatrix4( viewMatrix, viewNormalMatrix );
  15812. plane.normal.toArray( dstArray, i4 );
  15813. dstArray[ i4 + 3 ] = plane.constant;
  15814. }
  15815. }
  15816. uniform.value = dstArray;
  15817. uniform.needsUpdate = true;
  15818. }
  15819. scope.numPlanes = nPlanes;
  15820. return dstArray;
  15821. }
  15822. }
  15823. /**
  15824. * @author supereggbert / http://www.paulbrunt.co.uk/
  15825. * @author mrdoob / http://mrdoob.com/
  15826. * @author alteredq / http://alteredqualia.com/
  15827. * @author szimek / https://github.com/szimek/
  15828. * @author tschw
  15829. */
  15830. function WebGLRenderer( parameters ) {
  15831. console.log( 'THREE.WebGLRenderer', REVISION );
  15832. parameters = parameters || {};
  15833. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
  15834. _context = parameters.context !== undefined ? parameters.context : null,
  15835. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  15836. _depth = parameters.depth !== undefined ? parameters.depth : true,
  15837. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  15838. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  15839. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  15840. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false;
  15841. var lights = [];
  15842. var opaqueObjects = [];
  15843. var opaqueObjectsLastIndex = - 1;
  15844. var transparentObjects = [];
  15845. var transparentObjectsLastIndex = - 1;
  15846. var morphInfluences = new Float32Array( 8 );
  15847. var sprites = [];
  15848. var lensFlares = [];
  15849. // public properties
  15850. this.domElement = _canvas;
  15851. this.context = null;
  15852. // clearing
  15853. this.autoClear = true;
  15854. this.autoClearColor = true;
  15855. this.autoClearDepth = true;
  15856. this.autoClearStencil = true;
  15857. // scene graph
  15858. this.sortObjects = true;
  15859. // user-defined clipping
  15860. this.clippingPlanes = [];
  15861. this.localClippingEnabled = false;
  15862. // physically based shading
  15863. this.gammaFactor = 2.0; // for backwards compatibility
  15864. this.gammaInput = false;
  15865. this.gammaOutput = false;
  15866. // physical lights
  15867. this.physicallyCorrectLights = false;
  15868. // tone mapping
  15869. this.toneMapping = LinearToneMapping;
  15870. this.toneMappingExposure = 1.0;
  15871. this.toneMappingWhitePoint = 1.0;
  15872. // morphs
  15873. this.maxMorphTargets = 8;
  15874. this.maxMorphNormals = 4;
  15875. // internal properties
  15876. var _this = this,
  15877. // internal state cache
  15878. _currentProgram = null,
  15879. _currentRenderTarget = null,
  15880. _currentFramebuffer = null,
  15881. _currentMaterialId = - 1,
  15882. _currentGeometryProgram = '',
  15883. _currentCamera = null,
  15884. _currentScissor = new Vector4(),
  15885. _currentScissorTest = null,
  15886. _currentViewport = new Vector4(),
  15887. //
  15888. _usedTextureUnits = 0,
  15889. //
  15890. _clearColor = new Color( 0x000000 ),
  15891. _clearAlpha = 0,
  15892. _width = _canvas.width,
  15893. _height = _canvas.height,
  15894. _pixelRatio = 1,
  15895. _scissor = new Vector4( 0, 0, _width, _height ),
  15896. _scissorTest = false,
  15897. _viewport = new Vector4( 0, 0, _width, _height ),
  15898. // frustum
  15899. _frustum = new Frustum(),
  15900. // clipping
  15901. _clipping = new WebGLClipping(),
  15902. _clippingEnabled = false,
  15903. _localClippingEnabled = false,
  15904. _sphere = new Sphere(),
  15905. // camera matrices cache
  15906. _projScreenMatrix = new Matrix4(),
  15907. _vector3 = new Vector3(),
  15908. _matrix4 = new Matrix4(),
  15909. _matrix42 = new Matrix4(),
  15910. // light arrays cache
  15911. _lights = {
  15912. hash: '',
  15913. ambient: [ 0, 0, 0 ],
  15914. directional: [],
  15915. directionalShadowMap: [],
  15916. directionalShadowMatrix: [],
  15917. spot: [],
  15918. spotShadowMap: [],
  15919. spotShadowMatrix: [],
  15920. rectArea: [],
  15921. point: [],
  15922. pointShadowMap: [],
  15923. pointShadowMatrix: [],
  15924. hemi: [],
  15925. shadows: []
  15926. },
  15927. // info
  15928. _infoRender = {
  15929. calls: 0,
  15930. vertices: 0,
  15931. faces: 0,
  15932. points: 0
  15933. };
  15934. this.info = {
  15935. render: _infoRender,
  15936. memory: {
  15937. geometries: 0,
  15938. textures: 0
  15939. },
  15940. programs: null
  15941. };
  15942. // initialize
  15943. var _gl;
  15944. try {
  15945. var attributes = {
  15946. alpha: _alpha,
  15947. depth: _depth,
  15948. stencil: _stencil,
  15949. antialias: _antialias,
  15950. premultipliedAlpha: _premultipliedAlpha,
  15951. preserveDrawingBuffer: _preserveDrawingBuffer
  15952. };
  15953. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  15954. if ( _gl === null ) {
  15955. if ( _canvas.getContext( 'webgl' ) !== null ) {
  15956. throw 'Error creating WebGL context with your selected attributes.';
  15957. } else {
  15958. throw 'Error creating WebGL context.';
  15959. }
  15960. }
  15961. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  15962. if ( _gl.getShaderPrecisionFormat === undefined ) {
  15963. _gl.getShaderPrecisionFormat = function () {
  15964. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  15965. };
  15966. }
  15967. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  15968. } catch ( error ) {
  15969. console.error( 'THREE.WebGLRenderer: ' + error );
  15970. }
  15971. var extensions = new WebGLExtensions( _gl );
  15972. extensions.get( 'WEBGL_depth_texture' );
  15973. extensions.get( 'OES_texture_float' );
  15974. extensions.get( 'OES_texture_float_linear' );
  15975. extensions.get( 'OES_texture_half_float' );
  15976. extensions.get( 'OES_texture_half_float_linear' );
  15977. extensions.get( 'OES_standard_derivatives' );
  15978. extensions.get( 'ANGLE_instanced_arrays' );
  15979. if ( extensions.get( 'OES_element_index_uint' ) ) {
  15980. BufferGeometry.MaxIndex = 4294967296;
  15981. }
  15982. var capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  15983. var state = new WebGLState( _gl, extensions, paramThreeToGL );
  15984. var properties = new WebGLProperties();
  15985. var textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, this.info );
  15986. var objects = new WebGLObjects( _gl, properties, this.info );
  15987. var programCache = new WebGLPrograms( this, capabilities );
  15988. var lightCache = new WebGLLights();
  15989. this.info.programs = programCache.programs;
  15990. var bufferRenderer = new WebGLBufferRenderer( _gl, extensions, _infoRender );
  15991. var indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
  15992. //
  15993. var backgroundPlaneCamera, backgroundPlaneMesh;
  15994. var backgroundBoxCamera, backgroundBoxMesh;
  15995. //
  15996. function getTargetPixelRatio() {
  15997. return _currentRenderTarget === null ? _pixelRatio : 1;
  15998. }
  15999. function setDefaultGLState() {
  16000. state.init();
  16001. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  16002. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  16003. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  16004. }
  16005. function resetGLState() {
  16006. _currentProgram = null;
  16007. _currentCamera = null;
  16008. _currentGeometryProgram = '';
  16009. _currentMaterialId = - 1;
  16010. state.reset();
  16011. }
  16012. setDefaultGLState();
  16013. this.context = _gl;
  16014. this.capabilities = capabilities;
  16015. this.extensions = extensions;
  16016. this.properties = properties;
  16017. this.state = state;
  16018. // shadow map
  16019. var shadowMap = new WebGLShadowMap( this, _lights, objects, capabilities );
  16020. this.shadowMap = shadowMap;
  16021. // Plugins
  16022. var spritePlugin = new SpritePlugin( this, sprites );
  16023. var lensFlarePlugin = new LensFlarePlugin( this, lensFlares );
  16024. // API
  16025. this.getContext = function () {
  16026. return _gl;
  16027. };
  16028. this.getContextAttributes = function () {
  16029. return _gl.getContextAttributes();
  16030. };
  16031. this.forceContextLoss = function () {
  16032. extensions.get( 'WEBGL_lose_context' ).loseContext();
  16033. };
  16034. this.getMaxAnisotropy = function () {
  16035. return capabilities.getMaxAnisotropy();
  16036. };
  16037. this.getPrecision = function () {
  16038. return capabilities.precision;
  16039. };
  16040. this.getPixelRatio = function () {
  16041. return _pixelRatio;
  16042. };
  16043. this.setPixelRatio = function ( value ) {
  16044. if ( value === undefined ) return;
  16045. _pixelRatio = value;
  16046. this.setSize( _viewport.z, _viewport.w, false );
  16047. };
  16048. this.getSize = function () {
  16049. return {
  16050. width: _width,
  16051. height: _height
  16052. };
  16053. };
  16054. this.setSize = function ( width, height, updateStyle ) {
  16055. _width = width;
  16056. _height = height;
  16057. _canvas.width = width * _pixelRatio;
  16058. _canvas.height = height * _pixelRatio;
  16059. if ( updateStyle !== false ) {
  16060. _canvas.style.width = width + 'px';
  16061. _canvas.style.height = height + 'px';
  16062. }
  16063. this.setViewport( 0, 0, width, height );
  16064. };
  16065. this.setViewport = function ( x, y, width, height ) {
  16066. state.viewport( _viewport.set( x, y, width, height ) );
  16067. };
  16068. this.setScissor = function ( x, y, width, height ) {
  16069. state.scissor( _scissor.set( x, y, width, height ) );
  16070. };
  16071. this.setScissorTest = function ( boolean ) {
  16072. state.setScissorTest( _scissorTest = boolean );
  16073. };
  16074. // Clearing
  16075. this.getClearColor = function () {
  16076. return _clearColor;
  16077. };
  16078. this.setClearColor = function ( color, alpha ) {
  16079. _clearColor.set( color );
  16080. _clearAlpha = alpha !== undefined ? alpha : 1;
  16081. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  16082. };
  16083. this.getClearAlpha = function () {
  16084. return _clearAlpha;
  16085. };
  16086. this.setClearAlpha = function ( alpha ) {
  16087. _clearAlpha = alpha;
  16088. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  16089. };
  16090. this.clear = function ( color, depth, stencil ) {
  16091. var bits = 0;
  16092. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  16093. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  16094. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  16095. _gl.clear( bits );
  16096. };
  16097. this.clearColor = function () {
  16098. this.clear( true, false, false );
  16099. };
  16100. this.clearDepth = function () {
  16101. this.clear( false, true, false );
  16102. };
  16103. this.clearStencil = function () {
  16104. this.clear( false, false, true );
  16105. };
  16106. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  16107. this.setRenderTarget( renderTarget );
  16108. this.clear( color, depth, stencil );
  16109. };
  16110. // Reset
  16111. this.resetGLState = resetGLState;
  16112. this.dispose = function() {
  16113. transparentObjects = [];
  16114. transparentObjectsLastIndex = -1;
  16115. opaqueObjects = [];
  16116. opaqueObjectsLastIndex = -1;
  16117. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  16118. };
  16119. // Events
  16120. function onContextLost( event ) {
  16121. event.preventDefault();
  16122. resetGLState();
  16123. setDefaultGLState();
  16124. properties.clear();
  16125. }
  16126. function onMaterialDispose( event ) {
  16127. var material = event.target;
  16128. material.removeEventListener( 'dispose', onMaterialDispose );
  16129. deallocateMaterial( material );
  16130. }
  16131. // Buffer deallocation
  16132. function deallocateMaterial( material ) {
  16133. releaseMaterialProgramReference( material );
  16134. properties.delete( material );
  16135. }
  16136. function releaseMaterialProgramReference( material ) {
  16137. var programInfo = properties.get( material ).program;
  16138. material.program = undefined;
  16139. if ( programInfo !== undefined ) {
  16140. programCache.releaseProgram( programInfo );
  16141. }
  16142. }
  16143. // Buffer rendering
  16144. this.renderBufferImmediate = function ( object, program, material ) {
  16145. state.initAttributes();
  16146. var buffers = properties.get( object );
  16147. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  16148. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  16149. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  16150. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  16151. var attributes = program.getAttributes();
  16152. if ( object.hasPositions ) {
  16153. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  16154. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  16155. state.enableAttribute( attributes.position );
  16156. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  16157. }
  16158. if ( object.hasNormals ) {
  16159. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  16160. if ( ! material.isMeshPhongMaterial &&
  16161. ! material.isMeshStandardMaterial &&
  16162. ! material.isMeshNormalMaterial &&
  16163. material.shading === FlatShading ) {
  16164. for ( var i = 0, l = object.count * 3; i < l; i += 9 ) {
  16165. var array = object.normalArray;
  16166. var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3;
  16167. var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3;
  16168. var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3;
  16169. array[ i + 0 ] = nx;
  16170. array[ i + 1 ] = ny;
  16171. array[ i + 2 ] = nz;
  16172. array[ i + 3 ] = nx;
  16173. array[ i + 4 ] = ny;
  16174. array[ i + 5 ] = nz;
  16175. array[ i + 6 ] = nx;
  16176. array[ i + 7 ] = ny;
  16177. array[ i + 8 ] = nz;
  16178. }
  16179. }
  16180. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  16181. state.enableAttribute( attributes.normal );
  16182. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  16183. }
  16184. if ( object.hasUvs && material.map ) {
  16185. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  16186. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  16187. state.enableAttribute( attributes.uv );
  16188. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  16189. }
  16190. if ( object.hasColors && material.vertexColors !== NoColors ) {
  16191. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  16192. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  16193. state.enableAttribute( attributes.color );
  16194. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  16195. }
  16196. state.disableUnusedAttributes();
  16197. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  16198. object.count = 0;
  16199. };
  16200. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  16201. setMaterial( material );
  16202. var program = setProgram( camera, fog, material, object );
  16203. var updateBuffers = false;
  16204. var geometryProgram = geometry.id + '_' + program.id + '_' + material.wireframe;
  16205. if ( geometryProgram !== _currentGeometryProgram ) {
  16206. _currentGeometryProgram = geometryProgram;
  16207. updateBuffers = true;
  16208. }
  16209. // morph targets
  16210. var morphTargetInfluences = object.morphTargetInfluences;
  16211. if ( morphTargetInfluences !== undefined ) {
  16212. var activeInfluences = [];
  16213. for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) {
  16214. var influence = morphTargetInfluences[ i ];
  16215. activeInfluences.push( [ influence, i ] );
  16216. }
  16217. activeInfluences.sort( absNumericalSort );
  16218. if ( activeInfluences.length > 8 ) {
  16219. activeInfluences.length = 8;
  16220. }
  16221. var morphAttributes = geometry.morphAttributes;
  16222. for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) {
  16223. var influence = activeInfluences[ i ];
  16224. morphInfluences[ i ] = influence[ 0 ];
  16225. if ( influence[ 0 ] !== 0 ) {
  16226. var index = influence[ 1 ];
  16227. if ( material.morphTargets === true && morphAttributes.position ) geometry.addAttribute( 'morphTarget' + i, morphAttributes.position[ index ] );
  16228. if ( material.morphNormals === true && morphAttributes.normal ) geometry.addAttribute( 'morphNormal' + i, morphAttributes.normal[ index ] );
  16229. } else {
  16230. if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i );
  16231. if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i );
  16232. }
  16233. }
  16234. for ( var i = activeInfluences.length, il = morphInfluences.length; i < il; i ++ ) {
  16235. morphInfluences[ i ] = 0.0;
  16236. }
  16237. program.getUniforms().setValue(
  16238. _gl, 'morphTargetInfluences', morphInfluences );
  16239. updateBuffers = true;
  16240. }
  16241. //
  16242. var index = geometry.index;
  16243. var position = geometry.attributes.position;
  16244. var rangeFactor = 1;
  16245. if ( material.wireframe === true ) {
  16246. index = objects.getWireframeAttribute( geometry );
  16247. rangeFactor = 2;
  16248. }
  16249. var renderer;
  16250. if ( index !== null ) {
  16251. renderer = indexedBufferRenderer;
  16252. renderer.setIndex( index );
  16253. } else {
  16254. renderer = bufferRenderer;
  16255. }
  16256. if ( updateBuffers ) {
  16257. setupVertexAttributes( material, program, geometry );
  16258. if ( index !== null ) {
  16259. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, objects.getAttributeBuffer( index ) );
  16260. }
  16261. }
  16262. //
  16263. var dataCount = 0;
  16264. if ( index !== null ) {
  16265. dataCount = index.count;
  16266. } else if ( position !== undefined ) {
  16267. dataCount = position.count;
  16268. }
  16269. var rangeStart = geometry.drawRange.start * rangeFactor;
  16270. var rangeCount = geometry.drawRange.count * rangeFactor;
  16271. var groupStart = group !== null ? group.start * rangeFactor : 0;
  16272. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  16273. var drawStart = Math.max( rangeStart, groupStart );
  16274. var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  16275. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  16276. if ( drawCount === 0 ) return;
  16277. //
  16278. if ( object.isMesh ) {
  16279. if ( material.wireframe === true ) {
  16280. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  16281. renderer.setMode( _gl.LINES );
  16282. } else {
  16283. switch ( object.drawMode ) {
  16284. case TrianglesDrawMode:
  16285. renderer.setMode( _gl.TRIANGLES );
  16286. break;
  16287. case TriangleStripDrawMode:
  16288. renderer.setMode( _gl.TRIANGLE_STRIP );
  16289. break;
  16290. case TriangleFanDrawMode:
  16291. renderer.setMode( _gl.TRIANGLE_FAN );
  16292. break;
  16293. }
  16294. }
  16295. } else if ( object.isLine ) {
  16296. var lineWidth = material.linewidth;
  16297. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  16298. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  16299. if ( object.isLineSegments ) {
  16300. renderer.setMode( _gl.LINES );
  16301. } else {
  16302. renderer.setMode( _gl.LINE_STRIP );
  16303. }
  16304. } else if ( object.isPoints ) {
  16305. renderer.setMode( _gl.POINTS );
  16306. }
  16307. if ( geometry && geometry.isInstancedBufferGeometry ) {
  16308. if ( geometry.maxInstancedCount > 0 ) {
  16309. renderer.renderInstances( geometry, drawStart, drawCount );
  16310. }
  16311. } else {
  16312. renderer.render( drawStart, drawCount );
  16313. }
  16314. };
  16315. function setupVertexAttributes( material, program, geometry, startIndex ) {
  16316. var extension;
  16317. if ( geometry && geometry.isInstancedBufferGeometry ) {
  16318. extension = extensions.get( 'ANGLE_instanced_arrays' );
  16319. if ( extension === null ) {
  16320. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  16321. return;
  16322. }
  16323. }
  16324. if ( startIndex === undefined ) startIndex = 0;
  16325. state.initAttributes();
  16326. var geometryAttributes = geometry.attributes;
  16327. var programAttributes = program.getAttributes();
  16328. var materialDefaultAttributeValues = material.defaultAttributeValues;
  16329. for ( var name in programAttributes ) {
  16330. var programAttribute = programAttributes[ name ];
  16331. if ( programAttribute >= 0 ) {
  16332. var geometryAttribute = geometryAttributes[ name ];
  16333. if ( geometryAttribute !== undefined ) {
  16334. var normalized = geometryAttribute.normalized;
  16335. var size = geometryAttribute.itemSize;
  16336. var attributeProperties = objects.getAttributeProperties( geometryAttribute );
  16337. var buffer = attributeProperties.__webglBuffer;
  16338. var type = attributeProperties.type;
  16339. var bytesPerElement = attributeProperties.bytesPerElement;
  16340. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  16341. var data = geometryAttribute.data;
  16342. var stride = data.stride;
  16343. var offset = geometryAttribute.offset;
  16344. if ( data && data.isInstancedInterleavedBuffer ) {
  16345. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute, extension );
  16346. if ( geometry.maxInstancedCount === undefined ) {
  16347. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  16348. }
  16349. } else {
  16350. state.enableAttribute( programAttribute );
  16351. }
  16352. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  16353. _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, ( startIndex * stride + offset ) * bytesPerElement );
  16354. } else {
  16355. if ( geometryAttribute.isInstancedBufferAttribute ) {
  16356. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute, extension );
  16357. if ( geometry.maxInstancedCount === undefined ) {
  16358. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  16359. }
  16360. } else {
  16361. state.enableAttribute( programAttribute );
  16362. }
  16363. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  16364. _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * bytesPerElement );
  16365. }
  16366. } else if ( materialDefaultAttributeValues !== undefined ) {
  16367. var value = materialDefaultAttributeValues[ name ];
  16368. if ( value !== undefined ) {
  16369. switch ( value.length ) {
  16370. case 2:
  16371. _gl.vertexAttrib2fv( programAttribute, value );
  16372. break;
  16373. case 3:
  16374. _gl.vertexAttrib3fv( programAttribute, value );
  16375. break;
  16376. case 4:
  16377. _gl.vertexAttrib4fv( programAttribute, value );
  16378. break;
  16379. default:
  16380. _gl.vertexAttrib1fv( programAttribute, value );
  16381. }
  16382. }
  16383. }
  16384. }
  16385. }
  16386. state.disableUnusedAttributes();
  16387. }
  16388. // Sorting
  16389. function absNumericalSort( a, b ) {
  16390. return Math.abs( b[ 0 ] ) - Math.abs( a[ 0 ] );
  16391. }
  16392. function painterSortStable( a, b ) {
  16393. if ( a.object.renderOrder !== b.object.renderOrder ) {
  16394. return a.object.renderOrder - b.object.renderOrder;
  16395. } else if ( a.material.program && b.material.program && a.material.program !== b.material.program ) {
  16396. return a.material.program.id - b.material.program.id;
  16397. } else if ( a.material.id !== b.material.id ) {
  16398. return a.material.id - b.material.id;
  16399. } else if ( a.z !== b.z ) {
  16400. return a.z - b.z;
  16401. } else {
  16402. return a.id - b.id;
  16403. }
  16404. }
  16405. function reversePainterSortStable( a, b ) {
  16406. if ( a.object.renderOrder !== b.object.renderOrder ) {
  16407. return a.object.renderOrder - b.object.renderOrder;
  16408. } if ( a.z !== b.z ) {
  16409. return b.z - a.z;
  16410. } else {
  16411. return a.id - b.id;
  16412. }
  16413. }
  16414. // Rendering
  16415. this.render = function ( scene, camera, renderTarget, forceClear ) {
  16416. if ( camera !== undefined && camera.isCamera !== true ) {
  16417. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  16418. return;
  16419. }
  16420. // reset caching for this frame
  16421. _currentGeometryProgram = '';
  16422. _currentMaterialId = - 1;
  16423. _currentCamera = null;
  16424. // update scene graph
  16425. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  16426. // update camera matrices and frustum
  16427. if ( camera.parent === null ) camera.updateMatrixWorld();
  16428. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  16429. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  16430. _frustum.setFromMatrix( _projScreenMatrix );
  16431. lights.length = 0;
  16432. opaqueObjectsLastIndex = - 1;
  16433. transparentObjectsLastIndex = - 1;
  16434. sprites.length = 0;
  16435. lensFlares.length = 0;
  16436. _localClippingEnabled = this.localClippingEnabled;
  16437. _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  16438. projectObject( scene, camera );
  16439. opaqueObjects.length = opaqueObjectsLastIndex + 1;
  16440. transparentObjects.length = transparentObjectsLastIndex + 1;
  16441. if ( _this.sortObjects === true ) {
  16442. opaqueObjects.sort( painterSortStable );
  16443. transparentObjects.sort( reversePainterSortStable );
  16444. }
  16445. //
  16446. if ( _clippingEnabled ) _clipping.beginShadows();
  16447. setupShadows( lights );
  16448. shadowMap.render( scene, camera );
  16449. setupLights( lights, camera );
  16450. if ( _clippingEnabled ) _clipping.endShadows();
  16451. //
  16452. _infoRender.calls = 0;
  16453. _infoRender.vertices = 0;
  16454. _infoRender.faces = 0;
  16455. _infoRender.points = 0;
  16456. if ( renderTarget === undefined ) {
  16457. renderTarget = null;
  16458. }
  16459. this.setRenderTarget( renderTarget );
  16460. //
  16461. var background = scene.background;
  16462. if ( background === null ) {
  16463. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  16464. } else if ( background && background.isColor ) {
  16465. state.buffers.color.setClear( background.r, background.g, background.b, 1, _premultipliedAlpha );
  16466. forceClear = true;
  16467. }
  16468. if ( this.autoClear || forceClear ) {
  16469. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  16470. }
  16471. if ( background && background.isCubeTexture ) {
  16472. if ( backgroundBoxCamera === undefined ) {
  16473. backgroundBoxCamera = new PerspectiveCamera();
  16474. backgroundBoxMesh = new Mesh(
  16475. new BoxBufferGeometry( 5, 5, 5 ),
  16476. new ShaderMaterial( {
  16477. uniforms: ShaderLib.cube.uniforms,
  16478. vertexShader: ShaderLib.cube.vertexShader,
  16479. fragmentShader: ShaderLib.cube.fragmentShader,
  16480. side: BackSide,
  16481. depthTest: false,
  16482. depthWrite: false,
  16483. fog: false
  16484. } )
  16485. );
  16486. }
  16487. backgroundBoxCamera.projectionMatrix.copy( camera.projectionMatrix );
  16488. backgroundBoxCamera.matrixWorld.extractRotation( camera.matrixWorld );
  16489. backgroundBoxCamera.matrixWorldInverse.getInverse( backgroundBoxCamera.matrixWorld );
  16490. backgroundBoxMesh.material.uniforms[ "tCube" ].value = background;
  16491. backgroundBoxMesh.modelViewMatrix.multiplyMatrices( backgroundBoxCamera.matrixWorldInverse, backgroundBoxMesh.matrixWorld );
  16492. objects.update( backgroundBoxMesh );
  16493. _this.renderBufferDirect( backgroundBoxCamera, null, backgroundBoxMesh.geometry, backgroundBoxMesh.material, backgroundBoxMesh, null );
  16494. } else if ( background && background.isTexture ) {
  16495. if ( backgroundPlaneCamera === undefined ) {
  16496. backgroundPlaneCamera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  16497. backgroundPlaneMesh = new Mesh(
  16498. new PlaneBufferGeometry( 2, 2 ),
  16499. new MeshBasicMaterial( { depthTest: false, depthWrite: false, fog: false } )
  16500. );
  16501. }
  16502. backgroundPlaneMesh.material.map = background;
  16503. objects.update( backgroundPlaneMesh );
  16504. _this.renderBufferDirect( backgroundPlaneCamera, null, backgroundPlaneMesh.geometry, backgroundPlaneMesh.material, backgroundPlaneMesh, null );
  16505. }
  16506. //
  16507. if ( scene.overrideMaterial ) {
  16508. var overrideMaterial = scene.overrideMaterial;
  16509. renderObjects( opaqueObjects, scene, camera, overrideMaterial );
  16510. renderObjects( transparentObjects, scene, camera, overrideMaterial );
  16511. } else {
  16512. // opaque pass (front-to-back order)
  16513. state.setBlending( NoBlending );
  16514. renderObjects( opaqueObjects, scene, camera );
  16515. // transparent pass (back-to-front order)
  16516. renderObjects( transparentObjects, scene, camera );
  16517. }
  16518. // custom render plugins (post pass)
  16519. spritePlugin.render( scene, camera );
  16520. lensFlarePlugin.render( scene, camera, _currentViewport );
  16521. // Generate mipmap if we're using any kind of mipmap filtering
  16522. if ( renderTarget ) {
  16523. textures.updateRenderTargetMipmap( renderTarget );
  16524. }
  16525. // Ensure depth buffer writing is enabled so it can be cleared on next render
  16526. state.setDepthTest( true );
  16527. state.setDepthWrite( true );
  16528. state.setColorWrite( true );
  16529. // _gl.finish();
  16530. };
  16531. function pushRenderItem( object, geometry, material, z, group ) {
  16532. var array, index;
  16533. // allocate the next position in the appropriate array
  16534. if ( material.transparent ) {
  16535. array = transparentObjects;
  16536. index = ++ transparentObjectsLastIndex;
  16537. } else {
  16538. array = opaqueObjects;
  16539. index = ++ opaqueObjectsLastIndex;
  16540. }
  16541. // recycle existing render item or grow the array
  16542. var renderItem = array[ index ];
  16543. if ( renderItem !== undefined ) {
  16544. renderItem.id = object.id;
  16545. renderItem.object = object;
  16546. renderItem.geometry = geometry;
  16547. renderItem.material = material;
  16548. renderItem.z = _vector3.z;
  16549. renderItem.group = group;
  16550. } else {
  16551. renderItem = {
  16552. id: object.id,
  16553. object: object,
  16554. geometry: geometry,
  16555. material: material,
  16556. z: _vector3.z,
  16557. group: group
  16558. };
  16559. // assert( index === array.length );
  16560. array.push( renderItem );
  16561. }
  16562. }
  16563. // TODO Duplicated code (Frustum)
  16564. function isObjectViewable( object ) {
  16565. var geometry = object.geometry;
  16566. if ( geometry.boundingSphere === null )
  16567. geometry.computeBoundingSphere();
  16568. _sphere.copy( geometry.boundingSphere ).
  16569. applyMatrix4( object.matrixWorld );
  16570. return isSphereViewable( _sphere );
  16571. }
  16572. function isSpriteViewable( sprite ) {
  16573. _sphere.center.set( 0, 0, 0 );
  16574. _sphere.radius = 0.7071067811865476;
  16575. _sphere.applyMatrix4( sprite.matrixWorld );
  16576. return isSphereViewable( _sphere );
  16577. }
  16578. function isSphereViewable( sphere ) {
  16579. if ( ! _frustum.intersectsSphere( sphere ) ) return false;
  16580. var numPlanes = _clipping.numPlanes;
  16581. if ( numPlanes === 0 ) return true;
  16582. var planes = _this.clippingPlanes,
  16583. center = sphere.center,
  16584. negRad = - sphere.radius,
  16585. i = 0;
  16586. do {
  16587. // out when deeper than radius in the negative halfspace
  16588. if ( planes[ i ].distanceToPoint( center ) < negRad ) return false;
  16589. } while ( ++ i !== numPlanes );
  16590. return true;
  16591. }
  16592. function projectObject( object, camera ) {
  16593. if ( object.visible === false ) return;
  16594. var visible = ( object.layers.mask & camera.layers.mask ) !== 0;
  16595. if ( visible ) {
  16596. if ( object.isLight ) {
  16597. lights.push( object );
  16598. } else if ( object.isSprite ) {
  16599. if ( object.frustumCulled === false || isSpriteViewable( object ) === true ) {
  16600. sprites.push( object );
  16601. }
  16602. } else if ( object.isLensFlare ) {
  16603. lensFlares.push( object );
  16604. } else if ( object.isImmediateRenderObject ) {
  16605. if ( _this.sortObjects === true ) {
  16606. _vector3.setFromMatrixPosition( object.matrixWorld );
  16607. _vector3.applyMatrix4( _projScreenMatrix );
  16608. }
  16609. pushRenderItem( object, null, object.material, _vector3.z, null );
  16610. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  16611. if ( object.isSkinnedMesh ) {
  16612. object.skeleton.update();
  16613. }
  16614. if ( object.frustumCulled === false || isObjectViewable( object ) === true ) {
  16615. var material = object.material;
  16616. if ( material.visible === true ) {
  16617. if ( _this.sortObjects === true ) {
  16618. _vector3.setFromMatrixPosition( object.matrixWorld );
  16619. _vector3.applyMatrix4( _projScreenMatrix );
  16620. }
  16621. var geometry = objects.update( object );
  16622. if ( material.isMultiMaterial ) {
  16623. var groups = geometry.groups;
  16624. var materials = material.materials;
  16625. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  16626. var group = groups[ i ];
  16627. var groupMaterial = materials[ group.materialIndex ];
  16628. if ( groupMaterial.visible === true ) {
  16629. pushRenderItem( object, geometry, groupMaterial, _vector3.z, group );
  16630. }
  16631. }
  16632. } else {
  16633. pushRenderItem( object, geometry, material, _vector3.z, null );
  16634. }
  16635. }
  16636. }
  16637. }
  16638. }
  16639. var children = object.children;
  16640. for ( var i = 0, l = children.length; i < l; i ++ ) {
  16641. projectObject( children[ i ], camera );
  16642. }
  16643. }
  16644. function renderObjects( renderList, scene, camera, overrideMaterial ) {
  16645. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  16646. var renderItem = renderList[ i ];
  16647. var object = renderItem.object;
  16648. var geometry = renderItem.geometry;
  16649. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  16650. var group = renderItem.group;
  16651. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  16652. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  16653. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  16654. if ( object.isImmediateRenderObject ) {
  16655. setMaterial( material );
  16656. var program = setProgram( camera, scene.fog, material, object );
  16657. _currentGeometryProgram = '';
  16658. object.render( function ( object ) {
  16659. _this.renderBufferImmediate( object, program, material );
  16660. } );
  16661. } else {
  16662. _this.renderBufferDirect( camera, scene.fog, geometry, material, object, group );
  16663. }
  16664. object.onAfterRender( _this, scene, camera, geometry, material, group );
  16665. }
  16666. }
  16667. function initMaterial( material, fog, object ) {
  16668. var materialProperties = properties.get( material );
  16669. var parameters = programCache.getParameters(
  16670. material, _lights, fog, _clipping.numPlanes, _clipping.numIntersection, object );
  16671. var code = programCache.getProgramCode( material, parameters );
  16672. var program = materialProperties.program;
  16673. var programChange = true;
  16674. if ( program === undefined ) {
  16675. // new material
  16676. material.addEventListener( 'dispose', onMaterialDispose );
  16677. } else if ( program.code !== code ) {
  16678. // changed glsl or parameters
  16679. releaseMaterialProgramReference( material );
  16680. } else if ( parameters.shaderID !== undefined ) {
  16681. // same glsl and uniform list
  16682. return;
  16683. } else {
  16684. // only rebuild uniform list
  16685. programChange = false;
  16686. }
  16687. if ( programChange ) {
  16688. if ( parameters.shaderID ) {
  16689. var shader = ShaderLib[ parameters.shaderID ];
  16690. materialProperties.__webglShader = {
  16691. name: material.type,
  16692. uniforms: UniformsUtils.clone( shader.uniforms ),
  16693. vertexShader: shader.vertexShader,
  16694. fragmentShader: shader.fragmentShader
  16695. };
  16696. } else {
  16697. materialProperties.__webglShader = {
  16698. name: material.type,
  16699. uniforms: material.uniforms,
  16700. vertexShader: material.vertexShader,
  16701. fragmentShader: material.fragmentShader
  16702. };
  16703. }
  16704. material.__webglShader = materialProperties.__webglShader;
  16705. program = programCache.acquireProgram( material, parameters, code );
  16706. materialProperties.program = program;
  16707. material.program = program;
  16708. }
  16709. var attributes = program.getAttributes();
  16710. if ( material.morphTargets ) {
  16711. material.numSupportedMorphTargets = 0;
  16712. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  16713. if ( attributes[ 'morphTarget' + i ] >= 0 ) {
  16714. material.numSupportedMorphTargets ++;
  16715. }
  16716. }
  16717. }
  16718. if ( material.morphNormals ) {
  16719. material.numSupportedMorphNormals = 0;
  16720. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  16721. if ( attributes[ 'morphNormal' + i ] >= 0 ) {
  16722. material.numSupportedMorphNormals ++;
  16723. }
  16724. }
  16725. }
  16726. var uniforms = materialProperties.__webglShader.uniforms;
  16727. if ( ! material.isShaderMaterial &&
  16728. ! material.isRawShaderMaterial ||
  16729. material.clipping === true ) {
  16730. materialProperties.numClippingPlanes = _clipping.numPlanes;
  16731. materialProperties.numIntersection = _clipping.numIntersection;
  16732. uniforms.clippingPlanes = _clipping.uniform;
  16733. }
  16734. materialProperties.fog = fog;
  16735. // store the light setup it was created for
  16736. materialProperties.lightsHash = _lights.hash;
  16737. if ( material.lights ) {
  16738. // wire up the material to this renderer's lighting state
  16739. uniforms.ambientLightColor.value = _lights.ambient;
  16740. uniforms.directionalLights.value = _lights.directional;
  16741. uniforms.spotLights.value = _lights.spot;
  16742. uniforms.rectAreaLights.value = _lights.rectArea;
  16743. uniforms.pointLights.value = _lights.point;
  16744. uniforms.hemisphereLights.value = _lights.hemi;
  16745. uniforms.directionalShadowMap.value = _lights.directionalShadowMap;
  16746. uniforms.directionalShadowMatrix.value = _lights.directionalShadowMatrix;
  16747. uniforms.spotShadowMap.value = _lights.spotShadowMap;
  16748. uniforms.spotShadowMatrix.value = _lights.spotShadowMatrix;
  16749. uniforms.pointShadowMap.value = _lights.pointShadowMap;
  16750. uniforms.pointShadowMatrix.value = _lights.pointShadowMatrix;
  16751. // TODO (abelnation): add area lights shadow info to uniforms
  16752. }
  16753. var progUniforms = materialProperties.program.getUniforms(),
  16754. uniformsList =
  16755. WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  16756. materialProperties.uniformsList = uniformsList;
  16757. }
  16758. function setMaterial( material ) {
  16759. material.side === DoubleSide
  16760. ? state.disable( _gl.CULL_FACE )
  16761. : state.enable( _gl.CULL_FACE );
  16762. state.setFlipSided( material.side === BackSide );
  16763. material.transparent === true
  16764. ? state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha )
  16765. : state.setBlending( NoBlending );
  16766. state.setDepthFunc( material.depthFunc );
  16767. state.setDepthTest( material.depthTest );
  16768. state.setDepthWrite( material.depthWrite );
  16769. state.setColorWrite( material.colorWrite );
  16770. state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  16771. }
  16772. function setProgram( camera, fog, material, object ) {
  16773. _usedTextureUnits = 0;
  16774. var materialProperties = properties.get( material );
  16775. if ( _clippingEnabled ) {
  16776. if ( _localClippingEnabled || camera !== _currentCamera ) {
  16777. var useCache =
  16778. camera === _currentCamera &&
  16779. material.id === _currentMaterialId;
  16780. // we might want to call this function with some ClippingGroup
  16781. // object instead of the material, once it becomes feasible
  16782. // (#8465, #8379)
  16783. _clipping.setState(
  16784. material.clippingPlanes, material.clipIntersection, material.clipShadows,
  16785. camera, materialProperties, useCache );
  16786. }
  16787. }
  16788. if ( material.needsUpdate === false ) {
  16789. if ( materialProperties.program === undefined ) {
  16790. material.needsUpdate = true;
  16791. } else if ( material.fog && materialProperties.fog !== fog ) {
  16792. material.needsUpdate = true;
  16793. } else if ( material.lights && materialProperties.lightsHash !== _lights.hash ) {
  16794. material.needsUpdate = true;
  16795. } else if ( materialProperties.numClippingPlanes !== undefined &&
  16796. ( materialProperties.numClippingPlanes !== _clipping.numPlanes ||
  16797. materialProperties.numIntersection !== _clipping.numIntersection ) ) {
  16798. material.needsUpdate = true;
  16799. }
  16800. }
  16801. if ( material.needsUpdate ) {
  16802. initMaterial( material, fog, object );
  16803. material.needsUpdate = false;
  16804. }
  16805. var refreshProgram = false;
  16806. var refreshMaterial = false;
  16807. var refreshLights = false;
  16808. var program = materialProperties.program,
  16809. p_uniforms = program.getUniforms(),
  16810. m_uniforms = materialProperties.__webglShader.uniforms;
  16811. if ( program.id !== _currentProgram ) {
  16812. _gl.useProgram( program.program );
  16813. _currentProgram = program.id;
  16814. refreshProgram = true;
  16815. refreshMaterial = true;
  16816. refreshLights = true;
  16817. }
  16818. if ( material.id !== _currentMaterialId ) {
  16819. _currentMaterialId = material.id;
  16820. refreshMaterial = true;
  16821. }
  16822. if ( refreshProgram || camera !== _currentCamera ) {
  16823. p_uniforms.set( _gl, camera, 'projectionMatrix' );
  16824. if ( capabilities.logarithmicDepthBuffer ) {
  16825. p_uniforms.setValue( _gl, 'logDepthBufFC',
  16826. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  16827. }
  16828. if ( camera !== _currentCamera ) {
  16829. _currentCamera = camera;
  16830. // lighting uniforms depend on the camera so enforce an update
  16831. // now, in case this material supports lights - or later, when
  16832. // the next material that does gets activated:
  16833. refreshMaterial = true; // set to true on material change
  16834. refreshLights = true; // remains set until update done
  16835. }
  16836. // load material specific uniforms
  16837. // (shader material also gets them for the sake of genericity)
  16838. if ( material.isShaderMaterial ||
  16839. material.isMeshPhongMaterial ||
  16840. material.isMeshStandardMaterial ||
  16841. material.envMap ) {
  16842. var uCamPos = p_uniforms.map.cameraPosition;
  16843. if ( uCamPos !== undefined ) {
  16844. uCamPos.setValue( _gl,
  16845. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  16846. }
  16847. }
  16848. if ( material.isMeshPhongMaterial ||
  16849. material.isMeshLambertMaterial ||
  16850. material.isMeshBasicMaterial ||
  16851. material.isMeshStandardMaterial ||
  16852. material.isShaderMaterial ||
  16853. material.skinning ) {
  16854. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  16855. }
  16856. p_uniforms.set( _gl, _this, 'toneMappingExposure' );
  16857. p_uniforms.set( _gl, _this, 'toneMappingWhitePoint' );
  16858. }
  16859. // skinning uniforms must be set even if material didn't change
  16860. // auto-setting of texture unit for bone texture must go before other textures
  16861. // not sure why, but otherwise weird things happen
  16862. if ( material.skinning ) {
  16863. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  16864. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  16865. var skeleton = object.skeleton;
  16866. if ( skeleton ) {
  16867. if ( capabilities.floatVertexTextures && skeleton.useVertexTexture ) {
  16868. p_uniforms.set( _gl, skeleton, 'boneTexture' );
  16869. p_uniforms.set( _gl, skeleton, 'boneTextureWidth' );
  16870. p_uniforms.set( _gl, skeleton, 'boneTextureHeight' );
  16871. } else {
  16872. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  16873. }
  16874. }
  16875. }
  16876. if ( refreshMaterial ) {
  16877. if ( material.lights ) {
  16878. // the current material requires lighting info
  16879. // note: all lighting uniforms are always set correctly
  16880. // they simply reference the renderer's state for their
  16881. // values
  16882. //
  16883. // use the current material's .needsUpdate flags to set
  16884. // the GL state when required
  16885. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  16886. }
  16887. // refresh uniforms common to several materials
  16888. if ( fog && material.fog ) {
  16889. refreshUniformsFog( m_uniforms, fog );
  16890. }
  16891. if ( material.isMeshBasicMaterial ||
  16892. material.isMeshLambertMaterial ||
  16893. material.isMeshPhongMaterial ||
  16894. material.isMeshStandardMaterial ||
  16895. material.isMeshNormalMaterial ||
  16896. material.isMeshDepthMaterial ) {
  16897. refreshUniformsCommon( m_uniforms, material );
  16898. }
  16899. // refresh single material specific uniforms
  16900. if ( material.isLineBasicMaterial ) {
  16901. refreshUniformsLine( m_uniforms, material );
  16902. } else if ( material.isLineDashedMaterial ) {
  16903. refreshUniformsLine( m_uniforms, material );
  16904. refreshUniformsDash( m_uniforms, material );
  16905. } else if ( material.isPointsMaterial ) {
  16906. refreshUniformsPoints( m_uniforms, material );
  16907. } else if ( material.isMeshLambertMaterial ) {
  16908. refreshUniformsLambert( m_uniforms, material );
  16909. } else if ( material.isMeshToonMaterial ) {
  16910. refreshUniformsToon( m_uniforms, material );
  16911. } else if ( material.isMeshPhongMaterial ) {
  16912. refreshUniformsPhong( m_uniforms, material );
  16913. } else if ( material.isMeshPhysicalMaterial ) {
  16914. refreshUniformsPhysical( m_uniforms, material );
  16915. } else if ( material.isMeshStandardMaterial ) {
  16916. refreshUniformsStandard( m_uniforms, material );
  16917. } else if ( material.isMeshDepthMaterial ) {
  16918. if ( material.displacementMap ) {
  16919. m_uniforms.displacementMap.value = material.displacementMap;
  16920. m_uniforms.displacementScale.value = material.displacementScale;
  16921. m_uniforms.displacementBias.value = material.displacementBias;
  16922. }
  16923. } else if ( material.isMeshNormalMaterial ) {
  16924. refreshUniformsNormal( m_uniforms, material );
  16925. }
  16926. // RectAreaLight Texture
  16927. // TODO (mrdoob): Find a nicer implementation
  16928. if ( m_uniforms.ltcMat !== undefined ) m_uniforms.ltcMat.value = THREE.UniformsLib.LTC_MAT_TEXTURE;
  16929. if ( m_uniforms.ltcMag !== undefined ) m_uniforms.ltcMag.value = THREE.UniformsLib.LTC_MAG_TEXTURE;
  16930. WebGLUniforms.upload(
  16931. _gl, materialProperties.uniformsList, m_uniforms, _this );
  16932. }
  16933. // common matrices
  16934. p_uniforms.set( _gl, object, 'modelViewMatrix' );
  16935. p_uniforms.set( _gl, object, 'normalMatrix' );
  16936. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  16937. return program;
  16938. }
  16939. // Uniforms (refresh uniforms objects)
  16940. function refreshUniformsCommon( uniforms, material ) {
  16941. uniforms.opacity.value = material.opacity;
  16942. uniforms.diffuse.value = material.color;
  16943. if ( material.emissive ) {
  16944. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  16945. }
  16946. uniforms.map.value = material.map;
  16947. uniforms.specularMap.value = material.specularMap;
  16948. uniforms.alphaMap.value = material.alphaMap;
  16949. if ( material.lightMap ) {
  16950. uniforms.lightMap.value = material.lightMap;
  16951. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  16952. }
  16953. if ( material.aoMap ) {
  16954. uniforms.aoMap.value = material.aoMap;
  16955. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  16956. }
  16957. // uv repeat and offset setting priorities
  16958. // 1. color map
  16959. // 2. specular map
  16960. // 3. normal map
  16961. // 4. bump map
  16962. // 5. alpha map
  16963. // 6. emissive map
  16964. var uvScaleMap;
  16965. if ( material.map ) {
  16966. uvScaleMap = material.map;
  16967. } else if ( material.specularMap ) {
  16968. uvScaleMap = material.specularMap;
  16969. } else if ( material.displacementMap ) {
  16970. uvScaleMap = material.displacementMap;
  16971. } else if ( material.normalMap ) {
  16972. uvScaleMap = material.normalMap;
  16973. } else if ( material.bumpMap ) {
  16974. uvScaleMap = material.bumpMap;
  16975. } else if ( material.roughnessMap ) {
  16976. uvScaleMap = material.roughnessMap;
  16977. } else if ( material.metalnessMap ) {
  16978. uvScaleMap = material.metalnessMap;
  16979. } else if ( material.alphaMap ) {
  16980. uvScaleMap = material.alphaMap;
  16981. } else if ( material.emissiveMap ) {
  16982. uvScaleMap = material.emissiveMap;
  16983. }
  16984. if ( uvScaleMap !== undefined ) {
  16985. // backwards compatibility
  16986. if ( uvScaleMap.isWebGLRenderTarget ) {
  16987. uvScaleMap = uvScaleMap.texture;
  16988. }
  16989. var offset = uvScaleMap.offset;
  16990. var repeat = uvScaleMap.repeat;
  16991. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  16992. }
  16993. uniforms.envMap.value = material.envMap;
  16994. // don't flip CubeTexture envMaps, flip everything else:
  16995. // WebGLRenderTargetCube will be flipped for backwards compatibility
  16996. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  16997. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  16998. uniforms.flipEnvMap.value = ( ! ( material.envMap && material.envMap.isCubeTexture ) ) ? 1 : - 1;
  16999. uniforms.reflectivity.value = material.reflectivity;
  17000. uniforms.refractionRatio.value = material.refractionRatio;
  17001. }
  17002. function refreshUniformsLine( uniforms, material ) {
  17003. uniforms.diffuse.value = material.color;
  17004. uniforms.opacity.value = material.opacity;
  17005. }
  17006. function refreshUniformsDash( uniforms, material ) {
  17007. uniforms.dashSize.value = material.dashSize;
  17008. uniforms.totalSize.value = material.dashSize + material.gapSize;
  17009. uniforms.scale.value = material.scale;
  17010. }
  17011. function refreshUniformsPoints( uniforms, material ) {
  17012. uniforms.diffuse.value = material.color;
  17013. uniforms.opacity.value = material.opacity;
  17014. uniforms.size.value = material.size * _pixelRatio;
  17015. uniforms.scale.value = _height * 0.5;
  17016. uniforms.map.value = material.map;
  17017. if ( material.map !== null ) {
  17018. var offset = material.map.offset;
  17019. var repeat = material.map.repeat;
  17020. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  17021. }
  17022. }
  17023. function refreshUniformsFog( uniforms, fog ) {
  17024. uniforms.fogColor.value = fog.color;
  17025. if ( fog.isFog ) {
  17026. uniforms.fogNear.value = fog.near;
  17027. uniforms.fogFar.value = fog.far;
  17028. } else if ( fog.isFogExp2 ) {
  17029. uniforms.fogDensity.value = fog.density;
  17030. }
  17031. }
  17032. function refreshUniformsLambert( uniforms, material ) {
  17033. if ( material.emissiveMap ) {
  17034. uniforms.emissiveMap.value = material.emissiveMap;
  17035. }
  17036. }
  17037. function refreshUniformsPhong( uniforms, material ) {
  17038. uniforms.specular.value = material.specular;
  17039. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  17040. if ( material.emissiveMap ) {
  17041. uniforms.emissiveMap.value = material.emissiveMap;
  17042. }
  17043. if ( material.bumpMap ) {
  17044. uniforms.bumpMap.value = material.bumpMap;
  17045. uniforms.bumpScale.value = material.bumpScale;
  17046. }
  17047. if ( material.normalMap ) {
  17048. uniforms.normalMap.value = material.normalMap;
  17049. uniforms.normalScale.value.copy( material.normalScale );
  17050. }
  17051. if ( material.displacementMap ) {
  17052. uniforms.displacementMap.value = material.displacementMap;
  17053. uniforms.displacementScale.value = material.displacementScale;
  17054. uniforms.displacementBias.value = material.displacementBias;
  17055. }
  17056. }
  17057. function refreshUniformsToon( uniforms, material ) {
  17058. refreshUniformsPhong( uniforms, material );
  17059. if ( material.gradientMap ) {
  17060. uniforms.gradientMap.value = material.gradientMap;
  17061. }
  17062. }
  17063. function refreshUniformsStandard( uniforms, material ) {
  17064. uniforms.roughness.value = material.roughness;
  17065. uniforms.metalness.value = material.metalness;
  17066. if ( material.roughnessMap ) {
  17067. uniforms.roughnessMap.value = material.roughnessMap;
  17068. }
  17069. if ( material.metalnessMap ) {
  17070. uniforms.metalnessMap.value = material.metalnessMap;
  17071. }
  17072. if ( material.emissiveMap ) {
  17073. uniforms.emissiveMap.value = material.emissiveMap;
  17074. }
  17075. if ( material.bumpMap ) {
  17076. uniforms.bumpMap.value = material.bumpMap;
  17077. uniforms.bumpScale.value = material.bumpScale;
  17078. }
  17079. if ( material.normalMap ) {
  17080. uniforms.normalMap.value = material.normalMap;
  17081. uniforms.normalScale.value.copy( material.normalScale );
  17082. }
  17083. if ( material.displacementMap ) {
  17084. uniforms.displacementMap.value = material.displacementMap;
  17085. uniforms.displacementScale.value = material.displacementScale;
  17086. uniforms.displacementBias.value = material.displacementBias;
  17087. }
  17088. if ( material.envMap ) {
  17089. //uniforms.envMap.value = material.envMap; // part of uniforms common
  17090. uniforms.envMapIntensity.value = material.envMapIntensity;
  17091. }
  17092. }
  17093. function refreshUniformsPhysical( uniforms, material ) {
  17094. uniforms.clearCoat.value = material.clearCoat;
  17095. uniforms.clearCoatRoughness.value = material.clearCoatRoughness;
  17096. refreshUniformsStandard( uniforms, material );
  17097. }
  17098. function refreshUniformsNormal( uniforms, material ) {
  17099. if ( material.bumpMap ) {
  17100. uniforms.bumpMap.value = material.bumpMap;
  17101. uniforms.bumpScale.value = material.bumpScale;
  17102. }
  17103. if ( material.normalMap ) {
  17104. uniforms.normalMap.value = material.normalMap;
  17105. uniforms.normalScale.value.copy( material.normalScale );
  17106. }
  17107. if ( material.displacementMap ) {
  17108. uniforms.displacementMap.value = material.displacementMap;
  17109. uniforms.displacementScale.value = material.displacementScale;
  17110. uniforms.displacementBias.value = material.displacementBias;
  17111. }
  17112. }
  17113. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  17114. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  17115. uniforms.ambientLightColor.needsUpdate = value;
  17116. uniforms.directionalLights.needsUpdate = value;
  17117. uniforms.pointLights.needsUpdate = value;
  17118. uniforms.spotLights.needsUpdate = value;
  17119. uniforms.rectAreaLights.needsUpdate = value;
  17120. uniforms.hemisphereLights.needsUpdate = value;
  17121. }
  17122. // Lighting
  17123. function setupShadows( lights ) {
  17124. var lightShadowsLength = 0;
  17125. for ( var i = 0, l = lights.length; i < l; i ++ ) {
  17126. var light = lights[ i ];
  17127. if ( light.castShadow ) {
  17128. _lights.shadows[ lightShadowsLength ++ ] = light;
  17129. }
  17130. }
  17131. _lights.shadows.length = lightShadowsLength;
  17132. }
  17133. function setupLights( lights, camera ) {
  17134. var l, ll, light,
  17135. r = 0, g = 0, b = 0,
  17136. color,
  17137. intensity,
  17138. distance,
  17139. shadowMap,
  17140. viewMatrix = camera.matrixWorldInverse,
  17141. directionalLength = 0,
  17142. pointLength = 0,
  17143. spotLength = 0,
  17144. rectAreaLength = 0,
  17145. hemiLength = 0;
  17146. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  17147. light = lights[ l ];
  17148. color = light.color;
  17149. intensity = light.intensity;
  17150. distance = light.distance;
  17151. shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  17152. if ( light.isAmbientLight ) {
  17153. r += color.r * intensity;
  17154. g += color.g * intensity;
  17155. b += color.b * intensity;
  17156. } else if ( light.isDirectionalLight ) {
  17157. var uniforms = lightCache.get( light );
  17158. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  17159. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  17160. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  17161. uniforms.direction.sub( _vector3 );
  17162. uniforms.direction.transformDirection( viewMatrix );
  17163. uniforms.shadow = light.castShadow;
  17164. if ( light.castShadow ) {
  17165. uniforms.shadowBias = light.shadow.bias;
  17166. uniforms.shadowRadius = light.shadow.radius;
  17167. uniforms.shadowMapSize = light.shadow.mapSize;
  17168. }
  17169. _lights.directionalShadowMap[ directionalLength ] = shadowMap;
  17170. _lights.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  17171. _lights.directional[ directionalLength ++ ] = uniforms;
  17172. } else if ( light.isSpotLight ) {
  17173. var uniforms = lightCache.get( light );
  17174. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  17175. uniforms.position.applyMatrix4( viewMatrix );
  17176. uniforms.color.copy( color ).multiplyScalar( intensity );
  17177. uniforms.distance = distance;
  17178. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  17179. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  17180. uniforms.direction.sub( _vector3 );
  17181. uniforms.direction.transformDirection( viewMatrix );
  17182. uniforms.coneCos = Math.cos( light.angle );
  17183. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  17184. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  17185. uniforms.shadow = light.castShadow;
  17186. if ( light.castShadow ) {
  17187. uniforms.shadowBias = light.shadow.bias;
  17188. uniforms.shadowRadius = light.shadow.radius;
  17189. uniforms.shadowMapSize = light.shadow.mapSize;
  17190. }
  17191. _lights.spotShadowMap[ spotLength ] = shadowMap;
  17192. _lights.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  17193. _lights.spot[ spotLength ++ ] = uniforms;
  17194. } else if ( light.isRectAreaLight ) {
  17195. var uniforms = lightCache.get( light );
  17196. // (a) intensity controls irradiance of entire light
  17197. uniforms.color
  17198. .copy( color )
  17199. .multiplyScalar( intensity / ( light.width * light.height ) );
  17200. // (b) intensity controls the radiance per light area
  17201. // uniforms.color.copy( color ).multiplyScalar( intensity );
  17202. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  17203. uniforms.position.applyMatrix4( viewMatrix );
  17204. // extract local rotation of light to derive width/height half vectors
  17205. _matrix42.identity();
  17206. _matrix4.copy( light.matrixWorld );
  17207. _matrix4.premultiply( viewMatrix );
  17208. _matrix42.extractRotation( _matrix4 );
  17209. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  17210. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  17211. uniforms.halfWidth.applyMatrix4( _matrix42 );
  17212. uniforms.halfHeight.applyMatrix4( _matrix42 );
  17213. // TODO (abelnation): RectAreaLight distance?
  17214. // uniforms.distance = distance;
  17215. _lights.rectArea[ rectAreaLength ++ ] = uniforms;
  17216. } else if ( light.isPointLight ) {
  17217. var uniforms = lightCache.get( light );
  17218. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  17219. uniforms.position.applyMatrix4( viewMatrix );
  17220. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  17221. uniforms.distance = light.distance;
  17222. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  17223. uniforms.shadow = light.castShadow;
  17224. if ( light.castShadow ) {
  17225. uniforms.shadowBias = light.shadow.bias;
  17226. uniforms.shadowRadius = light.shadow.radius;
  17227. uniforms.shadowMapSize = light.shadow.mapSize;
  17228. }
  17229. _lights.pointShadowMap[ pointLength ] = shadowMap;
  17230. if ( _lights.pointShadowMatrix[ pointLength ] === undefined ) {
  17231. _lights.pointShadowMatrix[ pointLength ] = new Matrix4();
  17232. }
  17233. // for point lights we set the shadow matrix to be a translation-only matrix
  17234. // equal to inverse of the light's position
  17235. _vector3.setFromMatrixPosition( light.matrixWorld ).negate();
  17236. _lights.pointShadowMatrix[ pointLength ].identity().setPosition( _vector3 );
  17237. _lights.point[ pointLength ++ ] = uniforms;
  17238. } else if ( light.isHemisphereLight ) {
  17239. var uniforms = lightCache.get( light );
  17240. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  17241. uniforms.direction.transformDirection( viewMatrix );
  17242. uniforms.direction.normalize();
  17243. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  17244. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  17245. _lights.hemi[ hemiLength ++ ] = uniforms;
  17246. }
  17247. }
  17248. _lights.ambient[ 0 ] = r;
  17249. _lights.ambient[ 1 ] = g;
  17250. _lights.ambient[ 2 ] = b;
  17251. _lights.directional.length = directionalLength;
  17252. _lights.spot.length = spotLength;
  17253. _lights.rectArea.length = rectAreaLength;
  17254. _lights.point.length = pointLength;
  17255. _lights.hemi.length = hemiLength;
  17256. // TODO (sam-g-steel) why aren't we using join
  17257. _lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + rectAreaLength + ',' + hemiLength + ',' + _lights.shadows.length;
  17258. }
  17259. // GL state setting
  17260. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  17261. state.setCullFace( cullFace );
  17262. state.setFlipSided( frontFaceDirection === FrontFaceDirectionCW );
  17263. };
  17264. // Textures
  17265. function allocTextureUnit() {
  17266. var textureUnit = _usedTextureUnits;
  17267. if ( textureUnit >= capabilities.maxTextures ) {
  17268. console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  17269. }
  17270. _usedTextureUnits += 1;
  17271. return textureUnit;
  17272. }
  17273. this.allocTextureUnit = allocTextureUnit;
  17274. // this.setTexture2D = setTexture2D;
  17275. this.setTexture2D = ( function() {
  17276. var warned = false;
  17277. // backwards compatibility: peel texture.texture
  17278. return function setTexture2D( texture, slot ) {
  17279. if ( texture && texture.isWebGLRenderTarget ) {
  17280. if ( ! warned ) {
  17281. console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." );
  17282. warned = true;
  17283. }
  17284. texture = texture.texture;
  17285. }
  17286. textures.setTexture2D( texture, slot );
  17287. };
  17288. }() );
  17289. this.setTexture = ( function() {
  17290. var warned = false;
  17291. return function setTexture( texture, slot ) {
  17292. if ( ! warned ) {
  17293. console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." );
  17294. warned = true;
  17295. }
  17296. textures.setTexture2D( texture, slot );
  17297. };
  17298. }() );
  17299. this.setTextureCube = ( function() {
  17300. var warned = false;
  17301. return function setTextureCube( texture, slot ) {
  17302. // backwards compatibility: peel texture.texture
  17303. if ( texture && texture.isWebGLRenderTargetCube ) {
  17304. if ( ! warned ) {
  17305. console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
  17306. warned = true;
  17307. }
  17308. texture = texture.texture;
  17309. }
  17310. // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  17311. // TODO: unify these code paths
  17312. if ( ( texture && texture.isCubeTexture ) ||
  17313. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  17314. // CompressedTexture can have Array in image :/
  17315. // this function alone should take care of cube textures
  17316. textures.setTextureCube( texture, slot );
  17317. } else {
  17318. // assumed: texture property of THREE.WebGLRenderTargetCube
  17319. textures.setTextureCubeDynamic( texture, slot );
  17320. }
  17321. };
  17322. }() );
  17323. this.getCurrentRenderTarget = function() {
  17324. return _currentRenderTarget;
  17325. };
  17326. this.setRenderTarget = function ( renderTarget ) {
  17327. _currentRenderTarget = renderTarget;
  17328. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  17329. textures.setupRenderTarget( renderTarget );
  17330. }
  17331. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  17332. var framebuffer;
  17333. if ( renderTarget ) {
  17334. var renderTargetProperties = properties.get( renderTarget );
  17335. if ( isCube ) {
  17336. framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ];
  17337. } else {
  17338. framebuffer = renderTargetProperties.__webglFramebuffer;
  17339. }
  17340. _currentScissor.copy( renderTarget.scissor );
  17341. _currentScissorTest = renderTarget.scissorTest;
  17342. _currentViewport.copy( renderTarget.viewport );
  17343. } else {
  17344. framebuffer = null;
  17345. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
  17346. _currentScissorTest = _scissorTest;
  17347. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
  17348. }
  17349. if ( _currentFramebuffer !== framebuffer ) {
  17350. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  17351. _currentFramebuffer = framebuffer;
  17352. }
  17353. state.scissor( _currentScissor );
  17354. state.setScissorTest( _currentScissorTest );
  17355. state.viewport( _currentViewport );
  17356. if ( isCube ) {
  17357. var textureProperties = properties.get( renderTarget.texture );
  17358. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel );
  17359. }
  17360. };
  17361. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  17362. if ( ( renderTarget && renderTarget.isWebGLRenderTarget ) === false ) {
  17363. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  17364. return;
  17365. }
  17366. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  17367. if ( framebuffer ) {
  17368. var restore = false;
  17369. if ( framebuffer !== _currentFramebuffer ) {
  17370. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  17371. restore = true;
  17372. }
  17373. try {
  17374. var texture = renderTarget.texture;
  17375. var textureFormat = texture.format;
  17376. var textureType = texture.type;
  17377. if ( textureFormat !== RGBAFormat && paramThreeToGL( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  17378. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  17379. return;
  17380. }
  17381. if ( textureType !== UnsignedByteType && paramThreeToGL( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // IE11, Edge and Chrome Mac < 52 (#9513)
  17382. ! ( textureType === FloatType && ( extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  17383. ! ( textureType === HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
  17384. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  17385. return;
  17386. }
  17387. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  17388. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  17389. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  17390. _gl.readPixels( x, y, width, height, paramThreeToGL( textureFormat ), paramThreeToGL( textureType ), buffer );
  17391. }
  17392. } else {
  17393. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  17394. }
  17395. } finally {
  17396. if ( restore ) {
  17397. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  17398. }
  17399. }
  17400. }
  17401. };
  17402. // Map three.js constants to WebGL constants
  17403. function paramThreeToGL( p ) {
  17404. var extension;
  17405. if ( p === RepeatWrapping ) return _gl.REPEAT;
  17406. if ( p === ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  17407. if ( p === MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  17408. if ( p === NearestFilter ) return _gl.NEAREST;
  17409. if ( p === NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  17410. if ( p === NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  17411. if ( p === LinearFilter ) return _gl.LINEAR;
  17412. if ( p === LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  17413. if ( p === LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  17414. if ( p === UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  17415. if ( p === UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  17416. if ( p === UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  17417. if ( p === UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  17418. if ( p === ByteType ) return _gl.BYTE;
  17419. if ( p === ShortType ) return _gl.SHORT;
  17420. if ( p === UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  17421. if ( p === IntType ) return _gl.INT;
  17422. if ( p === UnsignedIntType ) return _gl.UNSIGNED_INT;
  17423. if ( p === FloatType ) return _gl.FLOAT;
  17424. if ( p === HalfFloatType ) {
  17425. extension = extensions.get( 'OES_texture_half_float' );
  17426. if ( extension !== null ) return extension.HALF_FLOAT_OES;
  17427. }
  17428. if ( p === AlphaFormat ) return _gl.ALPHA;
  17429. if ( p === RGBFormat ) return _gl.RGB;
  17430. if ( p === RGBAFormat ) return _gl.RGBA;
  17431. if ( p === LuminanceFormat ) return _gl.LUMINANCE;
  17432. if ( p === LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  17433. if ( p === DepthFormat ) return _gl.DEPTH_COMPONENT;
  17434. if ( p === DepthStencilFormat ) return _gl.DEPTH_STENCIL;
  17435. if ( p === AddEquation ) return _gl.FUNC_ADD;
  17436. if ( p === SubtractEquation ) return _gl.FUNC_SUBTRACT;
  17437. if ( p === ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  17438. if ( p === ZeroFactor ) return _gl.ZERO;
  17439. if ( p === OneFactor ) return _gl.ONE;
  17440. if ( p === SrcColorFactor ) return _gl.SRC_COLOR;
  17441. if ( p === OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  17442. if ( p === SrcAlphaFactor ) return _gl.SRC_ALPHA;
  17443. if ( p === OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  17444. if ( p === DstAlphaFactor ) return _gl.DST_ALPHA;
  17445. if ( p === OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  17446. if ( p === DstColorFactor ) return _gl.DST_COLOR;
  17447. if ( p === OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  17448. if ( p === SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  17449. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  17450. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  17451. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  17452. if ( extension !== null ) {
  17453. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  17454. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  17455. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  17456. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  17457. }
  17458. }
  17459. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  17460. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  17461. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  17462. if ( extension !== null ) {
  17463. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  17464. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  17465. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  17466. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  17467. }
  17468. }
  17469. if ( p === RGB_ETC1_Format ) {
  17470. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  17471. if ( extension !== null ) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  17472. }
  17473. if ( p === MinEquation || p === MaxEquation ) {
  17474. extension = extensions.get( 'EXT_blend_minmax' );
  17475. if ( extension !== null ) {
  17476. if ( p === MinEquation ) return extension.MIN_EXT;
  17477. if ( p === MaxEquation ) return extension.MAX_EXT;
  17478. }
  17479. }
  17480. if ( p === UnsignedInt248Type ) {
  17481. extension = extensions.get( 'WEBGL_depth_texture' );
  17482. if ( extension !== null ) return extension.UNSIGNED_INT_24_8_WEBGL;
  17483. }
  17484. return 0;
  17485. }
  17486. }
  17487. /**
  17488. * @author mrdoob / http://mrdoob.com/
  17489. * @author alteredq / http://alteredqualia.com/
  17490. */
  17491. function FogExp2 ( color, density ) {
  17492. this.name = '';
  17493. this.color = new Color( color );
  17494. this.density = ( density !== undefined ) ? density : 0.00025;
  17495. }
  17496. FogExp2.prototype.isFogExp2 = true;
  17497. FogExp2.prototype.clone = function () {
  17498. return new FogExp2( this.color.getHex(), this.density );
  17499. };
  17500. FogExp2.prototype.toJSON = function ( meta ) {
  17501. return {
  17502. type: 'FogExp2',
  17503. color: this.color.getHex(),
  17504. density: this.density
  17505. };
  17506. };
  17507. /**
  17508. * @author mrdoob / http://mrdoob.com/
  17509. * @author alteredq / http://alteredqualia.com/
  17510. */
  17511. function Fog ( color, near, far ) {
  17512. this.name = '';
  17513. this.color = new Color( color );
  17514. this.near = ( near !== undefined ) ? near : 1;
  17515. this.far = ( far !== undefined ) ? far : 1000;
  17516. }
  17517. Fog.prototype.isFog = true;
  17518. Fog.prototype.clone = function () {
  17519. return new Fog( this.color.getHex(), this.near, this.far );
  17520. };
  17521. Fog.prototype.toJSON = function ( meta ) {
  17522. return {
  17523. type: 'Fog',
  17524. color: this.color.getHex(),
  17525. near: this.near,
  17526. far: this.far
  17527. };
  17528. };
  17529. /**
  17530. * @author mrdoob / http://mrdoob.com/
  17531. */
  17532. function Scene () {
  17533. Object3D.call( this );
  17534. this.type = 'Scene';
  17535. this.background = null;
  17536. this.fog = null;
  17537. this.overrideMaterial = null;
  17538. this.autoUpdate = true; // checked by the renderer
  17539. }
  17540. Scene.prototype = Object.create( Object3D.prototype );
  17541. Scene.prototype.constructor = Scene;
  17542. Scene.prototype.copy = function ( source, recursive ) {
  17543. Object3D.prototype.copy.call( this, source, recursive );
  17544. if ( source.background !== null ) this.background = source.background.clone();
  17545. if ( source.fog !== null ) this.fog = source.fog.clone();
  17546. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  17547. this.autoUpdate = source.autoUpdate;
  17548. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17549. return this;
  17550. };
  17551. Scene.prototype.toJSON = function ( meta ) {
  17552. var data = Object3D.prototype.toJSON.call( this, meta );
  17553. if ( this.background !== null ) data.object.background = this.background.toJSON( meta );
  17554. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  17555. return data;
  17556. };
  17557. /**
  17558. * @author mikael emtinger / http://gomo.se/
  17559. * @author alteredq / http://alteredqualia.com/
  17560. */
  17561. function LensFlare( texture, size, distance, blending, color ) {
  17562. Object3D.call( this );
  17563. this.lensFlares = [];
  17564. this.positionScreen = new Vector3();
  17565. this.customUpdateCallback = undefined;
  17566. if ( texture !== undefined ) {
  17567. this.add( texture, size, distance, blending, color );
  17568. }
  17569. }
  17570. LensFlare.prototype = Object.assign( Object.create( Object3D.prototype ), {
  17571. constructor: LensFlare,
  17572. isLensFlare: true,
  17573. copy: function ( source ) {
  17574. Object3D.prototype.copy.call( this, source );
  17575. this.positionScreen.copy( source.positionScreen );
  17576. this.customUpdateCallback = source.customUpdateCallback;
  17577. for ( var i = 0, l = source.lensFlares.length; i < l; i ++ ) {
  17578. this.lensFlares.push( source.lensFlares[ i ] );
  17579. }
  17580. return this;
  17581. },
  17582. add: function ( texture, size, distance, blending, color, opacity ) {
  17583. if ( size === undefined ) size = - 1;
  17584. if ( distance === undefined ) distance = 0;
  17585. if ( opacity === undefined ) opacity = 1;
  17586. if ( color === undefined ) color = new Color( 0xffffff );
  17587. if ( blending === undefined ) blending = NormalBlending;
  17588. distance = Math.min( distance, Math.max( 0, distance ) );
  17589. this.lensFlares.push( {
  17590. texture: texture, // THREE.Texture
  17591. size: size, // size in pixels (-1 = use texture.width)
  17592. distance: distance, // distance (0-1) from light source (0=at light source)
  17593. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is in front z = 1 is back
  17594. scale: 1, // scale
  17595. rotation: 0, // rotation
  17596. opacity: opacity, // opacity
  17597. color: color, // color
  17598. blending: blending // blending
  17599. } );
  17600. },
  17601. /*
  17602. * Update lens flares update positions on all flares based on the screen position
  17603. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  17604. */
  17605. updateLensFlares: function () {
  17606. var f, fl = this.lensFlares.length;
  17607. var flare;
  17608. var vecX = - this.positionScreen.x * 2;
  17609. var vecY = - this.positionScreen.y * 2;
  17610. for ( f = 0; f < fl; f ++ ) {
  17611. flare = this.lensFlares[ f ];
  17612. flare.x = this.positionScreen.x + vecX * flare.distance;
  17613. flare.y = this.positionScreen.y + vecY * flare.distance;
  17614. flare.wantedRotation = flare.x * Math.PI * 0.25;
  17615. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  17616. }
  17617. }
  17618. } );
  17619. /**
  17620. * @author alteredq / http://alteredqualia.com/
  17621. *
  17622. * parameters = {
  17623. * color: <hex>,
  17624. * opacity: <float>,
  17625. * map: new THREE.Texture( <Image> ),
  17626. *
  17627. * uvOffset: new THREE.Vector2(),
  17628. * uvScale: new THREE.Vector2()
  17629. * }
  17630. */
  17631. function SpriteMaterial( parameters ) {
  17632. Material.call( this );
  17633. this.type = 'SpriteMaterial';
  17634. this.color = new Color( 0xffffff );
  17635. this.map = null;
  17636. this.rotation = 0;
  17637. this.fog = false;
  17638. this.lights = false;
  17639. this.setValues( parameters );
  17640. }
  17641. SpriteMaterial.prototype = Object.create( Material.prototype );
  17642. SpriteMaterial.prototype.constructor = SpriteMaterial;
  17643. SpriteMaterial.prototype.copy = function ( source ) {
  17644. Material.prototype.copy.call( this, source );
  17645. this.color.copy( source.color );
  17646. this.map = source.map;
  17647. this.rotation = source.rotation;
  17648. return this;
  17649. };
  17650. /**
  17651. * @author mikael emtinger / http://gomo.se/
  17652. * @author alteredq / http://alteredqualia.com/
  17653. */
  17654. function Sprite( material ) {
  17655. Object3D.call( this );
  17656. this.type = 'Sprite';
  17657. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  17658. }
  17659. Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), {
  17660. constructor: Sprite,
  17661. isSprite: true,
  17662. raycast: ( function () {
  17663. var matrixPosition = new Vector3();
  17664. return function raycast( raycaster, intersects ) {
  17665. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  17666. var distanceSq = raycaster.ray.distanceSqToPoint( matrixPosition );
  17667. var guessSizeSq = this.scale.x * this.scale.y / 4;
  17668. if ( distanceSq > guessSizeSq ) {
  17669. return;
  17670. }
  17671. intersects.push( {
  17672. distance: Math.sqrt( distanceSq ),
  17673. point: this.position,
  17674. face: null,
  17675. object: this
  17676. } );
  17677. };
  17678. }() ),
  17679. clone: function () {
  17680. return new this.constructor( this.material ).copy( this );
  17681. }
  17682. } );
  17683. /**
  17684. * @author mikael emtinger / http://gomo.se/
  17685. * @author alteredq / http://alteredqualia.com/
  17686. * @author mrdoob / http://mrdoob.com/
  17687. */
  17688. function LOD() {
  17689. Object3D.call( this );
  17690. this.type = 'LOD';
  17691. Object.defineProperties( this, {
  17692. levels: {
  17693. enumerable: true,
  17694. value: []
  17695. }
  17696. } );
  17697. }
  17698. LOD.prototype = Object.assign( Object.create( Object3D.prototype ), {
  17699. constructor: LOD,
  17700. copy: function ( source ) {
  17701. Object3D.prototype.copy.call( this, source, false );
  17702. var levels = source.levels;
  17703. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  17704. var level = levels[ i ];
  17705. this.addLevel( level.object.clone(), level.distance );
  17706. }
  17707. return this;
  17708. },
  17709. addLevel: function ( object, distance ) {
  17710. if ( distance === undefined ) distance = 0;
  17711. distance = Math.abs( distance );
  17712. var levels = this.levels;
  17713. for ( var l = 0; l < levels.length; l ++ ) {
  17714. if ( distance < levels[ l ].distance ) {
  17715. break;
  17716. }
  17717. }
  17718. levels.splice( l, 0, { distance: distance, object: object } );
  17719. this.add( object );
  17720. },
  17721. getObjectForDistance: function ( distance ) {
  17722. var levels = this.levels;
  17723. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  17724. if ( distance < levels[ i ].distance ) {
  17725. break;
  17726. }
  17727. }
  17728. return levels[ i - 1 ].object;
  17729. },
  17730. raycast: ( function () {
  17731. var matrixPosition = new Vector3();
  17732. return function raycast( raycaster, intersects ) {
  17733. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  17734. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  17735. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  17736. };
  17737. }() ),
  17738. update: function () {
  17739. var v1 = new Vector3();
  17740. var v2 = new Vector3();
  17741. return function update( camera ) {
  17742. var levels = this.levels;
  17743. if ( levels.length > 1 ) {
  17744. v1.setFromMatrixPosition( camera.matrixWorld );
  17745. v2.setFromMatrixPosition( this.matrixWorld );
  17746. var distance = v1.distanceTo( v2 );
  17747. levels[ 0 ].object.visible = true;
  17748. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  17749. if ( distance >= levels[ i ].distance ) {
  17750. levels[ i - 1 ].object.visible = false;
  17751. levels[ i ].object.visible = true;
  17752. } else {
  17753. break;
  17754. }
  17755. }
  17756. for ( ; i < l; i ++ ) {
  17757. levels[ i ].object.visible = false;
  17758. }
  17759. }
  17760. };
  17761. }(),
  17762. toJSON: function ( meta ) {
  17763. var data = Object3D.prototype.toJSON.call( this, meta );
  17764. data.object.levels = [];
  17765. var levels = this.levels;
  17766. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  17767. var level = levels[ i ];
  17768. data.object.levels.push( {
  17769. object: level.object.uuid,
  17770. distance: level.distance
  17771. } );
  17772. }
  17773. return data;
  17774. }
  17775. } );
  17776. /**
  17777. * @author mikael emtinger / http://gomo.se/
  17778. * @author alteredq / http://alteredqualia.com/
  17779. * @author michael guerrero / http://realitymeltdown.com
  17780. * @author ikerr / http://verold.com
  17781. */
  17782. function Skeleton( bones, boneInverses, useVertexTexture ) {
  17783. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  17784. this.identityMatrix = new Matrix4();
  17785. // copy the bone array
  17786. bones = bones || [];
  17787. this.bones = bones.slice( 0 );
  17788. // create a bone texture or an array of floats
  17789. if ( this.useVertexTexture ) {
  17790. // layout (1 matrix = 4 pixels)
  17791. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  17792. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  17793. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  17794. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  17795. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  17796. var size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  17797. size = _Math.nextPowerOfTwo( Math.ceil( size ) );
  17798. size = Math.max( size, 4 );
  17799. this.boneTextureWidth = size;
  17800. this.boneTextureHeight = size;
  17801. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  17802. this.boneTexture = new DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, RGBAFormat, FloatType );
  17803. } else {
  17804. this.boneMatrices = new Float32Array( 16 * this.bones.length );
  17805. }
  17806. // use the supplied bone inverses or calculate the inverses
  17807. if ( boneInverses === undefined ) {
  17808. this.calculateInverses();
  17809. } else {
  17810. if ( this.bones.length === boneInverses.length ) {
  17811. this.boneInverses = boneInverses.slice( 0 );
  17812. } else {
  17813. console.warn( 'THREE.Skeleton bonInverses is the wrong length.' );
  17814. this.boneInverses = [];
  17815. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  17816. this.boneInverses.push( new Matrix4() );
  17817. }
  17818. }
  17819. }
  17820. }
  17821. Object.assign( Skeleton.prototype, {
  17822. calculateInverses: function () {
  17823. this.boneInverses = [];
  17824. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  17825. var inverse = new Matrix4();
  17826. if ( this.bones[ b ] ) {
  17827. inverse.getInverse( this.bones[ b ].matrixWorld );
  17828. }
  17829. this.boneInverses.push( inverse );
  17830. }
  17831. },
  17832. pose: function () {
  17833. var bone;
  17834. // recover the bind-time world matrices
  17835. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  17836. bone = this.bones[ b ];
  17837. if ( bone ) {
  17838. bone.matrixWorld.getInverse( this.boneInverses[ b ] );
  17839. }
  17840. }
  17841. // compute the local matrices, positions, rotations and scales
  17842. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  17843. bone = this.bones[ b ];
  17844. if ( bone ) {
  17845. if ( bone.parent && bone.parent.isBone ) {
  17846. bone.matrix.getInverse( bone.parent.matrixWorld );
  17847. bone.matrix.multiply( bone.matrixWorld );
  17848. } else {
  17849. bone.matrix.copy( bone.matrixWorld );
  17850. }
  17851. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  17852. }
  17853. }
  17854. },
  17855. update: ( function () {
  17856. var offsetMatrix = new Matrix4();
  17857. return function update() {
  17858. // flatten bone matrices to array
  17859. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  17860. // compute the offset between the current and the original transform
  17861. var matrix = this.bones[ b ] ? this.bones[ b ].matrixWorld : this.identityMatrix;
  17862. offsetMatrix.multiplyMatrices( matrix, this.boneInverses[ b ] );
  17863. offsetMatrix.toArray( this.boneMatrices, b * 16 );
  17864. }
  17865. if ( this.useVertexTexture ) {
  17866. this.boneTexture.needsUpdate = true;
  17867. }
  17868. };
  17869. } )(),
  17870. clone: function () {
  17871. return new Skeleton( this.bones, this.boneInverses, this.useVertexTexture );
  17872. }
  17873. } );
  17874. /**
  17875. * @author mikael emtinger / http://gomo.se/
  17876. * @author alteredq / http://alteredqualia.com/
  17877. * @author ikerr / http://verold.com
  17878. */
  17879. function Bone() {
  17880. Object3D.call( this );
  17881. this.type = 'Bone';
  17882. }
  17883. Bone.prototype = Object.assign( Object.create( Object3D.prototype ), {
  17884. constructor: Bone,
  17885. isBone: true
  17886. } );
  17887. /**
  17888. * @author mikael emtinger / http://gomo.se/
  17889. * @author alteredq / http://alteredqualia.com/
  17890. * @author ikerr / http://verold.com
  17891. */
  17892. function SkinnedMesh( geometry, material, useVertexTexture ) {
  17893. Mesh.call( this, geometry, material );
  17894. this.type = 'SkinnedMesh';
  17895. this.bindMode = "attached";
  17896. this.bindMatrix = new Matrix4();
  17897. this.bindMatrixInverse = new Matrix4();
  17898. // init bones
  17899. // TODO: remove bone creation as there is no reason (other than
  17900. // convenience) for THREE.SkinnedMesh to do this.
  17901. var bones = [];
  17902. if ( this.geometry && this.geometry.bones !== undefined ) {
  17903. var bone, gbone;
  17904. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  17905. gbone = this.geometry.bones[ b ];
  17906. bone = new Bone();
  17907. bones.push( bone );
  17908. bone.name = gbone.name;
  17909. bone.position.fromArray( gbone.pos );
  17910. bone.quaternion.fromArray( gbone.rotq );
  17911. if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl );
  17912. }
  17913. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  17914. gbone = this.geometry.bones[ b ];
  17915. if ( gbone.parent !== - 1 && gbone.parent !== null &&
  17916. bones[ gbone.parent ] !== undefined ) {
  17917. bones[ gbone.parent ].add( bones[ b ] );
  17918. } else {
  17919. this.add( bones[ b ] );
  17920. }
  17921. }
  17922. }
  17923. this.normalizeSkinWeights();
  17924. this.updateMatrixWorld( true );
  17925. this.bind( new Skeleton( bones, undefined, useVertexTexture ), this.matrixWorld );
  17926. }
  17927. SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  17928. constructor: SkinnedMesh,
  17929. isSkinnedMesh: true,
  17930. bind: function( skeleton, bindMatrix ) {
  17931. this.skeleton = skeleton;
  17932. if ( bindMatrix === undefined ) {
  17933. this.updateMatrixWorld( true );
  17934. this.skeleton.calculateInverses();
  17935. bindMatrix = this.matrixWorld;
  17936. }
  17937. this.bindMatrix.copy( bindMatrix );
  17938. this.bindMatrixInverse.getInverse( bindMatrix );
  17939. },
  17940. pose: function () {
  17941. this.skeleton.pose();
  17942. },
  17943. normalizeSkinWeights: function () {
  17944. if ( this.geometry && this.geometry.isGeometry ) {
  17945. for ( var i = 0; i < this.geometry.skinWeights.length; i ++ ) {
  17946. var sw = this.geometry.skinWeights[ i ];
  17947. var scale = 1.0 / sw.lengthManhattan();
  17948. if ( scale !== Infinity ) {
  17949. sw.multiplyScalar( scale );
  17950. } else {
  17951. sw.set( 1, 0, 0, 0 ); // do something reasonable
  17952. }
  17953. }
  17954. } else if ( this.geometry && this.geometry.isBufferGeometry ) {
  17955. var vec = new Vector4();
  17956. var skinWeight = this.geometry.attributes.skinWeight;
  17957. for ( var i = 0; i < skinWeight.count; i ++ ) {
  17958. vec.x = skinWeight.getX( i );
  17959. vec.y = skinWeight.getY( i );
  17960. vec.z = skinWeight.getZ( i );
  17961. vec.w = skinWeight.getW( i );
  17962. var scale = 1.0 / vec.lengthManhattan();
  17963. if ( scale !== Infinity ) {
  17964. vec.multiplyScalar( scale );
  17965. } else {
  17966. vec.set( 1, 0, 0, 0 ); // do something reasonable
  17967. }
  17968. skinWeight.setXYZW( i, vec.x, vec.y, vec.z, vec.w );
  17969. }
  17970. }
  17971. },
  17972. updateMatrixWorld: function( force ) {
  17973. Mesh.prototype.updateMatrixWorld.call( this, true );
  17974. if ( this.bindMode === "attached" ) {
  17975. this.bindMatrixInverse.getInverse( this.matrixWorld );
  17976. } else if ( this.bindMode === "detached" ) {
  17977. this.bindMatrixInverse.getInverse( this.bindMatrix );
  17978. } else {
  17979. console.warn( 'THREE.SkinnedMesh unrecognized bindMode: ' + this.bindMode );
  17980. }
  17981. },
  17982. clone: function() {
  17983. return new this.constructor( this.geometry, this.material, this.skeleton.useVertexTexture ).copy( this );
  17984. }
  17985. } );
  17986. /**
  17987. * @author mrdoob / http://mrdoob.com/
  17988. * @author alteredq / http://alteredqualia.com/
  17989. *
  17990. * parameters = {
  17991. * color: <hex>,
  17992. * opacity: <float>,
  17993. *
  17994. * linewidth: <float>,
  17995. * linecap: "round",
  17996. * linejoin: "round"
  17997. * }
  17998. */
  17999. function LineBasicMaterial( parameters ) {
  18000. Material.call( this );
  18001. this.type = 'LineBasicMaterial';
  18002. this.color = new Color( 0xffffff );
  18003. this.linewidth = 1;
  18004. this.linecap = 'round';
  18005. this.linejoin = 'round';
  18006. this.lights = false;
  18007. this.setValues( parameters );
  18008. }
  18009. LineBasicMaterial.prototype = Object.create( Material.prototype );
  18010. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  18011. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  18012. LineBasicMaterial.prototype.copy = function ( source ) {
  18013. Material.prototype.copy.call( this, source );
  18014. this.color.copy( source.color );
  18015. this.linewidth = source.linewidth;
  18016. this.linecap = source.linecap;
  18017. this.linejoin = source.linejoin;
  18018. return this;
  18019. };
  18020. /**
  18021. * @author mrdoob / http://mrdoob.com/
  18022. */
  18023. function Line( geometry, material, mode ) {
  18024. if ( mode === 1 ) {
  18025. console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' );
  18026. return new LineSegments( geometry, material );
  18027. }
  18028. Object3D.call( this );
  18029. this.type = 'Line';
  18030. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  18031. this.material = material !== undefined ? material : new LineBasicMaterial( { color: Math.random() * 0xffffff } );
  18032. }
  18033. Line.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18034. constructor: Line,
  18035. isLine: true,
  18036. raycast: ( function () {
  18037. var inverseMatrix = new Matrix4();
  18038. var ray = new Ray();
  18039. var sphere = new Sphere();
  18040. return function raycast( raycaster, intersects ) {
  18041. var precision = raycaster.linePrecision;
  18042. var precisionSq = precision * precision;
  18043. var geometry = this.geometry;
  18044. var matrixWorld = this.matrixWorld;
  18045. // Checking boundingSphere distance to ray
  18046. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18047. sphere.copy( geometry.boundingSphere );
  18048. sphere.applyMatrix4( matrixWorld );
  18049. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  18050. //
  18051. inverseMatrix.getInverse( matrixWorld );
  18052. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  18053. var vStart = new Vector3();
  18054. var vEnd = new Vector3();
  18055. var interSegment = new Vector3();
  18056. var interRay = new Vector3();
  18057. var step = (this && this.isLineSegments) ? 2 : 1;
  18058. if ( geometry.isBufferGeometry ) {
  18059. var index = geometry.index;
  18060. var attributes = geometry.attributes;
  18061. var positions = attributes.position.array;
  18062. if ( index !== null ) {
  18063. var indices = index.array;
  18064. for ( var i = 0, l = indices.length - 1; i < l; i += step ) {
  18065. var a = indices[ i ];
  18066. var b = indices[ i + 1 ];
  18067. vStart.fromArray( positions, a * 3 );
  18068. vEnd.fromArray( positions, b * 3 );
  18069. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  18070. if ( distSq > precisionSq ) continue;
  18071. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18072. var distance = raycaster.ray.origin.distanceTo( interRay );
  18073. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18074. intersects.push( {
  18075. distance: distance,
  18076. // What do we want? intersection point on the ray or on the segment??
  18077. // point: raycaster.ray.at( distance ),
  18078. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18079. index: i,
  18080. face: null,
  18081. faceIndex: null,
  18082. object: this
  18083. } );
  18084. }
  18085. } else {
  18086. for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) {
  18087. vStart.fromArray( positions, 3 * i );
  18088. vEnd.fromArray( positions, 3 * i + 3 );
  18089. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  18090. if ( distSq > precisionSq ) continue;
  18091. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18092. var distance = raycaster.ray.origin.distanceTo( interRay );
  18093. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18094. intersects.push( {
  18095. distance: distance,
  18096. // What do we want? intersection point on the ray or on the segment??
  18097. // point: raycaster.ray.at( distance ),
  18098. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18099. index: i,
  18100. face: null,
  18101. faceIndex: null,
  18102. object: this
  18103. } );
  18104. }
  18105. }
  18106. } else if ( geometry.isGeometry ) {
  18107. var vertices = geometry.vertices;
  18108. var nbVertices = vertices.length;
  18109. for ( var i = 0; i < nbVertices - 1; i += step ) {
  18110. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  18111. if ( distSq > precisionSq ) continue;
  18112. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18113. var distance = raycaster.ray.origin.distanceTo( interRay );
  18114. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18115. intersects.push( {
  18116. distance: distance,
  18117. // What do we want? intersection point on the ray or on the segment??
  18118. // point: raycaster.ray.at( distance ),
  18119. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18120. index: i,
  18121. face: null,
  18122. faceIndex: null,
  18123. object: this
  18124. } );
  18125. }
  18126. }
  18127. };
  18128. }() ),
  18129. clone: function () {
  18130. return new this.constructor( this.geometry, this.material ).copy( this );
  18131. }
  18132. } );
  18133. /**
  18134. * @author mrdoob / http://mrdoob.com/
  18135. */
  18136. function LineSegments( geometry, material ) {
  18137. Line.call( this, geometry, material );
  18138. this.type = 'LineSegments';
  18139. }
  18140. LineSegments.prototype = Object.assign( Object.create( Line.prototype ), {
  18141. constructor: LineSegments,
  18142. isLineSegments: true
  18143. } );
  18144. /**
  18145. * @author mrdoob / http://mrdoob.com/
  18146. * @author alteredq / http://alteredqualia.com/
  18147. *
  18148. * parameters = {
  18149. * color: <hex>,
  18150. * opacity: <float>,
  18151. * map: new THREE.Texture( <Image> ),
  18152. *
  18153. * size: <float>,
  18154. * sizeAttenuation: <bool>
  18155. * }
  18156. */
  18157. function PointsMaterial( parameters ) {
  18158. Material.call( this );
  18159. this.type = 'PointsMaterial';
  18160. this.color = new Color( 0xffffff );
  18161. this.map = null;
  18162. this.size = 1;
  18163. this.sizeAttenuation = true;
  18164. this.lights = false;
  18165. this.setValues( parameters );
  18166. }
  18167. PointsMaterial.prototype = Object.create( Material.prototype );
  18168. PointsMaterial.prototype.constructor = PointsMaterial;
  18169. PointsMaterial.prototype.isPointsMaterial = true;
  18170. PointsMaterial.prototype.copy = function ( source ) {
  18171. Material.prototype.copy.call( this, source );
  18172. this.color.copy( source.color );
  18173. this.map = source.map;
  18174. this.size = source.size;
  18175. this.sizeAttenuation = source.sizeAttenuation;
  18176. return this;
  18177. };
  18178. /**
  18179. * @author alteredq / http://alteredqualia.com/
  18180. */
  18181. function Points( geometry, material ) {
  18182. Object3D.call( this );
  18183. this.type = 'Points';
  18184. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  18185. this.material = material !== undefined ? material : new PointsMaterial( { color: Math.random() * 0xffffff } );
  18186. }
  18187. Points.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18188. constructor: Points,
  18189. isPoints: true,
  18190. raycast: ( function () {
  18191. var inverseMatrix = new Matrix4();
  18192. var ray = new Ray();
  18193. var sphere = new Sphere();
  18194. return function raycast( raycaster, intersects ) {
  18195. var object = this;
  18196. var geometry = this.geometry;
  18197. var matrixWorld = this.matrixWorld;
  18198. var threshold = raycaster.params.Points.threshold;
  18199. // Checking boundingSphere distance to ray
  18200. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18201. sphere.copy( geometry.boundingSphere );
  18202. sphere.applyMatrix4( matrixWorld );
  18203. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  18204. //
  18205. inverseMatrix.getInverse( matrixWorld );
  18206. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  18207. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  18208. var localThresholdSq = localThreshold * localThreshold;
  18209. var position = new Vector3();
  18210. function testPoint( point, index ) {
  18211. var rayPointDistanceSq = ray.distanceSqToPoint( point );
  18212. if ( rayPointDistanceSq < localThresholdSq ) {
  18213. var intersectPoint = ray.closestPointToPoint( point );
  18214. intersectPoint.applyMatrix4( matrixWorld );
  18215. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  18216. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18217. intersects.push( {
  18218. distance: distance,
  18219. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  18220. point: intersectPoint.clone(),
  18221. index: index,
  18222. face: null,
  18223. object: object
  18224. } );
  18225. }
  18226. }
  18227. if ( geometry.isBufferGeometry ) {
  18228. var index = geometry.index;
  18229. var attributes = geometry.attributes;
  18230. var positions = attributes.position.array;
  18231. if ( index !== null ) {
  18232. var indices = index.array;
  18233. for ( var i = 0, il = indices.length; i < il; i ++ ) {
  18234. var a = indices[ i ];
  18235. position.fromArray( positions, a * 3 );
  18236. testPoint( position, a );
  18237. }
  18238. } else {
  18239. for ( var i = 0, l = positions.length / 3; i < l; i ++ ) {
  18240. position.fromArray( positions, i * 3 );
  18241. testPoint( position, i );
  18242. }
  18243. }
  18244. } else {
  18245. var vertices = geometry.vertices;
  18246. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  18247. testPoint( vertices[ i ], i );
  18248. }
  18249. }
  18250. };
  18251. }() ),
  18252. clone: function () {
  18253. return new this.constructor( this.geometry, this.material ).copy( this );
  18254. }
  18255. } );
  18256. /**
  18257. * @author mrdoob / http://mrdoob.com/
  18258. */
  18259. function Group() {
  18260. Object3D.call( this );
  18261. this.type = 'Group';
  18262. }
  18263. Group.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18264. constructor: Group
  18265. } );
  18266. /**
  18267. * @author mrdoob / http://mrdoob.com/
  18268. */
  18269. function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  18270. Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  18271. this.generateMipmaps = false;
  18272. var scope = this;
  18273. function update() {
  18274. requestAnimationFrame( update );
  18275. if ( video.readyState >= video.HAVE_CURRENT_DATA ) {
  18276. scope.needsUpdate = true;
  18277. }
  18278. }
  18279. update();
  18280. }
  18281. VideoTexture.prototype = Object.create( Texture.prototype );
  18282. VideoTexture.prototype.constructor = VideoTexture;
  18283. /**
  18284. * @author alteredq / http://alteredqualia.com/
  18285. */
  18286. function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  18287. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  18288. this.image = { width: width, height: height };
  18289. this.mipmaps = mipmaps;
  18290. // no flipping for cube textures
  18291. // (also flipping doesn't work for compressed textures )
  18292. this.flipY = false;
  18293. // can't generate mipmaps for compressed textures
  18294. // mips must be embedded in DDS files
  18295. this.generateMipmaps = false;
  18296. }
  18297. CompressedTexture.prototype = Object.create( Texture.prototype );
  18298. CompressedTexture.prototype.constructor = CompressedTexture;
  18299. CompressedTexture.prototype.isCompressedTexture = true;
  18300. /**
  18301. * @author mrdoob / http://mrdoob.com/
  18302. */
  18303. function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  18304. Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  18305. this.needsUpdate = true;
  18306. }
  18307. CanvasTexture.prototype = Object.create( Texture.prototype );
  18308. CanvasTexture.prototype.constructor = CanvasTexture;
  18309. /**
  18310. * @author Matt DesLauriers / @mattdesl
  18311. * @author atix / arthursilber.de
  18312. */
  18313. function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  18314. format = format !== undefined ? format : DepthFormat;
  18315. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  18316. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' )
  18317. }
  18318. if ( type === undefined && format === DepthFormat ) type = UnsignedShortType;
  18319. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  18320. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  18321. this.image = { width: width, height: height };
  18322. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  18323. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  18324. this.flipY = false;
  18325. this.generateMipmaps = false;
  18326. }
  18327. DepthTexture.prototype = Object.create( Texture.prototype );
  18328. DepthTexture.prototype.constructor = DepthTexture;
  18329. DepthTexture.prototype.isDepthTexture = true;
  18330. /**
  18331. * @author mrdoob / http://mrdoob.com/
  18332. * @author Mugen87 / https://github.com/Mugen87
  18333. */
  18334. function WireframeGeometry( geometry ) {
  18335. BufferGeometry.call( this );
  18336. this.type = 'WireframeGeometry';
  18337. // buffer
  18338. var vertices = [];
  18339. // helper variables
  18340. var i, j, l, o, ol;
  18341. var edge = [ 0, 0 ], edges = {}, e;
  18342. var key, keys = [ 'a', 'b', 'c' ];
  18343. var vertex;
  18344. // different logic for Geometry and BufferGeometry
  18345. if ( geometry && geometry.isGeometry ) {
  18346. // create a data structure that contains all edges without duplicates
  18347. var faces = geometry.faces;
  18348. for ( i = 0, l = faces.length; i < l; i ++ ) {
  18349. var face = faces[ i ];
  18350. for ( j = 0; j < 3; j ++ ) {
  18351. edge[ 0 ] = face[ keys[ j ] ];
  18352. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  18353. edge.sort( sortFunction ); // sorting prevents duplicates
  18354. key = edge.toString();
  18355. if ( edges[ key ] === undefined ) {
  18356. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  18357. }
  18358. }
  18359. }
  18360. // generate vertices
  18361. for ( key in edges ) {
  18362. e = edges[ key ];
  18363. vertex = geometry.vertices[ e.index1 ];
  18364. vertices.push( vertex.x, vertex.y, vertex.z );
  18365. vertex = geometry.vertices[ e.index2 ];
  18366. vertices.push( vertex.x, vertex.y, vertex.z );
  18367. }
  18368. } else if ( geometry && geometry.isBufferGeometry ) {
  18369. var position, indices, groups;
  18370. var group, start, count;
  18371. var index1, index2;
  18372. vertex = new Vector3();
  18373. if ( geometry.index !== null ) {
  18374. // indexed BufferGeometry
  18375. position = geometry.attributes.position;
  18376. indices = geometry.index;
  18377. groups = geometry.groups;
  18378. if ( groups.length === 0 ) {
  18379. geometry.addGroup( 0, indices.count );
  18380. }
  18381. // create a data structure that contains all eges without duplicates
  18382. for ( o = 0, ol = groups.length; o < ol; ++ o ) {
  18383. group = groups[ o ];
  18384. start = group.start;
  18385. count = group.count;
  18386. for ( i = start, l = ( start + count ); i < l; i += 3 ) {
  18387. for ( j = 0; j < 3; j ++ ) {
  18388. edge[ 0 ] = indices.getX( i + j );
  18389. edge[ 1 ] = indices.getX( i + ( j + 1 ) % 3 );
  18390. edge.sort( sortFunction ); // sorting prevents duplicates
  18391. key = edge.toString();
  18392. if ( edges[ key ] === undefined ) {
  18393. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  18394. }
  18395. }
  18396. }
  18397. }
  18398. // generate vertices
  18399. for ( key in edges ) {
  18400. e = edges[ key ];
  18401. vertex.fromBufferAttribute( position, e.index1 );
  18402. vertices.push( vertex.x, vertex.y, vertex.z );
  18403. vertex.fromBufferAttribute( position, e.index2 );
  18404. vertices.push( vertex.x, vertex.y, vertex.z );
  18405. }
  18406. } else {
  18407. // non-indexed BufferGeometry
  18408. position = geometry.attributes.position;
  18409. for ( i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  18410. for ( j = 0; j < 3; j ++ ) {
  18411. // three edges per triangle, an edge is represented as (index1, index2)
  18412. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  18413. index1 = 3 * i + j;
  18414. vertex.fromBufferAttribute( position, index1 );
  18415. vertices.push( vertex.x, vertex.y, vertex.z );
  18416. index2 = 3 * i + ( ( j + 1 ) % 3 );
  18417. vertex.fromBufferAttribute( position, index2 );
  18418. vertices.push( vertex.x, vertex.y, vertex.z );
  18419. }
  18420. }
  18421. }
  18422. }
  18423. // build geometry
  18424. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18425. // custom array sort function
  18426. function sortFunction( a, b ) {
  18427. return a - b;
  18428. }
  18429. }
  18430. WireframeGeometry.prototype = Object.create( BufferGeometry.prototype );
  18431. WireframeGeometry.prototype.constructor = WireframeGeometry;
  18432. /**
  18433. * @author zz85 / https://github.com/zz85
  18434. *
  18435. * Parametric Surfaces Geometry
  18436. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  18437. */
  18438. function ParametricGeometry( func, slices, stacks ) {
  18439. Geometry.call( this );
  18440. this.type = 'ParametricGeometry';
  18441. this.parameters = {
  18442. func: func,
  18443. slices: slices,
  18444. stacks: stacks
  18445. };
  18446. this.fromBufferGeometry( new ParametricBufferGeometry( func, slices, stacks ) );
  18447. this.mergeVertices();
  18448. }
  18449. ParametricGeometry.prototype = Object.create( Geometry.prototype );
  18450. ParametricGeometry.prototype.constructor = ParametricGeometry;
  18451. /**
  18452. * @author Mugen87 / https://github.com/Mugen87
  18453. *
  18454. * Parametric Surfaces Geometry
  18455. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  18456. */
  18457. function ParametricBufferGeometry( func, slices, stacks ) {
  18458. BufferGeometry.call( this );
  18459. this.type = 'ParametricBufferGeometry';
  18460. this.parameters = {
  18461. func: func,
  18462. slices: slices,
  18463. stacks: stacks
  18464. };
  18465. // buffers
  18466. var indices = [];
  18467. var vertices = [];
  18468. var uvs = [];
  18469. var i, j;
  18470. // generate vertices and uvs
  18471. var sliceCount = slices + 1;
  18472. for ( i = 0; i <= stacks; i ++ ) {
  18473. var v = i / stacks;
  18474. for ( j = 0; j <= slices; j ++ ) {
  18475. var u = j / slices;
  18476. var p = func( u, v );
  18477. vertices.push( p.x, p.y, p.z );
  18478. uvs.push( u, v );
  18479. }
  18480. }
  18481. // generate indices
  18482. for ( i = 0; i < stacks; i ++ ) {
  18483. for ( j = 0; j < slices; j ++ ) {
  18484. var a = i * sliceCount + j;
  18485. var b = i * sliceCount + j + 1;
  18486. var c = ( i + 1 ) * sliceCount + j + 1;
  18487. var d = ( i + 1 ) * sliceCount + j;
  18488. // faces one and two
  18489. indices.push( a, b, d );
  18490. indices.push( b, c, d );
  18491. }
  18492. }
  18493. // build geometry
  18494. this.setIndex( indices );
  18495. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18496. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  18497. // generate normals
  18498. this.computeVertexNormals();
  18499. }
  18500. ParametricBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  18501. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  18502. /**
  18503. * @author clockworkgeek / https://github.com/clockworkgeek
  18504. * @author timothypratley / https://github.com/timothypratley
  18505. * @author WestLangley / http://github.com/WestLangley
  18506. */
  18507. function PolyhedronGeometry( vertices, indices, radius, detail ) {
  18508. Geometry.call( this );
  18509. this.type = 'PolyhedronGeometry';
  18510. this.parameters = {
  18511. vertices: vertices,
  18512. indices: indices,
  18513. radius: radius,
  18514. detail: detail
  18515. };
  18516. this.fromBufferGeometry( new PolyhedronBufferGeometry( vertices, indices, radius, detail ) );
  18517. this.mergeVertices();
  18518. }
  18519. PolyhedronGeometry.prototype = Object.create( Geometry.prototype );
  18520. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry;
  18521. /**
  18522. * @author Mugen87 / https://github.com/Mugen87
  18523. */
  18524. function PolyhedronBufferGeometry( vertices, indices, radius, detail ) {
  18525. BufferGeometry.call( this );
  18526. this.type = 'PolyhedronBufferGeometry';
  18527. this.parameters = {
  18528. vertices: vertices,
  18529. indices: indices,
  18530. radius: radius,
  18531. detail: detail
  18532. };
  18533. radius = radius || 1;
  18534. detail = detail || 0;
  18535. // default buffer data
  18536. var vertexBuffer = [];
  18537. var uvBuffer = [];
  18538. // the subdivision creates the vertex buffer data
  18539. subdivide( detail );
  18540. // all vertices should lie on a conceptual sphere with a given radius
  18541. appplyRadius( radius );
  18542. // finally, create the uv data
  18543. generateUVs();
  18544. // build non-indexed geometry
  18545. this.addAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  18546. this.addAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  18547. this.addAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  18548. this.normalizeNormals();
  18549. // helper functions
  18550. function subdivide( detail ) {
  18551. var a = new Vector3();
  18552. var b = new Vector3();
  18553. var c = new Vector3();
  18554. // iterate over all faces and apply a subdivison with the given detail value
  18555. for ( var i = 0; i < indices.length; i += 3 ) {
  18556. // get the vertices of the face
  18557. getVertexByIndex( indices[ i + 0 ], a );
  18558. getVertexByIndex( indices[ i + 1 ], b );
  18559. getVertexByIndex( indices[ i + 2 ], c );
  18560. // perform subdivision
  18561. subdivideFace( a, b, c, detail );
  18562. }
  18563. }
  18564. function subdivideFace( a, b, c, detail ) {
  18565. var cols = Math.pow( 2, detail );
  18566. // we use this multidimensional array as a data structure for creating the subdivision
  18567. var v = [];
  18568. var i, j;
  18569. // construct all of the vertices for this subdivision
  18570. for ( i = 0; i <= cols; i ++ ) {
  18571. v[ i ] = [];
  18572. var aj = a.clone().lerp( c, i / cols );
  18573. var bj = b.clone().lerp( c, i / cols );
  18574. var rows = cols - i;
  18575. for ( j = 0; j <= rows; j ++ ) {
  18576. if ( j === 0 && i === cols ) {
  18577. v[ i ][ j ] = aj;
  18578. } else {
  18579. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  18580. }
  18581. }
  18582. }
  18583. // construct all of the faces
  18584. for ( i = 0; i < cols; i ++ ) {
  18585. for ( j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  18586. var k = Math.floor( j / 2 );
  18587. if ( j % 2 === 0 ) {
  18588. pushVertex( v[ i ][ k + 1 ] );
  18589. pushVertex( v[ i + 1 ][ k ] );
  18590. pushVertex( v[ i ][ k ] );
  18591. } else {
  18592. pushVertex( v[ i ][ k + 1 ] );
  18593. pushVertex( v[ i + 1 ][ k + 1 ] );
  18594. pushVertex( v[ i + 1 ][ k ] );
  18595. }
  18596. }
  18597. }
  18598. }
  18599. function appplyRadius( radius ) {
  18600. var vertex = new Vector3();
  18601. // iterate over the entire buffer and apply the radius to each vertex
  18602. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  18603. vertex.x = vertexBuffer[ i + 0 ];
  18604. vertex.y = vertexBuffer[ i + 1 ];
  18605. vertex.z = vertexBuffer[ i + 2 ];
  18606. vertex.normalize().multiplyScalar( radius );
  18607. vertexBuffer[ i + 0 ] = vertex.x;
  18608. vertexBuffer[ i + 1 ] = vertex.y;
  18609. vertexBuffer[ i + 2 ] = vertex.z;
  18610. }
  18611. }
  18612. function generateUVs() {
  18613. var vertex = new Vector3();
  18614. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  18615. vertex.x = vertexBuffer[ i + 0 ];
  18616. vertex.y = vertexBuffer[ i + 1 ];
  18617. vertex.z = vertexBuffer[ i + 2 ];
  18618. var u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  18619. var v = inclination( vertex ) / Math.PI + 0.5;
  18620. uvBuffer.push( u, 1 - v );
  18621. }
  18622. correctUVs();
  18623. correctSeam();
  18624. }
  18625. function correctSeam() {
  18626. // handle case when face straddles the seam, see #3269
  18627. for ( var i = 0; i < uvBuffer.length; i += 6 ) {
  18628. // uv data of a single face
  18629. var x0 = uvBuffer[ i + 0 ];
  18630. var x1 = uvBuffer[ i + 2 ];
  18631. var x2 = uvBuffer[ i + 4 ];
  18632. var max = Math.max( x0, x1, x2 );
  18633. var min = Math.min( x0, x1, x2 );
  18634. // 0.9 is somewhat arbitrary
  18635. if ( max > 0.9 && min < 0.1 ) {
  18636. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  18637. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  18638. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  18639. }
  18640. }
  18641. }
  18642. function pushVertex( vertex ) {
  18643. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  18644. }
  18645. function getVertexByIndex( index, vertex ) {
  18646. var stride = index * 3;
  18647. vertex.x = vertices[ stride + 0 ];
  18648. vertex.y = vertices[ stride + 1 ];
  18649. vertex.z = vertices[ stride + 2 ];
  18650. }
  18651. function correctUVs() {
  18652. var a = new Vector3();
  18653. var b = new Vector3();
  18654. var c = new Vector3();
  18655. var centroid = new Vector3();
  18656. var uvA = new Vector2();
  18657. var uvB = new Vector2();
  18658. var uvC = new Vector2();
  18659. for ( var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  18660. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  18661. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  18662. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  18663. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  18664. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  18665. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  18666. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  18667. var azi = azimuth( centroid );
  18668. correctUV( uvA, j + 0, a, azi );
  18669. correctUV( uvB, j + 2, b, azi );
  18670. correctUV( uvC, j + 4, c, azi );
  18671. }
  18672. }
  18673. function correctUV( uv, stride, vector, azimuth ) {
  18674. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  18675. uvBuffer[ stride ] = uv.x - 1;
  18676. }
  18677. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  18678. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  18679. }
  18680. }
  18681. // Angle around the Y axis, counter-clockwise when looking from above.
  18682. function azimuth( vector ) {
  18683. return Math.atan2( vector.z, - vector.x );
  18684. }
  18685. // Angle above the XZ plane.
  18686. function inclination( vector ) {
  18687. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  18688. }
  18689. }
  18690. PolyhedronBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  18691. PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;
  18692. /**
  18693. * @author timothypratley / https://github.com/timothypratley
  18694. */
  18695. function TetrahedronGeometry( radius, detail ) {
  18696. Geometry.call( this );
  18697. this.type = 'TetrahedronGeometry';
  18698. this.parameters = {
  18699. radius: radius,
  18700. detail: detail
  18701. };
  18702. this.fromBufferGeometry( new TetrahedronBufferGeometry( radius, detail ) );
  18703. this.mergeVertices();
  18704. }
  18705. TetrahedronGeometry.prototype = Object.create( Geometry.prototype );
  18706. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry;
  18707. /**
  18708. * @author Mugen87 / https://github.com/Mugen87
  18709. */
  18710. function TetrahedronBufferGeometry( radius, detail ) {
  18711. var vertices = [
  18712. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  18713. ];
  18714. var indices = [
  18715. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  18716. ];
  18717. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  18718. this.type = 'TetrahedronBufferGeometry';
  18719. this.parameters = {
  18720. radius: radius,
  18721. detail: detail
  18722. };
  18723. }
  18724. TetrahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  18725. TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;
  18726. /**
  18727. * @author timothypratley / https://github.com/timothypratley
  18728. */
  18729. function OctahedronGeometry( radius, detail ) {
  18730. Geometry.call( this );
  18731. this.type = 'OctahedronGeometry';
  18732. this.parameters = {
  18733. radius: radius,
  18734. detail: detail
  18735. };
  18736. this.fromBufferGeometry( new OctahedronBufferGeometry( radius, detail ) );
  18737. this.mergeVertices();
  18738. }
  18739. OctahedronGeometry.prototype = Object.create( Geometry.prototype );
  18740. OctahedronGeometry.prototype.constructor = OctahedronGeometry;
  18741. /**
  18742. * @author Mugen87 / https://github.com/Mugen87
  18743. */
  18744. function OctahedronBufferGeometry( radius, detail ) {
  18745. var vertices = [
  18746. 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  18747. ];
  18748. var indices = [
  18749. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  18750. ];
  18751. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  18752. this.type = 'OctahedronBufferGeometry';
  18753. this.parameters = {
  18754. radius: radius,
  18755. detail: detail
  18756. };
  18757. }
  18758. OctahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  18759. OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;
  18760. /**
  18761. * @author timothypratley / https://github.com/timothypratley
  18762. */
  18763. function IcosahedronGeometry( radius, detail ) {
  18764. Geometry.call( this );
  18765. this.type = 'IcosahedronGeometry';
  18766. this.parameters = {
  18767. radius: radius,
  18768. detail: detail
  18769. };
  18770. this.fromBufferGeometry( new IcosahedronBufferGeometry( radius, detail ) );
  18771. this.mergeVertices();
  18772. }
  18773. IcosahedronGeometry.prototype = Object.create( Geometry.prototype );
  18774. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry;
  18775. /**
  18776. * @author Mugen87 / https://github.com/Mugen87
  18777. */
  18778. function IcosahedronBufferGeometry( radius, detail ) {
  18779. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  18780. var vertices = [
  18781. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  18782. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  18783. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  18784. ];
  18785. var indices = [
  18786. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  18787. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  18788. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  18789. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  18790. ];
  18791. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  18792. this.type = 'IcosahedronBufferGeometry';
  18793. this.parameters = {
  18794. radius: radius,
  18795. detail: detail
  18796. };
  18797. }
  18798. IcosahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  18799. IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;
  18800. /**
  18801. * @author Abe Pazos / https://hamoid.com
  18802. */
  18803. function DodecahedronGeometry( radius, detail ) {
  18804. Geometry.call( this );
  18805. this.type = 'DodecahedronGeometry';
  18806. this.parameters = {
  18807. radius: radius,
  18808. detail: detail
  18809. };
  18810. this.fromBufferGeometry( new DodecahedronBufferGeometry( radius, detail ) );
  18811. this.mergeVertices();
  18812. }
  18813. DodecahedronGeometry.prototype = Object.create( Geometry.prototype );
  18814. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry;
  18815. /**
  18816. * @author Mugen87 / https://github.com/Mugen87
  18817. */
  18818. function DodecahedronBufferGeometry( radius, detail ) {
  18819. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  18820. var r = 1 / t;
  18821. var vertices = [
  18822. // (±1, ±1, ±1)
  18823. - 1, - 1, - 1, - 1, - 1, 1,
  18824. - 1, 1, - 1, - 1, 1, 1,
  18825. 1, - 1, - 1, 1, - 1, 1,
  18826. 1, 1, - 1, 1, 1, 1,
  18827. // (0, ±1/φ, ±φ)
  18828. 0, - r, - t, 0, - r, t,
  18829. 0, r, - t, 0, r, t,
  18830. // (±1/φ, ±φ, 0)
  18831. - r, - t, 0, - r, t, 0,
  18832. r, - t, 0, r, t, 0,
  18833. // (±φ, 0, ±1/φ)
  18834. - t, 0, - r, t, 0, - r,
  18835. - t, 0, r, t, 0, r
  18836. ];
  18837. var indices = [
  18838. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  18839. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  18840. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  18841. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  18842. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  18843. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  18844. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  18845. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  18846. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  18847. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  18848. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  18849. 1, 12, 14, 1, 14, 5, 1, 5, 9
  18850. ];
  18851. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  18852. this.type = 'DodecahedronBufferGeometry';
  18853. this.parameters = {
  18854. radius: radius,
  18855. detail: detail
  18856. };
  18857. }
  18858. DodecahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  18859. DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;
  18860. /**
  18861. * @author oosmoxiecode / https://github.com/oosmoxiecode
  18862. * @author WestLangley / https://github.com/WestLangley
  18863. * @author zz85 / https://github.com/zz85
  18864. * @author miningold / https://github.com/miningold
  18865. * @author jonobr1 / https://github.com/jonobr1
  18866. *
  18867. * Creates a tube which extrudes along a 3d spline.
  18868. */
  18869. function TubeGeometry( path, tubularSegments, radius, radialSegments, closed, taper ) {
  18870. Geometry.call( this );
  18871. this.type = 'TubeGeometry';
  18872. this.parameters = {
  18873. path: path,
  18874. tubularSegments: tubularSegments,
  18875. radius: radius,
  18876. radialSegments: radialSegments,
  18877. closed: closed
  18878. };
  18879. if ( taper !== undefined ) console.warn( 'THREE.TubeGeometry: taper has been removed.' );
  18880. var bufferGeometry = new TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed );
  18881. // expose internals
  18882. this.tangents = bufferGeometry.tangents;
  18883. this.normals = bufferGeometry.normals;
  18884. this.binormals = bufferGeometry.binormals;
  18885. // create geometry
  18886. this.fromBufferGeometry( bufferGeometry );
  18887. this.mergeVertices();
  18888. }
  18889. TubeGeometry.prototype = Object.create( Geometry.prototype );
  18890. TubeGeometry.prototype.constructor = TubeGeometry;
  18891. /**
  18892. * @author Mugen87 / https://github.com/Mugen87
  18893. */
  18894. function TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed ) {
  18895. BufferGeometry.call( this );
  18896. this.type = 'TubeBufferGeometry';
  18897. this.parameters = {
  18898. path: path,
  18899. tubularSegments: tubularSegments,
  18900. radius: radius,
  18901. radialSegments: radialSegments,
  18902. closed: closed
  18903. };
  18904. tubularSegments = tubularSegments || 64;
  18905. radius = radius || 1;
  18906. radialSegments = radialSegments || 8;
  18907. closed = closed || false;
  18908. var frames = path.computeFrenetFrames( tubularSegments, closed );
  18909. // expose internals
  18910. this.tangents = frames.tangents;
  18911. this.normals = frames.normals;
  18912. this.binormals = frames.binormals;
  18913. // helper variables
  18914. var vertex = new Vector3();
  18915. var normal = new Vector3();
  18916. var uv = new Vector2();
  18917. var i, j;
  18918. // buffer
  18919. var vertices = [];
  18920. var normals = [];
  18921. var uvs = [];
  18922. var indices = [];
  18923. // create buffer data
  18924. generateBufferData();
  18925. // build geometry
  18926. this.setIndex( indices );
  18927. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18928. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  18929. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  18930. // functions
  18931. function generateBufferData() {
  18932. for ( i = 0; i < tubularSegments; i ++ ) {
  18933. generateSegment( i );
  18934. }
  18935. // if the geometry is not closed, generate the last row of vertices and normals
  18936. // at the regular position on the given path
  18937. //
  18938. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  18939. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  18940. // uvs are generated in a separate function.
  18941. // this makes it easy compute correct values for closed geometries
  18942. generateUVs();
  18943. // finally create faces
  18944. generateIndices();
  18945. }
  18946. function generateSegment( i ) {
  18947. // we use getPointAt to sample evenly distributed points from the given path
  18948. var P = path.getPointAt( i / tubularSegments );
  18949. // retrieve corresponding normal and binormal
  18950. var N = frames.normals[ i ];
  18951. var B = frames.binormals[ i ];
  18952. // generate normals and vertices for the current segment
  18953. for ( j = 0; j <= radialSegments; j ++ ) {
  18954. var v = j / radialSegments * Math.PI * 2;
  18955. var sin = Math.sin( v );
  18956. var cos = - Math.cos( v );
  18957. // normal
  18958. normal.x = ( cos * N.x + sin * B.x );
  18959. normal.y = ( cos * N.y + sin * B.y );
  18960. normal.z = ( cos * N.z + sin * B.z );
  18961. normal.normalize();
  18962. normals.push( normal.x, normal.y, normal.z );
  18963. // vertex
  18964. vertex.x = P.x + radius * normal.x;
  18965. vertex.y = P.y + radius * normal.y;
  18966. vertex.z = P.z + radius * normal.z;
  18967. vertices.push( vertex.x, vertex.y, vertex.z );
  18968. }
  18969. }
  18970. function generateIndices() {
  18971. for ( j = 1; j <= tubularSegments; j ++ ) {
  18972. for ( i = 1; i <= radialSegments; i ++ ) {
  18973. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  18974. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  18975. var c = ( radialSegments + 1 ) * j + i;
  18976. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  18977. // faces
  18978. indices.push( a, b, d );
  18979. indices.push( b, c, d );
  18980. }
  18981. }
  18982. }
  18983. function generateUVs() {
  18984. for ( i = 0; i <= tubularSegments; i ++ ) {
  18985. for ( j = 0; j <= radialSegments; j ++ ) {
  18986. uv.x = i / tubularSegments;
  18987. uv.y = j / radialSegments;
  18988. uvs.push( uv.x, uv.y );
  18989. }
  18990. }
  18991. }
  18992. }
  18993. TubeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  18994. TubeBufferGeometry.prototype.constructor = TubeBufferGeometry;
  18995. /**
  18996. * @author oosmoxiecode
  18997. */
  18998. function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {
  18999. Geometry.call( this );
  19000. this.type = 'TorusKnotGeometry';
  19001. this.parameters = {
  19002. radius: radius,
  19003. tube: tube,
  19004. tubularSegments: tubularSegments,
  19005. radialSegments: radialSegments,
  19006. p: p,
  19007. q: q
  19008. };
  19009. if ( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' );
  19010. this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
  19011. this.mergeVertices();
  19012. }
  19013. TorusKnotGeometry.prototype = Object.create( Geometry.prototype );
  19014. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry;
  19015. /**
  19016. * @author Mugen87 / https://github.com/Mugen87
  19017. * see: http://www.blackpawn.com/texts/pqtorus/
  19018. */
  19019. function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) {
  19020. BufferGeometry.call( this );
  19021. this.type = 'TorusKnotBufferGeometry';
  19022. this.parameters = {
  19023. radius: radius,
  19024. tube: tube,
  19025. tubularSegments: tubularSegments,
  19026. radialSegments: radialSegments,
  19027. p: p,
  19028. q: q
  19029. };
  19030. radius = radius || 100;
  19031. tube = tube || 40;
  19032. tubularSegments = Math.floor( tubularSegments ) || 64;
  19033. radialSegments = Math.floor( radialSegments ) || 8;
  19034. p = p || 2;
  19035. q = q || 3;
  19036. // buffers
  19037. var indices = [];
  19038. var vertices = [];
  19039. var normals = [];
  19040. var uvs = [];
  19041. // helper variables
  19042. var i, j;
  19043. var vertex = new Vector3();
  19044. var normal = new Vector3();
  19045. var uv = new Vector2();
  19046. var P1 = new Vector3();
  19047. var P2 = new Vector3();
  19048. var B = new Vector3();
  19049. var T = new Vector3();
  19050. var N = new Vector3();
  19051. // generate vertices, normals and uvs
  19052. for ( i = 0; i <= tubularSegments; ++ i ) {
  19053. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  19054. var u = i / tubularSegments * p * Math.PI * 2;
  19055. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  19056. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  19057. calculatePositionOnCurve( u, p, q, radius, P1 );
  19058. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  19059. // calculate orthonormal basis
  19060. T.subVectors( P2, P1 );
  19061. N.addVectors( P2, P1 );
  19062. B.crossVectors( T, N );
  19063. N.crossVectors( B, T );
  19064. // normalize B, N. T can be ignored, we don't use it
  19065. B.normalize();
  19066. N.normalize();
  19067. for ( j = 0; j <= radialSegments; ++ j ) {
  19068. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  19069. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  19070. var v = j / radialSegments * Math.PI * 2;
  19071. var cx = - tube * Math.cos( v );
  19072. var cy = tube * Math.sin( v );
  19073. // now calculate the final vertex position.
  19074. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  19075. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  19076. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  19077. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  19078. vertices.push( vertex.x, vertex.y, vertex.z );
  19079. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  19080. normal.subVectors( vertex, P1 ).normalize();
  19081. normals.push( normal.x, normal.y, normal.z );
  19082. // uv
  19083. uvs.push( i / tubularSegments );
  19084. uvs.push( j / radialSegments );
  19085. }
  19086. }
  19087. // generate indices
  19088. for ( j = 1; j <= tubularSegments; j ++ ) {
  19089. for ( i = 1; i <= radialSegments; i ++ ) {
  19090. // indices
  19091. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  19092. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  19093. var c = ( radialSegments + 1 ) * j + i;
  19094. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  19095. // faces
  19096. indices.push( a, b, d );
  19097. indices.push( b, c, d );
  19098. }
  19099. }
  19100. // build geometry
  19101. this.setIndex( indices );
  19102. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19103. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19104. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19105. // this function calculates the current position on the torus curve
  19106. function calculatePositionOnCurve( u, p, q, radius, position ) {
  19107. var cu = Math.cos( u );
  19108. var su = Math.sin( u );
  19109. var quOverP = q / p * u;
  19110. var cs = Math.cos( quOverP );
  19111. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  19112. position.y = radius * ( 2 + cs ) * su * 0.5;
  19113. position.z = radius * Math.sin( quOverP ) * 0.5;
  19114. }
  19115. }
  19116. TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  19117. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  19118. /**
  19119. * @author oosmoxiecode
  19120. * @author mrdoob / http://mrdoob.com/
  19121. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19122. */
  19123. function TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  19124. Geometry.call( this );
  19125. this.type = 'TorusGeometry';
  19126. this.parameters = {
  19127. radius: radius,
  19128. tube: tube,
  19129. radialSegments: radialSegments,
  19130. tubularSegments: tubularSegments,
  19131. arc: arc
  19132. };
  19133. this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) );
  19134. }
  19135. TorusGeometry.prototype = Object.create( Geometry.prototype );
  19136. TorusGeometry.prototype.constructor = TorusGeometry;
  19137. /**
  19138. * @author Mugen87 / https://github.com/Mugen87
  19139. */
  19140. function TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  19141. BufferGeometry.call( this );
  19142. this.type = 'TorusBufferGeometry';
  19143. this.parameters = {
  19144. radius: radius,
  19145. tube: tube,
  19146. radialSegments: radialSegments,
  19147. tubularSegments: tubularSegments,
  19148. arc: arc
  19149. };
  19150. radius = radius || 100;
  19151. tube = tube || 40;
  19152. radialSegments = Math.floor( radialSegments ) || 8;
  19153. tubularSegments = Math.floor( tubularSegments ) || 6;
  19154. arc = arc || Math.PI * 2;
  19155. // buffers
  19156. var indices = [];
  19157. var vertices = [];
  19158. var normals = [];
  19159. var uvs = [];
  19160. // helper variables
  19161. var center = new Vector3();
  19162. var vertex = new Vector3();
  19163. var normal = new Vector3();
  19164. var j, i;
  19165. // generate vertices, normals and uvs
  19166. for ( j = 0; j <= radialSegments; j ++ ) {
  19167. for ( i = 0; i <= tubularSegments; i ++ ) {
  19168. var u = i / tubularSegments * arc;
  19169. var v = j / radialSegments * Math.PI * 2;
  19170. // vertex
  19171. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  19172. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  19173. vertex.z = tube * Math.sin( v );
  19174. vertices.push( vertex.x, vertex.y, vertex.z );
  19175. // normal
  19176. center.x = radius * Math.cos( u );
  19177. center.y = radius * Math.sin( u );
  19178. normal.subVectors( vertex, center ).normalize();
  19179. normals.push( normal.x, normal.y, normal.z );
  19180. // uv
  19181. uvs.push( i / tubularSegments );
  19182. uvs.push( j / radialSegments );
  19183. }
  19184. }
  19185. // generate indices
  19186. for ( j = 1; j <= radialSegments; j ++ ) {
  19187. for ( i = 1; i <= tubularSegments; i ++ ) {
  19188. // indices
  19189. var a = ( tubularSegments + 1 ) * j + i - 1;
  19190. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19191. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  19192. var d = ( tubularSegments + 1 ) * j + i;
  19193. // faces
  19194. indices.push( a, b, d );
  19195. indices.push( b, c, d );
  19196. }
  19197. }
  19198. // build geometry
  19199. this.setIndex( indices );
  19200. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19201. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19202. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19203. }
  19204. TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  19205. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  19206. /**
  19207. * @author zz85 / http://www.lab4games.net/zz85/blog
  19208. */
  19209. var ShapeUtils = {
  19210. // calculate area of the contour polygon
  19211. area: function ( contour ) {
  19212. var n = contour.length;
  19213. var a = 0.0;
  19214. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  19215. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  19216. }
  19217. return a * 0.5;
  19218. },
  19219. triangulate: ( function () {
  19220. /**
  19221. * This code is a quick port of code written in C++ which was submitted to
  19222. * flipcode.com by John W. Ratcliff // July 22, 2000
  19223. * See original code and more information here:
  19224. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  19225. *
  19226. * ported to actionscript by Zevan Rosser
  19227. * www.actionsnippet.com
  19228. *
  19229. * ported to javascript by Joshua Koo
  19230. * http://www.lab4games.net/zz85/blog
  19231. *
  19232. */
  19233. function snip( contour, u, v, w, n, verts ) {
  19234. var p;
  19235. var ax, ay, bx, by;
  19236. var cx, cy, px, py;
  19237. ax = contour[ verts[ u ] ].x;
  19238. ay = contour[ verts[ u ] ].y;
  19239. bx = contour[ verts[ v ] ].x;
  19240. by = contour[ verts[ v ] ].y;
  19241. cx = contour[ verts[ w ] ].x;
  19242. cy = contour[ verts[ w ] ].y;
  19243. if ( ( bx - ax ) * ( cy - ay ) - ( by - ay ) * ( cx - ax ) <= 0 ) return false;
  19244. var aX, aY, bX, bY, cX, cY;
  19245. var apx, apy, bpx, bpy, cpx, cpy;
  19246. var cCROSSap, bCROSScp, aCROSSbp;
  19247. aX = cx - bx; aY = cy - by;
  19248. bX = ax - cx; bY = ay - cy;
  19249. cX = bx - ax; cY = by - ay;
  19250. for ( p = 0; p < n; p ++ ) {
  19251. px = contour[ verts[ p ] ].x;
  19252. py = contour[ verts[ p ] ].y;
  19253. if ( ( ( px === ax ) && ( py === ay ) ) ||
  19254. ( ( px === bx ) && ( py === by ) ) ||
  19255. ( ( px === cx ) && ( py === cy ) ) ) continue;
  19256. apx = px - ax; apy = py - ay;
  19257. bpx = px - bx; bpy = py - by;
  19258. cpx = px - cx; cpy = py - cy;
  19259. // see if p is inside triangle abc
  19260. aCROSSbp = aX * bpy - aY * bpx;
  19261. cCROSSap = cX * apy - cY * apx;
  19262. bCROSScp = bX * cpy - bY * cpx;
  19263. if ( ( aCROSSbp >= - Number.EPSILON ) && ( bCROSScp >= - Number.EPSILON ) && ( cCROSSap >= - Number.EPSILON ) ) return false;
  19264. }
  19265. return true;
  19266. }
  19267. // takes in an contour array and returns
  19268. return function triangulate( contour, indices ) {
  19269. var n = contour.length;
  19270. if ( n < 3 ) return null;
  19271. var result = [],
  19272. verts = [],
  19273. vertIndices = [];
  19274. /* we want a counter-clockwise polygon in verts */
  19275. var u, v, w;
  19276. if ( ShapeUtils.area( contour ) > 0.0 ) {
  19277. for ( v = 0; v < n; v ++ ) verts[ v ] = v;
  19278. } else {
  19279. for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v;
  19280. }
  19281. var nv = n;
  19282. /* remove nv - 2 vertices, creating 1 triangle every time */
  19283. var count = 2 * nv; /* error detection */
  19284. for ( v = nv - 1; nv > 2; ) {
  19285. /* if we loop, it is probably a non-simple polygon */
  19286. if ( ( count -- ) <= 0 ) {
  19287. //** Triangulate: ERROR - probable bad polygon!
  19288. //throw ( "Warning, unable to triangulate polygon!" );
  19289. //return null;
  19290. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  19291. console.warn( 'THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()' );
  19292. if ( indices ) return vertIndices;
  19293. return result;
  19294. }
  19295. /* three consecutive vertices in current polygon, <u,v,w> */
  19296. u = v; if ( nv <= u ) u = 0; /* previous */
  19297. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  19298. w = v + 1; if ( nv <= w ) w = 0; /* next */
  19299. if ( snip( contour, u, v, w, nv, verts ) ) {
  19300. var a, b, c, s, t;
  19301. /* true names of the vertices */
  19302. a = verts[ u ];
  19303. b = verts[ v ];
  19304. c = verts[ w ];
  19305. /* output Triangle */
  19306. result.push( [ contour[ a ],
  19307. contour[ b ],
  19308. contour[ c ] ] );
  19309. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  19310. /* remove v from the remaining polygon */
  19311. for ( s = v, t = v + 1; t < nv; s ++, t ++ ) {
  19312. verts[ s ] = verts[ t ];
  19313. }
  19314. nv --;
  19315. /* reset error detection counter */
  19316. count = 2 * nv;
  19317. }
  19318. }
  19319. if ( indices ) return vertIndices;
  19320. return result;
  19321. }
  19322. } )(),
  19323. triangulateShape: function ( contour, holes ) {
  19324. function removeDupEndPts(points) {
  19325. var l = points.length;
  19326. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  19327. points.pop();
  19328. }
  19329. }
  19330. removeDupEndPts( contour );
  19331. holes.forEach( removeDupEndPts );
  19332. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  19333. // inOtherPt needs to be collinear to the inSegment
  19334. if ( inSegPt1.x !== inSegPt2.x ) {
  19335. if ( inSegPt1.x < inSegPt2.x ) {
  19336. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  19337. } else {
  19338. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  19339. }
  19340. } else {
  19341. if ( inSegPt1.y < inSegPt2.y ) {
  19342. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  19343. } else {
  19344. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  19345. }
  19346. }
  19347. }
  19348. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  19349. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  19350. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  19351. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  19352. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  19353. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  19354. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  19355. if ( Math.abs( limit ) > Number.EPSILON ) {
  19356. // not parallel
  19357. var perpSeg2;
  19358. if ( limit > 0 ) {
  19359. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  19360. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  19361. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  19362. } else {
  19363. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  19364. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  19365. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  19366. }
  19367. // i.e. to reduce rounding errors
  19368. // intersection at endpoint of segment#1?
  19369. if ( perpSeg2 === 0 ) {
  19370. if ( ( inExcludeAdjacentSegs ) &&
  19371. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  19372. return [ inSeg1Pt1 ];
  19373. }
  19374. if ( perpSeg2 === limit ) {
  19375. if ( ( inExcludeAdjacentSegs ) &&
  19376. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  19377. return [ inSeg1Pt2 ];
  19378. }
  19379. // intersection at endpoint of segment#2?
  19380. if ( perpSeg1 === 0 ) return [ inSeg2Pt1 ];
  19381. if ( perpSeg1 === limit ) return [ inSeg2Pt2 ];
  19382. // return real intersection point
  19383. var factorSeg1 = perpSeg2 / limit;
  19384. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  19385. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  19386. } else {
  19387. // parallel or collinear
  19388. if ( ( perpSeg1 !== 0 ) ||
  19389. ( seg2dy * seg1seg2dx !== seg2dx * seg1seg2dy ) ) return [];
  19390. // they are collinear or degenerate
  19391. var seg1Pt = ( ( seg1dx === 0 ) && ( seg1dy === 0 ) ); // segment1 is just a point?
  19392. var seg2Pt = ( ( seg2dx === 0 ) && ( seg2dy === 0 ) ); // segment2 is just a point?
  19393. // both segments are points
  19394. if ( seg1Pt && seg2Pt ) {
  19395. if ( ( inSeg1Pt1.x !== inSeg2Pt1.x ) ||
  19396. ( inSeg1Pt1.y !== inSeg2Pt1.y ) ) return []; // they are distinct points
  19397. return [ inSeg1Pt1 ]; // they are the same point
  19398. }
  19399. // segment#1 is a single point
  19400. if ( seg1Pt ) {
  19401. if ( ! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  19402. return [ inSeg1Pt1 ];
  19403. }
  19404. // segment#2 is a single point
  19405. if ( seg2Pt ) {
  19406. if ( ! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  19407. return [ inSeg2Pt1 ];
  19408. }
  19409. // they are collinear segments, which might overlap
  19410. var seg1min, seg1max, seg1minVal, seg1maxVal;
  19411. var seg2min, seg2max, seg2minVal, seg2maxVal;
  19412. if ( seg1dx !== 0 ) {
  19413. // the segments are NOT on a vertical line
  19414. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  19415. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  19416. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  19417. } else {
  19418. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  19419. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  19420. }
  19421. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  19422. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  19423. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  19424. } else {
  19425. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  19426. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  19427. }
  19428. } else {
  19429. // the segments are on a vertical line
  19430. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  19431. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  19432. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  19433. } else {
  19434. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  19435. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  19436. }
  19437. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  19438. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  19439. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  19440. } else {
  19441. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  19442. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  19443. }
  19444. }
  19445. if ( seg1minVal <= seg2minVal ) {
  19446. if ( seg1maxVal < seg2minVal ) return [];
  19447. if ( seg1maxVal === seg2minVal ) {
  19448. if ( inExcludeAdjacentSegs ) return [];
  19449. return [ seg2min ];
  19450. }
  19451. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  19452. return [ seg2min, seg2max ];
  19453. } else {
  19454. if ( seg1minVal > seg2maxVal ) return [];
  19455. if ( seg1minVal === seg2maxVal ) {
  19456. if ( inExcludeAdjacentSegs ) return [];
  19457. return [ seg1min ];
  19458. }
  19459. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  19460. return [ seg1min, seg2max ];
  19461. }
  19462. }
  19463. }
  19464. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  19465. // The order of legs is important
  19466. // translation of all points, so that Vertex is at (0,0)
  19467. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  19468. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  19469. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  19470. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  19471. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  19472. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  19473. if ( Math.abs( from2toAngle ) > Number.EPSILON ) {
  19474. // angle != 180 deg.
  19475. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  19476. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  19477. if ( from2toAngle > 0 ) {
  19478. // main angle < 180 deg.
  19479. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  19480. } else {
  19481. // main angle > 180 deg.
  19482. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  19483. }
  19484. } else {
  19485. // angle == 180 deg.
  19486. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  19487. return ( from2otherAngle > 0 );
  19488. }
  19489. }
  19490. function removeHoles( contour, holes ) {
  19491. var shape = contour.concat(); // work on this shape
  19492. var hole;
  19493. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  19494. // Check if hole point lies within angle around shape point
  19495. var lastShapeIdx = shape.length - 1;
  19496. var prevShapeIdx = inShapeIdx - 1;
  19497. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  19498. var nextShapeIdx = inShapeIdx + 1;
  19499. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  19500. var insideAngle = isPointInsideAngle( shape[ inShapeIdx ], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[ inHoleIdx ] );
  19501. if ( ! insideAngle ) {
  19502. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  19503. return false;
  19504. }
  19505. // Check if shape point lies within angle around hole point
  19506. var lastHoleIdx = hole.length - 1;
  19507. var prevHoleIdx = inHoleIdx - 1;
  19508. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  19509. var nextHoleIdx = inHoleIdx + 1;
  19510. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  19511. insideAngle = isPointInsideAngle( hole[ inHoleIdx ], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[ inShapeIdx ] );
  19512. if ( ! insideAngle ) {
  19513. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  19514. return false;
  19515. }
  19516. return true;
  19517. }
  19518. function intersectsShapeEdge( inShapePt, inHolePt ) {
  19519. // checks for intersections with shape edges
  19520. var sIdx, nextIdx, intersection;
  19521. for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) {
  19522. nextIdx = sIdx + 1; nextIdx %= shape.length;
  19523. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[ sIdx ], shape[ nextIdx ], true );
  19524. if ( intersection.length > 0 ) return true;
  19525. }
  19526. return false;
  19527. }
  19528. var indepHoles = [];
  19529. function intersectsHoleEdge( inShapePt, inHolePt ) {
  19530. // checks for intersections with hole edges
  19531. var ihIdx, chkHole,
  19532. hIdx, nextIdx, intersection;
  19533. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) {
  19534. chkHole = holes[ indepHoles[ ihIdx ]];
  19535. for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) {
  19536. nextIdx = hIdx + 1; nextIdx %= chkHole.length;
  19537. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[ hIdx ], chkHole[ nextIdx ], true );
  19538. if ( intersection.length > 0 ) return true;
  19539. }
  19540. }
  19541. return false;
  19542. }
  19543. var holeIndex, shapeIndex,
  19544. shapePt, holePt,
  19545. holeIdx, cutKey, failedCuts = [],
  19546. tmpShape1, tmpShape2,
  19547. tmpHole1, tmpHole2;
  19548. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  19549. indepHoles.push( h );
  19550. }
  19551. var minShapeIndex = 0;
  19552. var counter = indepHoles.length * 2;
  19553. while ( indepHoles.length > 0 ) {
  19554. counter --;
  19555. if ( counter < 0 ) {
  19556. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  19557. break;
  19558. }
  19559. // search for shape-vertex and hole-vertex,
  19560. // which can be connected without intersections
  19561. for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) {
  19562. shapePt = shape[ shapeIndex ];
  19563. holeIndex = - 1;
  19564. // search for hole which can be reached without intersections
  19565. for ( var h = 0; h < indepHoles.length; h ++ ) {
  19566. holeIdx = indepHoles[ h ];
  19567. // prevent multiple checks
  19568. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  19569. if ( failedCuts[ cutKey ] !== undefined ) continue;
  19570. hole = holes[ holeIdx ];
  19571. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  19572. holePt = hole[ h2 ];
  19573. if ( ! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  19574. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  19575. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  19576. holeIndex = h2;
  19577. indepHoles.splice( h, 1 );
  19578. tmpShape1 = shape.slice( 0, shapeIndex + 1 );
  19579. tmpShape2 = shape.slice( shapeIndex );
  19580. tmpHole1 = hole.slice( holeIndex );
  19581. tmpHole2 = hole.slice( 0, holeIndex + 1 );
  19582. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  19583. minShapeIndex = shapeIndex;
  19584. // Debug only, to show the selected cuts
  19585. // glob_CutLines.push( [ shapePt, holePt ] );
  19586. break;
  19587. }
  19588. if ( holeIndex >= 0 ) break; // hole-vertex found
  19589. failedCuts[ cutKey ] = true; // remember failure
  19590. }
  19591. if ( holeIndex >= 0 ) break; // hole-vertex found
  19592. }
  19593. }
  19594. return shape; /* shape with no holes */
  19595. }
  19596. var i, il, f, face,
  19597. key, index,
  19598. allPointsMap = {};
  19599. // 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.
  19600. var allpoints = contour.concat();
  19601. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  19602. Array.prototype.push.apply( allpoints, holes[ h ] );
  19603. }
  19604. //console.log( "allpoints",allpoints, allpoints.length );
  19605. // prepare all points map
  19606. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  19607. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  19608. if ( allPointsMap[ key ] !== undefined ) {
  19609. console.warn( "THREE.ShapeUtils: Duplicate point", key, i );
  19610. }
  19611. allPointsMap[ key ] = i;
  19612. }
  19613. // remove holes by cutting paths to holes and adding them to the shape
  19614. var shapeWithoutHoles = removeHoles( contour, holes );
  19615. var triangles = ShapeUtils.triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  19616. //console.log( "triangles",triangles, triangles.length );
  19617. // check all face vertices against all points map
  19618. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  19619. face = triangles[ i ];
  19620. for ( f = 0; f < 3; f ++ ) {
  19621. key = face[ f ].x + ":" + face[ f ].y;
  19622. index = allPointsMap[ key ];
  19623. if ( index !== undefined ) {
  19624. face[ f ] = index;
  19625. }
  19626. }
  19627. }
  19628. return triangles.concat();
  19629. },
  19630. isClockWise: function ( pts ) {
  19631. return ShapeUtils.area( pts ) < 0;
  19632. }
  19633. };
  19634. /**
  19635. * @author zz85 / http://www.lab4games.net/zz85/blog
  19636. *
  19637. * Creates extruded geometry from a path shape.
  19638. *
  19639. * parameters = {
  19640. *
  19641. * curveSegments: <int>, // number of points on the curves
  19642. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  19643. * amount: <int>, // Depth to extrude the shape
  19644. *
  19645. * bevelEnabled: <bool>, // turn on bevel
  19646. * bevelThickness: <float>, // how deep into the original shape bevel goes
  19647. * bevelSize: <float>, // how far from shape outline is bevel
  19648. * bevelSegments: <int>, // number of bevel layers
  19649. *
  19650. * extrudePath: <THREE.Curve> // curve to extrude shape along
  19651. * frames: <Object> // containing arrays of tangents, normals, binormals
  19652. *
  19653. * uvGenerator: <Object> // object that provides UV generator functions
  19654. *
  19655. * }
  19656. **/
  19657. function ExtrudeGeometry( shapes, options ) {
  19658. if ( typeof( shapes ) === "undefined" ) {
  19659. shapes = [];
  19660. return;
  19661. }
  19662. Geometry.call( this );
  19663. this.type = 'ExtrudeGeometry';
  19664. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  19665. this.addShapeList( shapes, options );
  19666. this.computeFaceNormals();
  19667. // can't really use automatic vertex normals
  19668. // as then front and back sides get smoothed too
  19669. // should do separate smoothing just for sides
  19670. //this.computeVertexNormals();
  19671. //console.log( "took", ( Date.now() - startTime ) );
  19672. }
  19673. ExtrudeGeometry.prototype = Object.create( Geometry.prototype );
  19674. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  19675. ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19676. var sl = shapes.length;
  19677. for ( var s = 0; s < sl; s ++ ) {
  19678. var shape = shapes[ s ];
  19679. this.addShape( shape, options );
  19680. }
  19681. };
  19682. ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  19683. var amount = options.amount !== undefined ? options.amount : 100;
  19684. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  19685. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  19686. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  19687. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  19688. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19689. var steps = options.steps !== undefined ? options.steps : 1;
  19690. var extrudePath = options.extrudePath;
  19691. var extrudePts, extrudeByPath = false;
  19692. // Use default WorldUVGenerator if no UV generators are specified.
  19693. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : ExtrudeGeometry.WorldUVGenerator;
  19694. var splineTube, binormal, normal, position2;
  19695. if ( extrudePath ) {
  19696. extrudePts = extrudePath.getSpacedPoints( steps );
  19697. extrudeByPath = true;
  19698. bevelEnabled = false; // bevels not supported for path extrusion
  19699. // SETUP TNB variables
  19700. // TODO1 - have a .isClosed in spline?
  19701. splineTube = options.frames !== undefined ? options.frames : extrudePath.computeFrenetFrames( steps, false );
  19702. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  19703. binormal = new Vector3();
  19704. normal = new Vector3();
  19705. position2 = new Vector3();
  19706. }
  19707. // Safeguards if bevels are not enabled
  19708. if ( ! bevelEnabled ) {
  19709. bevelSegments = 0;
  19710. bevelThickness = 0;
  19711. bevelSize = 0;
  19712. }
  19713. // Variables initialization
  19714. var ahole, h, hl; // looping of holes
  19715. var scope = this;
  19716. var shapesOffset = this.vertices.length;
  19717. var shapePoints = shape.extractPoints( curveSegments );
  19718. var vertices = shapePoints.shape;
  19719. var holes = shapePoints.holes;
  19720. var reverse = ! ShapeUtils.isClockWise( vertices );
  19721. if ( reverse ) {
  19722. vertices = vertices.reverse();
  19723. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  19724. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19725. ahole = holes[ h ];
  19726. if ( ShapeUtils.isClockWise( ahole ) ) {
  19727. holes[ h ] = ahole.reverse();
  19728. }
  19729. }
  19730. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  19731. }
  19732. var faces = ShapeUtils.triangulateShape( vertices, holes );
  19733. /* Vertices */
  19734. var contour = vertices; // vertices has all points but contour has only points of circumference
  19735. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19736. ahole = holes[ h ];
  19737. vertices = vertices.concat( ahole );
  19738. }
  19739. function scalePt2( pt, vec, size ) {
  19740. if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" );
  19741. return vec.clone().multiplyScalar( size ).add( pt );
  19742. }
  19743. var b, bs, t, z,
  19744. vert, vlen = vertices.length,
  19745. face, flen = faces.length;
  19746. // Find directions for point movement
  19747. function getBevelVec( inPt, inPrev, inNext ) {
  19748. // computes for inPt the corresponding point inPt' on a new contour
  19749. // shifted by 1 unit (length of normalized vector) to the left
  19750. // if we walk along contour clockwise, this new contour is outside the old one
  19751. //
  19752. // inPt' is the intersection of the two lines parallel to the two
  19753. // adjacent edges of inPt at a distance of 1 unit on the left side.
  19754. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  19755. // good reading for geometry algorithms (here: line-line intersection)
  19756. // http://geomalgorithms.com/a05-_intersect-1.html
  19757. var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y;
  19758. var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y;
  19759. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  19760. // check for collinear edges
  19761. var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  19762. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  19763. // not collinear
  19764. // length of vectors for normalizing
  19765. var v_prev_len = Math.sqrt( v_prev_lensq );
  19766. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  19767. // shift adjacent points by unit vectors to the left
  19768. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  19769. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  19770. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  19771. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  19772. // scaling factor for v_prev to intersection point
  19773. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  19774. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  19775. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  19776. // vector from inPt to intersection point
  19777. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  19778. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  19779. // Don't normalize!, otherwise sharp corners become ugly
  19780. // but prevent crazy spikes
  19781. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  19782. if ( v_trans_lensq <= 2 ) {
  19783. return new Vector2( v_trans_x, v_trans_y );
  19784. } else {
  19785. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  19786. }
  19787. } else {
  19788. // handle special case of collinear edges
  19789. var direction_eq = false; // assumes: opposite
  19790. if ( v_prev_x > Number.EPSILON ) {
  19791. if ( v_next_x > Number.EPSILON ) {
  19792. direction_eq = true;
  19793. }
  19794. } else {
  19795. if ( v_prev_x < - Number.EPSILON ) {
  19796. if ( v_next_x < - Number.EPSILON ) {
  19797. direction_eq = true;
  19798. }
  19799. } else {
  19800. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  19801. direction_eq = true;
  19802. }
  19803. }
  19804. }
  19805. if ( direction_eq ) {
  19806. // console.log("Warning: lines are a straight sequence");
  19807. v_trans_x = - v_prev_y;
  19808. v_trans_y = v_prev_x;
  19809. shrink_by = Math.sqrt( v_prev_lensq );
  19810. } else {
  19811. // console.log("Warning: lines are a straight spike");
  19812. v_trans_x = v_prev_x;
  19813. v_trans_y = v_prev_y;
  19814. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  19815. }
  19816. }
  19817. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  19818. }
  19819. var contourMovements = [];
  19820. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19821. if ( j === il ) j = 0;
  19822. if ( k === il ) k = 0;
  19823. // (j)---(i)---(k)
  19824. // console.log('i,j,k', i, j , k)
  19825. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  19826. }
  19827. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  19828. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19829. ahole = holes[ h ];
  19830. oneHoleMovements = [];
  19831. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19832. if ( j === il ) j = 0;
  19833. if ( k === il ) k = 0;
  19834. // (j)---(i)---(k)
  19835. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  19836. }
  19837. holesMovements.push( oneHoleMovements );
  19838. verticesMovements = verticesMovements.concat( oneHoleMovements );
  19839. }
  19840. // Loop bevelSegments, 1 for the front, 1 for the back
  19841. for ( b = 0; b < bevelSegments; b ++ ) {
  19842. //for ( b = bevelSegments; b > 0; b -- ) {
  19843. t = b / bevelSegments;
  19844. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  19845. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  19846. // contract shape
  19847. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19848. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19849. v( vert.x, vert.y, - z );
  19850. }
  19851. // expand holes
  19852. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19853. ahole = holes[ h ];
  19854. oneHoleMovements = holesMovements[ h ];
  19855. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  19856. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19857. v( vert.x, vert.y, - z );
  19858. }
  19859. }
  19860. }
  19861. bs = bevelSize;
  19862. // Back facing vertices
  19863. for ( i = 0; i < vlen; i ++ ) {
  19864. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19865. if ( ! extrudeByPath ) {
  19866. v( vert.x, vert.y, 0 );
  19867. } else {
  19868. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19869. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  19870. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  19871. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  19872. v( position2.x, position2.y, position2.z );
  19873. }
  19874. }
  19875. // Add stepped vertices...
  19876. // Including front facing vertices
  19877. var s;
  19878. for ( s = 1; s <= steps; s ++ ) {
  19879. for ( i = 0; i < vlen; i ++ ) {
  19880. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19881. if ( ! extrudeByPath ) {
  19882. v( vert.x, vert.y, amount / steps * s );
  19883. } else {
  19884. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19885. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  19886. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  19887. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  19888. v( position2.x, position2.y, position2.z );
  19889. }
  19890. }
  19891. }
  19892. // Add bevel segments planes
  19893. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19894. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  19895. t = b / bevelSegments;
  19896. z = bevelThickness * Math.cos ( t * Math.PI / 2 );
  19897. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  19898. // contract shape
  19899. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19900. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19901. v( vert.x, vert.y, amount + z );
  19902. }
  19903. // expand holes
  19904. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19905. ahole = holes[ h ];
  19906. oneHoleMovements = holesMovements[ h ];
  19907. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  19908. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19909. if ( ! extrudeByPath ) {
  19910. v( vert.x, vert.y, amount + z );
  19911. } else {
  19912. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  19913. }
  19914. }
  19915. }
  19916. }
  19917. /* Faces */
  19918. // Top and bottom faces
  19919. buildLidFaces();
  19920. // Sides faces
  19921. buildSideFaces();
  19922. ///// Internal functions
  19923. function buildLidFaces() {
  19924. if ( bevelEnabled ) {
  19925. var layer = 0; // steps + 1
  19926. var offset = vlen * layer;
  19927. // Bottom faces
  19928. for ( i = 0; i < flen; i ++ ) {
  19929. face = faces[ i ];
  19930. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  19931. }
  19932. layer = steps + bevelSegments * 2;
  19933. offset = vlen * layer;
  19934. // Top faces
  19935. for ( i = 0; i < flen; i ++ ) {
  19936. face = faces[ i ];
  19937. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  19938. }
  19939. } else {
  19940. // Bottom faces
  19941. for ( i = 0; i < flen; i ++ ) {
  19942. face = faces[ i ];
  19943. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  19944. }
  19945. // Top faces
  19946. for ( i = 0; i < flen; i ++ ) {
  19947. face = faces[ i ];
  19948. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  19949. }
  19950. }
  19951. }
  19952. // Create faces for the z-sides of the shape
  19953. function buildSideFaces() {
  19954. var layeroffset = 0;
  19955. sidewalls( contour, layeroffset );
  19956. layeroffset += contour.length;
  19957. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19958. ahole = holes[ h ];
  19959. sidewalls( ahole, layeroffset );
  19960. //, true
  19961. layeroffset += ahole.length;
  19962. }
  19963. }
  19964. function sidewalls( contour, layeroffset ) {
  19965. var j, k;
  19966. i = contour.length;
  19967. while ( -- i >= 0 ) {
  19968. j = i;
  19969. k = i - 1;
  19970. if ( k < 0 ) k = contour.length - 1;
  19971. //console.log('b', i,j, i-1, k,vertices.length);
  19972. var s = 0, sl = steps + bevelSegments * 2;
  19973. for ( s = 0; s < sl; s ++ ) {
  19974. var slen1 = vlen * s;
  19975. var slen2 = vlen * ( s + 1 );
  19976. var a = layeroffset + j + slen1,
  19977. b = layeroffset + k + slen1,
  19978. c = layeroffset + k + slen2,
  19979. d = layeroffset + j + slen2;
  19980. f4( a, b, c, d, contour, s, sl, j, k );
  19981. }
  19982. }
  19983. }
  19984. function v( x, y, z ) {
  19985. scope.vertices.push( new Vector3( x, y, z ) );
  19986. }
  19987. function f3( a, b, c ) {
  19988. a += shapesOffset;
  19989. b += shapesOffset;
  19990. c += shapesOffset;
  19991. scope.faces.push( new Face3( a, b, c, null, null, 0 ) );
  19992. var uvs = uvgen.generateTopUV( scope, a, b, c );
  19993. scope.faceVertexUvs[ 0 ].push( uvs );
  19994. }
  19995. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  19996. a += shapesOffset;
  19997. b += shapesOffset;
  19998. c += shapesOffset;
  19999. d += shapesOffset;
  20000. scope.faces.push( new Face3( a, b, d, null, null, 1 ) );
  20001. scope.faces.push( new Face3( b, c, d, null, null, 1 ) );
  20002. var uvs = uvgen.generateSideWallUV( scope, a, b, c, d );
  20003. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  20004. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  20005. }
  20006. };
  20007. ExtrudeGeometry.WorldUVGenerator = {
  20008. generateTopUV: function ( geometry, indexA, indexB, indexC ) {
  20009. var vertices = geometry.vertices;
  20010. var a = vertices[ indexA ];
  20011. var b = vertices[ indexB ];
  20012. var c = vertices[ indexC ];
  20013. return [
  20014. new Vector2( a.x, a.y ),
  20015. new Vector2( b.x, b.y ),
  20016. new Vector2( c.x, c.y )
  20017. ];
  20018. },
  20019. generateSideWallUV: function ( geometry, indexA, indexB, indexC, indexD ) {
  20020. var vertices = geometry.vertices;
  20021. var a = vertices[ indexA ];
  20022. var b = vertices[ indexB ];
  20023. var c = vertices[ indexC ];
  20024. var d = vertices[ indexD ];
  20025. if ( Math.abs( a.y - b.y ) < 0.01 ) {
  20026. return [
  20027. new Vector2( a.x, 1 - a.z ),
  20028. new Vector2( b.x, 1 - b.z ),
  20029. new Vector2( c.x, 1 - c.z ),
  20030. new Vector2( d.x, 1 - d.z )
  20031. ];
  20032. } else {
  20033. return [
  20034. new Vector2( a.y, 1 - a.z ),
  20035. new Vector2( b.y, 1 - b.z ),
  20036. new Vector2( c.y, 1 - c.z ),
  20037. new Vector2( d.y, 1 - d.z )
  20038. ];
  20039. }
  20040. }
  20041. };
  20042. /**
  20043. * @author zz85 / http://www.lab4games.net/zz85/blog
  20044. * @author alteredq / http://alteredqualia.com/
  20045. *
  20046. * Text = 3D Text
  20047. *
  20048. * parameters = {
  20049. * font: <THREE.Font>, // font
  20050. *
  20051. * size: <float>, // size of the text
  20052. * height: <float>, // thickness to extrude text
  20053. * curveSegments: <int>, // number of points on the curves
  20054. *
  20055. * bevelEnabled: <bool>, // turn on bevel
  20056. * bevelThickness: <float>, // how deep into text bevel goes
  20057. * bevelSize: <float> // how far from text outline is bevel
  20058. * }
  20059. */
  20060. function TextGeometry( text, parameters ) {
  20061. parameters = parameters || {};
  20062. var font = parameters.font;
  20063. if ( ( font && font.isFont ) === false ) {
  20064. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  20065. return new Geometry();
  20066. }
  20067. var shapes = font.generateShapes( text, parameters.size, parameters.curveSegments );
  20068. // translate parameters to ExtrudeGeometry API
  20069. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  20070. // defaults
  20071. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  20072. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  20073. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  20074. ExtrudeGeometry.call( this, shapes, parameters );
  20075. this.type = 'TextGeometry';
  20076. }
  20077. TextGeometry.prototype = Object.create( ExtrudeGeometry.prototype );
  20078. TextGeometry.prototype.constructor = TextGeometry;
  20079. /**
  20080. * @author mrdoob / http://mrdoob.com/
  20081. */
  20082. function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  20083. Geometry.call( this );
  20084. this.type = 'SphereGeometry';
  20085. this.parameters = {
  20086. radius: radius,
  20087. widthSegments: widthSegments,
  20088. heightSegments: heightSegments,
  20089. phiStart: phiStart,
  20090. phiLength: phiLength,
  20091. thetaStart: thetaStart,
  20092. thetaLength: thetaLength
  20093. };
  20094. this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  20095. }
  20096. SphereGeometry.prototype = Object.create( Geometry.prototype );
  20097. SphereGeometry.prototype.constructor = SphereGeometry;
  20098. /**
  20099. * @author benaadams / https://twitter.com/ben_a_adams
  20100. * @author Mugen87 / https://github.com/Mugen87
  20101. */
  20102. function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  20103. BufferGeometry.call( this );
  20104. this.type = 'SphereBufferGeometry';
  20105. this.parameters = {
  20106. radius: radius,
  20107. widthSegments: widthSegments,
  20108. heightSegments: heightSegments,
  20109. phiStart: phiStart,
  20110. phiLength: phiLength,
  20111. thetaStart: thetaStart,
  20112. thetaLength: thetaLength
  20113. };
  20114. radius = radius || 50;
  20115. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  20116. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  20117. phiStart = phiStart !== undefined ? phiStart : 0;
  20118. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  20119. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  20120. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  20121. var thetaEnd = thetaStart + thetaLength;
  20122. var ix, iy;
  20123. var index = 0;
  20124. var grid = [];
  20125. var vertex = new Vector3();
  20126. var normal = new Vector3();
  20127. // buffers
  20128. var indices = [];
  20129. var vertices = [];
  20130. var normals = [];
  20131. var uvs = [];
  20132. // generate vertices, normals and uvs
  20133. for ( iy = 0; iy <= heightSegments; iy ++ ) {
  20134. var verticesRow = [];
  20135. var v = iy / heightSegments;
  20136. for ( ix = 0; ix <= widthSegments; ix ++ ) {
  20137. var u = ix / widthSegments;
  20138. // vertex
  20139. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  20140. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  20141. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  20142. vertices.push( vertex.x, vertex.y, vertex.z );
  20143. // normal
  20144. normal.set( vertex.x, vertex.y, vertex.z ).normalize();
  20145. normals.push( normal.x, normal.y, normal.z );
  20146. // uv
  20147. uvs.push( u, 1 - v );
  20148. verticesRow.push( index ++ );
  20149. }
  20150. grid.push( verticesRow );
  20151. }
  20152. // indices
  20153. for ( iy = 0; iy < heightSegments; iy ++ ) {
  20154. for ( ix = 0; ix < widthSegments; ix ++ ) {
  20155. var a = grid[ iy ][ ix + 1 ];
  20156. var b = grid[ iy ][ ix ];
  20157. var c = grid[ iy + 1 ][ ix ];
  20158. var d = grid[ iy + 1 ][ ix + 1 ];
  20159. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  20160. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  20161. }
  20162. }
  20163. // build geometry
  20164. this.setIndex( indices );
  20165. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20166. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20167. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20168. }
  20169. SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  20170. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  20171. /**
  20172. * @author Kaleb Murphy
  20173. */
  20174. function RingGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  20175. Geometry.call( this );
  20176. this.type = 'RingGeometry';
  20177. this.parameters = {
  20178. innerRadius: innerRadius,
  20179. outerRadius: outerRadius,
  20180. thetaSegments: thetaSegments,
  20181. phiSegments: phiSegments,
  20182. thetaStart: thetaStart,
  20183. thetaLength: thetaLength
  20184. };
  20185. this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) );
  20186. }
  20187. RingGeometry.prototype = Object.create( Geometry.prototype );
  20188. RingGeometry.prototype.constructor = RingGeometry;
  20189. /**
  20190. * @author Mugen87 / https://github.com/Mugen87
  20191. */
  20192. function RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  20193. BufferGeometry.call( this );
  20194. this.type = 'RingBufferGeometry';
  20195. this.parameters = {
  20196. innerRadius: innerRadius,
  20197. outerRadius: outerRadius,
  20198. thetaSegments: thetaSegments,
  20199. phiSegments: phiSegments,
  20200. thetaStart: thetaStart,
  20201. thetaLength: thetaLength
  20202. };
  20203. innerRadius = innerRadius || 20;
  20204. outerRadius = outerRadius || 50;
  20205. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  20206. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  20207. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  20208. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1;
  20209. // buffers
  20210. var indices = [];
  20211. var vertices = [];
  20212. var normals = [];
  20213. var uvs = [];
  20214. // some helper variables
  20215. var segment;
  20216. var radius = innerRadius;
  20217. var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  20218. var vertex = new Vector3();
  20219. var uv = new Vector2();
  20220. var j, i;
  20221. // generate vertices, normals and uvs
  20222. for ( j = 0; j <= phiSegments; j ++ ) {
  20223. for ( i = 0; i <= thetaSegments; i ++ ) {
  20224. // values are generate from the inside of the ring to the outside
  20225. segment = thetaStart + i / thetaSegments * thetaLength;
  20226. // vertex
  20227. vertex.x = radius * Math.cos( segment );
  20228. vertex.y = radius * Math.sin( segment );
  20229. vertices.push( vertex.x, vertex.y, vertex.z );
  20230. // normal
  20231. normals.push( 0, 0, 1 );
  20232. // uv
  20233. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  20234. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  20235. uvs.push( uv.x, uv.y );
  20236. }
  20237. // increase the radius for next row of vertices
  20238. radius += radiusStep;
  20239. }
  20240. // indices
  20241. for ( j = 0; j < phiSegments; j ++ ) {
  20242. var thetaSegmentLevel = j * ( thetaSegments + 1 );
  20243. for ( i = 0; i < thetaSegments; i ++ ) {
  20244. segment = i + thetaSegmentLevel;
  20245. var a = segment;
  20246. var b = segment + thetaSegments + 1;
  20247. var c = segment + thetaSegments + 2;
  20248. var d = segment + 1;
  20249. // faces
  20250. indices.push( a, b, d );
  20251. indices.push( b, c, d );
  20252. }
  20253. }
  20254. // build geometry
  20255. this.setIndex( indices );
  20256. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20257. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20258. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20259. }
  20260. RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  20261. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  20262. /**
  20263. * @author astrodud / http://astrodud.isgreat.org/
  20264. * @author zz85 / https://github.com/zz85
  20265. * @author bhouston / http://clara.io
  20266. */
  20267. // points - to create a closed torus, one must use a set of points
  20268. // like so: [ a, b, c, d, a ], see first is the same as last.
  20269. // segments - the number of circumference segments to create
  20270. // phiStart - the starting radian
  20271. // phiLength - the radian (0 to 2PI) range of the lathed section
  20272. // 2PI is a closed lathe, less than 2PI is a portion.
  20273. function LatheGeometry( points, segments, phiStart, phiLength ) {
  20274. Geometry.call( this );
  20275. this.type = 'LatheGeometry';
  20276. this.parameters = {
  20277. points: points,
  20278. segments: segments,
  20279. phiStart: phiStart,
  20280. phiLength: phiLength
  20281. };
  20282. this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) );
  20283. this.mergeVertices();
  20284. }
  20285. LatheGeometry.prototype = Object.create( Geometry.prototype );
  20286. LatheGeometry.prototype.constructor = LatheGeometry;
  20287. /**
  20288. * @author Mugen87 / https://github.com/Mugen87
  20289. */
  20290. function LatheBufferGeometry( points, segments, phiStart, phiLength ) {
  20291. BufferGeometry.call( this );
  20292. this.type = 'LatheBufferGeometry';
  20293. this.parameters = {
  20294. points: points,
  20295. segments: segments,
  20296. phiStart: phiStart,
  20297. phiLength: phiLength
  20298. };
  20299. segments = Math.floor( segments ) || 12;
  20300. phiStart = phiStart || 0;
  20301. phiLength = phiLength || Math.PI * 2;
  20302. // clamp phiLength so it's in range of [ 0, 2PI ]
  20303. phiLength = _Math.clamp( phiLength, 0, Math.PI * 2 );
  20304. // buffers
  20305. var indices = [];
  20306. var vertices = [];
  20307. var uvs = [];
  20308. // helper variables
  20309. var base;
  20310. var inverseSegments = 1.0 / segments;
  20311. var vertex = new Vector3();
  20312. var uv = new Vector2();
  20313. var i, j;
  20314. // generate vertices and uvs
  20315. for ( i = 0; i <= segments; i ++ ) {
  20316. var phi = phiStart + i * inverseSegments * phiLength;
  20317. var sin = Math.sin( phi );
  20318. var cos = Math.cos( phi );
  20319. for ( j = 0; j <= ( points.length - 1 ); j ++ ) {
  20320. // vertex
  20321. vertex.x = points[ j ].x * sin;
  20322. vertex.y = points[ j ].y;
  20323. vertex.z = points[ j ].x * cos;
  20324. vertices.push( vertex.x, vertex.y, vertex.z );
  20325. // uv
  20326. uv.x = i / segments;
  20327. uv.y = j / ( points.length - 1 );
  20328. uvs.push( uv.x, uv.y );
  20329. }
  20330. }
  20331. // indices
  20332. for ( i = 0; i < segments; i ++ ) {
  20333. for ( j = 0; j < ( points.length - 1 ); j ++ ) {
  20334. base = j + i * points.length;
  20335. var a = base;
  20336. var b = base + points.length;
  20337. var c = base + points.length + 1;
  20338. var d = base + 1;
  20339. // faces
  20340. indices.push( a, b, d );
  20341. indices.push( b, c, d );
  20342. }
  20343. }
  20344. // build geometry
  20345. this.setIndex( indices );
  20346. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20347. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20348. // generate normals
  20349. this.computeVertexNormals();
  20350. // if the geometry is closed, we need to average the normals along the seam.
  20351. // because the corresponding vertices are identical (but still have different UVs).
  20352. if ( phiLength === Math.PI * 2 ) {
  20353. var normals = this.attributes.normal.array;
  20354. var n1 = new Vector3();
  20355. var n2 = new Vector3();
  20356. var n = new Vector3();
  20357. // this is the buffer offset for the last line of vertices
  20358. base = segments * points.length * 3;
  20359. for ( i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  20360. // select the normal of the vertex in the first line
  20361. n1.x = normals[ j + 0 ];
  20362. n1.y = normals[ j + 1 ];
  20363. n1.z = normals[ j + 2 ];
  20364. // select the normal of the vertex in the last line
  20365. n2.x = normals[ base + j + 0 ];
  20366. n2.y = normals[ base + j + 1 ];
  20367. n2.z = normals[ base + j + 2 ];
  20368. // average normals
  20369. n.addVectors( n1, n2 ).normalize();
  20370. // assign the new values to both normals
  20371. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  20372. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  20373. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  20374. }
  20375. }
  20376. }
  20377. LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  20378. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  20379. /**
  20380. * @author jonobr1 / http://jonobr1.com
  20381. */
  20382. function ShapeGeometry( shapes, curveSegments ) {
  20383. Geometry.call( this );
  20384. this.type = 'ShapeGeometry';
  20385. if ( typeof curveSegments === 'object' ) {
  20386. console.warn( 'THREE.ShapeGeometry: Options parameter has been removed.' );
  20387. curveSegments = curveSegments.curveSegments;
  20388. }
  20389. this.parameters = {
  20390. shapes: shapes,
  20391. curveSegments: curveSegments
  20392. };
  20393. this.fromBufferGeometry( new ShapeBufferGeometry( shapes, curveSegments ) );
  20394. this.mergeVertices();
  20395. }
  20396. ShapeGeometry.prototype = Object.create( Geometry.prototype );
  20397. ShapeGeometry.prototype.constructor = ShapeGeometry;
  20398. /**
  20399. * @author Mugen87 / https://github.com/Mugen87
  20400. */
  20401. function ShapeBufferGeometry( shapes, curveSegments ) {
  20402. BufferGeometry.call( this );
  20403. this.type = 'ShapeBufferGeometry';
  20404. this.parameters = {
  20405. shapes: shapes,
  20406. curveSegments: curveSegments
  20407. };
  20408. curveSegments = curveSegments || 12;
  20409. // buffers
  20410. var indices = [];
  20411. var vertices = [];
  20412. var normals = [];
  20413. var uvs = [];
  20414. // helper variables
  20415. var groupStart = 0;
  20416. var groupCount = 0;
  20417. // allow single and array values for "shapes" parameter
  20418. if ( Array.isArray( shapes ) === false ) {
  20419. addShape( shapes );
  20420. } else {
  20421. for ( var i = 0; i < shapes.length; i ++ ) {
  20422. addShape( shapes[ i ] );
  20423. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  20424. groupStart += groupCount;
  20425. groupCount = 0;
  20426. }
  20427. }
  20428. // build geometry
  20429. this.setIndex( indices );
  20430. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20431. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20432. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20433. // helper functions
  20434. function addShape( shape ) {
  20435. var i, l, shapeHole;
  20436. var indexOffset = vertices.length / 3;
  20437. var points = shape.extractPoints( curveSegments );
  20438. var shapeVertices = points.shape;
  20439. var shapeHoles = points.holes;
  20440. // check direction of vertices
  20441. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  20442. shapeVertices = shapeVertices.reverse();
  20443. // also check if holes are in the opposite direction
  20444. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  20445. shapeHole = shapeHoles[ i ];
  20446. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  20447. shapeHoles[ i ] = shapeHole.reverse();
  20448. }
  20449. }
  20450. }
  20451. var faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  20452. // join vertices of inner and outer paths to a single array
  20453. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  20454. shapeHole = shapeHoles[ i ];
  20455. shapeVertices = shapeVertices.concat( shapeHole );
  20456. }
  20457. // vertices, normals, uvs
  20458. for ( i = 0, l = shapeVertices.length; i < l; i ++ ) {
  20459. var vertex = shapeVertices[ i ];
  20460. vertices.push( vertex.x, vertex.y, 0 );
  20461. normals.push( 0, 0, 1 );
  20462. uvs.push( vertex.x, vertex.y ); // world uvs
  20463. }
  20464. // incides
  20465. for ( i = 0, l = faces.length; i < l; i ++ ) {
  20466. var face = faces[ i ];
  20467. var a = face[ 0 ] + indexOffset;
  20468. var b = face[ 1 ] + indexOffset;
  20469. var c = face[ 2 ] + indexOffset;
  20470. indices.push( a, b, c );
  20471. groupCount += 3;
  20472. }
  20473. }
  20474. }
  20475. ShapeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  20476. ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;
  20477. /**
  20478. * @author WestLangley / http://github.com/WestLangley
  20479. * @author Mugen87 / https://github.com/Mugen87
  20480. */
  20481. function EdgesGeometry( geometry, thresholdAngle ) {
  20482. BufferGeometry.call( this );
  20483. this.type = 'EdgesGeometry';
  20484. this.parameters = {
  20485. thresholdAngle: thresholdAngle
  20486. };
  20487. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  20488. // buffer
  20489. var vertices = [];
  20490. // helper variables
  20491. var thresholdDot = Math.cos( _Math.DEG2RAD * thresholdAngle );
  20492. var edge = [ 0, 0 ], edges = {};
  20493. var key, keys = [ 'a', 'b', 'c' ];
  20494. // prepare source geometry
  20495. var geometry2;
  20496. if ( geometry.isBufferGeometry ) {
  20497. geometry2 = new Geometry();
  20498. geometry2.fromBufferGeometry( geometry );
  20499. } else {
  20500. geometry2 = geometry.clone();
  20501. }
  20502. geometry2.mergeVertices();
  20503. geometry2.computeFaceNormals();
  20504. var sourceVertices = geometry2.vertices;
  20505. var faces = geometry2.faces;
  20506. // now create a data structure where each entry represents an edge with its adjoining faces
  20507. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20508. var face = faces[ i ];
  20509. for ( var j = 0; j < 3; j ++ ) {
  20510. edge[ 0 ] = face[ keys[ j ] ];
  20511. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  20512. edge.sort( sortFunction );
  20513. key = edge.toString();
  20514. if ( edges[ key ] === undefined ) {
  20515. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ], face1: i, face2: undefined };
  20516. } else {
  20517. edges[ key ].face2 = i;
  20518. }
  20519. }
  20520. }
  20521. // generate vertices
  20522. for ( key in edges ) {
  20523. var e = edges[ key ];
  20524. // an edge is only rendered if the angle (in degrees) between the face normals of the adjoining faces exceeds this value. default = 1 degree.
  20525. if ( e.face2 === undefined || faces[ e.face1 ].normal.dot( faces[ e.face2 ].normal ) <= thresholdDot ) {
  20526. var vertex = sourceVertices[ e.index1 ];
  20527. vertices.push( vertex.x, vertex.y, vertex.z );
  20528. vertex = sourceVertices[ e.index2 ];
  20529. vertices.push( vertex.x, vertex.y, vertex.z );
  20530. }
  20531. }
  20532. // build geometry
  20533. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20534. // custom array sort function
  20535. function sortFunction( a, b ) {
  20536. return a - b;
  20537. }
  20538. }
  20539. EdgesGeometry.prototype = Object.create( BufferGeometry.prototype );
  20540. EdgesGeometry.prototype.constructor = EdgesGeometry;
  20541. /**
  20542. * @author mrdoob / http://mrdoob.com/
  20543. */
  20544. function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  20545. Geometry.call( this );
  20546. this.type = 'CylinderGeometry';
  20547. this.parameters = {
  20548. radiusTop: radiusTop,
  20549. radiusBottom: radiusBottom,
  20550. height: height,
  20551. radialSegments: radialSegments,
  20552. heightSegments: heightSegments,
  20553. openEnded: openEnded,
  20554. thetaStart: thetaStart,
  20555. thetaLength: thetaLength
  20556. };
  20557. this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
  20558. this.mergeVertices();
  20559. }
  20560. CylinderGeometry.prototype = Object.create( Geometry.prototype );
  20561. CylinderGeometry.prototype.constructor = CylinderGeometry;
  20562. /**
  20563. * @author Mugen87 / https://github.com/Mugen87
  20564. */
  20565. function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  20566. BufferGeometry.call( this );
  20567. this.type = 'CylinderBufferGeometry';
  20568. this.parameters = {
  20569. radiusTop: radiusTop,
  20570. radiusBottom: radiusBottom,
  20571. height: height,
  20572. radialSegments: radialSegments,
  20573. heightSegments: heightSegments,
  20574. openEnded: openEnded,
  20575. thetaStart: thetaStart,
  20576. thetaLength: thetaLength
  20577. };
  20578. var scope = this;
  20579. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  20580. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  20581. height = height !== undefined ? height : 100;
  20582. radialSegments = Math.floor( radialSegments ) || 8;
  20583. heightSegments = Math.floor( heightSegments ) || 1;
  20584. openEnded = openEnded !== undefined ? openEnded : false;
  20585. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  20586. thetaLength = thetaLength !== undefined ? thetaLength : 2.0 * Math.PI;
  20587. // buffers
  20588. var indices = [];
  20589. var vertices = [];
  20590. var normals = [];
  20591. var uvs = [];
  20592. // helper variables
  20593. var index = 0;
  20594. var indexOffset = 0;
  20595. var indexArray = [];
  20596. var halfHeight = height / 2;
  20597. var groupStart = 0;
  20598. // generate geometry
  20599. generateTorso();
  20600. if ( openEnded === false ) {
  20601. if ( radiusTop > 0 ) generateCap( true );
  20602. if ( radiusBottom > 0 ) generateCap( false );
  20603. }
  20604. // build geometry
  20605. this.setIndex( indices );
  20606. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20607. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20608. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20609. function generateTorso() {
  20610. var x, y;
  20611. var normal = new Vector3();
  20612. var vertex = new Vector3();
  20613. var groupCount = 0;
  20614. // this will be used to calculate the normal
  20615. var slope = ( radiusBottom - radiusTop ) / height;
  20616. // generate vertices, normals and uvs
  20617. for ( y = 0; y <= heightSegments; y ++ ) {
  20618. var indexRow = [];
  20619. var v = y / heightSegments;
  20620. // calculate the radius of the current row
  20621. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  20622. for ( x = 0; x <= radialSegments; x ++ ) {
  20623. var u = x / radialSegments;
  20624. var theta = u * thetaLength + thetaStart;
  20625. var sinTheta = Math.sin( theta );
  20626. var cosTheta = Math.cos( theta );
  20627. // vertex
  20628. vertex.x = radius * sinTheta;
  20629. vertex.y = - v * height + halfHeight;
  20630. vertex.z = radius * cosTheta;
  20631. vertices.push( vertex.x, vertex.y, vertex.z );
  20632. // normal
  20633. normal.set( sinTheta, slope, cosTheta ).normalize();
  20634. normals.push( normal.x, normal.y, normal.z );
  20635. // uv
  20636. uvs.push( u, 1 - v );
  20637. // save index of vertex in respective row
  20638. indexRow.push( index ++ );
  20639. }
  20640. // now save vertices of the row in our index array
  20641. indexArray.push( indexRow );
  20642. }
  20643. // generate indices
  20644. for ( x = 0; x < radialSegments; x ++ ) {
  20645. for ( y = 0; y < heightSegments; y ++ ) {
  20646. // we use the index array to access the correct indices
  20647. var a = indexArray[ y ][ x ];
  20648. var b = indexArray[ y + 1 ][ x ];
  20649. var c = indexArray[ y + 1 ][ x + 1 ];
  20650. var d = indexArray[ y ][ x + 1 ];
  20651. // faces
  20652. indices.push( a, b, d );
  20653. indices.push( b, c, d );
  20654. // update group counter
  20655. groupCount += 6;
  20656. }
  20657. }
  20658. // add a group to the geometry. this will ensure multi material support
  20659. scope.addGroup( groupStart, groupCount, 0 );
  20660. // calculate new start value for groups
  20661. groupStart += groupCount;
  20662. }
  20663. function generateCap( top ) {
  20664. var x, centerIndexStart, centerIndexEnd;
  20665. var uv = new Vector2();
  20666. var vertex = new Vector3();
  20667. var groupCount = 0;
  20668. var radius = ( top === true ) ? radiusTop : radiusBottom;
  20669. var sign = ( top === true ) ? 1 : - 1;
  20670. // save the index of the first center vertex
  20671. centerIndexStart = index;
  20672. // first we generate the center vertex data of the cap.
  20673. // because the geometry needs one set of uvs per face,
  20674. // we must generate a center vertex per face/segment
  20675. for ( x = 1; x <= radialSegments; x ++ ) {
  20676. // vertex
  20677. vertices.push( 0, halfHeight * sign, 0 );
  20678. // normal
  20679. normals.push( 0, sign, 0 );
  20680. // uv
  20681. uvs.push( 0.5, 0.5 );
  20682. // increase index
  20683. index ++;
  20684. }
  20685. // save the index of the last center vertex
  20686. centerIndexEnd = index;
  20687. // now we generate the surrounding vertices, normals and uvs
  20688. for ( x = 0; x <= radialSegments; x ++ ) {
  20689. var u = x / radialSegments;
  20690. var theta = u * thetaLength + thetaStart;
  20691. var cosTheta = Math.cos( theta );
  20692. var sinTheta = Math.sin( theta );
  20693. // vertex
  20694. vertex.x = radius * sinTheta;
  20695. vertex.y = halfHeight * sign;
  20696. vertex.z = radius * cosTheta;
  20697. vertices.push( vertex.x, vertex.y, vertex.z );
  20698. // normal
  20699. normals.push( 0, sign, 0 );
  20700. // uv
  20701. uv.x = ( cosTheta * 0.5 ) + 0.5;
  20702. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  20703. uvs.push( uv.x, uv.y );
  20704. // increase index
  20705. index ++;
  20706. }
  20707. // generate indices
  20708. for ( x = 0; x < radialSegments; x ++ ) {
  20709. var c = centerIndexStart + x;
  20710. var i = centerIndexEnd + x;
  20711. if ( top === true ) {
  20712. // face top
  20713. indices.push( i, i + 1, c );
  20714. } else {
  20715. // face bottom
  20716. indices.push( i + 1, i, c );
  20717. }
  20718. groupCount += 3;
  20719. }
  20720. // add a group to the geometry. this will ensure multi material support
  20721. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  20722. // calculate new start value for groups
  20723. groupStart += groupCount;
  20724. }
  20725. }
  20726. CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  20727. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  20728. /**
  20729. * @author abelnation / http://github.com/abelnation
  20730. */
  20731. function ConeGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  20732. CylinderGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  20733. this.type = 'ConeGeometry';
  20734. this.parameters = {
  20735. radius: radius,
  20736. height: height,
  20737. radialSegments: radialSegments,
  20738. heightSegments: heightSegments,
  20739. openEnded: openEnded,
  20740. thetaStart: thetaStart,
  20741. thetaLength: thetaLength
  20742. };
  20743. }
  20744. ConeGeometry.prototype = Object.create( CylinderGeometry.prototype );
  20745. ConeGeometry.prototype.constructor = ConeGeometry;
  20746. /**
  20747. * @author: abelnation / http://github.com/abelnation
  20748. */
  20749. function ConeBufferGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  20750. CylinderBufferGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  20751. this.type = 'ConeBufferGeometry';
  20752. this.parameters = {
  20753. radius: radius,
  20754. height: height,
  20755. radialSegments: radialSegments,
  20756. heightSegments: heightSegments,
  20757. openEnded: openEnded,
  20758. thetaStart: thetaStart,
  20759. thetaLength: thetaLength
  20760. };
  20761. }
  20762. ConeBufferGeometry.prototype = Object.create( CylinderBufferGeometry.prototype );
  20763. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  20764. /**
  20765. * @author hughes
  20766. */
  20767. function CircleGeometry( radius, segments, thetaStart, thetaLength ) {
  20768. Geometry.call( this );
  20769. this.type = 'CircleGeometry';
  20770. this.parameters = {
  20771. radius: radius,
  20772. segments: segments,
  20773. thetaStart: thetaStart,
  20774. thetaLength: thetaLength
  20775. };
  20776. this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  20777. }
  20778. CircleGeometry.prototype = Object.create( Geometry.prototype );
  20779. CircleGeometry.prototype.constructor = CircleGeometry;
  20780. /**
  20781. * @author benaadams / https://twitter.com/ben_a_adams
  20782. * @author Mugen87 / https://github.com/Mugen87
  20783. */
  20784. function CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) {
  20785. BufferGeometry.call( this );
  20786. this.type = 'CircleBufferGeometry';
  20787. this.parameters = {
  20788. radius: radius,
  20789. segments: segments,
  20790. thetaStart: thetaStart,
  20791. thetaLength: thetaLength
  20792. };
  20793. radius = radius || 50;
  20794. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  20795. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  20796. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  20797. // buffers
  20798. var indices = [];
  20799. var vertices = [];
  20800. var normals = [];
  20801. var uvs = [];
  20802. // helper variables
  20803. var i, s;
  20804. var vertex = new Vector3();
  20805. var uv = new Vector2();
  20806. // center point
  20807. vertices.push( 0, 0, 0 );
  20808. normals.push( 0, 0, 1 );
  20809. uvs.push( 0.5, 0.5 );
  20810. for ( s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  20811. var segment = thetaStart + s / segments * thetaLength;
  20812. // vertex
  20813. vertex.x = radius * Math.cos( segment );
  20814. vertex.y = radius * Math.sin( segment );
  20815. vertices.push( vertex.x, vertex.y, vertex.z );
  20816. // normal
  20817. normals.push( 0, 0, 1 );
  20818. // uvs
  20819. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  20820. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  20821. uvs.push( uv.x, uv.y );
  20822. }
  20823. // indices
  20824. for ( i = 1; i <= segments; i ++ ) {
  20825. indices.push( i, i + 1, 0 );
  20826. }
  20827. // build geometry
  20828. this.setIndex( indices );
  20829. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20830. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20831. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20832. }
  20833. CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  20834. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  20835. var Geometries = Object.freeze({
  20836. WireframeGeometry: WireframeGeometry,
  20837. ParametricGeometry: ParametricGeometry,
  20838. ParametricBufferGeometry: ParametricBufferGeometry,
  20839. TetrahedronGeometry: TetrahedronGeometry,
  20840. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  20841. OctahedronGeometry: OctahedronGeometry,
  20842. OctahedronBufferGeometry: OctahedronBufferGeometry,
  20843. IcosahedronGeometry: IcosahedronGeometry,
  20844. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  20845. DodecahedronGeometry: DodecahedronGeometry,
  20846. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  20847. PolyhedronGeometry: PolyhedronGeometry,
  20848. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  20849. TubeGeometry: TubeGeometry,
  20850. TubeBufferGeometry: TubeBufferGeometry,
  20851. TorusKnotGeometry: TorusKnotGeometry,
  20852. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  20853. TorusGeometry: TorusGeometry,
  20854. TorusBufferGeometry: TorusBufferGeometry,
  20855. TextGeometry: TextGeometry,
  20856. SphereGeometry: SphereGeometry,
  20857. SphereBufferGeometry: SphereBufferGeometry,
  20858. RingGeometry: RingGeometry,
  20859. RingBufferGeometry: RingBufferGeometry,
  20860. PlaneGeometry: PlaneGeometry,
  20861. PlaneBufferGeometry: PlaneBufferGeometry,
  20862. LatheGeometry: LatheGeometry,
  20863. LatheBufferGeometry: LatheBufferGeometry,
  20864. ShapeGeometry: ShapeGeometry,
  20865. ShapeBufferGeometry: ShapeBufferGeometry,
  20866. ExtrudeGeometry: ExtrudeGeometry,
  20867. EdgesGeometry: EdgesGeometry,
  20868. ConeGeometry: ConeGeometry,
  20869. ConeBufferGeometry: ConeBufferGeometry,
  20870. CylinderGeometry: CylinderGeometry,
  20871. CylinderBufferGeometry: CylinderBufferGeometry,
  20872. CircleGeometry: CircleGeometry,
  20873. CircleBufferGeometry: CircleBufferGeometry,
  20874. BoxGeometry: BoxGeometry,
  20875. BoxBufferGeometry: BoxBufferGeometry
  20876. });
  20877. /**
  20878. * @author mrdoob / http://mrdoob.com/
  20879. */
  20880. function ShadowMaterial() {
  20881. ShaderMaterial.call( this, {
  20882. uniforms: UniformsUtils.merge( [
  20883. UniformsLib.lights,
  20884. {
  20885. opacity: { value: 1.0 }
  20886. }
  20887. ] ),
  20888. vertexShader: ShaderChunk[ 'shadow_vert' ],
  20889. fragmentShader: ShaderChunk[ 'shadow_frag' ]
  20890. } );
  20891. this.lights = true;
  20892. this.transparent = true;
  20893. Object.defineProperties( this, {
  20894. opacity: {
  20895. enumerable: true,
  20896. get: function () {
  20897. return this.uniforms.opacity.value;
  20898. },
  20899. set: function ( value ) {
  20900. this.uniforms.opacity.value = value;
  20901. }
  20902. }
  20903. } );
  20904. }
  20905. ShadowMaterial.prototype = Object.create( ShaderMaterial.prototype );
  20906. ShadowMaterial.prototype.constructor = ShadowMaterial;
  20907. ShadowMaterial.prototype.isShadowMaterial = true;
  20908. /**
  20909. * @author mrdoob / http://mrdoob.com/
  20910. */
  20911. function RawShaderMaterial( parameters ) {
  20912. ShaderMaterial.call( this, parameters );
  20913. this.type = 'RawShaderMaterial';
  20914. }
  20915. RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype );
  20916. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  20917. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  20918. /**
  20919. * @author mrdoob / http://mrdoob.com/
  20920. */
  20921. function MultiMaterial( materials ) {
  20922. this.uuid = _Math.generateUUID();
  20923. this.type = 'MultiMaterial';
  20924. this.materials = Array.isArray( materials ) ? materials : [];
  20925. this.visible = true;
  20926. }
  20927. MultiMaterial.prototype = {
  20928. constructor: MultiMaterial,
  20929. isMultiMaterial: true,
  20930. toJSON: function ( meta ) {
  20931. var output = {
  20932. metadata: {
  20933. version: 4.2,
  20934. type: 'material',
  20935. generator: 'MaterialExporter'
  20936. },
  20937. uuid: this.uuid,
  20938. type: this.type,
  20939. materials: []
  20940. };
  20941. var materials = this.materials;
  20942. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  20943. var material = materials[ i ].toJSON( meta );
  20944. delete material.metadata;
  20945. output.materials.push( material );
  20946. }
  20947. output.visible = this.visible;
  20948. return output;
  20949. },
  20950. clone: function () {
  20951. var material = new this.constructor();
  20952. for ( var i = 0; i < this.materials.length; i ++ ) {
  20953. material.materials.push( this.materials[ i ].clone() );
  20954. }
  20955. material.visible = this.visible;
  20956. return material;
  20957. }
  20958. };
  20959. /**
  20960. * @author WestLangley / http://github.com/WestLangley
  20961. *
  20962. * parameters = {
  20963. * color: <hex>,
  20964. * roughness: <float>,
  20965. * metalness: <float>,
  20966. * opacity: <float>,
  20967. *
  20968. * map: new THREE.Texture( <Image> ),
  20969. *
  20970. * lightMap: new THREE.Texture( <Image> ),
  20971. * lightMapIntensity: <float>
  20972. *
  20973. * aoMap: new THREE.Texture( <Image> ),
  20974. * aoMapIntensity: <float>
  20975. *
  20976. * emissive: <hex>,
  20977. * emissiveIntensity: <float>
  20978. * emissiveMap: new THREE.Texture( <Image> ),
  20979. *
  20980. * bumpMap: new THREE.Texture( <Image> ),
  20981. * bumpScale: <float>,
  20982. *
  20983. * normalMap: new THREE.Texture( <Image> ),
  20984. * normalScale: <Vector2>,
  20985. *
  20986. * displacementMap: new THREE.Texture( <Image> ),
  20987. * displacementScale: <float>,
  20988. * displacementBias: <float>,
  20989. *
  20990. * roughnessMap: new THREE.Texture( <Image> ),
  20991. *
  20992. * metalnessMap: new THREE.Texture( <Image> ),
  20993. *
  20994. * alphaMap: new THREE.Texture( <Image> ),
  20995. *
  20996. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20997. * envMapIntensity: <float>
  20998. *
  20999. * refractionRatio: <float>,
  21000. *
  21001. * wireframe: <boolean>,
  21002. * wireframeLinewidth: <float>,
  21003. *
  21004. * skinning: <bool>,
  21005. * morphTargets: <bool>,
  21006. * morphNormals: <bool>
  21007. * }
  21008. */
  21009. function MeshStandardMaterial( parameters ) {
  21010. Material.call( this );
  21011. this.defines = { 'STANDARD': '' };
  21012. this.type = 'MeshStandardMaterial';
  21013. this.color = new Color( 0xffffff ); // diffuse
  21014. this.roughness = 0.5;
  21015. this.metalness = 0.5;
  21016. this.map = null;
  21017. this.lightMap = null;
  21018. this.lightMapIntensity = 1.0;
  21019. this.aoMap = null;
  21020. this.aoMapIntensity = 1.0;
  21021. this.emissive = new Color( 0x000000 );
  21022. this.emissiveIntensity = 1.0;
  21023. this.emissiveMap = null;
  21024. this.bumpMap = null;
  21025. this.bumpScale = 1;
  21026. this.normalMap = null;
  21027. this.normalScale = new Vector2( 1, 1 );
  21028. this.displacementMap = null;
  21029. this.displacementScale = 1;
  21030. this.displacementBias = 0;
  21031. this.roughnessMap = null;
  21032. this.metalnessMap = null;
  21033. this.alphaMap = null;
  21034. this.envMap = null;
  21035. this.envMapIntensity = 1.0;
  21036. this.refractionRatio = 0.98;
  21037. this.wireframe = false;
  21038. this.wireframeLinewidth = 1;
  21039. this.wireframeLinecap = 'round';
  21040. this.wireframeLinejoin = 'round';
  21041. this.skinning = false;
  21042. this.morphTargets = false;
  21043. this.morphNormals = false;
  21044. this.setValues( parameters );
  21045. }
  21046. MeshStandardMaterial.prototype = Object.create( Material.prototype );
  21047. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  21048. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  21049. MeshStandardMaterial.prototype.copy = function ( source ) {
  21050. Material.prototype.copy.call( this, source );
  21051. this.defines = { 'STANDARD': '' };
  21052. this.color.copy( source.color );
  21053. this.roughness = source.roughness;
  21054. this.metalness = source.metalness;
  21055. this.map = source.map;
  21056. this.lightMap = source.lightMap;
  21057. this.lightMapIntensity = source.lightMapIntensity;
  21058. this.aoMap = source.aoMap;
  21059. this.aoMapIntensity = source.aoMapIntensity;
  21060. this.emissive.copy( source.emissive );
  21061. this.emissiveMap = source.emissiveMap;
  21062. this.emissiveIntensity = source.emissiveIntensity;
  21063. this.bumpMap = source.bumpMap;
  21064. this.bumpScale = source.bumpScale;
  21065. this.normalMap = source.normalMap;
  21066. this.normalScale.copy( source.normalScale );
  21067. this.displacementMap = source.displacementMap;
  21068. this.displacementScale = source.displacementScale;
  21069. this.displacementBias = source.displacementBias;
  21070. this.roughnessMap = source.roughnessMap;
  21071. this.metalnessMap = source.metalnessMap;
  21072. this.alphaMap = source.alphaMap;
  21073. this.envMap = source.envMap;
  21074. this.envMapIntensity = source.envMapIntensity;
  21075. this.refractionRatio = source.refractionRatio;
  21076. this.wireframe = source.wireframe;
  21077. this.wireframeLinewidth = source.wireframeLinewidth;
  21078. this.wireframeLinecap = source.wireframeLinecap;
  21079. this.wireframeLinejoin = source.wireframeLinejoin;
  21080. this.skinning = source.skinning;
  21081. this.morphTargets = source.morphTargets;
  21082. this.morphNormals = source.morphNormals;
  21083. return this;
  21084. };
  21085. /**
  21086. * @author WestLangley / http://github.com/WestLangley
  21087. *
  21088. * parameters = {
  21089. * reflectivity: <float>
  21090. * }
  21091. */
  21092. function MeshPhysicalMaterial( parameters ) {
  21093. MeshStandardMaterial.call( this );
  21094. this.defines = { 'PHYSICAL': '' };
  21095. this.type = 'MeshPhysicalMaterial';
  21096. this.reflectivity = 0.5; // maps to F0 = 0.04
  21097. this.clearCoat = 0.0;
  21098. this.clearCoatRoughness = 0.0;
  21099. this.setValues( parameters );
  21100. }
  21101. MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
  21102. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  21103. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  21104. MeshPhysicalMaterial.prototype.copy = function ( source ) {
  21105. MeshStandardMaterial.prototype.copy.call( this, source );
  21106. this.defines = { 'PHYSICAL': '' };
  21107. this.reflectivity = source.reflectivity;
  21108. this.clearCoat = source.clearCoat;
  21109. this.clearCoatRoughness = source.clearCoatRoughness;
  21110. return this;
  21111. };
  21112. /**
  21113. * @author mrdoob / http://mrdoob.com/
  21114. * @author alteredq / http://alteredqualia.com/
  21115. *
  21116. * parameters = {
  21117. * color: <hex>,
  21118. * specular: <hex>,
  21119. * shininess: <float>,
  21120. * opacity: <float>,
  21121. *
  21122. * map: new THREE.Texture( <Image> ),
  21123. *
  21124. * lightMap: new THREE.Texture( <Image> ),
  21125. * lightMapIntensity: <float>
  21126. *
  21127. * aoMap: new THREE.Texture( <Image> ),
  21128. * aoMapIntensity: <float>
  21129. *
  21130. * emissive: <hex>,
  21131. * emissiveIntensity: <float>
  21132. * emissiveMap: new THREE.Texture( <Image> ),
  21133. *
  21134. * bumpMap: new THREE.Texture( <Image> ),
  21135. * bumpScale: <float>,
  21136. *
  21137. * normalMap: new THREE.Texture( <Image> ),
  21138. * normalScale: <Vector2>,
  21139. *
  21140. * displacementMap: new THREE.Texture( <Image> ),
  21141. * displacementScale: <float>,
  21142. * displacementBias: <float>,
  21143. *
  21144. * specularMap: new THREE.Texture( <Image> ),
  21145. *
  21146. * alphaMap: new THREE.Texture( <Image> ),
  21147. *
  21148. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  21149. * combine: THREE.Multiply,
  21150. * reflectivity: <float>,
  21151. * refractionRatio: <float>,
  21152. *
  21153. * wireframe: <boolean>,
  21154. * wireframeLinewidth: <float>,
  21155. *
  21156. * skinning: <bool>,
  21157. * morphTargets: <bool>,
  21158. * morphNormals: <bool>
  21159. * }
  21160. */
  21161. function MeshPhongMaterial( parameters ) {
  21162. Material.call( this );
  21163. this.type = 'MeshPhongMaterial';
  21164. this.color = new Color( 0xffffff ); // diffuse
  21165. this.specular = new Color( 0x111111 );
  21166. this.shininess = 30;
  21167. this.map = null;
  21168. this.lightMap = null;
  21169. this.lightMapIntensity = 1.0;
  21170. this.aoMap = null;
  21171. this.aoMapIntensity = 1.0;
  21172. this.emissive = new Color( 0x000000 );
  21173. this.emissiveIntensity = 1.0;
  21174. this.emissiveMap = null;
  21175. this.bumpMap = null;
  21176. this.bumpScale = 1;
  21177. this.normalMap = null;
  21178. this.normalScale = new Vector2( 1, 1 );
  21179. this.displacementMap = null;
  21180. this.displacementScale = 1;
  21181. this.displacementBias = 0;
  21182. this.specularMap = null;
  21183. this.alphaMap = null;
  21184. this.envMap = null;
  21185. this.combine = MultiplyOperation;
  21186. this.reflectivity = 1;
  21187. this.refractionRatio = 0.98;
  21188. this.wireframe = false;
  21189. this.wireframeLinewidth = 1;
  21190. this.wireframeLinecap = 'round';
  21191. this.wireframeLinejoin = 'round';
  21192. this.skinning = false;
  21193. this.morphTargets = false;
  21194. this.morphNormals = false;
  21195. this.setValues( parameters );
  21196. }
  21197. MeshPhongMaterial.prototype = Object.create( Material.prototype );
  21198. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  21199. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  21200. MeshPhongMaterial.prototype.copy = function ( source ) {
  21201. Material.prototype.copy.call( this, source );
  21202. this.color.copy( source.color );
  21203. this.specular.copy( source.specular );
  21204. this.shininess = source.shininess;
  21205. this.map = source.map;
  21206. this.lightMap = source.lightMap;
  21207. this.lightMapIntensity = source.lightMapIntensity;
  21208. this.aoMap = source.aoMap;
  21209. this.aoMapIntensity = source.aoMapIntensity;
  21210. this.emissive.copy( source.emissive );
  21211. this.emissiveMap = source.emissiveMap;
  21212. this.emissiveIntensity = source.emissiveIntensity;
  21213. this.bumpMap = source.bumpMap;
  21214. this.bumpScale = source.bumpScale;
  21215. this.normalMap = source.normalMap;
  21216. this.normalScale.copy( source.normalScale );
  21217. this.displacementMap = source.displacementMap;
  21218. this.displacementScale = source.displacementScale;
  21219. this.displacementBias = source.displacementBias;
  21220. this.specularMap = source.specularMap;
  21221. this.alphaMap = source.alphaMap;
  21222. this.envMap = source.envMap;
  21223. this.combine = source.combine;
  21224. this.reflectivity = source.reflectivity;
  21225. this.refractionRatio = source.refractionRatio;
  21226. this.wireframe = source.wireframe;
  21227. this.wireframeLinewidth = source.wireframeLinewidth;
  21228. this.wireframeLinecap = source.wireframeLinecap;
  21229. this.wireframeLinejoin = source.wireframeLinejoin;
  21230. this.skinning = source.skinning;
  21231. this.morphTargets = source.morphTargets;
  21232. this.morphNormals = source.morphNormals;
  21233. return this;
  21234. };
  21235. /**
  21236. * @author takahirox / http://github.com/takahirox
  21237. *
  21238. * parameters = {
  21239. * gradientMap: new THREE.Texture( <Image> )
  21240. * }
  21241. */
  21242. function MeshToonMaterial( parameters ) {
  21243. MeshPhongMaterial.call( this );
  21244. this.defines = { 'TOON': '' };
  21245. this.type = 'MeshToonMaterial';
  21246. this.gradientMap = null;
  21247. this.setValues( parameters );
  21248. }
  21249. MeshToonMaterial.prototype = Object.create( MeshPhongMaterial.prototype );
  21250. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  21251. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  21252. MeshToonMaterial.prototype.copy = function ( source ) {
  21253. MeshPhongMaterial.prototype.copy.call( this, source );
  21254. this.gradientMap = source.gradientMap;
  21255. return this;
  21256. };
  21257. /**
  21258. * @author mrdoob / http://mrdoob.com/
  21259. * @author WestLangley / http://github.com/WestLangley
  21260. *
  21261. * parameters = {
  21262. * opacity: <float>,
  21263. *
  21264. * bumpMap: new THREE.Texture( <Image> ),
  21265. * bumpScale: <float>,
  21266. *
  21267. * normalMap: new THREE.Texture( <Image> ),
  21268. * normalScale: <Vector2>,
  21269. *
  21270. * displacementMap: new THREE.Texture( <Image> ),
  21271. * displacementScale: <float>,
  21272. * displacementBias: <float>,
  21273. *
  21274. * wireframe: <boolean>,
  21275. * wireframeLinewidth: <float>
  21276. *
  21277. * skinning: <bool>,
  21278. * morphTargets: <bool>,
  21279. * morphNormals: <bool>
  21280. * }
  21281. */
  21282. function MeshNormalMaterial( parameters ) {
  21283. Material.call( this, parameters );
  21284. this.type = 'MeshNormalMaterial';
  21285. this.bumpMap = null;
  21286. this.bumpScale = 1;
  21287. this.normalMap = null;
  21288. this.normalScale = new Vector2( 1, 1 );
  21289. this.displacementMap = null;
  21290. this.displacementScale = 1;
  21291. this.displacementBias = 0;
  21292. this.wireframe = false;
  21293. this.wireframeLinewidth = 1;
  21294. this.fog = false;
  21295. this.lights = false;
  21296. this.skinning = false;
  21297. this.morphTargets = false;
  21298. this.morphNormals = false;
  21299. this.setValues( parameters );
  21300. }
  21301. MeshNormalMaterial.prototype = Object.create( Material.prototype );
  21302. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  21303. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  21304. MeshNormalMaterial.prototype.copy = function ( source ) {
  21305. Material.prototype.copy.call( this, source );
  21306. this.bumpMap = source.bumpMap;
  21307. this.bumpScale = source.bumpScale;
  21308. this.normalMap = source.normalMap;
  21309. this.normalScale.copy( source.normalScale );
  21310. this.displacementMap = source.displacementMap;
  21311. this.displacementScale = source.displacementScale;
  21312. this.displacementBias = source.displacementBias;
  21313. this.wireframe = source.wireframe;
  21314. this.wireframeLinewidth = source.wireframeLinewidth;
  21315. this.skinning = source.skinning;
  21316. this.morphTargets = source.morphTargets;
  21317. this.morphNormals = source.morphNormals;
  21318. return this;
  21319. };
  21320. /**
  21321. * @author mrdoob / http://mrdoob.com/
  21322. * @author alteredq / http://alteredqualia.com/
  21323. *
  21324. * parameters = {
  21325. * color: <hex>,
  21326. * opacity: <float>,
  21327. *
  21328. * map: new THREE.Texture( <Image> ),
  21329. *
  21330. * lightMap: new THREE.Texture( <Image> ),
  21331. * lightMapIntensity: <float>
  21332. *
  21333. * aoMap: new THREE.Texture( <Image> ),
  21334. * aoMapIntensity: <float>
  21335. *
  21336. * emissive: <hex>,
  21337. * emissiveIntensity: <float>
  21338. * emissiveMap: new THREE.Texture( <Image> ),
  21339. *
  21340. * specularMap: new THREE.Texture( <Image> ),
  21341. *
  21342. * alphaMap: new THREE.Texture( <Image> ),
  21343. *
  21344. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  21345. * combine: THREE.Multiply,
  21346. * reflectivity: <float>,
  21347. * refractionRatio: <float>,
  21348. *
  21349. * wireframe: <boolean>,
  21350. * wireframeLinewidth: <float>,
  21351. *
  21352. * skinning: <bool>,
  21353. * morphTargets: <bool>,
  21354. * morphNormals: <bool>
  21355. * }
  21356. */
  21357. function MeshLambertMaterial( parameters ) {
  21358. Material.call( this );
  21359. this.type = 'MeshLambertMaterial';
  21360. this.color = new Color( 0xffffff ); // diffuse
  21361. this.map = null;
  21362. this.lightMap = null;
  21363. this.lightMapIntensity = 1.0;
  21364. this.aoMap = null;
  21365. this.aoMapIntensity = 1.0;
  21366. this.emissive = new Color( 0x000000 );
  21367. this.emissiveIntensity = 1.0;
  21368. this.emissiveMap = null;
  21369. this.specularMap = null;
  21370. this.alphaMap = null;
  21371. this.envMap = null;
  21372. this.combine = MultiplyOperation;
  21373. this.reflectivity = 1;
  21374. this.refractionRatio = 0.98;
  21375. this.wireframe = false;
  21376. this.wireframeLinewidth = 1;
  21377. this.wireframeLinecap = 'round';
  21378. this.wireframeLinejoin = 'round';
  21379. this.skinning = false;
  21380. this.morphTargets = false;
  21381. this.morphNormals = false;
  21382. this.setValues( parameters );
  21383. }
  21384. MeshLambertMaterial.prototype = Object.create( Material.prototype );
  21385. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  21386. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  21387. MeshLambertMaterial.prototype.copy = function ( source ) {
  21388. Material.prototype.copy.call( this, source );
  21389. this.color.copy( source.color );
  21390. this.map = source.map;
  21391. this.lightMap = source.lightMap;
  21392. this.lightMapIntensity = source.lightMapIntensity;
  21393. this.aoMap = source.aoMap;
  21394. this.aoMapIntensity = source.aoMapIntensity;
  21395. this.emissive.copy( source.emissive );
  21396. this.emissiveMap = source.emissiveMap;
  21397. this.emissiveIntensity = source.emissiveIntensity;
  21398. this.specularMap = source.specularMap;
  21399. this.alphaMap = source.alphaMap;
  21400. this.envMap = source.envMap;
  21401. this.combine = source.combine;
  21402. this.reflectivity = source.reflectivity;
  21403. this.refractionRatio = source.refractionRatio;
  21404. this.wireframe = source.wireframe;
  21405. this.wireframeLinewidth = source.wireframeLinewidth;
  21406. this.wireframeLinecap = source.wireframeLinecap;
  21407. this.wireframeLinejoin = source.wireframeLinejoin;
  21408. this.skinning = source.skinning;
  21409. this.morphTargets = source.morphTargets;
  21410. this.morphNormals = source.morphNormals;
  21411. return this;
  21412. };
  21413. /**
  21414. * @author alteredq / http://alteredqualia.com/
  21415. *
  21416. * parameters = {
  21417. * color: <hex>,
  21418. * opacity: <float>,
  21419. *
  21420. * linewidth: <float>,
  21421. *
  21422. * scale: <float>,
  21423. * dashSize: <float>,
  21424. * gapSize: <float>
  21425. * }
  21426. */
  21427. function LineDashedMaterial( parameters ) {
  21428. Material.call( this );
  21429. this.type = 'LineDashedMaterial';
  21430. this.color = new Color( 0xffffff );
  21431. this.linewidth = 1;
  21432. this.scale = 1;
  21433. this.dashSize = 3;
  21434. this.gapSize = 1;
  21435. this.lights = false;
  21436. this.setValues( parameters );
  21437. }
  21438. LineDashedMaterial.prototype = Object.create( Material.prototype );
  21439. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  21440. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  21441. LineDashedMaterial.prototype.copy = function ( source ) {
  21442. Material.prototype.copy.call( this, source );
  21443. this.color.copy( source.color );
  21444. this.linewidth = source.linewidth;
  21445. this.scale = source.scale;
  21446. this.dashSize = source.dashSize;
  21447. this.gapSize = source.gapSize;
  21448. return this;
  21449. };
  21450. var Materials = Object.freeze({
  21451. ShadowMaterial: ShadowMaterial,
  21452. SpriteMaterial: SpriteMaterial,
  21453. RawShaderMaterial: RawShaderMaterial,
  21454. ShaderMaterial: ShaderMaterial,
  21455. PointsMaterial: PointsMaterial,
  21456. MultiMaterial: MultiMaterial,
  21457. MeshPhysicalMaterial: MeshPhysicalMaterial,
  21458. MeshStandardMaterial: MeshStandardMaterial,
  21459. MeshPhongMaterial: MeshPhongMaterial,
  21460. MeshToonMaterial: MeshToonMaterial,
  21461. MeshNormalMaterial: MeshNormalMaterial,
  21462. MeshLambertMaterial: MeshLambertMaterial,
  21463. MeshDepthMaterial: MeshDepthMaterial,
  21464. MeshBasicMaterial: MeshBasicMaterial,
  21465. LineDashedMaterial: LineDashedMaterial,
  21466. LineBasicMaterial: LineBasicMaterial,
  21467. Material: Material
  21468. });
  21469. /**
  21470. * @author mrdoob / http://mrdoob.com/
  21471. */
  21472. var Cache = {
  21473. enabled: false,
  21474. files: {},
  21475. add: function ( key, file ) {
  21476. if ( this.enabled === false ) return;
  21477. // console.log( 'THREE.Cache', 'Adding key:', key );
  21478. this.files[ key ] = file;
  21479. },
  21480. get: function ( key ) {
  21481. if ( this.enabled === false ) return;
  21482. // console.log( 'THREE.Cache', 'Checking key:', key );
  21483. return this.files[ key ];
  21484. },
  21485. remove: function ( key ) {
  21486. delete this.files[ key ];
  21487. },
  21488. clear: function () {
  21489. this.files = {};
  21490. }
  21491. };
  21492. /**
  21493. * @author mrdoob / http://mrdoob.com/
  21494. */
  21495. function LoadingManager( onLoad, onProgress, onError ) {
  21496. var scope = this;
  21497. var isLoading = false, itemsLoaded = 0, itemsTotal = 0;
  21498. this.onStart = undefined;
  21499. this.onLoad = onLoad;
  21500. this.onProgress = onProgress;
  21501. this.onError = onError;
  21502. this.itemStart = function ( url ) {
  21503. itemsTotal ++;
  21504. if ( isLoading === false ) {
  21505. if ( scope.onStart !== undefined ) {
  21506. scope.onStart( url, itemsLoaded, itemsTotal );
  21507. }
  21508. }
  21509. isLoading = true;
  21510. };
  21511. this.itemEnd = function ( url ) {
  21512. itemsLoaded ++;
  21513. if ( scope.onProgress !== undefined ) {
  21514. scope.onProgress( url, itemsLoaded, itemsTotal );
  21515. }
  21516. if ( itemsLoaded === itemsTotal ) {
  21517. isLoading = false;
  21518. if ( scope.onLoad !== undefined ) {
  21519. scope.onLoad();
  21520. }
  21521. }
  21522. };
  21523. this.itemError = function ( url ) {
  21524. if ( scope.onError !== undefined ) {
  21525. scope.onError( url );
  21526. }
  21527. };
  21528. }
  21529. var DefaultLoadingManager = new LoadingManager();
  21530. /**
  21531. * @author mrdoob / http://mrdoob.com/
  21532. */
  21533. function FileLoader( manager ) {
  21534. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  21535. }
  21536. Object.assign( FileLoader.prototype, {
  21537. load: function ( url, onLoad, onProgress, onError ) {
  21538. if ( url === undefined ) url = '';
  21539. if ( this.path !== undefined ) url = this.path + url;
  21540. var scope = this;
  21541. var cached = Cache.get( url );
  21542. if ( cached !== undefined ) {
  21543. scope.manager.itemStart( url );
  21544. setTimeout( function () {
  21545. if ( onLoad ) onLoad( cached );
  21546. scope.manager.itemEnd( url );
  21547. }, 0 );
  21548. return cached;
  21549. }
  21550. // Check for data: URI
  21551. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  21552. var dataUriRegexResult = url.match( dataUriRegex );
  21553. // Safari can not handle Data URIs through XMLHttpRequest so process manually
  21554. if ( dataUriRegexResult ) {
  21555. var mimeType = dataUriRegexResult[ 1 ];
  21556. var isBase64 = !! dataUriRegexResult[ 2 ];
  21557. var data = dataUriRegexResult[ 3 ];
  21558. data = window.decodeURIComponent( data );
  21559. if ( isBase64 ) data = window.atob( data );
  21560. try {
  21561. var response;
  21562. var responseType = ( this.responseType || '' ).toLowerCase();
  21563. switch ( responseType ) {
  21564. case 'arraybuffer':
  21565. case 'blob':
  21566. response = new ArrayBuffer( data.length );
  21567. var view = new Uint8Array( response );
  21568. for ( var i = 0; i < data.length; i ++ ) {
  21569. view[ i ] = data.charCodeAt( i );
  21570. }
  21571. if ( responseType === 'blob' ) {
  21572. response = new Blob( [ response ], { type: mimeType } );
  21573. }
  21574. break;
  21575. case 'document':
  21576. var parser = new DOMParser();
  21577. response = parser.parseFromString( data, mimeType );
  21578. break;
  21579. case 'json':
  21580. response = JSON.parse( data );
  21581. break;
  21582. default: // 'text' or other
  21583. response = data;
  21584. break;
  21585. }
  21586. // Wait for next browser tick
  21587. window.setTimeout( function () {
  21588. if ( onLoad ) onLoad( response );
  21589. scope.manager.itemEnd( url );
  21590. }, 0 );
  21591. } catch ( error ) {
  21592. // Wait for next browser tick
  21593. window.setTimeout( function () {
  21594. if ( onError ) onError( error );
  21595. scope.manager.itemError( url );
  21596. }, 0 );
  21597. }
  21598. } else {
  21599. var request = new XMLHttpRequest();
  21600. request.open( 'GET', url, true );
  21601. request.addEventListener( 'load', function ( event ) {
  21602. var response = event.target.response;
  21603. Cache.add( url, response );
  21604. if ( this.status === 200 ) {
  21605. if ( onLoad ) onLoad( response );
  21606. scope.manager.itemEnd( url );
  21607. } else if ( this.status === 0 ) {
  21608. // Some browsers return HTTP Status 0 when using non-http protocol
  21609. // e.g. 'file://' or 'data://'. Handle as success.
  21610. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  21611. if ( onLoad ) onLoad( response );
  21612. scope.manager.itemEnd( url );
  21613. } else {
  21614. if ( onError ) onError( event );
  21615. scope.manager.itemError( url );
  21616. }
  21617. }, false );
  21618. if ( onProgress !== undefined ) {
  21619. request.addEventListener( 'progress', function ( event ) {
  21620. onProgress( event );
  21621. }, false );
  21622. }
  21623. request.addEventListener( 'error', function ( event ) {
  21624. if ( onError ) onError( event );
  21625. scope.manager.itemError( url );
  21626. }, false );
  21627. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  21628. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  21629. if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );
  21630. request.send( null );
  21631. }
  21632. scope.manager.itemStart( url );
  21633. return request;
  21634. },
  21635. setPath: function ( value ) {
  21636. this.path = value;
  21637. return this;
  21638. },
  21639. setResponseType: function ( value ) {
  21640. this.responseType = value;
  21641. return this;
  21642. },
  21643. setWithCredentials: function ( value ) {
  21644. this.withCredentials = value;
  21645. return this;
  21646. },
  21647. setMimeType: function ( value ) {
  21648. this.mimeType = value;
  21649. return this;
  21650. }
  21651. } );
  21652. /**
  21653. * @author mrdoob / http://mrdoob.com/
  21654. *
  21655. * Abstract Base class to block based textures loader (dds, pvr, ...)
  21656. */
  21657. function CompressedTextureLoader( manager ) {
  21658. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  21659. // override in sub classes
  21660. this._parser = null;
  21661. }
  21662. Object.assign( CompressedTextureLoader.prototype, {
  21663. load: function ( url, onLoad, onProgress, onError ) {
  21664. var scope = this;
  21665. var images = [];
  21666. var texture = new CompressedTexture();
  21667. texture.image = images;
  21668. var loader = new FileLoader( this.manager );
  21669. loader.setPath( this.path );
  21670. loader.setResponseType( 'arraybuffer' );
  21671. function loadTexture( i ) {
  21672. loader.load( url[ i ], function ( buffer ) {
  21673. var texDatas = scope._parser( buffer, true );
  21674. images[ i ] = {
  21675. width: texDatas.width,
  21676. height: texDatas.height,
  21677. format: texDatas.format,
  21678. mipmaps: texDatas.mipmaps
  21679. };
  21680. loaded += 1;
  21681. if ( loaded === 6 ) {
  21682. if ( texDatas.mipmapCount === 1 )
  21683. texture.minFilter = LinearFilter;
  21684. texture.format = texDatas.format;
  21685. texture.needsUpdate = true;
  21686. if ( onLoad ) onLoad( texture );
  21687. }
  21688. }, onProgress, onError );
  21689. }
  21690. if ( Array.isArray( url ) ) {
  21691. var loaded = 0;
  21692. for ( var i = 0, il = url.length; i < il; ++ i ) {
  21693. loadTexture( i );
  21694. }
  21695. } else {
  21696. // compressed cubemap texture stored in a single DDS file
  21697. loader.load( url, function ( buffer ) {
  21698. var texDatas = scope._parser( buffer, true );
  21699. if ( texDatas.isCubemap ) {
  21700. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  21701. for ( var f = 0; f < faces; f ++ ) {
  21702. images[ f ] = { mipmaps : [] };
  21703. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  21704. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  21705. images[ f ].format = texDatas.format;
  21706. images[ f ].width = texDatas.width;
  21707. images[ f ].height = texDatas.height;
  21708. }
  21709. }
  21710. } else {
  21711. texture.image.width = texDatas.width;
  21712. texture.image.height = texDatas.height;
  21713. texture.mipmaps = texDatas.mipmaps;
  21714. }
  21715. if ( texDatas.mipmapCount === 1 ) {
  21716. texture.minFilter = LinearFilter;
  21717. }
  21718. texture.format = texDatas.format;
  21719. texture.needsUpdate = true;
  21720. if ( onLoad ) onLoad( texture );
  21721. }, onProgress, onError );
  21722. }
  21723. return texture;
  21724. },
  21725. setPath: function ( value ) {
  21726. this.path = value;
  21727. return this;
  21728. }
  21729. } );
  21730. /**
  21731. * @author Nikos M. / https://github.com/foo123/
  21732. *
  21733. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  21734. */
  21735. function DataTextureLoader( manager ) {
  21736. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  21737. // override in sub classes
  21738. this._parser = null;
  21739. }
  21740. Object.assign( DataTextureLoader.prototype, {
  21741. load: function ( url, onLoad, onProgress, onError ) {
  21742. var scope = this;
  21743. var texture = new DataTexture();
  21744. var loader = new FileLoader( this.manager );
  21745. loader.setResponseType( 'arraybuffer' );
  21746. loader.load( url, function ( buffer ) {
  21747. var texData = scope._parser( buffer );
  21748. if ( ! texData ) return;
  21749. if ( undefined !== texData.image ) {
  21750. texture.image = texData.image;
  21751. } else if ( undefined !== texData.data ) {
  21752. texture.image.width = texData.width;
  21753. texture.image.height = texData.height;
  21754. texture.image.data = texData.data;
  21755. }
  21756. texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : ClampToEdgeWrapping;
  21757. texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : ClampToEdgeWrapping;
  21758. texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : LinearFilter;
  21759. texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : LinearMipMapLinearFilter;
  21760. texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1;
  21761. if ( undefined !== texData.format ) {
  21762. texture.format = texData.format;
  21763. }
  21764. if ( undefined !== texData.type ) {
  21765. texture.type = texData.type;
  21766. }
  21767. if ( undefined !== texData.mipmaps ) {
  21768. texture.mipmaps = texData.mipmaps;
  21769. }
  21770. if ( 1 === texData.mipmapCount ) {
  21771. texture.minFilter = LinearFilter;
  21772. }
  21773. texture.needsUpdate = true;
  21774. if ( onLoad ) onLoad( texture, texData );
  21775. }, onProgress, onError );
  21776. return texture;
  21777. }
  21778. } );
  21779. /**
  21780. * @author mrdoob / http://mrdoob.com/
  21781. */
  21782. function ImageLoader( manager ) {
  21783. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  21784. }
  21785. Object.assign( ImageLoader.prototype, {
  21786. load: function ( url, onLoad, onProgress, onError ) {
  21787. if ( url === undefined ) url = '';
  21788. if ( this.path !== undefined ) url = this.path + url;
  21789. var scope = this;
  21790. var cached = Cache.get( url );
  21791. if ( cached !== undefined ) {
  21792. scope.manager.itemStart( url );
  21793. setTimeout( function () {
  21794. if ( onLoad ) onLoad( cached );
  21795. scope.manager.itemEnd( url );
  21796. }, 0 );
  21797. return cached;
  21798. }
  21799. var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  21800. image.addEventListener( 'load', function () {
  21801. Cache.add( url, this );
  21802. if ( onLoad ) onLoad( this );
  21803. scope.manager.itemEnd( url );
  21804. }, false );
  21805. /*
  21806. image.addEventListener( 'progress', function ( event ) {
  21807. if ( onProgress ) onProgress( event );
  21808. }, false );
  21809. */
  21810. image.addEventListener( 'error', function ( event ) {
  21811. if ( onError ) onError( event );
  21812. scope.manager.itemError( url );
  21813. }, false );
  21814. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  21815. scope.manager.itemStart( url );
  21816. image.src = url;
  21817. return image;
  21818. },
  21819. setCrossOrigin: function ( value ) {
  21820. this.crossOrigin = value;
  21821. return this;
  21822. },
  21823. setPath: function ( value ) {
  21824. this.path = value;
  21825. return this;
  21826. }
  21827. } );
  21828. /**
  21829. * @author mrdoob / http://mrdoob.com/
  21830. */
  21831. function CubeTextureLoader( manager ) {
  21832. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  21833. }
  21834. Object.assign( CubeTextureLoader.prototype, {
  21835. load: function ( urls, onLoad, onProgress, onError ) {
  21836. var texture = new CubeTexture();
  21837. var loader = new ImageLoader( this.manager );
  21838. loader.setCrossOrigin( this.crossOrigin );
  21839. loader.setPath( this.path );
  21840. var loaded = 0;
  21841. function loadTexture( i ) {
  21842. loader.load( urls[ i ], function ( image ) {
  21843. texture.images[ i ] = image;
  21844. loaded ++;
  21845. if ( loaded === 6 ) {
  21846. texture.needsUpdate = true;
  21847. if ( onLoad ) onLoad( texture );
  21848. }
  21849. }, undefined, onError );
  21850. }
  21851. for ( var i = 0; i < urls.length; ++ i ) {
  21852. loadTexture( i );
  21853. }
  21854. return texture;
  21855. },
  21856. setCrossOrigin: function ( value ) {
  21857. this.crossOrigin = value;
  21858. return this;
  21859. },
  21860. setPath: function ( value ) {
  21861. this.path = value;
  21862. return this;
  21863. }
  21864. } );
  21865. /**
  21866. * @author mrdoob / http://mrdoob.com/
  21867. */
  21868. function TextureLoader( manager ) {
  21869. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  21870. }
  21871. Object.assign( TextureLoader.prototype, {
  21872. load: function ( url, onLoad, onProgress, onError ) {
  21873. var texture = new Texture();
  21874. var loader = new ImageLoader( this.manager );
  21875. loader.setCrossOrigin( this.crossOrigin );
  21876. loader.setPath( this.path );
  21877. loader.load( url, function ( image ) {
  21878. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  21879. var isJPEG = url.search( /\.(jpg|jpeg)$/ ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  21880. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  21881. texture.image = image;
  21882. texture.needsUpdate = true;
  21883. if ( onLoad !== undefined ) {
  21884. onLoad( texture );
  21885. }
  21886. }, onProgress, onError );
  21887. return texture;
  21888. },
  21889. setCrossOrigin: function ( value ) {
  21890. this.crossOrigin = value;
  21891. return this;
  21892. },
  21893. setPath: function ( value ) {
  21894. this.path = value;
  21895. return this;
  21896. }
  21897. } );
  21898. /**
  21899. * @author mrdoob / http://mrdoob.com/
  21900. * @author alteredq / http://alteredqualia.com/
  21901. */
  21902. function Light( color, intensity ) {
  21903. Object3D.call( this );
  21904. this.type = 'Light';
  21905. this.color = new Color( color );
  21906. this.intensity = intensity !== undefined ? intensity : 1;
  21907. this.receiveShadow = undefined;
  21908. }
  21909. Light.prototype = Object.assign( Object.create( Object3D.prototype ), {
  21910. constructor: Light,
  21911. isLight: true,
  21912. copy: function ( source ) {
  21913. Object3D.prototype.copy.call( this, source );
  21914. this.color.copy( source.color );
  21915. this.intensity = source.intensity;
  21916. return this;
  21917. },
  21918. toJSON: function ( meta ) {
  21919. var data = Object3D.prototype.toJSON.call( this, meta );
  21920. data.object.color = this.color.getHex();
  21921. data.object.intensity = this.intensity;
  21922. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  21923. if ( this.distance !== undefined ) data.object.distance = this.distance;
  21924. if ( this.angle !== undefined ) data.object.angle = this.angle;
  21925. if ( this.decay !== undefined ) data.object.decay = this.decay;
  21926. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  21927. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  21928. return data;
  21929. }
  21930. } );
  21931. /**
  21932. * @author alteredq / http://alteredqualia.com/
  21933. */
  21934. function HemisphereLight( skyColor, groundColor, intensity ) {
  21935. Light.call( this, skyColor, intensity );
  21936. this.type = 'HemisphereLight';
  21937. this.castShadow = undefined;
  21938. this.position.copy( Object3D.DefaultUp );
  21939. this.updateMatrix();
  21940. this.groundColor = new Color( groundColor );
  21941. }
  21942. HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), {
  21943. constructor: HemisphereLight,
  21944. isHemisphereLight: true,
  21945. copy: function ( source ) {
  21946. Light.prototype.copy.call( this, source );
  21947. this.groundColor.copy( source.groundColor );
  21948. return this;
  21949. }
  21950. } );
  21951. /**
  21952. * @author mrdoob / http://mrdoob.com/
  21953. */
  21954. function LightShadow( camera ) {
  21955. this.camera = camera;
  21956. this.bias = 0;
  21957. this.radius = 1;
  21958. this.mapSize = new Vector2( 512, 512 );
  21959. this.map = null;
  21960. this.matrix = new Matrix4();
  21961. }
  21962. Object.assign( LightShadow.prototype, {
  21963. copy: function ( source ) {
  21964. this.camera = source.camera.clone();
  21965. this.bias = source.bias;
  21966. this.radius = source.radius;
  21967. this.mapSize.copy( source.mapSize );
  21968. return this;
  21969. },
  21970. clone: function () {
  21971. return new this.constructor().copy( this );
  21972. },
  21973. toJSON: function () {
  21974. var object = {};
  21975. if ( this.bias !== 0 ) object.bias = this.bias;
  21976. if ( this.radius !== 1 ) object.radius = this.radius;
  21977. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  21978. object.camera = this.camera.toJSON( false ).object;
  21979. delete object.camera.matrix;
  21980. return object;
  21981. }
  21982. } );
  21983. /**
  21984. * @author mrdoob / http://mrdoob.com/
  21985. */
  21986. function SpotLightShadow() {
  21987. LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  21988. }
  21989. SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  21990. constructor: SpotLightShadow,
  21991. isSpotLightShadow: true,
  21992. update: function ( light ) {
  21993. var fov = _Math.RAD2DEG * 2 * light.angle;
  21994. var aspect = this.mapSize.width / this.mapSize.height;
  21995. var far = light.distance || 500;
  21996. var camera = this.camera;
  21997. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  21998. camera.fov = fov;
  21999. camera.aspect = aspect;
  22000. camera.far = far;
  22001. camera.updateProjectionMatrix();
  22002. }
  22003. }
  22004. } );
  22005. /**
  22006. * @author alteredq / http://alteredqualia.com/
  22007. */
  22008. function SpotLight( color, intensity, distance, angle, penumbra, decay ) {
  22009. Light.call( this, color, intensity );
  22010. this.type = 'SpotLight';
  22011. this.position.copy( Object3D.DefaultUp );
  22012. this.updateMatrix();
  22013. this.target = new Object3D();
  22014. Object.defineProperty( this, 'power', {
  22015. get: function () {
  22016. // intensity = power per solid angle.
  22017. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  22018. return this.intensity * Math.PI;
  22019. },
  22020. set: function ( power ) {
  22021. // intensity = power per solid angle.
  22022. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  22023. this.intensity = power / Math.PI;
  22024. }
  22025. } );
  22026. this.distance = ( distance !== undefined ) ? distance : 0;
  22027. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  22028. this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;
  22029. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  22030. this.shadow = new SpotLightShadow();
  22031. }
  22032. SpotLight.prototype = Object.assign( Object.create( Light.prototype ), {
  22033. constructor: SpotLight,
  22034. isSpotLight: true,
  22035. copy: function ( source ) {
  22036. Light.prototype.copy.call( this, source );
  22037. this.distance = source.distance;
  22038. this.angle = source.angle;
  22039. this.penumbra = source.penumbra;
  22040. this.decay = source.decay;
  22041. this.target = source.target.clone();
  22042. this.shadow = source.shadow.clone();
  22043. return this;
  22044. }
  22045. } );
  22046. /**
  22047. * @author mrdoob / http://mrdoob.com/
  22048. */
  22049. function PointLight( color, intensity, distance, decay ) {
  22050. Light.call( this, color, intensity );
  22051. this.type = 'PointLight';
  22052. Object.defineProperty( this, 'power', {
  22053. get: function () {
  22054. // intensity = power per solid angle.
  22055. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  22056. return this.intensity * 4 * Math.PI;
  22057. },
  22058. set: function ( power ) {
  22059. // intensity = power per solid angle.
  22060. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  22061. this.intensity = power / ( 4 * Math.PI );
  22062. }
  22063. } );
  22064. this.distance = ( distance !== undefined ) ? distance : 0;
  22065. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  22066. this.shadow = new LightShadow( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  22067. }
  22068. PointLight.prototype = Object.assign( Object.create( Light.prototype ), {
  22069. constructor: PointLight,
  22070. isPointLight: true,
  22071. copy: function ( source ) {
  22072. Light.prototype.copy.call( this, source );
  22073. this.distance = source.distance;
  22074. this.decay = source.decay;
  22075. this.shadow = source.shadow.clone();
  22076. return this;
  22077. }
  22078. } );
  22079. /**
  22080. * @author mrdoob / http://mrdoob.com/
  22081. */
  22082. function DirectionalLightShadow( ) {
  22083. LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  22084. }
  22085. DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  22086. constructor: DirectionalLightShadow
  22087. } );
  22088. /**
  22089. * @author mrdoob / http://mrdoob.com/
  22090. * @author alteredq / http://alteredqualia.com/
  22091. */
  22092. function DirectionalLight( color, intensity ) {
  22093. Light.call( this, color, intensity );
  22094. this.type = 'DirectionalLight';
  22095. this.position.copy( Object3D.DefaultUp );
  22096. this.updateMatrix();
  22097. this.target = new Object3D();
  22098. this.shadow = new DirectionalLightShadow();
  22099. }
  22100. DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), {
  22101. constructor: DirectionalLight,
  22102. isDirectionalLight: true,
  22103. copy: function ( source ) {
  22104. Light.prototype.copy.call( this, source );
  22105. this.target = source.target.clone();
  22106. this.shadow = source.shadow.clone();
  22107. return this;
  22108. }
  22109. } );
  22110. /**
  22111. * @author mrdoob / http://mrdoob.com/
  22112. */
  22113. function AmbientLight( color, intensity ) {
  22114. Light.call( this, color, intensity );
  22115. this.type = 'AmbientLight';
  22116. this.castShadow = undefined;
  22117. }
  22118. AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {
  22119. constructor: AmbientLight,
  22120. isAmbientLight: true
  22121. } );
  22122. /**
  22123. * @author tschw
  22124. * @author Ben Houston / http://clara.io/
  22125. * @author David Sarno / http://lighthaus.us/
  22126. */
  22127. var AnimationUtils = {
  22128. // same as Array.prototype.slice, but also works on typed arrays
  22129. arraySlice: function( array, from, to ) {
  22130. if ( AnimationUtils.isTypedArray( array ) ) {
  22131. return new array.constructor( array.subarray( from, to ) );
  22132. }
  22133. return array.slice( from, to );
  22134. },
  22135. // converts an array to a specific type
  22136. convertArray: function( array, type, forceClone ) {
  22137. if ( ! array || // let 'undefined' and 'null' pass
  22138. ! forceClone && array.constructor === type ) return array;
  22139. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  22140. return new type( array ); // create typed array
  22141. }
  22142. return Array.prototype.slice.call( array ); // create Array
  22143. },
  22144. isTypedArray: function( object ) {
  22145. return ArrayBuffer.isView( object ) &&
  22146. ! ( object instanceof DataView );
  22147. },
  22148. // returns an array by which times and values can be sorted
  22149. getKeyframeOrder: function( times ) {
  22150. function compareTime( i, j ) {
  22151. return times[ i ] - times[ j ];
  22152. }
  22153. var n = times.length;
  22154. var result = new Array( n );
  22155. for ( var i = 0; i !== n; ++ i ) result[ i ] = i;
  22156. result.sort( compareTime );
  22157. return result;
  22158. },
  22159. // uses the array previously returned by 'getKeyframeOrder' to sort data
  22160. sortedArray: function( values, stride, order ) {
  22161. var nValues = values.length;
  22162. var result = new values.constructor( nValues );
  22163. for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  22164. var srcOffset = order[ i ] * stride;
  22165. for ( var j = 0; j !== stride; ++ j ) {
  22166. result[ dstOffset ++ ] = values[ srcOffset + j ];
  22167. }
  22168. }
  22169. return result;
  22170. },
  22171. // function for parsing AOS keyframe formats
  22172. flattenJSON: function( jsonKeys, times, values, valuePropertyName ) {
  22173. var i = 1, key = jsonKeys[ 0 ];
  22174. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  22175. key = jsonKeys[ i ++ ];
  22176. }
  22177. if ( key === undefined ) return; // no data
  22178. var value = key[ valuePropertyName ];
  22179. if ( value === undefined ) return; // no data
  22180. if ( Array.isArray( value ) ) {
  22181. do {
  22182. value = key[ valuePropertyName ];
  22183. if ( value !== undefined ) {
  22184. times.push( key.time );
  22185. values.push.apply( values, value ); // push all elements
  22186. }
  22187. key = jsonKeys[ i ++ ];
  22188. } while ( key !== undefined );
  22189. } else if ( value.toArray !== undefined ) {
  22190. // ...assume THREE.Math-ish
  22191. do {
  22192. value = key[ valuePropertyName ];
  22193. if ( value !== undefined ) {
  22194. times.push( key.time );
  22195. value.toArray( values, values.length );
  22196. }
  22197. key = jsonKeys[ i ++ ];
  22198. } while ( key !== undefined );
  22199. } else {
  22200. // otherwise push as-is
  22201. do {
  22202. value = key[ valuePropertyName ];
  22203. if ( value !== undefined ) {
  22204. times.push( key.time );
  22205. values.push( value );
  22206. }
  22207. key = jsonKeys[ i ++ ];
  22208. } while ( key !== undefined );
  22209. }
  22210. }
  22211. };
  22212. /**
  22213. * Abstract base class of interpolants over parametric samples.
  22214. *
  22215. * The parameter domain is one dimensional, typically the time or a path
  22216. * along a curve defined by the data.
  22217. *
  22218. * The sample values can have any dimensionality and derived classes may
  22219. * apply special interpretations to the data.
  22220. *
  22221. * This class provides the interval seek in a Template Method, deferring
  22222. * the actual interpolation to derived classes.
  22223. *
  22224. * Time complexity is O(1) for linear access crossing at most two points
  22225. * and O(log N) for random access, where N is the number of positions.
  22226. *
  22227. * References:
  22228. *
  22229. * http://www.oodesign.com/template-method-pattern.html
  22230. *
  22231. * @author tschw
  22232. */
  22233. function Interpolant(
  22234. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22235. this.parameterPositions = parameterPositions;
  22236. this._cachedIndex = 0;
  22237. this.resultBuffer = resultBuffer !== undefined ?
  22238. resultBuffer : new sampleValues.constructor( sampleSize );
  22239. this.sampleValues = sampleValues;
  22240. this.valueSize = sampleSize;
  22241. }
  22242. Interpolant.prototype = {
  22243. constructor: Interpolant,
  22244. evaluate: function( t ) {
  22245. var pp = this.parameterPositions,
  22246. i1 = this._cachedIndex,
  22247. t1 = pp[ i1 ],
  22248. t0 = pp[ i1 - 1 ];
  22249. validate_interval: {
  22250. seek: {
  22251. var right;
  22252. linear_scan: {
  22253. //- See http://jsperf.com/comparison-to-undefined/3
  22254. //- slower code:
  22255. //-
  22256. //- if ( t >= t1 || t1 === undefined ) {
  22257. forward_scan: if ( ! ( t < t1 ) ) {
  22258. for ( var giveUpAt = i1 + 2; ;) {
  22259. if ( t1 === undefined ) {
  22260. if ( t < t0 ) break forward_scan;
  22261. // after end
  22262. i1 = pp.length;
  22263. this._cachedIndex = i1;
  22264. return this.afterEnd_( i1 - 1, t, t0 );
  22265. }
  22266. if ( i1 === giveUpAt ) break; // this loop
  22267. t0 = t1;
  22268. t1 = pp[ ++ i1 ];
  22269. if ( t < t1 ) {
  22270. // we have arrived at the sought interval
  22271. break seek;
  22272. }
  22273. }
  22274. // prepare binary search on the right side of the index
  22275. right = pp.length;
  22276. break linear_scan;
  22277. }
  22278. //- slower code:
  22279. //- if ( t < t0 || t0 === undefined ) {
  22280. if ( ! ( t >= t0 ) ) {
  22281. // looping?
  22282. var t1global = pp[ 1 ];
  22283. if ( t < t1global ) {
  22284. i1 = 2; // + 1, using the scan for the details
  22285. t0 = t1global;
  22286. }
  22287. // linear reverse scan
  22288. for ( var giveUpAt = i1 - 2; ;) {
  22289. if ( t0 === undefined ) {
  22290. // before start
  22291. this._cachedIndex = 0;
  22292. return this.beforeStart_( 0, t, t1 );
  22293. }
  22294. if ( i1 === giveUpAt ) break; // this loop
  22295. t1 = t0;
  22296. t0 = pp[ -- i1 - 1 ];
  22297. if ( t >= t0 ) {
  22298. // we have arrived at the sought interval
  22299. break seek;
  22300. }
  22301. }
  22302. // prepare binary search on the left side of the index
  22303. right = i1;
  22304. i1 = 0;
  22305. break linear_scan;
  22306. }
  22307. // the interval is valid
  22308. break validate_interval;
  22309. } // linear scan
  22310. // binary search
  22311. while ( i1 < right ) {
  22312. var mid = ( i1 + right ) >>> 1;
  22313. if ( t < pp[ mid ] ) {
  22314. right = mid;
  22315. } else {
  22316. i1 = mid + 1;
  22317. }
  22318. }
  22319. t1 = pp[ i1 ];
  22320. t0 = pp[ i1 - 1 ];
  22321. // check boundary cases, again
  22322. if ( t0 === undefined ) {
  22323. this._cachedIndex = 0;
  22324. return this.beforeStart_( 0, t, t1 );
  22325. }
  22326. if ( t1 === undefined ) {
  22327. i1 = pp.length;
  22328. this._cachedIndex = i1;
  22329. return this.afterEnd_( i1 - 1, t0, t );
  22330. }
  22331. } // seek
  22332. this._cachedIndex = i1;
  22333. this.intervalChanged_( i1, t0, t1 );
  22334. } // validate_interval
  22335. return this.interpolate_( i1, t0, t, t1 );
  22336. },
  22337. settings: null, // optional, subclass-specific settings structure
  22338. // Note: The indirection allows central control of many interpolants.
  22339. // --- Protected interface
  22340. DefaultSettings_: {},
  22341. getSettings_: function() {
  22342. return this.settings || this.DefaultSettings_;
  22343. },
  22344. copySampleValue_: function( index ) {
  22345. // copies a sample value to the result buffer
  22346. var result = this.resultBuffer,
  22347. values = this.sampleValues,
  22348. stride = this.valueSize,
  22349. offset = index * stride;
  22350. for ( var i = 0; i !== stride; ++ i ) {
  22351. result[ i ] = values[ offset + i ];
  22352. }
  22353. return result;
  22354. },
  22355. // Template methods for derived classes:
  22356. interpolate_: function( i1, t0, t, t1 ) {
  22357. throw new Error( "call to abstract method" );
  22358. // implementations shall return this.resultBuffer
  22359. },
  22360. intervalChanged_: function( i1, t0, t1 ) {
  22361. // empty
  22362. }
  22363. };
  22364. Object.assign( Interpolant.prototype, {
  22365. beforeStart_: //( 0, t, t0 ), returns this.resultBuffer
  22366. Interpolant.prototype.copySampleValue_,
  22367. afterEnd_: //( N-1, tN-1, t ), returns this.resultBuffer
  22368. Interpolant.prototype.copySampleValue_
  22369. } );
  22370. /**
  22371. * Fast and simple cubic spline interpolant.
  22372. *
  22373. * It was derived from a Hermitian construction setting the first derivative
  22374. * at each sample position to the linear slope between neighboring positions
  22375. * over their parameter interval.
  22376. *
  22377. * @author tschw
  22378. */
  22379. function CubicInterpolant(
  22380. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22381. Interpolant.call(
  22382. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  22383. this._weightPrev = -0;
  22384. this._offsetPrev = -0;
  22385. this._weightNext = -0;
  22386. this._offsetNext = -0;
  22387. }
  22388. CubicInterpolant.prototype =
  22389. Object.assign( Object.create( Interpolant.prototype ), {
  22390. constructor: CubicInterpolant,
  22391. DefaultSettings_: {
  22392. endingStart: ZeroCurvatureEnding,
  22393. endingEnd: ZeroCurvatureEnding
  22394. },
  22395. intervalChanged_: function( i1, t0, t1 ) {
  22396. var pp = this.parameterPositions,
  22397. iPrev = i1 - 2,
  22398. iNext = i1 + 1,
  22399. tPrev = pp[ iPrev ],
  22400. tNext = pp[ iNext ];
  22401. if ( tPrev === undefined ) {
  22402. switch ( this.getSettings_().endingStart ) {
  22403. case ZeroSlopeEnding:
  22404. // f'(t0) = 0
  22405. iPrev = i1;
  22406. tPrev = 2 * t0 - t1;
  22407. break;
  22408. case WrapAroundEnding:
  22409. // use the other end of the curve
  22410. iPrev = pp.length - 2;
  22411. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  22412. break;
  22413. default: // ZeroCurvatureEnding
  22414. // f''(t0) = 0 a.k.a. Natural Spline
  22415. iPrev = i1;
  22416. tPrev = t1;
  22417. }
  22418. }
  22419. if ( tNext === undefined ) {
  22420. switch ( this.getSettings_().endingEnd ) {
  22421. case ZeroSlopeEnding:
  22422. // f'(tN) = 0
  22423. iNext = i1;
  22424. tNext = 2 * t1 - t0;
  22425. break;
  22426. case WrapAroundEnding:
  22427. // use the other end of the curve
  22428. iNext = 1;
  22429. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  22430. break;
  22431. default: // ZeroCurvatureEnding
  22432. // f''(tN) = 0, a.k.a. Natural Spline
  22433. iNext = i1 - 1;
  22434. tNext = t0;
  22435. }
  22436. }
  22437. var halfDt = ( t1 - t0 ) * 0.5,
  22438. stride = this.valueSize;
  22439. this._weightPrev = halfDt / ( t0 - tPrev );
  22440. this._weightNext = halfDt / ( tNext - t1 );
  22441. this._offsetPrev = iPrev * stride;
  22442. this._offsetNext = iNext * stride;
  22443. },
  22444. interpolate_: function( i1, t0, t, t1 ) {
  22445. var result = this.resultBuffer,
  22446. values = this.sampleValues,
  22447. stride = this.valueSize,
  22448. o1 = i1 * stride, o0 = o1 - stride,
  22449. oP = this._offsetPrev, oN = this._offsetNext,
  22450. wP = this._weightPrev, wN = this._weightNext,
  22451. p = ( t - t0 ) / ( t1 - t0 ),
  22452. pp = p * p,
  22453. ppp = pp * p;
  22454. // evaluate polynomials
  22455. var sP = - wP * ppp + 2 * wP * pp - wP * p;
  22456. var s0 = ( 1 + wP ) * ppp + (-1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  22457. var s1 = (-1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  22458. var sN = wN * ppp - wN * pp;
  22459. // combine data linearly
  22460. for ( var i = 0; i !== stride; ++ i ) {
  22461. result[ i ] =
  22462. sP * values[ oP + i ] +
  22463. s0 * values[ o0 + i ] +
  22464. s1 * values[ o1 + i ] +
  22465. sN * values[ oN + i ];
  22466. }
  22467. return result;
  22468. }
  22469. } );
  22470. /**
  22471. * @author tschw
  22472. */
  22473. function LinearInterpolant(
  22474. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22475. Interpolant.call(
  22476. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  22477. }
  22478. LinearInterpolant.prototype =
  22479. Object.assign( Object.create( Interpolant.prototype ), {
  22480. constructor: LinearInterpolant,
  22481. interpolate_: function( i1, t0, t, t1 ) {
  22482. var result = this.resultBuffer,
  22483. values = this.sampleValues,
  22484. stride = this.valueSize,
  22485. offset1 = i1 * stride,
  22486. offset0 = offset1 - stride,
  22487. weight1 = ( t - t0 ) / ( t1 - t0 ),
  22488. weight0 = 1 - weight1;
  22489. for ( var i = 0; i !== stride; ++ i ) {
  22490. result[ i ] =
  22491. values[ offset0 + i ] * weight0 +
  22492. values[ offset1 + i ] * weight1;
  22493. }
  22494. return result;
  22495. }
  22496. } );
  22497. /**
  22498. *
  22499. * Interpolant that evaluates to the sample value at the position preceeding
  22500. * the parameter.
  22501. *
  22502. * @author tschw
  22503. */
  22504. function DiscreteInterpolant(
  22505. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22506. Interpolant.call(
  22507. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  22508. }
  22509. DiscreteInterpolant.prototype =
  22510. Object.assign( Object.create( Interpolant.prototype ), {
  22511. constructor: DiscreteInterpolant,
  22512. interpolate_: function( i1, t0, t, t1 ) {
  22513. return this.copySampleValue_( i1 - 1 );
  22514. }
  22515. } );
  22516. var KeyframeTrackPrototype;
  22517. KeyframeTrackPrototype = {
  22518. TimeBufferType: Float32Array,
  22519. ValueBufferType: Float32Array,
  22520. DefaultInterpolation: InterpolateLinear,
  22521. InterpolantFactoryMethodDiscrete: function ( result ) {
  22522. return new DiscreteInterpolant(
  22523. this.times, this.values, this.getValueSize(), result );
  22524. },
  22525. InterpolantFactoryMethodLinear: function ( result ) {
  22526. return new LinearInterpolant(
  22527. this.times, this.values, this.getValueSize(), result );
  22528. },
  22529. InterpolantFactoryMethodSmooth: function ( result ) {
  22530. return new CubicInterpolant(
  22531. this.times, this.values, this.getValueSize(), result );
  22532. },
  22533. setInterpolation: function ( interpolation ) {
  22534. var factoryMethod;
  22535. switch ( interpolation ) {
  22536. case InterpolateDiscrete:
  22537. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  22538. break;
  22539. case InterpolateLinear:
  22540. factoryMethod = this.InterpolantFactoryMethodLinear;
  22541. break;
  22542. case InterpolateSmooth:
  22543. factoryMethod = this.InterpolantFactoryMethodSmooth;
  22544. break;
  22545. }
  22546. if ( factoryMethod === undefined ) {
  22547. var message = "unsupported interpolation for " +
  22548. this.ValueTypeName + " keyframe track named " + this.name;
  22549. if ( this.createInterpolant === undefined ) {
  22550. // fall back to default, unless the default itself is messed up
  22551. if ( interpolation !== this.DefaultInterpolation ) {
  22552. this.setInterpolation( this.DefaultInterpolation );
  22553. } else {
  22554. throw new Error( message ); // fatal, in this case
  22555. }
  22556. }
  22557. console.warn( message );
  22558. return;
  22559. }
  22560. this.createInterpolant = factoryMethod;
  22561. },
  22562. getInterpolation: function () {
  22563. switch ( this.createInterpolant ) {
  22564. case this.InterpolantFactoryMethodDiscrete:
  22565. return InterpolateDiscrete;
  22566. case this.InterpolantFactoryMethodLinear:
  22567. return InterpolateLinear;
  22568. case this.InterpolantFactoryMethodSmooth:
  22569. return InterpolateSmooth;
  22570. }
  22571. },
  22572. getValueSize: function () {
  22573. return this.values.length / this.times.length;
  22574. },
  22575. // move all keyframes either forwards or backwards in time
  22576. shift: function ( timeOffset ) {
  22577. if ( timeOffset !== 0.0 ) {
  22578. var times = this.times;
  22579. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  22580. times[ i ] += timeOffset;
  22581. }
  22582. }
  22583. return this;
  22584. },
  22585. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  22586. scale: function ( timeScale ) {
  22587. if ( timeScale !== 1.0 ) {
  22588. var times = this.times;
  22589. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  22590. times[ i ] *= timeScale;
  22591. }
  22592. }
  22593. return this;
  22594. },
  22595. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  22596. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  22597. trim: function ( startTime, endTime ) {
  22598. var times = this.times,
  22599. nKeys = times.length,
  22600. from = 0,
  22601. to = nKeys - 1;
  22602. while ( from !== nKeys && times[ from ] < startTime ) ++ from;
  22603. while ( to !== - 1 && times[ to ] > endTime ) -- to;
  22604. ++ to; // inclusive -> exclusive bound
  22605. if ( from !== 0 || to !== nKeys ) {
  22606. // empty tracks are forbidden, so keep at least one keyframe
  22607. if ( from >= to ) to = Math.max( to, 1 ), from = to - 1;
  22608. var stride = this.getValueSize();
  22609. this.times = AnimationUtils.arraySlice( times, from, to );
  22610. this.values = AnimationUtils.
  22611. arraySlice( this.values, from * stride, to * stride );
  22612. }
  22613. return this;
  22614. },
  22615. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  22616. validate: function () {
  22617. var valid = true;
  22618. var valueSize = this.getValueSize();
  22619. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  22620. console.error( "invalid value size in track", this );
  22621. valid = false;
  22622. }
  22623. var times = this.times,
  22624. values = this.values,
  22625. nKeys = times.length;
  22626. if ( nKeys === 0 ) {
  22627. console.error( "track is empty", this );
  22628. valid = false;
  22629. }
  22630. var prevTime = null;
  22631. for ( var i = 0; i !== nKeys; i ++ ) {
  22632. var currTime = times[ i ];
  22633. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  22634. console.error( "time is not a valid number", this, i, currTime );
  22635. valid = false;
  22636. break;
  22637. }
  22638. if ( prevTime !== null && prevTime > currTime ) {
  22639. console.error( "out of order keys", this, i, currTime, prevTime );
  22640. valid = false;
  22641. break;
  22642. }
  22643. prevTime = currTime;
  22644. }
  22645. if ( values !== undefined ) {
  22646. if ( AnimationUtils.isTypedArray( values ) ) {
  22647. for ( var i = 0, n = values.length; i !== n; ++ i ) {
  22648. var value = values[ i ];
  22649. if ( isNaN( value ) ) {
  22650. console.error( "value is not a valid number", this, i, value );
  22651. valid = false;
  22652. break;
  22653. }
  22654. }
  22655. }
  22656. }
  22657. return valid;
  22658. },
  22659. // removes equivalent sequential keys as common in morph target sequences
  22660. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  22661. optimize: function () {
  22662. var times = this.times,
  22663. values = this.values,
  22664. stride = this.getValueSize(),
  22665. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  22666. writeIndex = 1,
  22667. lastIndex = times.length - 1;
  22668. for ( var i = 1; i < lastIndex; ++ i ) {
  22669. var keep = false;
  22670. var time = times[ i ];
  22671. var timeNext = times[ i + 1 ];
  22672. // remove adjacent keyframes scheduled at the same time
  22673. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  22674. if ( ! smoothInterpolation ) {
  22675. // remove unnecessary keyframes same as their neighbors
  22676. var offset = i * stride,
  22677. offsetP = offset - stride,
  22678. offsetN = offset + stride;
  22679. for ( var j = 0; j !== stride; ++ j ) {
  22680. var value = values[ offset + j ];
  22681. if ( value !== values[ offsetP + j ] ||
  22682. value !== values[ offsetN + j ] ) {
  22683. keep = true;
  22684. break;
  22685. }
  22686. }
  22687. } else keep = true;
  22688. }
  22689. // in-place compaction
  22690. if ( keep ) {
  22691. if ( i !== writeIndex ) {
  22692. times[ writeIndex ] = times[ i ];
  22693. var readOffset = i * stride,
  22694. writeOffset = writeIndex * stride;
  22695. for ( var j = 0; j !== stride; ++ j )
  22696. values[ writeOffset + j ] = values[ readOffset + j ];
  22697. }
  22698. ++ writeIndex;
  22699. }
  22700. }
  22701. // flush last keyframe (compaction looks ahead)
  22702. if ( lastIndex > 0 ) {
  22703. times[ writeIndex ] = times[ lastIndex ];
  22704. for ( var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j )
  22705. values[ writeOffset + j ] = values[ readOffset + j ];
  22706. ++ writeIndex;
  22707. }
  22708. if ( writeIndex !== times.length ) {
  22709. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  22710. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  22711. }
  22712. return this;
  22713. }
  22714. };
  22715. function KeyframeTrackConstructor( name, times, values, interpolation ) {
  22716. if( name === undefined ) throw new Error( "track name is undefined" );
  22717. if( times === undefined || times.length === 0 ) {
  22718. throw new Error( "no keyframes in track named " + name );
  22719. }
  22720. this.name = name;
  22721. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  22722. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  22723. this.setInterpolation( interpolation || this.DefaultInterpolation );
  22724. this.validate();
  22725. this.optimize();
  22726. }
  22727. /**
  22728. *
  22729. * A Track of vectored keyframe values.
  22730. *
  22731. *
  22732. * @author Ben Houston / http://clara.io/
  22733. * @author David Sarno / http://lighthaus.us/
  22734. * @author tschw
  22735. */
  22736. function VectorKeyframeTrack( name, times, values, interpolation ) {
  22737. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  22738. }
  22739. VectorKeyframeTrack.prototype =
  22740. Object.assign( Object.create( KeyframeTrackPrototype ), {
  22741. constructor: VectorKeyframeTrack,
  22742. ValueTypeName: 'vector'
  22743. // ValueBufferType is inherited
  22744. // DefaultInterpolation is inherited
  22745. } );
  22746. /**
  22747. * Spherical linear unit quaternion interpolant.
  22748. *
  22749. * @author tschw
  22750. */
  22751. function QuaternionLinearInterpolant(
  22752. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22753. Interpolant.call(
  22754. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  22755. }
  22756. QuaternionLinearInterpolant.prototype =
  22757. Object.assign( Object.create( Interpolant.prototype ), {
  22758. constructor: QuaternionLinearInterpolant,
  22759. interpolate_: function( i1, t0, t, t1 ) {
  22760. var result = this.resultBuffer,
  22761. values = this.sampleValues,
  22762. stride = this.valueSize,
  22763. offset = i1 * stride,
  22764. alpha = ( t - t0 ) / ( t1 - t0 );
  22765. for ( var end = offset + stride; offset !== end; offset += 4 ) {
  22766. Quaternion.slerpFlat( result, 0,
  22767. values, offset - stride, values, offset, alpha );
  22768. }
  22769. return result;
  22770. }
  22771. } );
  22772. /**
  22773. *
  22774. * A Track of quaternion keyframe values.
  22775. *
  22776. * @author Ben Houston / http://clara.io/
  22777. * @author David Sarno / http://lighthaus.us/
  22778. * @author tschw
  22779. */
  22780. function QuaternionKeyframeTrack( name, times, values, interpolation ) {
  22781. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  22782. }
  22783. QuaternionKeyframeTrack.prototype =
  22784. Object.assign( Object.create( KeyframeTrackPrototype ), {
  22785. constructor: QuaternionKeyframeTrack,
  22786. ValueTypeName: 'quaternion',
  22787. // ValueBufferType is inherited
  22788. DefaultInterpolation: InterpolateLinear,
  22789. InterpolantFactoryMethodLinear: function( result ) {
  22790. return new QuaternionLinearInterpolant(
  22791. this.times, this.values, this.getValueSize(), result );
  22792. },
  22793. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  22794. } );
  22795. /**
  22796. *
  22797. * A Track of numeric keyframe values.
  22798. *
  22799. * @author Ben Houston / http://clara.io/
  22800. * @author David Sarno / http://lighthaus.us/
  22801. * @author tschw
  22802. */
  22803. function NumberKeyframeTrack( name, times, values, interpolation ) {
  22804. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  22805. }
  22806. NumberKeyframeTrack.prototype =
  22807. Object.assign( Object.create( KeyframeTrackPrototype ), {
  22808. constructor: NumberKeyframeTrack,
  22809. ValueTypeName: 'number'
  22810. // ValueBufferType is inherited
  22811. // DefaultInterpolation is inherited
  22812. } );
  22813. /**
  22814. *
  22815. * A Track that interpolates Strings
  22816. *
  22817. *
  22818. * @author Ben Houston / http://clara.io/
  22819. * @author David Sarno / http://lighthaus.us/
  22820. * @author tschw
  22821. */
  22822. function StringKeyframeTrack( name, times, values, interpolation ) {
  22823. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  22824. }
  22825. StringKeyframeTrack.prototype =
  22826. Object.assign( Object.create( KeyframeTrackPrototype ), {
  22827. constructor: StringKeyframeTrack,
  22828. ValueTypeName: 'string',
  22829. ValueBufferType: Array,
  22830. DefaultInterpolation: InterpolateDiscrete,
  22831. InterpolantFactoryMethodLinear: undefined,
  22832. InterpolantFactoryMethodSmooth: undefined
  22833. } );
  22834. /**
  22835. *
  22836. * A Track of Boolean keyframe values.
  22837. *
  22838. *
  22839. * @author Ben Houston / http://clara.io/
  22840. * @author David Sarno / http://lighthaus.us/
  22841. * @author tschw
  22842. */
  22843. function BooleanKeyframeTrack( name, times, values ) {
  22844. KeyframeTrackConstructor.call( this, name, times, values );
  22845. }
  22846. BooleanKeyframeTrack.prototype =
  22847. Object.assign( Object.create( KeyframeTrackPrototype ), {
  22848. constructor: BooleanKeyframeTrack,
  22849. ValueTypeName: 'bool',
  22850. ValueBufferType: Array,
  22851. DefaultInterpolation: InterpolateDiscrete,
  22852. InterpolantFactoryMethodLinear: undefined,
  22853. InterpolantFactoryMethodSmooth: undefined
  22854. // Note: Actually this track could have a optimized / compressed
  22855. // representation of a single value and a custom interpolant that
  22856. // computes "firstValue ^ isOdd( index )".
  22857. } );
  22858. /**
  22859. *
  22860. * A Track of keyframe values that represent color.
  22861. *
  22862. *
  22863. * @author Ben Houston / http://clara.io/
  22864. * @author David Sarno / http://lighthaus.us/
  22865. * @author tschw
  22866. */
  22867. function ColorKeyframeTrack( name, times, values, interpolation ) {
  22868. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  22869. }
  22870. ColorKeyframeTrack.prototype =
  22871. Object.assign( Object.create( KeyframeTrackPrototype ), {
  22872. constructor: ColorKeyframeTrack,
  22873. ValueTypeName: 'color'
  22874. // ValueBufferType is inherited
  22875. // DefaultInterpolation is inherited
  22876. // Note: Very basic implementation and nothing special yet.
  22877. // However, this is the place for color space parameterization.
  22878. } );
  22879. /**
  22880. *
  22881. * A timed sequence of keyframes for a specific property.
  22882. *
  22883. *
  22884. * @author Ben Houston / http://clara.io/
  22885. * @author David Sarno / http://lighthaus.us/
  22886. * @author tschw
  22887. */
  22888. function KeyframeTrack( name, times, values, interpolation ) {
  22889. KeyframeTrackConstructor.apply( this, arguments );
  22890. }
  22891. KeyframeTrack.prototype = KeyframeTrackPrototype;
  22892. KeyframeTrackPrototype.constructor = KeyframeTrack;
  22893. // Static methods:
  22894. Object.assign( KeyframeTrack, {
  22895. // Serialization (in static context, because of constructor invocation
  22896. // and automatic invocation of .toJSON):
  22897. parse: function( json ) {
  22898. if( json.type === undefined ) {
  22899. throw new Error( "track type undefined, can not parse" );
  22900. }
  22901. var trackType = KeyframeTrack._getTrackTypeForValueTypeName( json.type );
  22902. if ( json.times === undefined ) {
  22903. var times = [], values = [];
  22904. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  22905. json.times = times;
  22906. json.values = values;
  22907. }
  22908. // derived classes can define a static parse method
  22909. if ( trackType.parse !== undefined ) {
  22910. return trackType.parse( json );
  22911. } else {
  22912. // by default, we asssume a constructor compatible with the base
  22913. return new trackType(
  22914. json.name, json.times, json.values, json.interpolation );
  22915. }
  22916. },
  22917. toJSON: function( track ) {
  22918. var trackType = track.constructor;
  22919. var json;
  22920. // derived classes can define a static toJSON method
  22921. if ( trackType.toJSON !== undefined ) {
  22922. json = trackType.toJSON( track );
  22923. } else {
  22924. // by default, we assume the data can be serialized as-is
  22925. json = {
  22926. 'name': track.name,
  22927. 'times': AnimationUtils.convertArray( track.times, Array ),
  22928. 'values': AnimationUtils.convertArray( track.values, Array )
  22929. };
  22930. var interpolation = track.getInterpolation();
  22931. if ( interpolation !== track.DefaultInterpolation ) {
  22932. json.interpolation = interpolation;
  22933. }
  22934. }
  22935. json.type = track.ValueTypeName; // mandatory
  22936. return json;
  22937. },
  22938. _getTrackTypeForValueTypeName: function( typeName ) {
  22939. switch( typeName.toLowerCase() ) {
  22940. case "scalar":
  22941. case "double":
  22942. case "float":
  22943. case "number":
  22944. case "integer":
  22945. return NumberKeyframeTrack;
  22946. case "vector":
  22947. case "vector2":
  22948. case "vector3":
  22949. case "vector4":
  22950. return VectorKeyframeTrack;
  22951. case "color":
  22952. return ColorKeyframeTrack;
  22953. case "quaternion":
  22954. return QuaternionKeyframeTrack;
  22955. case "bool":
  22956. case "boolean":
  22957. return BooleanKeyframeTrack;
  22958. case "string":
  22959. return StringKeyframeTrack;
  22960. }
  22961. throw new Error( "Unsupported typeName: " + typeName );
  22962. }
  22963. } );
  22964. /**
  22965. *
  22966. * Reusable set of Tracks that represent an animation.
  22967. *
  22968. * @author Ben Houston / http://clara.io/
  22969. * @author David Sarno / http://lighthaus.us/
  22970. */
  22971. function AnimationClip( name, duration, tracks ) {
  22972. this.name = name;
  22973. this.tracks = tracks;
  22974. this.duration = ( duration !== undefined ) ? duration : -1;
  22975. this.uuid = _Math.generateUUID();
  22976. // this means it should figure out its duration by scanning the tracks
  22977. if ( this.duration < 0 ) {
  22978. this.resetDuration();
  22979. }
  22980. this.optimize();
  22981. }
  22982. AnimationClip.prototype = {
  22983. constructor: AnimationClip,
  22984. resetDuration: function() {
  22985. var tracks = this.tracks,
  22986. duration = 0;
  22987. for ( var i = 0, n = tracks.length; i !== n; ++ i ) {
  22988. var track = this.tracks[ i ];
  22989. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  22990. }
  22991. this.duration = duration;
  22992. },
  22993. trim: function() {
  22994. for ( var i = 0; i < this.tracks.length; i ++ ) {
  22995. this.tracks[ i ].trim( 0, this.duration );
  22996. }
  22997. return this;
  22998. },
  22999. optimize: function() {
  23000. for ( var i = 0; i < this.tracks.length; i ++ ) {
  23001. this.tracks[ i ].optimize();
  23002. }
  23003. return this;
  23004. }
  23005. };
  23006. // Static methods:
  23007. Object.assign( AnimationClip, {
  23008. parse: function( json ) {
  23009. var tracks = [],
  23010. jsonTracks = json.tracks,
  23011. frameTime = 1.0 / ( json.fps || 1.0 );
  23012. for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  23013. tracks.push( KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) );
  23014. }
  23015. return new AnimationClip( json.name, json.duration, tracks );
  23016. },
  23017. toJSON: function( clip ) {
  23018. var tracks = [],
  23019. clipTracks = clip.tracks;
  23020. var json = {
  23021. 'name': clip.name,
  23022. 'duration': clip.duration,
  23023. 'tracks': tracks
  23024. };
  23025. for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) {
  23026. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  23027. }
  23028. return json;
  23029. },
  23030. CreateFromMorphTargetSequence: function( name, morphTargetSequence, fps, noLoop ) {
  23031. var numMorphTargets = morphTargetSequence.length;
  23032. var tracks = [];
  23033. for ( var i = 0; i < numMorphTargets; i ++ ) {
  23034. var times = [];
  23035. var values = [];
  23036. times.push(
  23037. ( i + numMorphTargets - 1 ) % numMorphTargets,
  23038. i,
  23039. ( i + 1 ) % numMorphTargets );
  23040. values.push( 0, 1, 0 );
  23041. var order = AnimationUtils.getKeyframeOrder( times );
  23042. times = AnimationUtils.sortedArray( times, 1, order );
  23043. values = AnimationUtils.sortedArray( values, 1, order );
  23044. // if there is a key at the first frame, duplicate it as the
  23045. // last frame as well for perfect loop.
  23046. if ( ! noLoop && times[ 0 ] === 0 ) {
  23047. times.push( numMorphTargets );
  23048. values.push( values[ 0 ] );
  23049. }
  23050. tracks.push(
  23051. new NumberKeyframeTrack(
  23052. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  23053. times, values
  23054. ).scale( 1.0 / fps ) );
  23055. }
  23056. return new AnimationClip( name, -1, tracks );
  23057. },
  23058. findByName: function( objectOrClipArray, name ) {
  23059. var clipArray = objectOrClipArray;
  23060. if ( ! Array.isArray( objectOrClipArray ) ) {
  23061. var o = objectOrClipArray;
  23062. clipArray = o.geometry && o.geometry.animations || o.animations;
  23063. }
  23064. for ( var i = 0; i < clipArray.length; i ++ ) {
  23065. if ( clipArray[ i ].name === name ) {
  23066. return clipArray[ i ];
  23067. }
  23068. }
  23069. return null;
  23070. },
  23071. CreateClipsFromMorphTargetSequences: function( morphTargets, fps, noLoop ) {
  23072. var animationToMorphTargets = {};
  23073. // tested with https://regex101.com/ on trick sequences
  23074. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  23075. var pattern = /^([\w-]*?)([\d]+)$/;
  23076. // sort morph target names into animation groups based
  23077. // patterns like Walk_001, Walk_002, Run_001, Run_002
  23078. for ( var i = 0, il = morphTargets.length; i < il; i ++ ) {
  23079. var morphTarget = morphTargets[ i ];
  23080. var parts = morphTarget.name.match( pattern );
  23081. if ( parts && parts.length > 1 ) {
  23082. var name = parts[ 1 ];
  23083. var animationMorphTargets = animationToMorphTargets[ name ];
  23084. if ( ! animationMorphTargets ) {
  23085. animationToMorphTargets[ name ] = animationMorphTargets = [];
  23086. }
  23087. animationMorphTargets.push( morphTarget );
  23088. }
  23089. }
  23090. var clips = [];
  23091. for ( var name in animationToMorphTargets ) {
  23092. clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  23093. }
  23094. return clips;
  23095. },
  23096. // parse the animation.hierarchy format
  23097. parseAnimation: function( animation, bones ) {
  23098. if ( ! animation ) {
  23099. console.error( " no animation in JSONLoader data" );
  23100. return null;
  23101. }
  23102. var addNonemptyTrack = function(
  23103. trackType, trackName, animationKeys, propertyName, destTracks ) {
  23104. // only return track if there are actually keys.
  23105. if ( animationKeys.length !== 0 ) {
  23106. var times = [];
  23107. var values = [];
  23108. AnimationUtils.flattenJSON(
  23109. animationKeys, times, values, propertyName );
  23110. // empty keys are filtered out, so check again
  23111. if ( times.length !== 0 ) {
  23112. destTracks.push( new trackType( trackName, times, values ) );
  23113. }
  23114. }
  23115. };
  23116. var tracks = [];
  23117. var clipName = animation.name || 'default';
  23118. // automatic length determination in AnimationClip.
  23119. var duration = animation.length || -1;
  23120. var fps = animation.fps || 30;
  23121. var hierarchyTracks = animation.hierarchy || [];
  23122. for ( var h = 0; h < hierarchyTracks.length; h ++ ) {
  23123. var animationKeys = hierarchyTracks[ h ].keys;
  23124. // skip empty tracks
  23125. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  23126. // process morph targets in a way exactly compatible
  23127. // with AnimationHandler.init( animation )
  23128. if ( animationKeys[0].morphTargets ) {
  23129. // figure out all morph targets used in this track
  23130. var morphTargetNames = {};
  23131. for ( var k = 0; k < animationKeys.length; k ++ ) {
  23132. if ( animationKeys[k].morphTargets ) {
  23133. for ( var m = 0; m < animationKeys[k].morphTargets.length; m ++ ) {
  23134. morphTargetNames[ animationKeys[k].morphTargets[m] ] = -1;
  23135. }
  23136. }
  23137. }
  23138. // create a track for each morph target with all zero
  23139. // morphTargetInfluences except for the keys in which
  23140. // the morphTarget is named.
  23141. for ( var morphTargetName in morphTargetNames ) {
  23142. var times = [];
  23143. var values = [];
  23144. for ( var m = 0; m !== animationKeys[k].morphTargets.length; ++ m ) {
  23145. var animationKey = animationKeys[k];
  23146. times.push( animationKey.time );
  23147. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  23148. }
  23149. tracks.push( new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  23150. }
  23151. duration = morphTargetNames.length * ( fps || 1.0 );
  23152. } else {
  23153. // ...assume skeletal animation
  23154. var boneName = '.bones[' + bones[ h ].name + ']';
  23155. addNonemptyTrack(
  23156. VectorKeyframeTrack, boneName + '.position',
  23157. animationKeys, 'pos', tracks );
  23158. addNonemptyTrack(
  23159. QuaternionKeyframeTrack, boneName + '.quaternion',
  23160. animationKeys, 'rot', tracks );
  23161. addNonemptyTrack(
  23162. VectorKeyframeTrack, boneName + '.scale',
  23163. animationKeys, 'scl', tracks );
  23164. }
  23165. }
  23166. if ( tracks.length === 0 ) {
  23167. return null;
  23168. }
  23169. var clip = new AnimationClip( clipName, duration, tracks );
  23170. return clip;
  23171. }
  23172. } );
  23173. /**
  23174. * @author mrdoob / http://mrdoob.com/
  23175. */
  23176. function MaterialLoader( manager ) {
  23177. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  23178. this.textures = {};
  23179. }
  23180. Object.assign( MaterialLoader.prototype, {
  23181. load: function ( url, onLoad, onProgress, onError ) {
  23182. var scope = this;
  23183. var loader = new FileLoader( scope.manager );
  23184. loader.load( url, function ( text ) {
  23185. onLoad( scope.parse( JSON.parse( text ) ) );
  23186. }, onProgress, onError );
  23187. },
  23188. setTextures: function ( value ) {
  23189. this.textures = value;
  23190. },
  23191. parse: function ( json ) {
  23192. var textures = this.textures;
  23193. function getTexture( name ) {
  23194. if ( textures[ name ] === undefined ) {
  23195. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  23196. }
  23197. return textures[ name ];
  23198. }
  23199. var material = new Materials[ json.type ]();
  23200. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  23201. if ( json.name !== undefined ) material.name = json.name;
  23202. if ( json.color !== undefined ) material.color.setHex( json.color );
  23203. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  23204. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  23205. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  23206. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  23207. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  23208. if ( json.clearCoat !== undefined ) material.clearCoat = json.clearCoat;
  23209. if ( json.clearCoatRoughness !== undefined ) material.clearCoatRoughness = json.clearCoatRoughness;
  23210. if ( json.uniforms !== undefined ) material.uniforms = json.uniforms;
  23211. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  23212. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  23213. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  23214. if ( json.fog !== undefined ) material.fog = json.fog;
  23215. if ( json.shading !== undefined ) material.shading = json.shading;
  23216. if ( json.blending !== undefined ) material.blending = json.blending;
  23217. if ( json.side !== undefined ) material.side = json.side;
  23218. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  23219. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  23220. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  23221. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  23222. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  23223. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  23224. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  23225. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  23226. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  23227. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  23228. if ( json.skinning !== undefined ) material.skinning = json.skinning;
  23229. if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets;
  23230. // for PointsMaterial
  23231. if ( json.size !== undefined ) material.size = json.size;
  23232. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  23233. // maps
  23234. if ( json.map !== undefined ) material.map = getTexture( json.map );
  23235. if ( json.alphaMap !== undefined ) {
  23236. material.alphaMap = getTexture( json.alphaMap );
  23237. material.transparent = true;
  23238. }
  23239. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  23240. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  23241. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  23242. if ( json.normalScale !== undefined ) {
  23243. var normalScale = json.normalScale;
  23244. if ( Array.isArray( normalScale ) === false ) {
  23245. // Blender exporter used to export a scalar. See #7459
  23246. normalScale = [ normalScale, normalScale ];
  23247. }
  23248. material.normalScale = new Vector2().fromArray( normalScale );
  23249. }
  23250. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  23251. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  23252. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  23253. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  23254. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  23255. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  23256. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  23257. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  23258. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  23259. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  23260. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  23261. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  23262. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  23263. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  23264. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  23265. // MultiMaterial
  23266. if ( json.materials !== undefined ) {
  23267. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  23268. material.materials.push( this.parse( json.materials[ i ] ) );
  23269. }
  23270. }
  23271. return material;
  23272. }
  23273. } );
  23274. /**
  23275. * @author mrdoob / http://mrdoob.com/
  23276. */
  23277. function BufferGeometryLoader( manager ) {
  23278. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  23279. }
  23280. Object.assign( BufferGeometryLoader.prototype, {
  23281. load: function ( url, onLoad, onProgress, onError ) {
  23282. var scope = this;
  23283. var loader = new FileLoader( scope.manager );
  23284. loader.load( url, function ( text ) {
  23285. onLoad( scope.parse( JSON.parse( text ) ) );
  23286. }, onProgress, onError );
  23287. },
  23288. parse: function ( json ) {
  23289. var geometry = new BufferGeometry();
  23290. var index = json.data.index;
  23291. var TYPED_ARRAYS = {
  23292. 'Int8Array': Int8Array,
  23293. 'Uint8Array': Uint8Array,
  23294. 'Uint8ClampedArray': Uint8ClampedArray,
  23295. 'Int16Array': Int16Array,
  23296. 'Uint16Array': Uint16Array,
  23297. 'Int32Array': Int32Array,
  23298. 'Uint32Array': Uint32Array,
  23299. 'Float32Array': Float32Array,
  23300. 'Float64Array': Float64Array
  23301. };
  23302. if ( index !== undefined ) {
  23303. var typedArray = new TYPED_ARRAYS[ index.type ]( index.array );
  23304. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  23305. }
  23306. var attributes = json.data.attributes;
  23307. for ( var key in attributes ) {
  23308. var attribute = attributes[ key ];
  23309. var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
  23310. geometry.addAttribute( key, new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) );
  23311. }
  23312. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  23313. if ( groups !== undefined ) {
  23314. for ( var i = 0, n = groups.length; i !== n; ++ i ) {
  23315. var group = groups[ i ];
  23316. geometry.addGroup( group.start, group.count, group.materialIndex );
  23317. }
  23318. }
  23319. var boundingSphere = json.data.boundingSphere;
  23320. if ( boundingSphere !== undefined ) {
  23321. var center = new Vector3();
  23322. if ( boundingSphere.center !== undefined ) {
  23323. center.fromArray( boundingSphere.center );
  23324. }
  23325. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  23326. }
  23327. return geometry;
  23328. }
  23329. } );
  23330. /**
  23331. * @author alteredq / http://alteredqualia.com/
  23332. */
  23333. function Loader() {
  23334. this.onLoadStart = function () {};
  23335. this.onLoadProgress = function () {};
  23336. this.onLoadComplete = function () {};
  23337. }
  23338. Loader.prototype = {
  23339. constructor: Loader,
  23340. crossOrigin: undefined,
  23341. extractUrlBase: function ( url ) {
  23342. var parts = url.split( '/' );
  23343. if ( parts.length === 1 ) return './';
  23344. parts.pop();
  23345. return parts.join( '/' ) + '/';
  23346. },
  23347. initMaterials: function ( materials, texturePath, crossOrigin ) {
  23348. var array = [];
  23349. for ( var i = 0; i < materials.length; ++ i ) {
  23350. array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin );
  23351. }
  23352. return array;
  23353. },
  23354. createMaterial: ( function () {
  23355. var BlendingMode = {
  23356. NoBlending: NoBlending,
  23357. NormalBlending: NormalBlending,
  23358. AdditiveBlending: AdditiveBlending,
  23359. SubtractiveBlending: SubtractiveBlending,
  23360. MultiplyBlending: MultiplyBlending,
  23361. CustomBlending: CustomBlending
  23362. };
  23363. var color, textureLoader, materialLoader;
  23364. return function createMaterial( m, texturePath, crossOrigin ) {
  23365. if ( color === undefined ) color = new Color();
  23366. if ( textureLoader === undefined ) textureLoader = new TextureLoader();
  23367. if ( materialLoader === undefined ) materialLoader = new MaterialLoader();
  23368. // convert from old material format
  23369. var textures = {};
  23370. function loadTexture( path, repeat, offset, wrap, anisotropy ) {
  23371. var fullPath = texturePath + path;
  23372. var loader = Loader.Handlers.get( fullPath );
  23373. var texture;
  23374. if ( loader !== null ) {
  23375. texture = loader.load( fullPath );
  23376. } else {
  23377. textureLoader.setCrossOrigin( crossOrigin );
  23378. texture = textureLoader.load( fullPath );
  23379. }
  23380. if ( repeat !== undefined ) {
  23381. texture.repeat.fromArray( repeat );
  23382. if ( repeat[ 0 ] !== 1 ) texture.wrapS = RepeatWrapping;
  23383. if ( repeat[ 1 ] !== 1 ) texture.wrapT = RepeatWrapping;
  23384. }
  23385. if ( offset !== undefined ) {
  23386. texture.offset.fromArray( offset );
  23387. }
  23388. if ( wrap !== undefined ) {
  23389. if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = RepeatWrapping;
  23390. if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = MirroredRepeatWrapping;
  23391. if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = RepeatWrapping;
  23392. if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = MirroredRepeatWrapping;
  23393. }
  23394. if ( anisotropy !== undefined ) {
  23395. texture.anisotropy = anisotropy;
  23396. }
  23397. var uuid = _Math.generateUUID();
  23398. textures[ uuid ] = texture;
  23399. return uuid;
  23400. }
  23401. //
  23402. var json = {
  23403. uuid: _Math.generateUUID(),
  23404. type: 'MeshLambertMaterial'
  23405. };
  23406. for ( var name in m ) {
  23407. var value = m[ name ];
  23408. switch ( name ) {
  23409. case 'DbgColor':
  23410. case 'DbgIndex':
  23411. case 'opticalDensity':
  23412. case 'illumination':
  23413. break;
  23414. case 'DbgName':
  23415. json.name = value;
  23416. break;
  23417. case 'blending':
  23418. json.blending = BlendingMode[ value ];
  23419. break;
  23420. case 'colorAmbient':
  23421. case 'mapAmbient':
  23422. console.warn( 'THREE.Loader.createMaterial:', name, 'is no longer supported.' );
  23423. break;
  23424. case 'colorDiffuse':
  23425. json.color = color.fromArray( value ).getHex();
  23426. break;
  23427. case 'colorSpecular':
  23428. json.specular = color.fromArray( value ).getHex();
  23429. break;
  23430. case 'colorEmissive':
  23431. json.emissive = color.fromArray( value ).getHex();
  23432. break;
  23433. case 'specularCoef':
  23434. json.shininess = value;
  23435. break;
  23436. case 'shading':
  23437. if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial';
  23438. if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial';
  23439. if ( value.toLowerCase() === 'standard' ) json.type = 'MeshStandardMaterial';
  23440. break;
  23441. case 'mapDiffuse':
  23442. json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  23443. break;
  23444. case 'mapDiffuseRepeat':
  23445. case 'mapDiffuseOffset':
  23446. case 'mapDiffuseWrap':
  23447. case 'mapDiffuseAnisotropy':
  23448. break;
  23449. case 'mapEmissive':
  23450. json.emissiveMap = loadTexture( value, m.mapEmissiveRepeat, m.mapEmissiveOffset, m.mapEmissiveWrap, m.mapEmissiveAnisotropy );
  23451. break;
  23452. case 'mapEmissiveRepeat':
  23453. case 'mapEmissiveOffset':
  23454. case 'mapEmissiveWrap':
  23455. case 'mapEmissiveAnisotropy':
  23456. break;
  23457. case 'mapLight':
  23458. json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  23459. break;
  23460. case 'mapLightRepeat':
  23461. case 'mapLightOffset':
  23462. case 'mapLightWrap':
  23463. case 'mapLightAnisotropy':
  23464. break;
  23465. case 'mapAO':
  23466. json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy );
  23467. break;
  23468. case 'mapAORepeat':
  23469. case 'mapAOOffset':
  23470. case 'mapAOWrap':
  23471. case 'mapAOAnisotropy':
  23472. break;
  23473. case 'mapBump':
  23474. json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  23475. break;
  23476. case 'mapBumpScale':
  23477. json.bumpScale = value;
  23478. break;
  23479. case 'mapBumpRepeat':
  23480. case 'mapBumpOffset':
  23481. case 'mapBumpWrap':
  23482. case 'mapBumpAnisotropy':
  23483. break;
  23484. case 'mapNormal':
  23485. json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  23486. break;
  23487. case 'mapNormalFactor':
  23488. json.normalScale = [ value, value ];
  23489. break;
  23490. case 'mapNormalRepeat':
  23491. case 'mapNormalOffset':
  23492. case 'mapNormalWrap':
  23493. case 'mapNormalAnisotropy':
  23494. break;
  23495. case 'mapSpecular':
  23496. json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  23497. break;
  23498. case 'mapSpecularRepeat':
  23499. case 'mapSpecularOffset':
  23500. case 'mapSpecularWrap':
  23501. case 'mapSpecularAnisotropy':
  23502. break;
  23503. case 'mapMetalness':
  23504. json.metalnessMap = loadTexture( value, m.mapMetalnessRepeat, m.mapMetalnessOffset, m.mapMetalnessWrap, m.mapMetalnessAnisotropy );
  23505. break;
  23506. case 'mapMetalnessRepeat':
  23507. case 'mapMetalnessOffset':
  23508. case 'mapMetalnessWrap':
  23509. case 'mapMetalnessAnisotropy':
  23510. break;
  23511. case 'mapRoughness':
  23512. json.roughnessMap = loadTexture( value, m.mapRoughnessRepeat, m.mapRoughnessOffset, m.mapRoughnessWrap, m.mapRoughnessAnisotropy );
  23513. break;
  23514. case 'mapRoughnessRepeat':
  23515. case 'mapRoughnessOffset':
  23516. case 'mapRoughnessWrap':
  23517. case 'mapRoughnessAnisotropy':
  23518. break;
  23519. case 'mapAlpha':
  23520. json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy );
  23521. break;
  23522. case 'mapAlphaRepeat':
  23523. case 'mapAlphaOffset':
  23524. case 'mapAlphaWrap':
  23525. case 'mapAlphaAnisotropy':
  23526. break;
  23527. case 'flipSided':
  23528. json.side = BackSide;
  23529. break;
  23530. case 'doubleSided':
  23531. json.side = DoubleSide;
  23532. break;
  23533. case 'transparency':
  23534. console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' );
  23535. json.opacity = value;
  23536. break;
  23537. case 'depthTest':
  23538. case 'depthWrite':
  23539. case 'colorWrite':
  23540. case 'opacity':
  23541. case 'reflectivity':
  23542. case 'transparent':
  23543. case 'visible':
  23544. case 'wireframe':
  23545. json[ name ] = value;
  23546. break;
  23547. case 'vertexColors':
  23548. if ( value === true ) json.vertexColors = VertexColors;
  23549. if ( value === 'face' ) json.vertexColors = FaceColors;
  23550. break;
  23551. default:
  23552. console.error( 'THREE.Loader.createMaterial: Unsupported', name, value );
  23553. break;
  23554. }
  23555. }
  23556. if ( json.type === 'MeshBasicMaterial' ) delete json.emissive;
  23557. if ( json.type !== 'MeshPhongMaterial' ) delete json.specular;
  23558. if ( json.opacity < 1 ) json.transparent = true;
  23559. materialLoader.setTextures( textures );
  23560. return materialLoader.parse( json );
  23561. };
  23562. } )()
  23563. };
  23564. Loader.Handlers = {
  23565. handlers: [],
  23566. add: function ( regex, loader ) {
  23567. this.handlers.push( regex, loader );
  23568. },
  23569. get: function ( file ) {
  23570. var handlers = this.handlers;
  23571. for ( var i = 0, l = handlers.length; i < l; i += 2 ) {
  23572. var regex = handlers[ i ];
  23573. var loader = handlers[ i + 1 ];
  23574. if ( regex.test( file ) ) {
  23575. return loader;
  23576. }
  23577. }
  23578. return null;
  23579. }
  23580. };
  23581. /**
  23582. * @author mrdoob / http://mrdoob.com/
  23583. * @author alteredq / http://alteredqualia.com/
  23584. */
  23585. function JSONLoader( manager ) {
  23586. if ( typeof manager === 'boolean' ) {
  23587. console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' );
  23588. manager = undefined;
  23589. }
  23590. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  23591. this.withCredentials = false;
  23592. }
  23593. Object.assign( JSONLoader.prototype, {
  23594. load: function( url, onLoad, onProgress, onError ) {
  23595. var scope = this;
  23596. var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : Loader.prototype.extractUrlBase( url );
  23597. var loader = new FileLoader( this.manager );
  23598. loader.setWithCredentials( this.withCredentials );
  23599. loader.load( url, function ( text ) {
  23600. var json = JSON.parse( text );
  23601. var metadata = json.metadata;
  23602. if ( metadata !== undefined ) {
  23603. var type = metadata.type;
  23604. if ( type !== undefined ) {
  23605. if ( type.toLowerCase() === 'object' ) {
  23606. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' );
  23607. return;
  23608. }
  23609. if ( type.toLowerCase() === 'scene' ) {
  23610. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' );
  23611. return;
  23612. }
  23613. }
  23614. }
  23615. var object = scope.parse( json, texturePath );
  23616. onLoad( object.geometry, object.materials );
  23617. }, onProgress, onError );
  23618. },
  23619. setTexturePath: function ( value ) {
  23620. this.texturePath = value;
  23621. },
  23622. parse: function ( json, texturePath ) {
  23623. var geometry = new Geometry(),
  23624. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  23625. parseModel( scale );
  23626. parseSkin();
  23627. parseMorphing( scale );
  23628. parseAnimations();
  23629. geometry.computeFaceNormals();
  23630. geometry.computeBoundingSphere();
  23631. function parseModel( scale ) {
  23632. function isBitSet( value, position ) {
  23633. return value & ( 1 << position );
  23634. }
  23635. var i, j, fi,
  23636. offset, zLength,
  23637. colorIndex, normalIndex, uvIndex, materialIndex,
  23638. type,
  23639. isQuad,
  23640. hasMaterial,
  23641. hasFaceVertexUv,
  23642. hasFaceNormal, hasFaceVertexNormal,
  23643. hasFaceColor, hasFaceVertexColor,
  23644. vertex, face, faceA, faceB, hex, normal,
  23645. uvLayer, uv, u, v,
  23646. faces = json.faces,
  23647. vertices = json.vertices,
  23648. normals = json.normals,
  23649. colors = json.colors,
  23650. nUvLayers = 0;
  23651. if ( json.uvs !== undefined ) {
  23652. // disregard empty arrays
  23653. for ( i = 0; i < json.uvs.length; i ++ ) {
  23654. if ( json.uvs[ i ].length ) nUvLayers ++;
  23655. }
  23656. for ( i = 0; i < nUvLayers; i ++ ) {
  23657. geometry.faceVertexUvs[ i ] = [];
  23658. }
  23659. }
  23660. offset = 0;
  23661. zLength = vertices.length;
  23662. while ( offset < zLength ) {
  23663. vertex = new Vector3();
  23664. vertex.x = vertices[ offset ++ ] * scale;
  23665. vertex.y = vertices[ offset ++ ] * scale;
  23666. vertex.z = vertices[ offset ++ ] * scale;
  23667. geometry.vertices.push( vertex );
  23668. }
  23669. offset = 0;
  23670. zLength = faces.length;
  23671. while ( offset < zLength ) {
  23672. type = faces[ offset ++ ];
  23673. isQuad = isBitSet( type, 0 );
  23674. hasMaterial = isBitSet( type, 1 );
  23675. hasFaceVertexUv = isBitSet( type, 3 );
  23676. hasFaceNormal = isBitSet( type, 4 );
  23677. hasFaceVertexNormal = isBitSet( type, 5 );
  23678. hasFaceColor = isBitSet( type, 6 );
  23679. hasFaceVertexColor = isBitSet( type, 7 );
  23680. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  23681. if ( isQuad ) {
  23682. faceA = new Face3();
  23683. faceA.a = faces[ offset ];
  23684. faceA.b = faces[ offset + 1 ];
  23685. faceA.c = faces[ offset + 3 ];
  23686. faceB = new Face3();
  23687. faceB.a = faces[ offset + 1 ];
  23688. faceB.b = faces[ offset + 2 ];
  23689. faceB.c = faces[ offset + 3 ];
  23690. offset += 4;
  23691. if ( hasMaterial ) {
  23692. materialIndex = faces[ offset ++ ];
  23693. faceA.materialIndex = materialIndex;
  23694. faceB.materialIndex = materialIndex;
  23695. }
  23696. // to get face <=> uv index correspondence
  23697. fi = geometry.faces.length;
  23698. if ( hasFaceVertexUv ) {
  23699. for ( i = 0; i < nUvLayers; i ++ ) {
  23700. uvLayer = json.uvs[ i ];
  23701. geometry.faceVertexUvs[ i ][ fi ] = [];
  23702. geometry.faceVertexUvs[ i ][ fi + 1 ] = [];
  23703. for ( j = 0; j < 4; j ++ ) {
  23704. uvIndex = faces[ offset ++ ];
  23705. u = uvLayer[ uvIndex * 2 ];
  23706. v = uvLayer[ uvIndex * 2 + 1 ];
  23707. uv = new Vector2( u, v );
  23708. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  23709. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  23710. }
  23711. }
  23712. }
  23713. if ( hasFaceNormal ) {
  23714. normalIndex = faces[ offset ++ ] * 3;
  23715. faceA.normal.set(
  23716. normals[ normalIndex ++ ],
  23717. normals[ normalIndex ++ ],
  23718. normals[ normalIndex ]
  23719. );
  23720. faceB.normal.copy( faceA.normal );
  23721. }
  23722. if ( hasFaceVertexNormal ) {
  23723. for ( i = 0; i < 4; i ++ ) {
  23724. normalIndex = faces[ offset ++ ] * 3;
  23725. normal = new Vector3(
  23726. normals[ normalIndex ++ ],
  23727. normals[ normalIndex ++ ],
  23728. normals[ normalIndex ]
  23729. );
  23730. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  23731. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  23732. }
  23733. }
  23734. if ( hasFaceColor ) {
  23735. colorIndex = faces[ offset ++ ];
  23736. hex = colors[ colorIndex ];
  23737. faceA.color.setHex( hex );
  23738. faceB.color.setHex( hex );
  23739. }
  23740. if ( hasFaceVertexColor ) {
  23741. for ( i = 0; i < 4; i ++ ) {
  23742. colorIndex = faces[ offset ++ ];
  23743. hex = colors[ colorIndex ];
  23744. if ( i !== 2 ) faceA.vertexColors.push( new Color( hex ) );
  23745. if ( i !== 0 ) faceB.vertexColors.push( new Color( hex ) );
  23746. }
  23747. }
  23748. geometry.faces.push( faceA );
  23749. geometry.faces.push( faceB );
  23750. } else {
  23751. face = new Face3();
  23752. face.a = faces[ offset ++ ];
  23753. face.b = faces[ offset ++ ];
  23754. face.c = faces[ offset ++ ];
  23755. if ( hasMaterial ) {
  23756. materialIndex = faces[ offset ++ ];
  23757. face.materialIndex = materialIndex;
  23758. }
  23759. // to get face <=> uv index correspondence
  23760. fi = geometry.faces.length;
  23761. if ( hasFaceVertexUv ) {
  23762. for ( i = 0; i < nUvLayers; i ++ ) {
  23763. uvLayer = json.uvs[ i ];
  23764. geometry.faceVertexUvs[ i ][ fi ] = [];
  23765. for ( j = 0; j < 3; j ++ ) {
  23766. uvIndex = faces[ offset ++ ];
  23767. u = uvLayer[ uvIndex * 2 ];
  23768. v = uvLayer[ uvIndex * 2 + 1 ];
  23769. uv = new Vector2( u, v );
  23770. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  23771. }
  23772. }
  23773. }
  23774. if ( hasFaceNormal ) {
  23775. normalIndex = faces[ offset ++ ] * 3;
  23776. face.normal.set(
  23777. normals[ normalIndex ++ ],
  23778. normals[ normalIndex ++ ],
  23779. normals[ normalIndex ]
  23780. );
  23781. }
  23782. if ( hasFaceVertexNormal ) {
  23783. for ( i = 0; i < 3; i ++ ) {
  23784. normalIndex = faces[ offset ++ ] * 3;
  23785. normal = new Vector3(
  23786. normals[ normalIndex ++ ],
  23787. normals[ normalIndex ++ ],
  23788. normals[ normalIndex ]
  23789. );
  23790. face.vertexNormals.push( normal );
  23791. }
  23792. }
  23793. if ( hasFaceColor ) {
  23794. colorIndex = faces[ offset ++ ];
  23795. face.color.setHex( colors[ colorIndex ] );
  23796. }
  23797. if ( hasFaceVertexColor ) {
  23798. for ( i = 0; i < 3; i ++ ) {
  23799. colorIndex = faces[ offset ++ ];
  23800. face.vertexColors.push( new Color( colors[ colorIndex ] ) );
  23801. }
  23802. }
  23803. geometry.faces.push( face );
  23804. }
  23805. }
  23806. }
  23807. function parseSkin() {
  23808. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  23809. if ( json.skinWeights ) {
  23810. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  23811. var x = json.skinWeights[ i ];
  23812. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  23813. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  23814. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  23815. geometry.skinWeights.push( new Vector4( x, y, z, w ) );
  23816. }
  23817. }
  23818. if ( json.skinIndices ) {
  23819. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  23820. var a = json.skinIndices[ i ];
  23821. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  23822. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  23823. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  23824. geometry.skinIndices.push( new Vector4( a, b, c, d ) );
  23825. }
  23826. }
  23827. geometry.bones = json.bones;
  23828. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  23829. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  23830. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  23831. }
  23832. }
  23833. function parseMorphing( scale ) {
  23834. if ( json.morphTargets !== undefined ) {
  23835. for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  23836. geometry.morphTargets[ i ] = {};
  23837. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  23838. geometry.morphTargets[ i ].vertices = [];
  23839. var dstVertices = geometry.morphTargets[ i ].vertices;
  23840. var srcVertices = json.morphTargets[ i ].vertices;
  23841. for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  23842. var vertex = new Vector3();
  23843. vertex.x = srcVertices[ v ] * scale;
  23844. vertex.y = srcVertices[ v + 1 ] * scale;
  23845. vertex.z = srcVertices[ v + 2 ] * scale;
  23846. dstVertices.push( vertex );
  23847. }
  23848. }
  23849. }
  23850. if ( json.morphColors !== undefined && json.morphColors.length > 0 ) {
  23851. console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' );
  23852. var faces = geometry.faces;
  23853. var morphColors = json.morphColors[ 0 ].colors;
  23854. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  23855. faces[ i ].color.fromArray( morphColors, i * 3 );
  23856. }
  23857. }
  23858. }
  23859. function parseAnimations() {
  23860. var outputAnimations = [];
  23861. // parse old style Bone/Hierarchy animations
  23862. var animations = [];
  23863. if ( json.animation !== undefined ) {
  23864. animations.push( json.animation );
  23865. }
  23866. if ( json.animations !== undefined ) {
  23867. if ( json.animations.length ) {
  23868. animations = animations.concat( json.animations );
  23869. } else {
  23870. animations.push( json.animations );
  23871. }
  23872. }
  23873. for ( var i = 0; i < animations.length; i ++ ) {
  23874. var clip = AnimationClip.parseAnimation( animations[ i ], geometry.bones );
  23875. if ( clip ) outputAnimations.push( clip );
  23876. }
  23877. // parse implicit morph animations
  23878. if ( geometry.morphTargets ) {
  23879. // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary.
  23880. var morphAnimationClips = AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 );
  23881. outputAnimations = outputAnimations.concat( morphAnimationClips );
  23882. }
  23883. if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations;
  23884. }
  23885. if ( json.materials === undefined || json.materials.length === 0 ) {
  23886. return { geometry: geometry };
  23887. } else {
  23888. var materials = Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin );
  23889. return { geometry: geometry, materials: materials };
  23890. }
  23891. }
  23892. } );
  23893. /**
  23894. * @author mrdoob / http://mrdoob.com/
  23895. */
  23896. function ObjectLoader( manager ) {
  23897. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  23898. this.texturePath = '';
  23899. }
  23900. Object.assign( ObjectLoader.prototype, {
  23901. load: function ( url, onLoad, onProgress, onError ) {
  23902. if ( this.texturePath === '' ) {
  23903. this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 );
  23904. }
  23905. var scope = this;
  23906. var loader = new FileLoader( scope.manager );
  23907. loader.load( url, function ( text ) {
  23908. var json = null;
  23909. try {
  23910. json = JSON.parse( text );
  23911. } catch ( error ) {
  23912. if ( onError !== undefined ) onError( error );
  23913. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  23914. return;
  23915. }
  23916. var metadata = json.metadata;
  23917. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  23918. console.error( 'THREE.ObjectLoader: Can\'t load ' + url + '. Use THREE.JSONLoader instead.' );
  23919. return;
  23920. }
  23921. scope.parse( json, onLoad );
  23922. }, onProgress, onError );
  23923. },
  23924. setTexturePath: function ( value ) {
  23925. this.texturePath = value;
  23926. },
  23927. setCrossOrigin: function ( value ) {
  23928. this.crossOrigin = value;
  23929. },
  23930. parse: function ( json, onLoad ) {
  23931. var geometries = this.parseGeometries( json.geometries );
  23932. var images = this.parseImages( json.images, function () {
  23933. if ( onLoad !== undefined ) onLoad( object );
  23934. } );
  23935. var textures = this.parseTextures( json.textures, images );
  23936. var materials = this.parseMaterials( json.materials, textures );
  23937. var object = this.parseObject( json.object, geometries, materials );
  23938. if ( json.animations ) {
  23939. object.animations = this.parseAnimations( json.animations );
  23940. }
  23941. if ( json.images === undefined || json.images.length === 0 ) {
  23942. if ( onLoad !== undefined ) onLoad( object );
  23943. }
  23944. return object;
  23945. },
  23946. parseGeometries: function ( json ) {
  23947. var geometries = {};
  23948. if ( json !== undefined ) {
  23949. var geometryLoader = new JSONLoader();
  23950. var bufferGeometryLoader = new BufferGeometryLoader();
  23951. for ( var i = 0, l = json.length; i < l; i ++ ) {
  23952. var geometry;
  23953. var data = json[ i ];
  23954. switch ( data.type ) {
  23955. case 'PlaneGeometry':
  23956. case 'PlaneBufferGeometry':
  23957. geometry = new Geometries[ data.type ](
  23958. data.width,
  23959. data.height,
  23960. data.widthSegments,
  23961. data.heightSegments
  23962. );
  23963. break;
  23964. case 'BoxGeometry':
  23965. case 'BoxBufferGeometry':
  23966. case 'CubeGeometry': // backwards compatible
  23967. geometry = new Geometries[ data.type ](
  23968. data.width,
  23969. data.height,
  23970. data.depth,
  23971. data.widthSegments,
  23972. data.heightSegments,
  23973. data.depthSegments
  23974. );
  23975. break;
  23976. case 'CircleGeometry':
  23977. case 'CircleBufferGeometry':
  23978. geometry = new Geometries[ data.type ](
  23979. data.radius,
  23980. data.segments,
  23981. data.thetaStart,
  23982. data.thetaLength
  23983. );
  23984. break;
  23985. case 'CylinderGeometry':
  23986. case 'CylinderBufferGeometry':
  23987. geometry = new Geometries[ data.type ](
  23988. data.radiusTop,
  23989. data.radiusBottom,
  23990. data.height,
  23991. data.radialSegments,
  23992. data.heightSegments,
  23993. data.openEnded,
  23994. data.thetaStart,
  23995. data.thetaLength
  23996. );
  23997. break;
  23998. case 'ConeGeometry':
  23999. case 'ConeBufferGeometry':
  24000. geometry = new Geometries[ data.type ](
  24001. data.radius,
  24002. data.height,
  24003. data.radialSegments,
  24004. data.heightSegments,
  24005. data.openEnded,
  24006. data.thetaStart,
  24007. data.thetaLength
  24008. );
  24009. break;
  24010. case 'SphereGeometry':
  24011. case 'SphereBufferGeometry':
  24012. geometry = new Geometries[ data.type ](
  24013. data.radius,
  24014. data.widthSegments,
  24015. data.heightSegments,
  24016. data.phiStart,
  24017. data.phiLength,
  24018. data.thetaStart,
  24019. data.thetaLength
  24020. );
  24021. break;
  24022. case 'DodecahedronGeometry':
  24023. case 'IcosahedronGeometry':
  24024. case 'OctahedronGeometry':
  24025. case 'TetrahedronGeometry':
  24026. geometry = new Geometries[ data.type ](
  24027. data.radius,
  24028. data.detail
  24029. );
  24030. break;
  24031. case 'RingGeometry':
  24032. case 'RingBufferGeometry':
  24033. geometry = new Geometries[ data.type ](
  24034. data.innerRadius,
  24035. data.outerRadius,
  24036. data.thetaSegments,
  24037. data.phiSegments,
  24038. data.thetaStart,
  24039. data.thetaLength
  24040. );
  24041. break;
  24042. case 'TorusGeometry':
  24043. case 'TorusBufferGeometry':
  24044. geometry = new Geometries[ data.type ](
  24045. data.radius,
  24046. data.tube,
  24047. data.radialSegments,
  24048. data.tubularSegments,
  24049. data.arc
  24050. );
  24051. break;
  24052. case 'TorusKnotGeometry':
  24053. case 'TorusKnotBufferGeometry':
  24054. geometry = new Geometries[ data.type ](
  24055. data.radius,
  24056. data.tube,
  24057. data.tubularSegments,
  24058. data.radialSegments,
  24059. data.p,
  24060. data.q
  24061. );
  24062. break;
  24063. case 'LatheGeometry':
  24064. case 'LatheBufferGeometry':
  24065. geometry = new Geometries[ data.type ](
  24066. data.points,
  24067. data.segments,
  24068. data.phiStart,
  24069. data.phiLength
  24070. );
  24071. break;
  24072. case 'BufferGeometry':
  24073. geometry = bufferGeometryLoader.parse( data );
  24074. break;
  24075. case 'Geometry':
  24076. geometry = geometryLoader.parse( data.data, this.texturePath ).geometry;
  24077. break;
  24078. default:
  24079. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  24080. continue;
  24081. }
  24082. geometry.uuid = data.uuid;
  24083. if ( data.name !== undefined ) geometry.name = data.name;
  24084. geometries[ data.uuid ] = geometry;
  24085. }
  24086. }
  24087. return geometries;
  24088. },
  24089. parseMaterials: function ( json, textures ) {
  24090. var materials = {};
  24091. if ( json !== undefined ) {
  24092. var loader = new MaterialLoader();
  24093. loader.setTextures( textures );
  24094. for ( var i = 0, l = json.length; i < l; i ++ ) {
  24095. var material = loader.parse( json[ i ] );
  24096. materials[ material.uuid ] = material;
  24097. }
  24098. }
  24099. return materials;
  24100. },
  24101. parseAnimations: function ( json ) {
  24102. var animations = [];
  24103. for ( var i = 0; i < json.length; i ++ ) {
  24104. var clip = AnimationClip.parse( json[ i ] );
  24105. animations.push( clip );
  24106. }
  24107. return animations;
  24108. },
  24109. parseImages: function ( json, onLoad ) {
  24110. var scope = this;
  24111. var images = {};
  24112. function loadImage( url ) {
  24113. scope.manager.itemStart( url );
  24114. return loader.load( url, function () {
  24115. scope.manager.itemEnd( url );
  24116. }, undefined, function () {
  24117. scope.manager.itemError( url );
  24118. } );
  24119. }
  24120. if ( json !== undefined && json.length > 0 ) {
  24121. var manager = new LoadingManager( onLoad );
  24122. var loader = new ImageLoader( manager );
  24123. loader.setCrossOrigin( this.crossOrigin );
  24124. for ( var i = 0, l = json.length; i < l; i ++ ) {
  24125. var image = json[ i ];
  24126. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url;
  24127. images[ image.uuid ] = loadImage( path );
  24128. }
  24129. }
  24130. return images;
  24131. },
  24132. parseTextures: function ( json, images ) {
  24133. var TextureMapping = {
  24134. UVMapping: UVMapping,
  24135. CubeReflectionMapping: CubeReflectionMapping,
  24136. CubeRefractionMapping: CubeRefractionMapping,
  24137. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  24138. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  24139. SphericalReflectionMapping: SphericalReflectionMapping,
  24140. CubeUVReflectionMapping: CubeUVReflectionMapping,
  24141. CubeUVRefractionMapping: CubeUVRefractionMapping
  24142. };
  24143. var TextureWrapping = {
  24144. RepeatWrapping: RepeatWrapping,
  24145. ClampToEdgeWrapping: ClampToEdgeWrapping,
  24146. MirroredRepeatWrapping: MirroredRepeatWrapping
  24147. };
  24148. var TextureFilter = {
  24149. NearestFilter: NearestFilter,
  24150. NearestMipMapNearestFilter: NearestMipMapNearestFilter,
  24151. NearestMipMapLinearFilter: NearestMipMapLinearFilter,
  24152. LinearFilter: LinearFilter,
  24153. LinearMipMapNearestFilter: LinearMipMapNearestFilter,
  24154. LinearMipMapLinearFilter: LinearMipMapLinearFilter
  24155. };
  24156. function parseConstant( value, type ) {
  24157. if ( typeof( value ) === 'number' ) return value;
  24158. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  24159. return type[ value ];
  24160. }
  24161. var textures = {};
  24162. if ( json !== undefined ) {
  24163. for ( var i = 0, l = json.length; i < l; i ++ ) {
  24164. var data = json[ i ];
  24165. if ( data.image === undefined ) {
  24166. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  24167. }
  24168. if ( images[ data.image ] === undefined ) {
  24169. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  24170. }
  24171. var texture = new Texture( images[ data.image ] );
  24172. texture.needsUpdate = true;
  24173. texture.uuid = data.uuid;
  24174. if ( data.name !== undefined ) texture.name = data.name;
  24175. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TextureMapping );
  24176. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  24177. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  24178. if ( data.wrap !== undefined ) {
  24179. texture.wrapS = parseConstant( data.wrap[ 0 ], TextureWrapping );
  24180. texture.wrapT = parseConstant( data.wrap[ 1 ], TextureWrapping );
  24181. }
  24182. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TextureFilter );
  24183. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TextureFilter );
  24184. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  24185. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  24186. textures[ data.uuid ] = texture;
  24187. }
  24188. }
  24189. return textures;
  24190. },
  24191. parseObject: function () {
  24192. var matrix = new Matrix4();
  24193. return function parseObject( data, geometries, materials ) {
  24194. var object;
  24195. function getGeometry( name ) {
  24196. if ( geometries[ name ] === undefined ) {
  24197. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  24198. }
  24199. return geometries[ name ];
  24200. }
  24201. function getMaterial( name ) {
  24202. if ( name === undefined ) return undefined;
  24203. if ( materials[ name ] === undefined ) {
  24204. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  24205. }
  24206. return materials[ name ];
  24207. }
  24208. switch ( data.type ) {
  24209. case 'Scene':
  24210. object = new Scene();
  24211. if ( data.background !== undefined ) {
  24212. if ( Number.isInteger( data.background ) ) {
  24213. object.background = new Color( data.background );
  24214. }
  24215. }
  24216. if ( data.fog !== undefined ) {
  24217. if ( data.fog.type === 'Fog' ) {
  24218. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  24219. } else if ( data.fog.type === 'FogExp2' ) {
  24220. object.fog = new FogExp2( data.fog.color, data.fog.density );
  24221. }
  24222. }
  24223. break;
  24224. case 'PerspectiveCamera':
  24225. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  24226. if ( data.focus !== undefined ) object.focus = data.focus;
  24227. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  24228. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  24229. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  24230. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  24231. break;
  24232. case 'OrthographicCamera':
  24233. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  24234. break;
  24235. case 'AmbientLight':
  24236. object = new AmbientLight( data.color, data.intensity );
  24237. break;
  24238. case 'DirectionalLight':
  24239. object = new DirectionalLight( data.color, data.intensity );
  24240. break;
  24241. case 'PointLight':
  24242. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  24243. break;
  24244. case 'SpotLight':
  24245. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  24246. break;
  24247. case 'HemisphereLight':
  24248. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  24249. break;
  24250. case 'Mesh':
  24251. var geometry = getGeometry( data.geometry );
  24252. var material = getMaterial( data.material );
  24253. if ( geometry.bones && geometry.bones.length > 0 ) {
  24254. object = new SkinnedMesh( geometry, material );
  24255. } else {
  24256. object = new Mesh( geometry, material );
  24257. }
  24258. break;
  24259. case 'LOD':
  24260. object = new LOD();
  24261. break;
  24262. case 'Line':
  24263. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  24264. break;
  24265. case 'LineSegments':
  24266. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  24267. break;
  24268. case 'PointCloud':
  24269. case 'Points':
  24270. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  24271. break;
  24272. case 'Sprite':
  24273. object = new Sprite( getMaterial( data.material ) );
  24274. break;
  24275. case 'Group':
  24276. object = new Group();
  24277. break;
  24278. case 'SkinnedMesh':
  24279. console.warn( 'THREE.ObjectLoader.parseObject() does not support SkinnedMesh type. Instantiates Object3D instead.' );
  24280. default:
  24281. object = new Object3D();
  24282. }
  24283. object.uuid = data.uuid;
  24284. if ( data.name !== undefined ) object.name = data.name;
  24285. if ( data.matrix !== undefined ) {
  24286. matrix.fromArray( data.matrix );
  24287. matrix.decompose( object.position, object.quaternion, object.scale );
  24288. } else {
  24289. if ( data.position !== undefined ) object.position.fromArray( data.position );
  24290. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  24291. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  24292. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  24293. }
  24294. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  24295. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  24296. if ( data.shadow ) {
  24297. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  24298. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  24299. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  24300. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  24301. }
  24302. if ( data.visible !== undefined ) object.visible = data.visible;
  24303. if ( data.userData !== undefined ) object.userData = data.userData;
  24304. if ( data.children !== undefined ) {
  24305. for ( var child in data.children ) {
  24306. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  24307. }
  24308. }
  24309. if ( data.type === 'LOD' ) {
  24310. var levels = data.levels;
  24311. for ( var l = 0; l < levels.length; l ++ ) {
  24312. var level = levels[ l ];
  24313. var child = object.getObjectByProperty( 'uuid', level.object );
  24314. if ( child !== undefined ) {
  24315. object.addLevel( child, level.distance );
  24316. }
  24317. }
  24318. }
  24319. return object;
  24320. };
  24321. }()
  24322. } );
  24323. /**
  24324. * @author zz85 / http://www.lab4games.net/zz85/blog
  24325. *
  24326. * Bezier Curves formulas obtained from
  24327. * http://en.wikipedia.org/wiki/Bézier_curve
  24328. */
  24329. function CatmullRom( t, p0, p1, p2, p3 ) {
  24330. var v0 = ( p2 - p0 ) * 0.5;
  24331. var v1 = ( p3 - p1 ) * 0.5;
  24332. var t2 = t * t;
  24333. var t3 = t * t2;
  24334. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  24335. }
  24336. //
  24337. function QuadraticBezierP0( t, p ) {
  24338. var k = 1 - t;
  24339. return k * k * p;
  24340. }
  24341. function QuadraticBezierP1( t, p ) {
  24342. return 2 * ( 1 - t ) * t * p;
  24343. }
  24344. function QuadraticBezierP2( t, p ) {
  24345. return t * t * p;
  24346. }
  24347. function QuadraticBezier( t, p0, p1, p2 ) {
  24348. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  24349. QuadraticBezierP2( t, p2 );
  24350. }
  24351. //
  24352. function CubicBezierP0( t, p ) {
  24353. var k = 1 - t;
  24354. return k * k * k * p;
  24355. }
  24356. function CubicBezierP1( t, p ) {
  24357. var k = 1 - t;
  24358. return 3 * k * k * t * p;
  24359. }
  24360. function CubicBezierP2( t, p ) {
  24361. return 3 * ( 1 - t ) * t * t * p;
  24362. }
  24363. function CubicBezierP3( t, p ) {
  24364. return t * t * t * p;
  24365. }
  24366. function CubicBezier( t, p0, p1, p2, p3 ) {
  24367. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  24368. CubicBezierP3( t, p3 );
  24369. }
  24370. /**
  24371. * @author zz85 / http://www.lab4games.net/zz85/blog
  24372. * Extensible curve object
  24373. *
  24374. * Some common of Curve methods
  24375. * .getPoint(t), getTangent(t)
  24376. * .getPointAt(u), getTangentAt(u)
  24377. * .getPoints(), .getSpacedPoints()
  24378. * .getLength()
  24379. * .updateArcLengths()
  24380. *
  24381. * This following classes subclasses THREE.Curve:
  24382. *
  24383. * -- 2d classes --
  24384. * THREE.LineCurve
  24385. * THREE.QuadraticBezierCurve
  24386. * THREE.CubicBezierCurve
  24387. * THREE.SplineCurve
  24388. * THREE.ArcCurve
  24389. * THREE.EllipseCurve
  24390. *
  24391. * -- 3d classes --
  24392. * THREE.LineCurve3
  24393. * THREE.QuadraticBezierCurve3
  24394. * THREE.CubicBezierCurve3
  24395. * THREE.CatmullRomCurve3
  24396. *
  24397. * A series of curves can be represented as a THREE.CurvePath
  24398. *
  24399. **/
  24400. /**************************************************************
  24401. * Abstract Curve base class
  24402. **************************************************************/
  24403. function Curve() {}
  24404. Curve.prototype = {
  24405. constructor: Curve,
  24406. // Virtual base class method to overwrite and implement in subclasses
  24407. // - t [0 .. 1]
  24408. getPoint: function ( t ) {
  24409. console.warn( "THREE.Curve: Warning, getPoint() not implemented!" );
  24410. return null;
  24411. },
  24412. // Get point at relative position in curve according to arc length
  24413. // - u [0 .. 1]
  24414. getPointAt: function ( u ) {
  24415. var t = this.getUtoTmapping( u );
  24416. return this.getPoint( t );
  24417. },
  24418. // Get sequence of points using getPoint( t )
  24419. getPoints: function ( divisions ) {
  24420. if ( isNaN( divisions ) ) divisions = 5;
  24421. var points = [];
  24422. for ( var d = 0; d <= divisions; d ++ ) {
  24423. points.push( this.getPoint( d / divisions ) );
  24424. }
  24425. return points;
  24426. },
  24427. // Get sequence of points using getPointAt( u )
  24428. getSpacedPoints: function ( divisions ) {
  24429. if ( isNaN( divisions ) ) divisions = 5;
  24430. var points = [];
  24431. for ( var d = 0; d <= divisions; d ++ ) {
  24432. points.push( this.getPointAt( d / divisions ) );
  24433. }
  24434. return points;
  24435. },
  24436. // Get total curve arc length
  24437. getLength: function () {
  24438. var lengths = this.getLengths();
  24439. return lengths[ lengths.length - 1 ];
  24440. },
  24441. // Get list of cumulative segment lengths
  24442. getLengths: function ( divisions ) {
  24443. if ( isNaN( divisions ) ) divisions = ( this.__arcLengthDivisions ) ? ( this.__arcLengthDivisions ) : 200;
  24444. if ( this.cacheArcLengths
  24445. && ( this.cacheArcLengths.length === divisions + 1 )
  24446. && ! this.needsUpdate ) {
  24447. //console.log( "cached", this.cacheArcLengths );
  24448. return this.cacheArcLengths;
  24449. }
  24450. this.needsUpdate = false;
  24451. var cache = [];
  24452. var current, last = this.getPoint( 0 );
  24453. var p, sum = 0;
  24454. cache.push( 0 );
  24455. for ( p = 1; p <= divisions; p ++ ) {
  24456. current = this.getPoint ( p / divisions );
  24457. sum += current.distanceTo( last );
  24458. cache.push( sum );
  24459. last = current;
  24460. }
  24461. this.cacheArcLengths = cache;
  24462. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  24463. },
  24464. updateArcLengths: function() {
  24465. this.needsUpdate = true;
  24466. this.getLengths();
  24467. },
  24468. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  24469. getUtoTmapping: function ( u, distance ) {
  24470. var arcLengths = this.getLengths();
  24471. var i = 0, il = arcLengths.length;
  24472. var targetArcLength; // The targeted u distance value to get
  24473. if ( distance ) {
  24474. targetArcLength = distance;
  24475. } else {
  24476. targetArcLength = u * arcLengths[ il - 1 ];
  24477. }
  24478. //var time = Date.now();
  24479. // binary search for the index with largest value smaller than target u distance
  24480. var low = 0, high = il - 1, comparison;
  24481. while ( low <= high ) {
  24482. 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
  24483. comparison = arcLengths[ i ] - targetArcLength;
  24484. if ( comparison < 0 ) {
  24485. low = i + 1;
  24486. } else if ( comparison > 0 ) {
  24487. high = i - 1;
  24488. } else {
  24489. high = i;
  24490. break;
  24491. // DONE
  24492. }
  24493. }
  24494. i = high;
  24495. //console.log('b' , i, low, high, Date.now()- time);
  24496. if ( arcLengths[ i ] === targetArcLength ) {
  24497. var t = i / ( il - 1 );
  24498. return t;
  24499. }
  24500. // we could get finer grain at lengths, or use simple interpolation between two points
  24501. var lengthBefore = arcLengths[ i ];
  24502. var lengthAfter = arcLengths[ i + 1 ];
  24503. var segmentLength = lengthAfter - lengthBefore;
  24504. // determine where we are between the 'before' and 'after' points
  24505. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  24506. // add that fractional amount to t
  24507. var t = ( i + segmentFraction ) / ( il - 1 );
  24508. return t;
  24509. },
  24510. // Returns a unit vector tangent at t
  24511. // In case any sub curve does not implement its tangent derivation,
  24512. // 2 points a small delta apart will be used to find its gradient
  24513. // which seems to give a reasonable approximation
  24514. getTangent: function( t ) {
  24515. var delta = 0.0001;
  24516. var t1 = t - delta;
  24517. var t2 = t + delta;
  24518. // Capping in case of danger
  24519. if ( t1 < 0 ) t1 = 0;
  24520. if ( t2 > 1 ) t2 = 1;
  24521. var pt1 = this.getPoint( t1 );
  24522. var pt2 = this.getPoint( t2 );
  24523. var vec = pt2.clone().sub( pt1 );
  24524. return vec.normalize();
  24525. },
  24526. getTangentAt: function ( u ) {
  24527. var t = this.getUtoTmapping( u );
  24528. return this.getTangent( t );
  24529. },
  24530. computeFrenetFrames: function ( segments, closed ) {
  24531. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  24532. var normal = new Vector3();
  24533. var tangents = [];
  24534. var normals = [];
  24535. var binormals = [];
  24536. var vec = new Vector3();
  24537. var mat = new Matrix4();
  24538. var i, u, theta;
  24539. // compute the tangent vectors for each segment on the curve
  24540. for ( i = 0; i <= segments; i ++ ) {
  24541. u = i / segments;
  24542. tangents[ i ] = this.getTangentAt( u );
  24543. tangents[ i ].normalize();
  24544. }
  24545. // select an initial normal vector perpendicular to the first tangent vector,
  24546. // and in the direction of the minimum tangent xyz component
  24547. normals[ 0 ] = new Vector3();
  24548. binormals[ 0 ] = new Vector3();
  24549. var min = Number.MAX_VALUE;
  24550. var tx = Math.abs( tangents[ 0 ].x );
  24551. var ty = Math.abs( tangents[ 0 ].y );
  24552. var tz = Math.abs( tangents[ 0 ].z );
  24553. if ( tx <= min ) {
  24554. min = tx;
  24555. normal.set( 1, 0, 0 );
  24556. }
  24557. if ( ty <= min ) {
  24558. min = ty;
  24559. normal.set( 0, 1, 0 );
  24560. }
  24561. if ( tz <= min ) {
  24562. normal.set( 0, 0, 1 );
  24563. }
  24564. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  24565. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  24566. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  24567. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  24568. for ( i = 1; i <= segments; i ++ ) {
  24569. normals[ i ] = normals[ i - 1 ].clone();
  24570. binormals[ i ] = binormals[ i - 1 ].clone();
  24571. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  24572. if ( vec.length() > Number.EPSILON ) {
  24573. vec.normalize();
  24574. theta = Math.acos( _Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  24575. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  24576. }
  24577. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  24578. }
  24579. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  24580. if ( closed === true ) {
  24581. theta = Math.acos( _Math.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  24582. theta /= segments;
  24583. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  24584. theta = - theta;
  24585. }
  24586. for ( i = 1; i <= segments; i ++ ) {
  24587. // twist a little...
  24588. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  24589. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  24590. }
  24591. }
  24592. return {
  24593. tangents: tangents,
  24594. normals: normals,
  24595. binormals: binormals
  24596. };
  24597. }
  24598. };
  24599. function LineCurve( v1, v2 ) {
  24600. this.v1 = v1;
  24601. this.v2 = v2;
  24602. }
  24603. LineCurve.prototype = Object.create( Curve.prototype );
  24604. LineCurve.prototype.constructor = LineCurve;
  24605. LineCurve.prototype.isLineCurve = true;
  24606. LineCurve.prototype.getPoint = function ( t ) {
  24607. if ( t === 1 ) {
  24608. return this.v2.clone();
  24609. }
  24610. var point = this.v2.clone().sub( this.v1 );
  24611. point.multiplyScalar( t ).add( this.v1 );
  24612. return point;
  24613. };
  24614. // Line curve is linear, so we can overwrite default getPointAt
  24615. LineCurve.prototype.getPointAt = function ( u ) {
  24616. return this.getPoint( u );
  24617. };
  24618. LineCurve.prototype.getTangent = function ( t ) {
  24619. var tangent = this.v2.clone().sub( this.v1 );
  24620. return tangent.normalize();
  24621. };
  24622. /**
  24623. * @author zz85 / http://www.lab4games.net/zz85/blog
  24624. *
  24625. **/
  24626. /**************************************************************
  24627. * Curved Path - a curve path is simply a array of connected
  24628. * curves, but retains the api of a curve
  24629. **************************************************************/
  24630. function CurvePath() {
  24631. this.curves = [];
  24632. this.autoClose = false; // Automatically closes the path
  24633. }
  24634. CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), {
  24635. constructor: CurvePath,
  24636. add: function ( curve ) {
  24637. this.curves.push( curve );
  24638. },
  24639. closePath: function () {
  24640. // Add a line curve if start and end of lines are not connected
  24641. var startPoint = this.curves[ 0 ].getPoint( 0 );
  24642. var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  24643. if ( ! startPoint.equals( endPoint ) ) {
  24644. this.curves.push( new LineCurve( endPoint, startPoint ) );
  24645. }
  24646. },
  24647. // To get accurate point with reference to
  24648. // entire path distance at time t,
  24649. // following has to be done:
  24650. // 1. Length of each sub path have to be known
  24651. // 2. Locate and identify type of curve
  24652. // 3. Get t for the curve
  24653. // 4. Return curve.getPointAt(t')
  24654. getPoint: function ( t ) {
  24655. var d = t * this.getLength();
  24656. var curveLengths = this.getCurveLengths();
  24657. var i = 0;
  24658. // To think about boundaries points.
  24659. while ( i < curveLengths.length ) {
  24660. if ( curveLengths[ i ] >= d ) {
  24661. var diff = curveLengths[ i ] - d;
  24662. var curve = this.curves[ i ];
  24663. var segmentLength = curve.getLength();
  24664. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  24665. return curve.getPointAt( u );
  24666. }
  24667. i ++;
  24668. }
  24669. return null;
  24670. // loop where sum != 0, sum > d , sum+1 <d
  24671. },
  24672. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  24673. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  24674. // getPoint() depends on getLength
  24675. getLength: function () {
  24676. var lens = this.getCurveLengths();
  24677. return lens[ lens.length - 1 ];
  24678. },
  24679. // cacheLengths must be recalculated.
  24680. updateArcLengths: function () {
  24681. this.needsUpdate = true;
  24682. this.cacheLengths = null;
  24683. this.getLengths();
  24684. },
  24685. // Compute lengths and cache them
  24686. // We cannot overwrite getLengths() because UtoT mapping uses it.
  24687. getCurveLengths: function () {
  24688. // We use cache values if curves and cache array are same length
  24689. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  24690. return this.cacheLengths;
  24691. }
  24692. // Get length of sub-curve
  24693. // Push sums into cached array
  24694. var lengths = [], sums = 0;
  24695. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  24696. sums += this.curves[ i ].getLength();
  24697. lengths.push( sums );
  24698. }
  24699. this.cacheLengths = lengths;
  24700. return lengths;
  24701. },
  24702. getSpacedPoints: function ( divisions ) {
  24703. if ( isNaN( divisions ) ) divisions = 40;
  24704. var points = [];
  24705. for ( var i = 0; i <= divisions; i ++ ) {
  24706. points.push( this.getPoint( i / divisions ) );
  24707. }
  24708. if ( this.autoClose ) {
  24709. points.push( points[ 0 ] );
  24710. }
  24711. return points;
  24712. },
  24713. getPoints: function ( divisions ) {
  24714. divisions = divisions || 12;
  24715. var points = [], last;
  24716. for ( var i = 0, curves = this.curves; i < curves.length; i ++ ) {
  24717. var curve = curves[ i ];
  24718. var resolution = (curve && curve.isEllipseCurve) ? divisions * 2
  24719. : (curve && curve.isLineCurve) ? 1
  24720. : (curve && curve.isSplineCurve) ? divisions * curve.points.length
  24721. : divisions;
  24722. var pts = curve.getPoints( resolution );
  24723. for ( var j = 0; j < pts.length; j++ ) {
  24724. var point = pts[ j ];
  24725. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  24726. points.push( point );
  24727. last = point;
  24728. }
  24729. }
  24730. if ( this.autoClose && points.length > 1 && !points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  24731. points.push( points[ 0 ] );
  24732. }
  24733. return points;
  24734. },
  24735. /**************************************************************
  24736. * Create Geometries Helpers
  24737. **************************************************************/
  24738. /// Generate geometry from path points (for Line or Points objects)
  24739. createPointsGeometry: function ( divisions ) {
  24740. var pts = this.getPoints( divisions );
  24741. return this.createGeometry( pts );
  24742. },
  24743. // Generate geometry from equidistant sampling along the path
  24744. createSpacedPointsGeometry: function ( divisions ) {
  24745. var pts = this.getSpacedPoints( divisions );
  24746. return this.createGeometry( pts );
  24747. },
  24748. createGeometry: function ( points ) {
  24749. var geometry = new Geometry();
  24750. for ( var i = 0, l = points.length; i < l; i ++ ) {
  24751. var point = points[ i ];
  24752. geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  24753. }
  24754. return geometry;
  24755. }
  24756. } );
  24757. function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24758. this.aX = aX;
  24759. this.aY = aY;
  24760. this.xRadius = xRadius;
  24761. this.yRadius = yRadius;
  24762. this.aStartAngle = aStartAngle;
  24763. this.aEndAngle = aEndAngle;
  24764. this.aClockwise = aClockwise;
  24765. this.aRotation = aRotation || 0;
  24766. }
  24767. EllipseCurve.prototype = Object.create( Curve.prototype );
  24768. EllipseCurve.prototype.constructor = EllipseCurve;
  24769. EllipseCurve.prototype.isEllipseCurve = true;
  24770. EllipseCurve.prototype.getPoint = function ( t ) {
  24771. var twoPi = Math.PI * 2;
  24772. var deltaAngle = this.aEndAngle - this.aStartAngle;
  24773. var samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  24774. // ensures that deltaAngle is 0 .. 2 PI
  24775. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  24776. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  24777. if ( deltaAngle < Number.EPSILON ) {
  24778. if ( samePoints ) {
  24779. deltaAngle = 0;
  24780. } else {
  24781. deltaAngle = twoPi;
  24782. }
  24783. }
  24784. if ( this.aClockwise === true && ! samePoints ) {
  24785. if ( deltaAngle === twoPi ) {
  24786. deltaAngle = - twoPi;
  24787. } else {
  24788. deltaAngle = deltaAngle - twoPi;
  24789. }
  24790. }
  24791. var angle = this.aStartAngle + t * deltaAngle;
  24792. var x = this.aX + this.xRadius * Math.cos( angle );
  24793. var y = this.aY + this.yRadius * Math.sin( angle );
  24794. if ( this.aRotation !== 0 ) {
  24795. var cos = Math.cos( this.aRotation );
  24796. var sin = Math.sin( this.aRotation );
  24797. var tx = x - this.aX;
  24798. var ty = y - this.aY;
  24799. // Rotate the point about the center of the ellipse.
  24800. x = tx * cos - ty * sin + this.aX;
  24801. y = tx * sin + ty * cos + this.aY;
  24802. }
  24803. return new Vector2( x, y );
  24804. };
  24805. function SplineCurve( points /* array of Vector2 */ ) {
  24806. this.points = ( points === undefined ) ? [] : points;
  24807. }
  24808. SplineCurve.prototype = Object.create( Curve.prototype );
  24809. SplineCurve.prototype.constructor = SplineCurve;
  24810. SplineCurve.prototype.isSplineCurve = true;
  24811. SplineCurve.prototype.getPoint = function ( t ) {
  24812. var points = this.points;
  24813. var point = ( points.length - 1 ) * t;
  24814. var intPoint = Math.floor( point );
  24815. var weight = point - intPoint;
  24816. var point0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  24817. var point1 = points[ intPoint ];
  24818. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  24819. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  24820. return new Vector2(
  24821. CatmullRom( weight, point0.x, point1.x, point2.x, point3.x ),
  24822. CatmullRom( weight, point0.y, point1.y, point2.y, point3.y )
  24823. );
  24824. };
  24825. function CubicBezierCurve( v0, v1, v2, v3 ) {
  24826. this.v0 = v0;
  24827. this.v1 = v1;
  24828. this.v2 = v2;
  24829. this.v3 = v3;
  24830. }
  24831. CubicBezierCurve.prototype = Object.create( Curve.prototype );
  24832. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  24833. CubicBezierCurve.prototype.getPoint = function ( t ) {
  24834. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  24835. return new Vector2(
  24836. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  24837. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  24838. );
  24839. };
  24840. function QuadraticBezierCurve( v0, v1, v2 ) {
  24841. this.v0 = v0;
  24842. this.v1 = v1;
  24843. this.v2 = v2;
  24844. }
  24845. QuadraticBezierCurve.prototype = Object.create( Curve.prototype );
  24846. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  24847. QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  24848. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24849. return new Vector2(
  24850. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24851. QuadraticBezier( t, v0.y, v1.y, v2.y )
  24852. );
  24853. };
  24854. var PathPrototype = Object.assign( Object.create( CurvePath.prototype ), {
  24855. fromPoints: function ( vectors ) {
  24856. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  24857. for ( var i = 1, l = vectors.length; i < l; i ++ ) {
  24858. this.lineTo( vectors[ i ].x, vectors[ i ].y );
  24859. }
  24860. },
  24861. moveTo: function ( x, y ) {
  24862. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  24863. },
  24864. lineTo: function ( x, y ) {
  24865. var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  24866. this.curves.push( curve );
  24867. this.currentPoint.set( x, y );
  24868. },
  24869. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  24870. var curve = new QuadraticBezierCurve(
  24871. this.currentPoint.clone(),
  24872. new Vector2( aCPx, aCPy ),
  24873. new Vector2( aX, aY )
  24874. );
  24875. this.curves.push( curve );
  24876. this.currentPoint.set( aX, aY );
  24877. },
  24878. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  24879. var curve = new CubicBezierCurve(
  24880. this.currentPoint.clone(),
  24881. new Vector2( aCP1x, aCP1y ),
  24882. new Vector2( aCP2x, aCP2y ),
  24883. new Vector2( aX, aY )
  24884. );
  24885. this.curves.push( curve );
  24886. this.currentPoint.set( aX, aY );
  24887. },
  24888. splineThru: function ( pts /*Array of Vector*/ ) {
  24889. var npts = [ this.currentPoint.clone() ].concat( pts );
  24890. var curve = new SplineCurve( npts );
  24891. this.curves.push( curve );
  24892. this.currentPoint.copy( pts[ pts.length - 1 ] );
  24893. },
  24894. arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24895. var x0 = this.currentPoint.x;
  24896. var y0 = this.currentPoint.y;
  24897. this.absarc( aX + x0, aY + y0, aRadius,
  24898. aStartAngle, aEndAngle, aClockwise );
  24899. },
  24900. absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24901. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  24902. },
  24903. ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24904. var x0 = this.currentPoint.x;
  24905. var y0 = this.currentPoint.y;
  24906. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24907. },
  24908. absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24909. var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24910. if ( this.curves.length > 0 ) {
  24911. // if a previous curve is present, attempt to join
  24912. var firstPoint = curve.getPoint( 0 );
  24913. if ( ! firstPoint.equals( this.currentPoint ) ) {
  24914. this.lineTo( firstPoint.x, firstPoint.y );
  24915. }
  24916. }
  24917. this.curves.push( curve );
  24918. var lastPoint = curve.getPoint( 1 );
  24919. this.currentPoint.copy( lastPoint );
  24920. }
  24921. } );
  24922. /**
  24923. * @author zz85 / http://www.lab4games.net/zz85/blog
  24924. * Creates free form 2d path using series of points, lines or curves.
  24925. **/
  24926. function Path( points ) {
  24927. CurvePath.call( this );
  24928. this.currentPoint = new Vector2();
  24929. if ( points ) {
  24930. this.fromPoints( points );
  24931. }
  24932. }
  24933. Path.prototype = PathPrototype;
  24934. PathPrototype.constructor = Path;
  24935. /**
  24936. * @author zz85 / http://www.lab4games.net/zz85/blog
  24937. * Defines a 2d shape plane using paths.
  24938. **/
  24939. // STEP 1 Create a path.
  24940. // STEP 2 Turn path into shape.
  24941. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  24942. // STEP 3a - Extract points from each shape, turn to vertices
  24943. // STEP 3b - Triangulate each shape, add faces.
  24944. function Shape() {
  24945. Path.apply( this, arguments );
  24946. this.holes = [];
  24947. }
  24948. Shape.prototype = Object.assign( Object.create( PathPrototype ), {
  24949. constructor: Shape,
  24950. getPointsHoles: function ( divisions ) {
  24951. var holesPts = [];
  24952. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  24953. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  24954. }
  24955. return holesPts;
  24956. },
  24957. // Get points of shape and holes (keypoints based on segments parameter)
  24958. extractAllPoints: function ( divisions ) {
  24959. return {
  24960. shape: this.getPoints( divisions ),
  24961. holes: this.getPointsHoles( divisions )
  24962. };
  24963. },
  24964. extractPoints: function ( divisions ) {
  24965. return this.extractAllPoints( divisions );
  24966. }
  24967. } );
  24968. /**
  24969. * @author zz85 / http://www.lab4games.net/zz85/blog
  24970. * minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
  24971. **/
  24972. function ShapePath() {
  24973. this.subPaths = [];
  24974. this.currentPath = null;
  24975. }
  24976. ShapePath.prototype = {
  24977. moveTo: function ( x, y ) {
  24978. this.currentPath = new Path();
  24979. this.subPaths.push( this.currentPath );
  24980. this.currentPath.moveTo( x, y );
  24981. },
  24982. lineTo: function ( x, y ) {
  24983. this.currentPath.lineTo( x, y );
  24984. },
  24985. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  24986. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  24987. },
  24988. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  24989. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  24990. },
  24991. splineThru: function ( pts ) {
  24992. this.currentPath.splineThru( pts );
  24993. },
  24994. toShapes: function ( isCCW, noHoles ) {
  24995. function toShapesNoHoles( inSubpaths ) {
  24996. var shapes = [];
  24997. for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) {
  24998. var tmpPath = inSubpaths[ i ];
  24999. var tmpShape = new Shape();
  25000. tmpShape.curves = tmpPath.curves;
  25001. shapes.push( tmpShape );
  25002. }
  25003. return shapes;
  25004. }
  25005. function isPointInsidePolygon( inPt, inPolygon ) {
  25006. var polyLen = inPolygon.length;
  25007. // inPt on polygon contour => immediate success or
  25008. // toggling of inside/outside at every single! intersection point of an edge
  25009. // with the horizontal line through inPt, left of inPt
  25010. // not counting lowerY endpoints of edges and whole edges on that line
  25011. var inside = false;
  25012. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  25013. var edgeLowPt = inPolygon[ p ];
  25014. var edgeHighPt = inPolygon[ q ];
  25015. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  25016. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  25017. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  25018. // not parallel
  25019. if ( edgeDy < 0 ) {
  25020. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  25021. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  25022. }
  25023. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  25024. if ( inPt.y === edgeLowPt.y ) {
  25025. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  25026. // continue; // no intersection or edgeLowPt => doesn't count !!!
  25027. } else {
  25028. var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  25029. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  25030. if ( perpEdge < 0 ) continue;
  25031. inside = ! inside; // true intersection left of inPt
  25032. }
  25033. } else {
  25034. // parallel or collinear
  25035. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  25036. // edge lies on the same horizontal line as inPt
  25037. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  25038. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  25039. // continue;
  25040. }
  25041. }
  25042. return inside;
  25043. }
  25044. var isClockWise = ShapeUtils.isClockWise;
  25045. var subPaths = this.subPaths;
  25046. if ( subPaths.length === 0 ) return [];
  25047. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  25048. var solid, tmpPath, tmpShape, shapes = [];
  25049. if ( subPaths.length === 1 ) {
  25050. tmpPath = subPaths[ 0 ];
  25051. tmpShape = new Shape();
  25052. tmpShape.curves = tmpPath.curves;
  25053. shapes.push( tmpShape );
  25054. return shapes;
  25055. }
  25056. var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  25057. holesFirst = isCCW ? ! holesFirst : holesFirst;
  25058. // console.log("Holes first", holesFirst);
  25059. var betterShapeHoles = [];
  25060. var newShapes = [];
  25061. var newShapeHoles = [];
  25062. var mainIdx = 0;
  25063. var tmpPoints;
  25064. newShapes[ mainIdx ] = undefined;
  25065. newShapeHoles[ mainIdx ] = [];
  25066. for ( var i = 0, l = subPaths.length; i < l; i ++ ) {
  25067. tmpPath = subPaths[ i ];
  25068. tmpPoints = tmpPath.getPoints();
  25069. solid = isClockWise( tmpPoints );
  25070. solid = isCCW ? ! solid : solid;
  25071. if ( solid ) {
  25072. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  25073. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  25074. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  25075. if ( holesFirst ) mainIdx ++;
  25076. newShapeHoles[ mainIdx ] = [];
  25077. //console.log('cw', i);
  25078. } else {
  25079. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  25080. //console.log('ccw', i);
  25081. }
  25082. }
  25083. // only Holes? -> probably all Shapes with wrong orientation
  25084. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  25085. if ( newShapes.length > 1 ) {
  25086. var ambiguous = false;
  25087. var toChange = [];
  25088. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  25089. betterShapeHoles[ sIdx ] = [];
  25090. }
  25091. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  25092. var sho = newShapeHoles[ sIdx ];
  25093. for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  25094. var ho = sho[ hIdx ];
  25095. var hole_unassigned = true;
  25096. for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  25097. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  25098. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  25099. if ( hole_unassigned ) {
  25100. hole_unassigned = false;
  25101. betterShapeHoles[ s2Idx ].push( ho );
  25102. } else {
  25103. ambiguous = true;
  25104. }
  25105. }
  25106. }
  25107. if ( hole_unassigned ) {
  25108. betterShapeHoles[ sIdx ].push( ho );
  25109. }
  25110. }
  25111. }
  25112. // console.log("ambiguous: ", ambiguous);
  25113. if ( toChange.length > 0 ) {
  25114. // console.log("to change: ", toChange);
  25115. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  25116. }
  25117. }
  25118. var tmpHoles;
  25119. for ( var i = 0, il = newShapes.length; i < il; i ++ ) {
  25120. tmpShape = newShapes[ i ].s;
  25121. shapes.push( tmpShape );
  25122. tmpHoles = newShapeHoles[ i ];
  25123. for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  25124. tmpShape.holes.push( tmpHoles[ j ].h );
  25125. }
  25126. }
  25127. //console.log("shape", shapes);
  25128. return shapes;
  25129. }
  25130. };
  25131. /**
  25132. * @author zz85 / http://www.lab4games.net/zz85/blog
  25133. * @author mrdoob / http://mrdoob.com/
  25134. */
  25135. function Font( data ) {
  25136. this.data = data;
  25137. }
  25138. Object.assign( Font.prototype, {
  25139. isFont: true,
  25140. generateShapes: function ( text, size, divisions ) {
  25141. function createPaths( text ) {
  25142. var chars = String( text ).split( '' );
  25143. var scale = size / data.resolution;
  25144. var line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale;
  25145. var offsetX = 0, offsetY = 0;
  25146. var paths = [];
  25147. for ( var i = 0; i < chars.length; i ++ ) {
  25148. var char = chars[ i ];
  25149. if ( char === '\n' ) {
  25150. offsetX = 0;
  25151. offsetY -= line_height;
  25152. } else {
  25153. var ret = createPath( char, scale, offsetX, offsetY );
  25154. offsetX += ret.offsetX;
  25155. paths.push( ret.path );
  25156. }
  25157. }
  25158. return paths;
  25159. }
  25160. function createPath( c, scale, offsetX, offsetY ) {
  25161. var glyph = data.glyphs[ c ] || data.glyphs[ '?' ];
  25162. if ( ! glyph ) return;
  25163. var path = new ShapePath();
  25164. var pts = [];
  25165. var x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2, laste;
  25166. if ( glyph.o ) {
  25167. var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  25168. for ( var i = 0, l = outline.length; i < l; ) {
  25169. var action = outline[ i ++ ];
  25170. switch ( action ) {
  25171. case 'm': // moveTo
  25172. x = outline[ i ++ ] * scale + offsetX;
  25173. y = outline[ i ++ ] * scale + offsetY;
  25174. path.moveTo( x, y );
  25175. break;
  25176. case 'l': // lineTo
  25177. x = outline[ i ++ ] * scale + offsetX;
  25178. y = outline[ i ++ ] * scale + offsetY;
  25179. path.lineTo( x, y );
  25180. break;
  25181. case 'q': // quadraticCurveTo
  25182. cpx = outline[ i ++ ] * scale + offsetX;
  25183. cpy = outline[ i ++ ] * scale + offsetY;
  25184. cpx1 = outline[ i ++ ] * scale + offsetX;
  25185. cpy1 = outline[ i ++ ] * scale + offsetY;
  25186. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  25187. laste = pts[ pts.length - 1 ];
  25188. if ( laste ) {
  25189. cpx0 = laste.x;
  25190. cpy0 = laste.y;
  25191. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  25192. var t = i2 / divisions;
  25193. QuadraticBezier( t, cpx0, cpx1, cpx );
  25194. QuadraticBezier( t, cpy0, cpy1, cpy );
  25195. }
  25196. }
  25197. break;
  25198. case 'b': // bezierCurveTo
  25199. cpx = outline[ i ++ ] * scale + offsetX;
  25200. cpy = outline[ i ++ ] * scale + offsetY;
  25201. cpx1 = outline[ i ++ ] * scale + offsetX;
  25202. cpy1 = outline[ i ++ ] * scale + offsetY;
  25203. cpx2 = outline[ i ++ ] * scale + offsetX;
  25204. cpy2 = outline[ i ++ ] * scale + offsetY;
  25205. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  25206. laste = pts[ pts.length - 1 ];
  25207. if ( laste ) {
  25208. cpx0 = laste.x;
  25209. cpy0 = laste.y;
  25210. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  25211. var t = i2 / divisions;
  25212. CubicBezier( t, cpx0, cpx1, cpx2, cpx );
  25213. CubicBezier( t, cpy0, cpy1, cpy2, cpy );
  25214. }
  25215. }
  25216. break;
  25217. }
  25218. }
  25219. }
  25220. return { offsetX: glyph.ha * scale, path: path };
  25221. }
  25222. //
  25223. if ( size === undefined ) size = 100;
  25224. if ( divisions === undefined ) divisions = 4;
  25225. var data = this.data;
  25226. var paths = createPaths( text );
  25227. var shapes = [];
  25228. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  25229. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  25230. }
  25231. return shapes;
  25232. }
  25233. } );
  25234. /**
  25235. * @author mrdoob / http://mrdoob.com/
  25236. */
  25237. function FontLoader( manager ) {
  25238. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  25239. }
  25240. Object.assign( FontLoader.prototype, {
  25241. load: function ( url, onLoad, onProgress, onError ) {
  25242. var scope = this;
  25243. var loader = new FileLoader( this.manager );
  25244. loader.load( url, function ( text ) {
  25245. var json;
  25246. try {
  25247. json = JSON.parse( text );
  25248. } catch ( e ) {
  25249. console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
  25250. json = JSON.parse( text.substring( 65, text.length - 2 ) );
  25251. }
  25252. var font = scope.parse( json );
  25253. if ( onLoad ) onLoad( font );
  25254. }, onProgress, onError );
  25255. },
  25256. parse: function ( json ) {
  25257. return new Font( json );
  25258. }
  25259. } );
  25260. var context;
  25261. var AudioContext = {
  25262. getContext: function () {
  25263. if ( context === undefined ) {
  25264. context = new ( window.AudioContext || window.webkitAudioContext )();
  25265. }
  25266. return context;
  25267. },
  25268. setContext: function ( value ) {
  25269. context = value;
  25270. }
  25271. };
  25272. /**
  25273. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  25274. */
  25275. function AudioLoader( manager ) {
  25276. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  25277. }
  25278. Object.assign( AudioLoader.prototype, {
  25279. load: function ( url, onLoad, onProgress, onError ) {
  25280. var loader = new FileLoader( this.manager );
  25281. loader.setResponseType( 'arraybuffer' );
  25282. loader.load( url, function ( buffer ) {
  25283. var context = AudioContext.getContext();
  25284. context.decodeAudioData( buffer, function ( audioBuffer ) {
  25285. onLoad( audioBuffer );
  25286. } );
  25287. }, onProgress, onError );
  25288. }
  25289. } );
  25290. /**
  25291. * @author abelnation / http://github.com/abelnation
  25292. */
  25293. function RectAreaLight ( color, intensity, width, height ) {
  25294. Light.call( this, color, intensity );
  25295. this.type = 'RectAreaLight';
  25296. this.position.set( 0, 1, 0 );
  25297. this.updateMatrix();
  25298. this.width = ( width !== undefined ) ? width : 10;
  25299. this.height = ( height !== undefined ) ? height : 10;
  25300. // TODO (abelnation): distance/decay
  25301. // TODO (abelnation): update method for RectAreaLight to update transform to lookat target
  25302. // TODO (abelnation): shadows
  25303. // this.shadow = new THREE.RectAreaLightShadow( new THREE.PerspectiveCamera( 90, 1, 0.5, 500 ) );
  25304. }
  25305. // TODO (abelnation): RectAreaLight update when light shape is changed
  25306. RectAreaLight.prototype = Object.assign( Object.create( Light.prototype ), {
  25307. constructor: RectAreaLight,
  25308. isRectAreaLight: true,
  25309. copy: function ( source ) {
  25310. Light.prototype.copy.call( this, source );
  25311. this.width = source.width;
  25312. this.height = source.height;
  25313. // this.shadow = source.shadow.clone();
  25314. return this;
  25315. }
  25316. } );
  25317. /**
  25318. * @author mrdoob / http://mrdoob.com/
  25319. */
  25320. function StereoCamera() {
  25321. this.type = 'StereoCamera';
  25322. this.aspect = 1;
  25323. this.eyeSep = 0.064;
  25324. this.cameraL = new PerspectiveCamera();
  25325. this.cameraL.layers.enable( 1 );
  25326. this.cameraL.matrixAutoUpdate = false;
  25327. this.cameraR = new PerspectiveCamera();
  25328. this.cameraR.layers.enable( 2 );
  25329. this.cameraR.matrixAutoUpdate = false;
  25330. }
  25331. Object.assign( StereoCamera.prototype, {
  25332. update: ( function () {
  25333. var instance, focus, fov, aspect, near, far, zoom;
  25334. var eyeRight = new Matrix4();
  25335. var eyeLeft = new Matrix4();
  25336. return function update( camera ) {
  25337. var needsUpdate = instance !== this || focus !== camera.focus || fov !== camera.fov ||
  25338. aspect !== camera.aspect * this.aspect || near !== camera.near ||
  25339. far !== camera.far || zoom !== camera.zoom;
  25340. if ( needsUpdate ) {
  25341. instance = this;
  25342. focus = camera.focus;
  25343. fov = camera.fov;
  25344. aspect = camera.aspect * this.aspect;
  25345. near = camera.near;
  25346. far = camera.far;
  25347. zoom = camera.zoom;
  25348. // Off-axis stereoscopic effect based on
  25349. // http://paulbourke.net/stereographics/stereorender/
  25350. var projectionMatrix = camera.projectionMatrix.clone();
  25351. var eyeSep = this.eyeSep / 2;
  25352. var eyeSepOnProjection = eyeSep * near / focus;
  25353. var ymax = ( near * Math.tan( _Math.DEG2RAD * fov * 0.5 ) ) / zoom;
  25354. var xmin, xmax;
  25355. // translate xOffset
  25356. eyeLeft.elements[ 12 ] = - eyeSep;
  25357. eyeRight.elements[ 12 ] = eyeSep;
  25358. // for left eye
  25359. xmin = - ymax * aspect + eyeSepOnProjection;
  25360. xmax = ymax * aspect + eyeSepOnProjection;
  25361. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  25362. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  25363. this.cameraL.projectionMatrix.copy( projectionMatrix );
  25364. // for right eye
  25365. xmin = - ymax * aspect - eyeSepOnProjection;
  25366. xmax = ymax * aspect - eyeSepOnProjection;
  25367. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  25368. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  25369. this.cameraR.projectionMatrix.copy( projectionMatrix );
  25370. }
  25371. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( eyeLeft );
  25372. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( eyeRight );
  25373. };
  25374. } )()
  25375. } );
  25376. /**
  25377. * Camera for rendering cube maps
  25378. * - renders scene into axis-aligned cube
  25379. *
  25380. * @author alteredq / http://alteredqualia.com/
  25381. */
  25382. function CubeCamera( near, far, cubeResolution ) {
  25383. Object3D.call( this );
  25384. this.type = 'CubeCamera';
  25385. var fov = 90, aspect = 1;
  25386. var cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  25387. cameraPX.up.set( 0, - 1, 0 );
  25388. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  25389. this.add( cameraPX );
  25390. var cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  25391. cameraNX.up.set( 0, - 1, 0 );
  25392. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  25393. this.add( cameraNX );
  25394. var cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  25395. cameraPY.up.set( 0, 0, 1 );
  25396. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  25397. this.add( cameraPY );
  25398. var cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  25399. cameraNY.up.set( 0, 0, - 1 );
  25400. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  25401. this.add( cameraNY );
  25402. var cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  25403. cameraPZ.up.set( 0, - 1, 0 );
  25404. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  25405. this.add( cameraPZ );
  25406. var cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  25407. cameraNZ.up.set( 0, - 1, 0 );
  25408. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  25409. this.add( cameraNZ );
  25410. var options = { format: RGBFormat, magFilter: LinearFilter, minFilter: LinearFilter };
  25411. this.renderTarget = new WebGLRenderTargetCube( cubeResolution, cubeResolution, options );
  25412. this.updateCubeMap = function ( renderer, scene ) {
  25413. if ( this.parent === null ) this.updateMatrixWorld();
  25414. var renderTarget = this.renderTarget;
  25415. var generateMipmaps = renderTarget.texture.generateMipmaps;
  25416. renderTarget.texture.generateMipmaps = false;
  25417. renderTarget.activeCubeFace = 0;
  25418. renderer.render( scene, cameraPX, renderTarget );
  25419. renderTarget.activeCubeFace = 1;
  25420. renderer.render( scene, cameraNX, renderTarget );
  25421. renderTarget.activeCubeFace = 2;
  25422. renderer.render( scene, cameraPY, renderTarget );
  25423. renderTarget.activeCubeFace = 3;
  25424. renderer.render( scene, cameraNY, renderTarget );
  25425. renderTarget.activeCubeFace = 4;
  25426. renderer.render( scene, cameraPZ, renderTarget );
  25427. renderTarget.texture.generateMipmaps = generateMipmaps;
  25428. renderTarget.activeCubeFace = 5;
  25429. renderer.render( scene, cameraNZ, renderTarget );
  25430. renderer.setRenderTarget( null );
  25431. };
  25432. }
  25433. CubeCamera.prototype = Object.create( Object3D.prototype );
  25434. CubeCamera.prototype.constructor = CubeCamera;
  25435. /**
  25436. * @author mrdoob / http://mrdoob.com/
  25437. */
  25438. function AudioListener() {
  25439. Object3D.call( this );
  25440. this.type = 'AudioListener';
  25441. this.context = AudioContext.getContext();
  25442. this.gain = this.context.createGain();
  25443. this.gain.connect( this.context.destination );
  25444. this.filter = null;
  25445. }
  25446. AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), {
  25447. constructor: AudioListener,
  25448. getInput: function () {
  25449. return this.gain;
  25450. },
  25451. removeFilter: function ( ) {
  25452. if ( this.filter !== null ) {
  25453. this.gain.disconnect( this.filter );
  25454. this.filter.disconnect( this.context.destination );
  25455. this.gain.connect( this.context.destination );
  25456. this.filter = null;
  25457. }
  25458. },
  25459. getFilter: function () {
  25460. return this.filter;
  25461. },
  25462. setFilter: function ( value ) {
  25463. if ( this.filter !== null ) {
  25464. this.gain.disconnect( this.filter );
  25465. this.filter.disconnect( this.context.destination );
  25466. } else {
  25467. this.gain.disconnect( this.context.destination );
  25468. }
  25469. this.filter = value;
  25470. this.gain.connect( this.filter );
  25471. this.filter.connect( this.context.destination );
  25472. },
  25473. getMasterVolume: function () {
  25474. return this.gain.gain.value;
  25475. },
  25476. setMasterVolume: function ( value ) {
  25477. this.gain.gain.value = value;
  25478. },
  25479. updateMatrixWorld: ( function () {
  25480. var position = new Vector3();
  25481. var quaternion = new Quaternion();
  25482. var scale = new Vector3();
  25483. var orientation = new Vector3();
  25484. return function updateMatrixWorld( force ) {
  25485. Object3D.prototype.updateMatrixWorld.call( this, force );
  25486. var listener = this.context.listener;
  25487. var up = this.up;
  25488. this.matrixWorld.decompose( position, quaternion, scale );
  25489. orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  25490. if ( listener.positionX ) {
  25491. listener.positionX.setValueAtTime( position.x, this.context.currentTime );
  25492. listener.positionY.setValueAtTime( position.y, this.context.currentTime );
  25493. listener.positionZ.setValueAtTime( position.z, this.context.currentTime );
  25494. listener.forwardX.setValueAtTime( orientation.x, this.context.currentTime );
  25495. listener.forwardY.setValueAtTime( orientation.y, this.context.currentTime );
  25496. listener.forwardZ.setValueAtTime( orientation.z, this.context.currentTime );
  25497. listener.upX.setValueAtTime( up.x, this.context.currentTime );
  25498. listener.upY.setValueAtTime( up.y, this.context.currentTime );
  25499. listener.upZ.setValueAtTime( up.z, this.context.currentTime );
  25500. } else {
  25501. listener.setPosition( position.x, position.y, position.z );
  25502. listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z );
  25503. }
  25504. };
  25505. } )()
  25506. } );
  25507. /**
  25508. * @author mrdoob / http://mrdoob.com/
  25509. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  25510. */
  25511. function Audio( listener ) {
  25512. Object3D.call( this );
  25513. this.type = 'Audio';
  25514. this.context = listener.context;
  25515. this.gain = this.context.createGain();
  25516. this.gain.connect( listener.getInput() );
  25517. this.autoplay = false;
  25518. this.buffer = null;
  25519. this.loop = false;
  25520. this.startTime = 0;
  25521. this.playbackRate = 1;
  25522. this.isPlaying = false;
  25523. this.hasPlaybackControl = true;
  25524. this.sourceType = 'empty';
  25525. this.filters = [];
  25526. }
  25527. Audio.prototype = Object.assign( Object.create( Object3D.prototype ), {
  25528. constructor: Audio,
  25529. getOutput: function () {
  25530. return this.gain;
  25531. },
  25532. setNodeSource: function ( audioNode ) {
  25533. this.hasPlaybackControl = false;
  25534. this.sourceType = 'audioNode';
  25535. this.source = audioNode;
  25536. this.connect();
  25537. return this;
  25538. },
  25539. setBuffer: function ( audioBuffer ) {
  25540. this.buffer = audioBuffer;
  25541. this.sourceType = 'buffer';
  25542. if ( this.autoplay ) this.play();
  25543. return this;
  25544. },
  25545. play: function () {
  25546. if ( this.isPlaying === true ) {
  25547. console.warn( 'THREE.Audio: Audio is already playing.' );
  25548. return;
  25549. }
  25550. if ( this.hasPlaybackControl === false ) {
  25551. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25552. return;
  25553. }
  25554. var source = this.context.createBufferSource();
  25555. source.buffer = this.buffer;
  25556. source.loop = this.loop;
  25557. source.onended = this.onEnded.bind( this );
  25558. source.playbackRate.setValueAtTime( this.playbackRate, this.startTime );
  25559. source.start( 0, this.startTime );
  25560. this.isPlaying = true;
  25561. this.source = source;
  25562. return this.connect();
  25563. },
  25564. pause: function () {
  25565. if ( this.hasPlaybackControl === false ) {
  25566. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25567. return;
  25568. }
  25569. this.source.stop();
  25570. this.startTime = this.context.currentTime;
  25571. this.isPlaying = false;
  25572. return this;
  25573. },
  25574. stop: function () {
  25575. if ( this.hasPlaybackControl === false ) {
  25576. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25577. return;
  25578. }
  25579. this.source.stop();
  25580. this.startTime = 0;
  25581. this.isPlaying = false;
  25582. return this;
  25583. },
  25584. connect: function () {
  25585. if ( this.filters.length > 0 ) {
  25586. this.source.connect( this.filters[ 0 ] );
  25587. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  25588. this.filters[ i - 1 ].connect( this.filters[ i ] );
  25589. }
  25590. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  25591. } else {
  25592. this.source.connect( this.getOutput() );
  25593. }
  25594. return this;
  25595. },
  25596. disconnect: function () {
  25597. if ( this.filters.length > 0 ) {
  25598. this.source.disconnect( this.filters[ 0 ] );
  25599. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  25600. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  25601. }
  25602. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  25603. } else {
  25604. this.source.disconnect( this.getOutput() );
  25605. }
  25606. return this;
  25607. },
  25608. getFilters: function () {
  25609. return this.filters;
  25610. },
  25611. setFilters: function ( value ) {
  25612. if ( ! value ) value = [];
  25613. if ( this.isPlaying === true ) {
  25614. this.disconnect();
  25615. this.filters = value;
  25616. this.connect();
  25617. } else {
  25618. this.filters = value;
  25619. }
  25620. return this;
  25621. },
  25622. getFilter: function () {
  25623. return this.getFilters()[ 0 ];
  25624. },
  25625. setFilter: function ( filter ) {
  25626. return this.setFilters( filter ? [ filter ] : [] );
  25627. },
  25628. setPlaybackRate: function ( value ) {
  25629. if ( this.hasPlaybackControl === false ) {
  25630. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25631. return;
  25632. }
  25633. this.playbackRate = value;
  25634. if ( this.isPlaying === true ) {
  25635. this.source.playbackRate.setValueAtTime( this.playbackRate, this.context.currentTime );
  25636. }
  25637. return this;
  25638. },
  25639. getPlaybackRate: function () {
  25640. return this.playbackRate;
  25641. },
  25642. onEnded: function () {
  25643. this.isPlaying = false;
  25644. },
  25645. getLoop: function () {
  25646. if ( this.hasPlaybackControl === false ) {
  25647. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25648. return false;
  25649. }
  25650. return this.loop;
  25651. },
  25652. setLoop: function ( value ) {
  25653. if ( this.hasPlaybackControl === false ) {
  25654. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25655. return;
  25656. }
  25657. this.loop = value;
  25658. if ( this.isPlaying === true ) {
  25659. this.source.loop = this.loop;
  25660. }
  25661. return this;
  25662. },
  25663. getVolume: function () {
  25664. return this.gain.gain.value;
  25665. },
  25666. setVolume: function ( value ) {
  25667. this.gain.gain.value = value;
  25668. return this;
  25669. }
  25670. } );
  25671. /**
  25672. * @author mrdoob / http://mrdoob.com/
  25673. */
  25674. function PositionalAudio( listener ) {
  25675. Audio.call( this, listener );
  25676. this.panner = this.context.createPanner();
  25677. this.panner.connect( this.gain );
  25678. }
  25679. PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), {
  25680. constructor: PositionalAudio,
  25681. getOutput: function () {
  25682. return this.panner;
  25683. },
  25684. getRefDistance: function () {
  25685. return this.panner.refDistance;
  25686. },
  25687. setRefDistance: function ( value ) {
  25688. this.panner.refDistance = value;
  25689. },
  25690. getRolloffFactor: function () {
  25691. return this.panner.rolloffFactor;
  25692. },
  25693. setRolloffFactor: function ( value ) {
  25694. this.panner.rolloffFactor = value;
  25695. },
  25696. getDistanceModel: function () {
  25697. return this.panner.distanceModel;
  25698. },
  25699. setDistanceModel: function ( value ) {
  25700. this.panner.distanceModel = value;
  25701. },
  25702. getMaxDistance: function () {
  25703. return this.panner.maxDistance;
  25704. },
  25705. setMaxDistance: function ( value ) {
  25706. this.panner.maxDistance = value;
  25707. },
  25708. updateMatrixWorld: ( function () {
  25709. var position = new Vector3();
  25710. return function updateMatrixWorld( force ) {
  25711. Object3D.prototype.updateMatrixWorld.call( this, force );
  25712. position.setFromMatrixPosition( this.matrixWorld );
  25713. this.panner.setPosition( position.x, position.y, position.z );
  25714. };
  25715. } )()
  25716. } );
  25717. /**
  25718. * @author mrdoob / http://mrdoob.com/
  25719. */
  25720. function AudioAnalyser( audio, fftSize ) {
  25721. this.analyser = audio.context.createAnalyser();
  25722. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  25723. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  25724. audio.getOutput().connect( this.analyser );
  25725. }
  25726. Object.assign( AudioAnalyser.prototype, {
  25727. getFrequencyData: function () {
  25728. this.analyser.getByteFrequencyData( this.data );
  25729. return this.data;
  25730. },
  25731. getAverageFrequency: function () {
  25732. var value = 0, data = this.getFrequencyData();
  25733. for ( var i = 0; i < data.length; i ++ ) {
  25734. value += data[ i ];
  25735. }
  25736. return value / data.length;
  25737. }
  25738. } );
  25739. /**
  25740. *
  25741. * Buffered scene graph property that allows weighted accumulation.
  25742. *
  25743. *
  25744. * @author Ben Houston / http://clara.io/
  25745. * @author David Sarno / http://lighthaus.us/
  25746. * @author tschw
  25747. */
  25748. function PropertyMixer( binding, typeName, valueSize ) {
  25749. this.binding = binding;
  25750. this.valueSize = valueSize;
  25751. var bufferType = Float64Array,
  25752. mixFunction;
  25753. switch ( typeName ) {
  25754. case 'quaternion':
  25755. mixFunction = this._slerp;
  25756. break;
  25757. case 'string':
  25758. case 'bool':
  25759. bufferType = Array;
  25760. mixFunction = this._select;
  25761. break;
  25762. default:
  25763. mixFunction = this._lerp;
  25764. }
  25765. this.buffer = new bufferType( valueSize * 4 );
  25766. // layout: [ incoming | accu0 | accu1 | orig ]
  25767. //
  25768. // interpolators can use .buffer as their .result
  25769. // the data then goes to 'incoming'
  25770. //
  25771. // 'accu0' and 'accu1' are used frame-interleaved for
  25772. // the cumulative result and are compared to detect
  25773. // changes
  25774. //
  25775. // 'orig' stores the original state of the property
  25776. this._mixBufferRegion = mixFunction;
  25777. this.cumulativeWeight = 0;
  25778. this.useCount = 0;
  25779. this.referenceCount = 0;
  25780. }
  25781. PropertyMixer.prototype = {
  25782. constructor: PropertyMixer,
  25783. // accumulate data in the 'incoming' region into 'accu<i>'
  25784. accumulate: function( accuIndex, weight ) {
  25785. // note: happily accumulating nothing when weight = 0, the caller knows
  25786. // the weight and shouldn't have made the call in the first place
  25787. var buffer = this.buffer,
  25788. stride = this.valueSize,
  25789. offset = accuIndex * stride + stride,
  25790. currentWeight = this.cumulativeWeight;
  25791. if ( currentWeight === 0 ) {
  25792. // accuN := incoming * weight
  25793. for ( var i = 0; i !== stride; ++ i ) {
  25794. buffer[ offset + i ] = buffer[ i ];
  25795. }
  25796. currentWeight = weight;
  25797. } else {
  25798. // accuN := accuN + incoming * weight
  25799. currentWeight += weight;
  25800. var mix = weight / currentWeight;
  25801. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  25802. }
  25803. this.cumulativeWeight = currentWeight;
  25804. },
  25805. // apply the state of 'accu<i>' to the binding when accus differ
  25806. apply: function( accuIndex ) {
  25807. var stride = this.valueSize,
  25808. buffer = this.buffer,
  25809. offset = accuIndex * stride + stride,
  25810. weight = this.cumulativeWeight,
  25811. binding = this.binding;
  25812. this.cumulativeWeight = 0;
  25813. if ( weight < 1 ) {
  25814. // accuN := accuN + original * ( 1 - cumulativeWeight )
  25815. var originalValueOffset = stride * 3;
  25816. this._mixBufferRegion(
  25817. buffer, offset, originalValueOffset, 1 - weight, stride );
  25818. }
  25819. for ( var i = stride, e = stride + stride; i !== e; ++ i ) {
  25820. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  25821. // value has changed -> update scene graph
  25822. binding.setValue( buffer, offset );
  25823. break;
  25824. }
  25825. }
  25826. },
  25827. // remember the state of the bound property and copy it to both accus
  25828. saveOriginalState: function() {
  25829. var binding = this.binding;
  25830. var buffer = this.buffer,
  25831. stride = this.valueSize,
  25832. originalValueOffset = stride * 3;
  25833. binding.getValue( buffer, originalValueOffset );
  25834. // accu[0..1] := orig -- initially detect changes against the original
  25835. for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) {
  25836. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  25837. }
  25838. this.cumulativeWeight = 0;
  25839. },
  25840. // apply the state previously taken via 'saveOriginalState' to the binding
  25841. restoreOriginalState: function() {
  25842. var originalValueOffset = this.valueSize * 3;
  25843. this.binding.setValue( this.buffer, originalValueOffset );
  25844. },
  25845. // mix functions
  25846. _select: function( buffer, dstOffset, srcOffset, t, stride ) {
  25847. if ( t >= 0.5 ) {
  25848. for ( var i = 0; i !== stride; ++ i ) {
  25849. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  25850. }
  25851. }
  25852. },
  25853. _slerp: function( buffer, dstOffset, srcOffset, t, stride ) {
  25854. Quaternion.slerpFlat( buffer, dstOffset,
  25855. buffer, dstOffset, buffer, srcOffset, t );
  25856. },
  25857. _lerp: function( buffer, dstOffset, srcOffset, t, stride ) {
  25858. var s = 1 - t;
  25859. for ( var i = 0; i !== stride; ++ i ) {
  25860. var j = dstOffset + i;
  25861. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  25862. }
  25863. }
  25864. };
  25865. /**
  25866. *
  25867. * A reference to a real property in the scene graph.
  25868. *
  25869. *
  25870. * @author Ben Houston / http://clara.io/
  25871. * @author David Sarno / http://lighthaus.us/
  25872. * @author tschw
  25873. */
  25874. function PropertyBinding( rootNode, path, parsedPath ) {
  25875. this.path = path;
  25876. this.parsedPath = parsedPath ||
  25877. PropertyBinding.parseTrackName( path );
  25878. this.node = PropertyBinding.findNode(
  25879. rootNode, this.parsedPath.nodeName ) || rootNode;
  25880. this.rootNode = rootNode;
  25881. }
  25882. PropertyBinding.prototype = {
  25883. constructor: PropertyBinding,
  25884. getValue: function getValue_unbound( targetArray, offset ) {
  25885. this.bind();
  25886. this.getValue( targetArray, offset );
  25887. // Note: This class uses a State pattern on a per-method basis:
  25888. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  25889. // prototype version of these methods with one that represents
  25890. // the bound state. When the property is not found, the methods
  25891. // become no-ops.
  25892. },
  25893. setValue: function getValue_unbound( sourceArray, offset ) {
  25894. this.bind();
  25895. this.setValue( sourceArray, offset );
  25896. },
  25897. // create getter / setter pair for a property in the scene graph
  25898. bind: function() {
  25899. var targetObject = this.node,
  25900. parsedPath = this.parsedPath,
  25901. objectName = parsedPath.objectName,
  25902. propertyName = parsedPath.propertyName,
  25903. propertyIndex = parsedPath.propertyIndex;
  25904. if ( ! targetObject ) {
  25905. targetObject = PropertyBinding.findNode(
  25906. this.rootNode, parsedPath.nodeName ) || this.rootNode;
  25907. this.node = targetObject;
  25908. }
  25909. // set fail state so we can just 'return' on error
  25910. this.getValue = this._getValue_unavailable;
  25911. this.setValue = this._setValue_unavailable;
  25912. // ensure there is a value node
  25913. if ( ! targetObject ) {
  25914. console.error( " trying to update node for track: " + this.path + " but it wasn't found." );
  25915. return;
  25916. }
  25917. if ( objectName ) {
  25918. var objectIndex = parsedPath.objectIndex;
  25919. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  25920. switch ( objectName ) {
  25921. case 'materials':
  25922. if ( ! targetObject.material ) {
  25923. console.error( ' can not bind to material as node does not have a material', this );
  25924. return;
  25925. }
  25926. if ( ! targetObject.material.materials ) {
  25927. console.error( ' can not bind to material.materials as node.material does not have a materials array', this );
  25928. return;
  25929. }
  25930. targetObject = targetObject.material.materials;
  25931. break;
  25932. case 'bones':
  25933. if ( ! targetObject.skeleton ) {
  25934. console.error( ' can not bind to bones as node does not have a skeleton', this );
  25935. return;
  25936. }
  25937. // potential future optimization: skip this if propertyIndex is already an integer
  25938. // and convert the integer string to a true integer.
  25939. targetObject = targetObject.skeleton.bones;
  25940. // support resolving morphTarget names into indices.
  25941. for ( var i = 0; i < targetObject.length; i ++ ) {
  25942. if ( targetObject[ i ].name === objectIndex ) {
  25943. objectIndex = i;
  25944. break;
  25945. }
  25946. }
  25947. break;
  25948. default:
  25949. if ( targetObject[ objectName ] === undefined ) {
  25950. console.error( ' can not bind to objectName of node, undefined', this );
  25951. return;
  25952. }
  25953. targetObject = targetObject[ objectName ];
  25954. }
  25955. if ( objectIndex !== undefined ) {
  25956. if ( targetObject[ objectIndex ] === undefined ) {
  25957. console.error( " trying to bind to objectIndex of objectName, but is undefined:", this, targetObject );
  25958. return;
  25959. }
  25960. targetObject = targetObject[ objectIndex ];
  25961. }
  25962. }
  25963. // resolve property
  25964. var nodeProperty = targetObject[ propertyName ];
  25965. if ( nodeProperty === undefined ) {
  25966. var nodeName = parsedPath.nodeName;
  25967. console.error( " trying to update property for track: " + nodeName +
  25968. '.' + propertyName + " but it wasn't found.", targetObject );
  25969. return;
  25970. }
  25971. // determine versioning scheme
  25972. var versioning = this.Versioning.None;
  25973. if ( targetObject.needsUpdate !== undefined ) { // material
  25974. versioning = this.Versioning.NeedsUpdate;
  25975. this.targetObject = targetObject;
  25976. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  25977. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  25978. this.targetObject = targetObject;
  25979. }
  25980. // determine how the property gets bound
  25981. var bindingType = this.BindingType.Direct;
  25982. if ( propertyIndex !== undefined ) {
  25983. // access a sub element of the property array (only primitives are supported right now)
  25984. if ( propertyName === "morphTargetInfluences" ) {
  25985. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  25986. // support resolving morphTarget names into indices.
  25987. if ( ! targetObject.geometry ) {
  25988. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry', this );
  25989. return;
  25990. }
  25991. if ( ! targetObject.geometry.morphTargets ) {
  25992. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry.morphTargets', this );
  25993. return;
  25994. }
  25995. for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {
  25996. if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) {
  25997. propertyIndex = i;
  25998. break;
  25999. }
  26000. }
  26001. }
  26002. bindingType = this.BindingType.ArrayElement;
  26003. this.resolvedProperty = nodeProperty;
  26004. this.propertyIndex = propertyIndex;
  26005. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  26006. // must use copy for Object3D.Euler/Quaternion
  26007. bindingType = this.BindingType.HasFromToArray;
  26008. this.resolvedProperty = nodeProperty;
  26009. } else if ( nodeProperty.length !== undefined ) {
  26010. bindingType = this.BindingType.EntireArray;
  26011. this.resolvedProperty = nodeProperty;
  26012. } else {
  26013. this.propertyName = propertyName;
  26014. }
  26015. // select getter / setter
  26016. this.getValue = this.GetterByBindingType[ bindingType ];
  26017. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  26018. },
  26019. unbind: function() {
  26020. this.node = null;
  26021. // back to the prototype version of getValue / setValue
  26022. // note: avoiding to mutate the shape of 'this' via 'delete'
  26023. this.getValue = this._getValue_unbound;
  26024. this.setValue = this._setValue_unbound;
  26025. }
  26026. };
  26027. Object.assign( PropertyBinding.prototype, { // prototype, continued
  26028. // these are used to "bind" a nonexistent property
  26029. _getValue_unavailable: function() {},
  26030. _setValue_unavailable: function() {},
  26031. // initial state of these methods that calls 'bind'
  26032. _getValue_unbound: PropertyBinding.prototype.getValue,
  26033. _setValue_unbound: PropertyBinding.prototype.setValue,
  26034. BindingType: {
  26035. Direct: 0,
  26036. EntireArray: 1,
  26037. ArrayElement: 2,
  26038. HasFromToArray: 3
  26039. },
  26040. Versioning: {
  26041. None: 0,
  26042. NeedsUpdate: 1,
  26043. MatrixWorldNeedsUpdate: 2
  26044. },
  26045. GetterByBindingType: [
  26046. function getValue_direct( buffer, offset ) {
  26047. buffer[ offset ] = this.node[ this.propertyName ];
  26048. },
  26049. function getValue_array( buffer, offset ) {
  26050. var source = this.resolvedProperty;
  26051. for ( var i = 0, n = source.length; i !== n; ++ i ) {
  26052. buffer[ offset ++ ] = source[ i ];
  26053. }
  26054. },
  26055. function getValue_arrayElement( buffer, offset ) {
  26056. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  26057. },
  26058. function getValue_toArray( buffer, offset ) {
  26059. this.resolvedProperty.toArray( buffer, offset );
  26060. }
  26061. ],
  26062. SetterByBindingTypeAndVersioning: [
  26063. [
  26064. // Direct
  26065. function setValue_direct( buffer, offset ) {
  26066. this.node[ this.propertyName ] = buffer[ offset ];
  26067. },
  26068. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  26069. this.node[ this.propertyName ] = buffer[ offset ];
  26070. this.targetObject.needsUpdate = true;
  26071. },
  26072. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26073. this.node[ this.propertyName ] = buffer[ offset ];
  26074. this.targetObject.matrixWorldNeedsUpdate = true;
  26075. }
  26076. ], [
  26077. // EntireArray
  26078. function setValue_array( buffer, offset ) {
  26079. var dest = this.resolvedProperty;
  26080. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  26081. dest[ i ] = buffer[ offset ++ ];
  26082. }
  26083. },
  26084. function setValue_array_setNeedsUpdate( buffer, offset ) {
  26085. var dest = this.resolvedProperty;
  26086. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  26087. dest[ i ] = buffer[ offset ++ ];
  26088. }
  26089. this.targetObject.needsUpdate = true;
  26090. },
  26091. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26092. var dest = this.resolvedProperty;
  26093. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  26094. dest[ i ] = buffer[ offset ++ ];
  26095. }
  26096. this.targetObject.matrixWorldNeedsUpdate = true;
  26097. }
  26098. ], [
  26099. // ArrayElement
  26100. function setValue_arrayElement( buffer, offset ) {
  26101. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26102. },
  26103. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  26104. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26105. this.targetObject.needsUpdate = true;
  26106. },
  26107. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26108. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26109. this.targetObject.matrixWorldNeedsUpdate = true;
  26110. }
  26111. ], [
  26112. // HasToFromArray
  26113. function setValue_fromArray( buffer, offset ) {
  26114. this.resolvedProperty.fromArray( buffer, offset );
  26115. },
  26116. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  26117. this.resolvedProperty.fromArray( buffer, offset );
  26118. this.targetObject.needsUpdate = true;
  26119. },
  26120. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26121. this.resolvedProperty.fromArray( buffer, offset );
  26122. this.targetObject.matrixWorldNeedsUpdate = true;
  26123. }
  26124. ]
  26125. ]
  26126. } );
  26127. PropertyBinding.Composite =
  26128. function( targetGroup, path, optionalParsedPath ) {
  26129. var parsedPath = optionalParsedPath ||
  26130. PropertyBinding.parseTrackName( path );
  26131. this._targetGroup = targetGroup;
  26132. this._bindings = targetGroup.subscribe_( path, parsedPath );
  26133. };
  26134. PropertyBinding.Composite.prototype = {
  26135. constructor: PropertyBinding.Composite,
  26136. getValue: function( array, offset ) {
  26137. this.bind(); // bind all binding
  26138. var firstValidIndex = this._targetGroup.nCachedObjects_,
  26139. binding = this._bindings[ firstValidIndex ];
  26140. // and only call .getValue on the first
  26141. if ( binding !== undefined ) binding.getValue( array, offset );
  26142. },
  26143. setValue: function( array, offset ) {
  26144. var bindings = this._bindings;
  26145. for ( var i = this._targetGroup.nCachedObjects_,
  26146. n = bindings.length; i !== n; ++ i ) {
  26147. bindings[ i ].setValue( array, offset );
  26148. }
  26149. },
  26150. bind: function() {
  26151. var bindings = this._bindings;
  26152. for ( var i = this._targetGroup.nCachedObjects_,
  26153. n = bindings.length; i !== n; ++ i ) {
  26154. bindings[ i ].bind();
  26155. }
  26156. },
  26157. unbind: function() {
  26158. var bindings = this._bindings;
  26159. for ( var i = this._targetGroup.nCachedObjects_,
  26160. n = bindings.length; i !== n; ++ i ) {
  26161. bindings[ i ].unbind();
  26162. }
  26163. }
  26164. };
  26165. PropertyBinding.create = function( root, path, parsedPath ) {
  26166. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  26167. return new PropertyBinding( root, path, parsedPath );
  26168. } else {
  26169. return new PropertyBinding.Composite( root, path, parsedPath );
  26170. }
  26171. };
  26172. PropertyBinding.parseTrackName = function( trackName ) {
  26173. // matches strings in the form of:
  26174. // nodeName.property
  26175. // nodeName.property[accessor]
  26176. // nodeName.material.property[accessor]
  26177. // uuid.property[accessor]
  26178. // uuid.objectName[objectIndex].propertyName[propertyIndex]
  26179. // parentName/nodeName.property
  26180. // parentName/parentName/nodeName.property[index]
  26181. // .bone[Armature.DEF_cog].position
  26182. // scene:helium_balloon_model:helium_balloon_model.position
  26183. // created and tested via https://regex101.com/#javascript
  26184. var re = /^((?:[\w-]+[\/:])*)([\w-]+)?(?:\.([\w-]+)(?:\[(.+)\])?)?\.([\w-]+)(?:\[(.+)\])?$/;
  26185. var matches = re.exec( trackName );
  26186. if ( ! matches ) {
  26187. throw new Error( "cannot parse trackName at all: " + trackName );
  26188. }
  26189. var results = {
  26190. // directoryName: matches[ 1 ], // (tschw) currently unused
  26191. nodeName: matches[ 2 ], // allowed to be null, specified root node.
  26192. objectName: matches[ 3 ],
  26193. objectIndex: matches[ 4 ],
  26194. propertyName: matches[ 5 ],
  26195. propertyIndex: matches[ 6 ] // allowed to be null, specifies that the whole property is set.
  26196. };
  26197. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  26198. throw new Error( "can not parse propertyName from trackName: " + trackName );
  26199. }
  26200. return results;
  26201. };
  26202. PropertyBinding.findNode = function( root, nodeName ) {
  26203. if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  26204. return root;
  26205. }
  26206. // search into skeleton bones.
  26207. if ( root.skeleton ) {
  26208. var searchSkeleton = function( skeleton ) {
  26209. for( var i = 0; i < skeleton.bones.length; i ++ ) {
  26210. var bone = skeleton.bones[ i ];
  26211. if ( bone.name === nodeName ) {
  26212. return bone;
  26213. }
  26214. }
  26215. return null;
  26216. };
  26217. var bone = searchSkeleton( root.skeleton );
  26218. if ( bone ) {
  26219. return bone;
  26220. }
  26221. }
  26222. // search into node subtree.
  26223. if ( root.children ) {
  26224. var searchNodeSubtree = function( children ) {
  26225. for( var i = 0; i < children.length; i ++ ) {
  26226. var childNode = children[ i ];
  26227. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  26228. return childNode;
  26229. }
  26230. var result = searchNodeSubtree( childNode.children );
  26231. if ( result ) return result;
  26232. }
  26233. return null;
  26234. };
  26235. var subTreeNode = searchNodeSubtree( root.children );
  26236. if ( subTreeNode ) {
  26237. return subTreeNode;
  26238. }
  26239. }
  26240. return null;
  26241. };
  26242. /**
  26243. *
  26244. * A group of objects that receives a shared animation state.
  26245. *
  26246. * Usage:
  26247. *
  26248. * - Add objects you would otherwise pass as 'root' to the
  26249. * constructor or the .clipAction method of AnimationMixer.
  26250. *
  26251. * - Instead pass this object as 'root'.
  26252. *
  26253. * - You can also add and remove objects later when the mixer
  26254. * is running.
  26255. *
  26256. * Note:
  26257. *
  26258. * Objects of this class appear as one object to the mixer,
  26259. * so cache control of the individual objects must be done
  26260. * on the group.
  26261. *
  26262. * Limitation:
  26263. *
  26264. * - The animated properties must be compatible among the
  26265. * all objects in the group.
  26266. *
  26267. * - A single property can either be controlled through a
  26268. * target group or directly, but not both.
  26269. *
  26270. * @author tschw
  26271. */
  26272. function AnimationObjectGroup( var_args ) {
  26273. this.uuid = _Math.generateUUID();
  26274. // cached objects followed by the active ones
  26275. this._objects = Array.prototype.slice.call( arguments );
  26276. this.nCachedObjects_ = 0; // threshold
  26277. // note: read by PropertyBinding.Composite
  26278. var indices = {};
  26279. this._indicesByUUID = indices; // for bookkeeping
  26280. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  26281. indices[ arguments[ i ].uuid ] = i;
  26282. }
  26283. this._paths = []; // inside: string
  26284. this._parsedPaths = []; // inside: { we don't care, here }
  26285. this._bindings = []; // inside: Array< PropertyBinding >
  26286. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  26287. var scope = this;
  26288. this.stats = {
  26289. objects: {
  26290. get total() { return scope._objects.length; },
  26291. get inUse() { return this.total - scope.nCachedObjects_; }
  26292. },
  26293. get bindingsPerObject() { return scope._bindings.length; }
  26294. };
  26295. }
  26296. AnimationObjectGroup.prototype = {
  26297. constructor: AnimationObjectGroup,
  26298. isAnimationObjectGroup: true,
  26299. add: function( var_args ) {
  26300. var objects = this._objects,
  26301. nObjects = objects.length,
  26302. nCachedObjects = this.nCachedObjects_,
  26303. indicesByUUID = this._indicesByUUID,
  26304. paths = this._paths,
  26305. parsedPaths = this._parsedPaths,
  26306. bindings = this._bindings,
  26307. nBindings = bindings.length;
  26308. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  26309. var object = arguments[ i ],
  26310. uuid = object.uuid,
  26311. index = indicesByUUID[ uuid ],
  26312. knownObject = undefined;
  26313. if ( index === undefined ) {
  26314. // unknown object -> add it to the ACTIVE region
  26315. index = nObjects ++;
  26316. indicesByUUID[ uuid ] = index;
  26317. objects.push( object );
  26318. // accounting is done, now do the same for all bindings
  26319. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  26320. bindings[ j ].push(
  26321. new PropertyBinding(
  26322. object, paths[ j ], parsedPaths[ j ] ) );
  26323. }
  26324. } else if ( index < nCachedObjects ) {
  26325. knownObject = objects[ index ];
  26326. // move existing object to the ACTIVE region
  26327. var firstActiveIndex = -- nCachedObjects,
  26328. lastCachedObject = objects[ firstActiveIndex ];
  26329. indicesByUUID[ lastCachedObject.uuid ] = index;
  26330. objects[ index ] = lastCachedObject;
  26331. indicesByUUID[ uuid ] = firstActiveIndex;
  26332. objects[ firstActiveIndex ] = object;
  26333. // accounting is done, now do the same for all bindings
  26334. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  26335. var bindingsForPath = bindings[ j ],
  26336. lastCached = bindingsForPath[ firstActiveIndex ],
  26337. binding = bindingsForPath[ index ];
  26338. bindingsForPath[ index ] = lastCached;
  26339. if ( binding === undefined ) {
  26340. // since we do not bother to create new bindings
  26341. // for objects that are cached, the binding may
  26342. // or may not exist
  26343. binding = new PropertyBinding(
  26344. object, paths[ j ], parsedPaths[ j ] );
  26345. }
  26346. bindingsForPath[ firstActiveIndex ] = binding;
  26347. }
  26348. } else if ( objects[ index ] !== knownObject) {
  26349. console.error( "Different objects with the same UUID " +
  26350. "detected. Clean the caches or recreate your " +
  26351. "infrastructure when reloading scenes..." );
  26352. } // else the object is already where we want it to be
  26353. } // for arguments
  26354. this.nCachedObjects_ = nCachedObjects;
  26355. },
  26356. remove: function( var_args ) {
  26357. var objects = this._objects,
  26358. nCachedObjects = this.nCachedObjects_,
  26359. indicesByUUID = this._indicesByUUID,
  26360. bindings = this._bindings,
  26361. nBindings = bindings.length;
  26362. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  26363. var object = arguments[ i ],
  26364. uuid = object.uuid,
  26365. index = indicesByUUID[ uuid ];
  26366. if ( index !== undefined && index >= nCachedObjects ) {
  26367. // move existing object into the CACHED region
  26368. var lastCachedIndex = nCachedObjects ++,
  26369. firstActiveObject = objects[ lastCachedIndex ];
  26370. indicesByUUID[ firstActiveObject.uuid ] = index;
  26371. objects[ index ] = firstActiveObject;
  26372. indicesByUUID[ uuid ] = lastCachedIndex;
  26373. objects[ lastCachedIndex ] = object;
  26374. // accounting is done, now do the same for all bindings
  26375. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  26376. var bindingsForPath = bindings[ j ],
  26377. firstActive = bindingsForPath[ lastCachedIndex ],
  26378. binding = bindingsForPath[ index ];
  26379. bindingsForPath[ index ] = firstActive;
  26380. bindingsForPath[ lastCachedIndex ] = binding;
  26381. }
  26382. }
  26383. } // for arguments
  26384. this.nCachedObjects_ = nCachedObjects;
  26385. },
  26386. // remove & forget
  26387. uncache: function( var_args ) {
  26388. var objects = this._objects,
  26389. nObjects = objects.length,
  26390. nCachedObjects = this.nCachedObjects_,
  26391. indicesByUUID = this._indicesByUUID,
  26392. bindings = this._bindings,
  26393. nBindings = bindings.length;
  26394. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  26395. var object = arguments[ i ],
  26396. uuid = object.uuid,
  26397. index = indicesByUUID[ uuid ];
  26398. if ( index !== undefined ) {
  26399. delete indicesByUUID[ uuid ];
  26400. if ( index < nCachedObjects ) {
  26401. // object is cached, shrink the CACHED region
  26402. var firstActiveIndex = -- nCachedObjects,
  26403. lastCachedObject = objects[ firstActiveIndex ],
  26404. lastIndex = -- nObjects,
  26405. lastObject = objects[ lastIndex ];
  26406. // last cached object takes this object's place
  26407. indicesByUUID[ lastCachedObject.uuid ] = index;
  26408. objects[ index ] = lastCachedObject;
  26409. // last object goes to the activated slot and pop
  26410. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  26411. objects[ firstActiveIndex ] = lastObject;
  26412. objects.pop();
  26413. // accounting is done, now do the same for all bindings
  26414. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  26415. var bindingsForPath = bindings[ j ],
  26416. lastCached = bindingsForPath[ firstActiveIndex ],
  26417. last = bindingsForPath[ lastIndex ];
  26418. bindingsForPath[ index ] = lastCached;
  26419. bindingsForPath[ firstActiveIndex ] = last;
  26420. bindingsForPath.pop();
  26421. }
  26422. } else {
  26423. // object is active, just swap with the last and pop
  26424. var lastIndex = -- nObjects,
  26425. lastObject = objects[ lastIndex ];
  26426. indicesByUUID[ lastObject.uuid ] = index;
  26427. objects[ index ] = lastObject;
  26428. objects.pop();
  26429. // accounting is done, now do the same for all bindings
  26430. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  26431. var bindingsForPath = bindings[ j ];
  26432. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  26433. bindingsForPath.pop();
  26434. }
  26435. } // cached or active
  26436. } // if object is known
  26437. } // for arguments
  26438. this.nCachedObjects_ = nCachedObjects;
  26439. },
  26440. // Internal interface used by befriended PropertyBinding.Composite:
  26441. subscribe_: function( path, parsedPath ) {
  26442. // returns an array of bindings for the given path that is changed
  26443. // according to the contained objects in the group
  26444. var indicesByPath = this._bindingsIndicesByPath,
  26445. index = indicesByPath[ path ],
  26446. bindings = this._bindings;
  26447. if ( index !== undefined ) return bindings[ index ];
  26448. var paths = this._paths,
  26449. parsedPaths = this._parsedPaths,
  26450. objects = this._objects,
  26451. nObjects = objects.length,
  26452. nCachedObjects = this.nCachedObjects_,
  26453. bindingsForPath = new Array( nObjects );
  26454. index = bindings.length;
  26455. indicesByPath[ path ] = index;
  26456. paths.push( path );
  26457. parsedPaths.push( parsedPath );
  26458. bindings.push( bindingsForPath );
  26459. for ( var i = nCachedObjects,
  26460. n = objects.length; i !== n; ++ i ) {
  26461. var object = objects[ i ];
  26462. bindingsForPath[ i ] =
  26463. new PropertyBinding( object, path, parsedPath );
  26464. }
  26465. return bindingsForPath;
  26466. },
  26467. unsubscribe_: function( path ) {
  26468. // tells the group to forget about a property path and no longer
  26469. // update the array previously obtained with 'subscribe_'
  26470. var indicesByPath = this._bindingsIndicesByPath,
  26471. index = indicesByPath[ path ];
  26472. if ( index !== undefined ) {
  26473. var paths = this._paths,
  26474. parsedPaths = this._parsedPaths,
  26475. bindings = this._bindings,
  26476. lastBindingsIndex = bindings.length - 1,
  26477. lastBindings = bindings[ lastBindingsIndex ],
  26478. lastBindingsPath = path[ lastBindingsIndex ];
  26479. indicesByPath[ lastBindingsPath ] = index;
  26480. bindings[ index ] = lastBindings;
  26481. bindings.pop();
  26482. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  26483. parsedPaths.pop();
  26484. paths[ index ] = paths[ lastBindingsIndex ];
  26485. paths.pop();
  26486. }
  26487. }
  26488. };
  26489. /**
  26490. *
  26491. * Action provided by AnimationMixer for scheduling clip playback on specific
  26492. * objects.
  26493. *
  26494. * @author Ben Houston / http://clara.io/
  26495. * @author David Sarno / http://lighthaus.us/
  26496. * @author tschw
  26497. *
  26498. */
  26499. function AnimationAction( mixer, clip, localRoot ) {
  26500. this._mixer = mixer;
  26501. this._clip = clip;
  26502. this._localRoot = localRoot || null;
  26503. var tracks = clip.tracks,
  26504. nTracks = tracks.length,
  26505. interpolants = new Array( nTracks );
  26506. var interpolantSettings = {
  26507. endingStart: ZeroCurvatureEnding,
  26508. endingEnd: ZeroCurvatureEnding
  26509. };
  26510. for ( var i = 0; i !== nTracks; ++ i ) {
  26511. var interpolant = tracks[ i ].createInterpolant( null );
  26512. interpolants[ i ] = interpolant;
  26513. interpolant.settings = interpolantSettings;
  26514. }
  26515. this._interpolantSettings = interpolantSettings;
  26516. this._interpolants = interpolants; // bound by the mixer
  26517. // inside: PropertyMixer (managed by the mixer)
  26518. this._propertyBindings = new Array( nTracks );
  26519. this._cacheIndex = null; // for the memory manager
  26520. this._byClipCacheIndex = null; // for the memory manager
  26521. this._timeScaleInterpolant = null;
  26522. this._weightInterpolant = null;
  26523. this.loop = LoopRepeat;
  26524. this._loopCount = -1;
  26525. // global mixer time when the action is to be started
  26526. // it's set back to 'null' upon start of the action
  26527. this._startTime = null;
  26528. // scaled local time of the action
  26529. // gets clamped or wrapped to 0..clip.duration according to loop
  26530. this.time = 0;
  26531. this.timeScale = 1;
  26532. this._effectiveTimeScale = 1;
  26533. this.weight = 1;
  26534. this._effectiveWeight = 1;
  26535. this.repetitions = Infinity; // no. of repetitions when looping
  26536. this.paused = false; // false -> zero effective time scale
  26537. this.enabled = true; // true -> zero effective weight
  26538. this.clampWhenFinished = false; // keep feeding the last frame?
  26539. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  26540. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  26541. }
  26542. AnimationAction.prototype = {
  26543. constructor: AnimationAction,
  26544. // State & Scheduling
  26545. play: function() {
  26546. this._mixer._activateAction( this );
  26547. return this;
  26548. },
  26549. stop: function() {
  26550. this._mixer._deactivateAction( this );
  26551. return this.reset();
  26552. },
  26553. reset: function() {
  26554. this.paused = false;
  26555. this.enabled = true;
  26556. this.time = 0; // restart clip
  26557. this._loopCount = -1; // forget previous loops
  26558. this._startTime = null; // forget scheduling
  26559. return this.stopFading().stopWarping();
  26560. },
  26561. isRunning: function() {
  26562. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  26563. this._startTime === null && this._mixer._isActiveAction( this );
  26564. },
  26565. // return true when play has been called
  26566. isScheduled: function() {
  26567. return this._mixer._isActiveAction( this );
  26568. },
  26569. startAt: function( time ) {
  26570. this._startTime = time;
  26571. return this;
  26572. },
  26573. setLoop: function( mode, repetitions ) {
  26574. this.loop = mode;
  26575. this.repetitions = repetitions;
  26576. return this;
  26577. },
  26578. // Weight
  26579. // set the weight stopping any scheduled fading
  26580. // although .enabled = false yields an effective weight of zero, this
  26581. // method does *not* change .enabled, because it would be confusing
  26582. setEffectiveWeight: function( weight ) {
  26583. this.weight = weight;
  26584. // note: same logic as when updated at runtime
  26585. this._effectiveWeight = this.enabled ? weight : 0;
  26586. return this.stopFading();
  26587. },
  26588. // return the weight considering fading and .enabled
  26589. getEffectiveWeight: function() {
  26590. return this._effectiveWeight;
  26591. },
  26592. fadeIn: function( duration ) {
  26593. return this._scheduleFading( duration, 0, 1 );
  26594. },
  26595. fadeOut: function( duration ) {
  26596. return this._scheduleFading( duration, 1, 0 );
  26597. },
  26598. crossFadeFrom: function( fadeOutAction, duration, warp ) {
  26599. fadeOutAction.fadeOut( duration );
  26600. this.fadeIn( duration );
  26601. if( warp ) {
  26602. var fadeInDuration = this._clip.duration,
  26603. fadeOutDuration = fadeOutAction._clip.duration,
  26604. startEndRatio = fadeOutDuration / fadeInDuration,
  26605. endStartRatio = fadeInDuration / fadeOutDuration;
  26606. fadeOutAction.warp( 1.0, startEndRatio, duration );
  26607. this.warp( endStartRatio, 1.0, duration );
  26608. }
  26609. return this;
  26610. },
  26611. crossFadeTo: function( fadeInAction, duration, warp ) {
  26612. return fadeInAction.crossFadeFrom( this, duration, warp );
  26613. },
  26614. stopFading: function() {
  26615. var weightInterpolant = this._weightInterpolant;
  26616. if ( weightInterpolant !== null ) {
  26617. this._weightInterpolant = null;
  26618. this._mixer._takeBackControlInterpolant( weightInterpolant );
  26619. }
  26620. return this;
  26621. },
  26622. // Time Scale Control
  26623. // set the weight stopping any scheduled warping
  26624. // although .paused = true yields an effective time scale of zero, this
  26625. // method does *not* change .paused, because it would be confusing
  26626. setEffectiveTimeScale: function( timeScale ) {
  26627. this.timeScale = timeScale;
  26628. this._effectiveTimeScale = this.paused ? 0 :timeScale;
  26629. return this.stopWarping();
  26630. },
  26631. // return the time scale considering warping and .paused
  26632. getEffectiveTimeScale: function() {
  26633. return this._effectiveTimeScale;
  26634. },
  26635. setDuration: function( duration ) {
  26636. this.timeScale = this._clip.duration / duration;
  26637. return this.stopWarping();
  26638. },
  26639. syncWith: function( action ) {
  26640. this.time = action.time;
  26641. this.timeScale = action.timeScale;
  26642. return this.stopWarping();
  26643. },
  26644. halt: function( duration ) {
  26645. return this.warp( this._effectiveTimeScale, 0, duration );
  26646. },
  26647. warp: function( startTimeScale, endTimeScale, duration ) {
  26648. var mixer = this._mixer, now = mixer.time,
  26649. interpolant = this._timeScaleInterpolant,
  26650. timeScale = this.timeScale;
  26651. if ( interpolant === null ) {
  26652. interpolant = mixer._lendControlInterpolant();
  26653. this._timeScaleInterpolant = interpolant;
  26654. }
  26655. var times = interpolant.parameterPositions,
  26656. values = interpolant.sampleValues;
  26657. times[ 0 ] = now;
  26658. times[ 1 ] = now + duration;
  26659. values[ 0 ] = startTimeScale / timeScale;
  26660. values[ 1 ] = endTimeScale / timeScale;
  26661. return this;
  26662. },
  26663. stopWarping: function() {
  26664. var timeScaleInterpolant = this._timeScaleInterpolant;
  26665. if ( timeScaleInterpolant !== null ) {
  26666. this._timeScaleInterpolant = null;
  26667. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  26668. }
  26669. return this;
  26670. },
  26671. // Object Accessors
  26672. getMixer: function() {
  26673. return this._mixer;
  26674. },
  26675. getClip: function() {
  26676. return this._clip;
  26677. },
  26678. getRoot: function() {
  26679. return this._localRoot || this._mixer._root;
  26680. },
  26681. // Interna
  26682. _update: function( time, deltaTime, timeDirection, accuIndex ) {
  26683. // called by the mixer
  26684. var startTime = this._startTime;
  26685. if ( startTime !== null ) {
  26686. // check for scheduled start of action
  26687. var timeRunning = ( time - startTime ) * timeDirection;
  26688. if ( timeRunning < 0 || timeDirection === 0 ) {
  26689. return; // yet to come / don't decide when delta = 0
  26690. }
  26691. // start
  26692. this._startTime = null; // unschedule
  26693. deltaTime = timeDirection * timeRunning;
  26694. }
  26695. // apply time scale and advance time
  26696. deltaTime *= this._updateTimeScale( time );
  26697. var clipTime = this._updateTime( deltaTime );
  26698. // note: _updateTime may disable the action resulting in
  26699. // an effective weight of 0
  26700. var weight = this._updateWeight( time );
  26701. if ( weight > 0 ) {
  26702. var interpolants = this._interpolants;
  26703. var propertyMixers = this._propertyBindings;
  26704. for ( var j = 0, m = interpolants.length; j !== m; ++ j ) {
  26705. interpolants[ j ].evaluate( clipTime );
  26706. propertyMixers[ j ].accumulate( accuIndex, weight );
  26707. }
  26708. }
  26709. },
  26710. _updateWeight: function( time ) {
  26711. var weight = 0;
  26712. if ( this.enabled ) {
  26713. weight = this.weight;
  26714. var interpolant = this._weightInterpolant;
  26715. if ( interpolant !== null ) {
  26716. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  26717. weight *= interpolantValue;
  26718. if ( time > interpolant.parameterPositions[ 1 ] ) {
  26719. this.stopFading();
  26720. if ( interpolantValue === 0 ) {
  26721. // faded out, disable
  26722. this.enabled = false;
  26723. }
  26724. }
  26725. }
  26726. }
  26727. this._effectiveWeight = weight;
  26728. return weight;
  26729. },
  26730. _updateTimeScale: function( time ) {
  26731. var timeScale = 0;
  26732. if ( ! this.paused ) {
  26733. timeScale = this.timeScale;
  26734. var interpolant = this._timeScaleInterpolant;
  26735. if ( interpolant !== null ) {
  26736. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  26737. timeScale *= interpolantValue;
  26738. if ( time > interpolant.parameterPositions[ 1 ] ) {
  26739. this.stopWarping();
  26740. if ( timeScale === 0 ) {
  26741. // motion has halted, pause
  26742. this.paused = true;
  26743. } else {
  26744. // warp done - apply final time scale
  26745. this.timeScale = timeScale;
  26746. }
  26747. }
  26748. }
  26749. }
  26750. this._effectiveTimeScale = timeScale;
  26751. return timeScale;
  26752. },
  26753. _updateTime: function( deltaTime ) {
  26754. var time = this.time + deltaTime;
  26755. if ( deltaTime === 0 ) return time;
  26756. var duration = this._clip.duration,
  26757. loop = this.loop,
  26758. loopCount = this._loopCount;
  26759. if ( loop === LoopOnce ) {
  26760. if ( loopCount === -1 ) {
  26761. // just started
  26762. this._loopCount = 0;
  26763. this._setEndings( true, true, false );
  26764. }
  26765. handle_stop: {
  26766. if ( time >= duration ) {
  26767. time = duration;
  26768. } else if ( time < 0 ) {
  26769. time = 0;
  26770. } else break handle_stop;
  26771. if ( this.clampWhenFinished ) this.paused = true;
  26772. else this.enabled = false;
  26773. this._mixer.dispatchEvent( {
  26774. type: 'finished', action: this,
  26775. direction: deltaTime < 0 ? -1 : 1
  26776. } );
  26777. }
  26778. } else { // repetitive Repeat or PingPong
  26779. var pingPong = ( loop === LoopPingPong );
  26780. if ( loopCount === -1 ) {
  26781. // just started
  26782. if ( deltaTime >= 0 ) {
  26783. loopCount = 0;
  26784. this._setEndings(
  26785. true, this.repetitions === 0, pingPong );
  26786. } else {
  26787. // when looping in reverse direction, the initial
  26788. // transition through zero counts as a repetition,
  26789. // so leave loopCount at -1
  26790. this._setEndings(
  26791. this.repetitions === 0, true, pingPong );
  26792. }
  26793. }
  26794. if ( time >= duration || time < 0 ) {
  26795. // wrap around
  26796. var loopDelta = Math.floor( time / duration ); // signed
  26797. time -= duration * loopDelta;
  26798. loopCount += Math.abs( loopDelta );
  26799. var pending = this.repetitions - loopCount;
  26800. if ( pending < 0 ) {
  26801. // have to stop (switch state, clamp time, fire event)
  26802. if ( this.clampWhenFinished ) this.paused = true;
  26803. else this.enabled = false;
  26804. time = deltaTime > 0 ? duration : 0;
  26805. this._mixer.dispatchEvent( {
  26806. type: 'finished', action: this,
  26807. direction: deltaTime > 0 ? 1 : -1
  26808. } );
  26809. } else {
  26810. // keep running
  26811. if ( pending === 0 ) {
  26812. // entering the last round
  26813. var atStart = deltaTime < 0;
  26814. this._setEndings( atStart, ! atStart, pingPong );
  26815. } else {
  26816. this._setEndings( false, false, pingPong );
  26817. }
  26818. this._loopCount = loopCount;
  26819. this._mixer.dispatchEvent( {
  26820. type: 'loop', action: this, loopDelta: loopDelta
  26821. } );
  26822. }
  26823. }
  26824. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  26825. // invert time for the "pong round"
  26826. this.time = time;
  26827. return duration - time;
  26828. }
  26829. }
  26830. this.time = time;
  26831. return time;
  26832. },
  26833. _setEndings: function( atStart, atEnd, pingPong ) {
  26834. var settings = this._interpolantSettings;
  26835. if ( pingPong ) {
  26836. settings.endingStart = ZeroSlopeEnding;
  26837. settings.endingEnd = ZeroSlopeEnding;
  26838. } else {
  26839. // assuming for LoopOnce atStart == atEnd == true
  26840. if ( atStart ) {
  26841. settings.endingStart = this.zeroSlopeAtStart ?
  26842. ZeroSlopeEnding : ZeroCurvatureEnding;
  26843. } else {
  26844. settings.endingStart = WrapAroundEnding;
  26845. }
  26846. if ( atEnd ) {
  26847. settings.endingEnd = this.zeroSlopeAtEnd ?
  26848. ZeroSlopeEnding : ZeroCurvatureEnding;
  26849. } else {
  26850. settings.endingEnd = WrapAroundEnding;
  26851. }
  26852. }
  26853. },
  26854. _scheduleFading: function( duration, weightNow, weightThen ) {
  26855. var mixer = this._mixer, now = mixer.time,
  26856. interpolant = this._weightInterpolant;
  26857. if ( interpolant === null ) {
  26858. interpolant = mixer._lendControlInterpolant();
  26859. this._weightInterpolant = interpolant;
  26860. }
  26861. var times = interpolant.parameterPositions,
  26862. values = interpolant.sampleValues;
  26863. times[ 0 ] = now; values[ 0 ] = weightNow;
  26864. times[ 1 ] = now + duration; values[ 1 ] = weightThen;
  26865. return this;
  26866. }
  26867. };
  26868. /**
  26869. *
  26870. * Player for AnimationClips.
  26871. *
  26872. *
  26873. * @author Ben Houston / http://clara.io/
  26874. * @author David Sarno / http://lighthaus.us/
  26875. * @author tschw
  26876. */
  26877. function AnimationMixer( root ) {
  26878. this._root = root;
  26879. this._initMemoryManager();
  26880. this._accuIndex = 0;
  26881. this.time = 0;
  26882. this.timeScale = 1.0;
  26883. }
  26884. AnimationMixer.prototype = {
  26885. constructor: AnimationMixer,
  26886. // return an action for a clip optionally using a custom root target
  26887. // object (this method allocates a lot of dynamic memory in case a
  26888. // previously unknown clip/root combination is specified)
  26889. clipAction: function ( clip, optionalRoot ) {
  26890. var root = optionalRoot || this._root,
  26891. rootUuid = root.uuid,
  26892. clipObject = typeof clip === 'string' ?
  26893. AnimationClip.findByName( root, clip ) : clip,
  26894. clipUuid = clipObject !== null ? clipObject.uuid : clip,
  26895. actionsForClip = this._actionsByClip[ clipUuid ],
  26896. prototypeAction = null;
  26897. if ( actionsForClip !== undefined ) {
  26898. var existingAction =
  26899. actionsForClip.actionByRoot[ rootUuid ];
  26900. if ( existingAction !== undefined ) {
  26901. return existingAction;
  26902. }
  26903. // we know the clip, so we don't have to parse all
  26904. // the bindings again but can just copy
  26905. prototypeAction = actionsForClip.knownActions[ 0 ];
  26906. // also, take the clip from the prototype action
  26907. if ( clipObject === null )
  26908. clipObject = prototypeAction._clip;
  26909. }
  26910. // clip must be known when specified via string
  26911. if ( clipObject === null ) return null;
  26912. // allocate all resources required to run it
  26913. var newAction = new AnimationAction( this, clipObject, optionalRoot );
  26914. this._bindAction( newAction, prototypeAction );
  26915. // and make the action known to the memory manager
  26916. this._addInactiveAction( newAction, clipUuid, rootUuid );
  26917. return newAction;
  26918. },
  26919. // get an existing action
  26920. existingAction: function ( clip, optionalRoot ) {
  26921. var root = optionalRoot || this._root,
  26922. rootUuid = root.uuid,
  26923. clipObject = typeof clip === 'string' ?
  26924. AnimationClip.findByName( root, clip ) : clip,
  26925. clipUuid = clipObject ? clipObject.uuid : clip,
  26926. actionsForClip = this._actionsByClip[ clipUuid ];
  26927. if ( actionsForClip !== undefined ) {
  26928. return actionsForClip.actionByRoot[ rootUuid ] || null;
  26929. }
  26930. return null;
  26931. },
  26932. // deactivates all previously scheduled actions
  26933. stopAllAction: function () {
  26934. var actions = this._actions,
  26935. nActions = this._nActiveActions,
  26936. bindings = this._bindings,
  26937. nBindings = this._nActiveBindings;
  26938. this._nActiveActions = 0;
  26939. this._nActiveBindings = 0;
  26940. for ( var i = 0; i !== nActions; ++ i ) {
  26941. actions[ i ].reset();
  26942. }
  26943. for ( var i = 0; i !== nBindings; ++ i ) {
  26944. bindings[ i ].useCount = 0;
  26945. }
  26946. return this;
  26947. },
  26948. // advance the time and update apply the animation
  26949. update: function ( deltaTime ) {
  26950. deltaTime *= this.timeScale;
  26951. var actions = this._actions,
  26952. nActions = this._nActiveActions,
  26953. time = this.time += deltaTime,
  26954. timeDirection = Math.sign( deltaTime ),
  26955. accuIndex = this._accuIndex ^= 1;
  26956. // run active actions
  26957. for ( var i = 0; i !== nActions; ++ i ) {
  26958. var action = actions[ i ];
  26959. if ( action.enabled ) {
  26960. action._update( time, deltaTime, timeDirection, accuIndex );
  26961. }
  26962. }
  26963. // update scene graph
  26964. var bindings = this._bindings,
  26965. nBindings = this._nActiveBindings;
  26966. for ( var i = 0; i !== nBindings; ++ i ) {
  26967. bindings[ i ].apply( accuIndex );
  26968. }
  26969. return this;
  26970. },
  26971. // return this mixer's root target object
  26972. getRoot: function () {
  26973. return this._root;
  26974. },
  26975. // free all resources specific to a particular clip
  26976. uncacheClip: function ( clip ) {
  26977. var actions = this._actions,
  26978. clipUuid = clip.uuid,
  26979. actionsByClip = this._actionsByClip,
  26980. actionsForClip = actionsByClip[ clipUuid ];
  26981. if ( actionsForClip !== undefined ) {
  26982. // note: just calling _removeInactiveAction would mess up the
  26983. // iteration state and also require updating the state we can
  26984. // just throw away
  26985. var actionsToRemove = actionsForClip.knownActions;
  26986. for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  26987. var action = actionsToRemove[ i ];
  26988. this._deactivateAction( action );
  26989. var cacheIndex = action._cacheIndex,
  26990. lastInactiveAction = actions[ actions.length - 1 ];
  26991. action._cacheIndex = null;
  26992. action._byClipCacheIndex = null;
  26993. lastInactiveAction._cacheIndex = cacheIndex;
  26994. actions[ cacheIndex ] = lastInactiveAction;
  26995. actions.pop();
  26996. this._removeInactiveBindingsForAction( action );
  26997. }
  26998. delete actionsByClip[ clipUuid ];
  26999. }
  27000. },
  27001. // free all resources specific to a particular root target object
  27002. uncacheRoot: function ( root ) {
  27003. var rootUuid = root.uuid,
  27004. actionsByClip = this._actionsByClip;
  27005. for ( var clipUuid in actionsByClip ) {
  27006. var actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  27007. action = actionByRoot[ rootUuid ];
  27008. if ( action !== undefined ) {
  27009. this._deactivateAction( action );
  27010. this._removeInactiveAction( action );
  27011. }
  27012. }
  27013. var bindingsByRoot = this._bindingsByRootAndName,
  27014. bindingByName = bindingsByRoot[ rootUuid ];
  27015. if ( bindingByName !== undefined ) {
  27016. for ( var trackName in bindingByName ) {
  27017. var binding = bindingByName[ trackName ];
  27018. binding.restoreOriginalState();
  27019. this._removeInactiveBinding( binding );
  27020. }
  27021. }
  27022. },
  27023. // remove a targeted clip from the cache
  27024. uncacheAction: function ( clip, optionalRoot ) {
  27025. var action = this.existingAction( clip, optionalRoot );
  27026. if ( action !== null ) {
  27027. this._deactivateAction( action );
  27028. this._removeInactiveAction( action );
  27029. }
  27030. }
  27031. };
  27032. // Implementation details:
  27033. Object.assign( AnimationMixer.prototype, {
  27034. _bindAction: function ( action, prototypeAction ) {
  27035. var root = action._localRoot || this._root,
  27036. tracks = action._clip.tracks,
  27037. nTracks = tracks.length,
  27038. bindings = action._propertyBindings,
  27039. interpolants = action._interpolants,
  27040. rootUuid = root.uuid,
  27041. bindingsByRoot = this._bindingsByRootAndName,
  27042. bindingsByName = bindingsByRoot[ rootUuid ];
  27043. if ( bindingsByName === undefined ) {
  27044. bindingsByName = {};
  27045. bindingsByRoot[ rootUuid ] = bindingsByName;
  27046. }
  27047. for ( var i = 0; i !== nTracks; ++ i ) {
  27048. var track = tracks[ i ],
  27049. trackName = track.name,
  27050. binding = bindingsByName[ trackName ];
  27051. if ( binding !== undefined ) {
  27052. bindings[ i ] = binding;
  27053. } else {
  27054. binding = bindings[ i ];
  27055. if ( binding !== undefined ) {
  27056. // existing binding, make sure the cache knows
  27057. if ( binding._cacheIndex === null ) {
  27058. ++ binding.referenceCount;
  27059. this._addInactiveBinding( binding, rootUuid, trackName );
  27060. }
  27061. continue;
  27062. }
  27063. var path = prototypeAction && prototypeAction.
  27064. _propertyBindings[ i ].binding.parsedPath;
  27065. binding = new PropertyMixer(
  27066. PropertyBinding.create( root, trackName, path ),
  27067. track.ValueTypeName, track.getValueSize() );
  27068. ++ binding.referenceCount;
  27069. this._addInactiveBinding( binding, rootUuid, trackName );
  27070. bindings[ i ] = binding;
  27071. }
  27072. interpolants[ i ].resultBuffer = binding.buffer;
  27073. }
  27074. },
  27075. _activateAction: function ( action ) {
  27076. if ( ! this._isActiveAction( action ) ) {
  27077. if ( action._cacheIndex === null ) {
  27078. // this action has been forgotten by the cache, but the user
  27079. // appears to be still using it -> rebind
  27080. var rootUuid = ( action._localRoot || this._root ).uuid,
  27081. clipUuid = action._clip.uuid,
  27082. actionsForClip = this._actionsByClip[ clipUuid ];
  27083. this._bindAction( action,
  27084. actionsForClip && actionsForClip.knownActions[ 0 ] );
  27085. this._addInactiveAction( action, clipUuid, rootUuid );
  27086. }
  27087. var bindings = action._propertyBindings;
  27088. // increment reference counts / sort out state
  27089. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  27090. var binding = bindings[ i ];
  27091. if ( binding.useCount ++ === 0 ) {
  27092. this._lendBinding( binding );
  27093. binding.saveOriginalState();
  27094. }
  27095. }
  27096. this._lendAction( action );
  27097. }
  27098. },
  27099. _deactivateAction: function ( action ) {
  27100. if ( this._isActiveAction( action ) ) {
  27101. var bindings = action._propertyBindings;
  27102. // decrement reference counts / sort out state
  27103. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  27104. var binding = bindings[ i ];
  27105. if ( -- binding.useCount === 0 ) {
  27106. binding.restoreOriginalState();
  27107. this._takeBackBinding( binding );
  27108. }
  27109. }
  27110. this._takeBackAction( action );
  27111. }
  27112. },
  27113. // Memory manager
  27114. _initMemoryManager: function () {
  27115. this._actions = []; // 'nActiveActions' followed by inactive ones
  27116. this._nActiveActions = 0;
  27117. this._actionsByClip = {};
  27118. // inside:
  27119. // {
  27120. // knownActions: Array< AnimationAction > - used as prototypes
  27121. // actionByRoot: AnimationAction - lookup
  27122. // }
  27123. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  27124. this._nActiveBindings = 0;
  27125. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  27126. this._controlInterpolants = []; // same game as above
  27127. this._nActiveControlInterpolants = 0;
  27128. var scope = this;
  27129. this.stats = {
  27130. actions: {
  27131. get total() { return scope._actions.length; },
  27132. get inUse() { return scope._nActiveActions; }
  27133. },
  27134. bindings: {
  27135. get total() { return scope._bindings.length; },
  27136. get inUse() { return scope._nActiveBindings; }
  27137. },
  27138. controlInterpolants: {
  27139. get total() { return scope._controlInterpolants.length; },
  27140. get inUse() { return scope._nActiveControlInterpolants; }
  27141. }
  27142. };
  27143. },
  27144. // Memory management for AnimationAction objects
  27145. _isActiveAction: function ( action ) {
  27146. var index = action._cacheIndex;
  27147. return index !== null && index < this._nActiveActions;
  27148. },
  27149. _addInactiveAction: function ( action, clipUuid, rootUuid ) {
  27150. var actions = this._actions,
  27151. actionsByClip = this._actionsByClip,
  27152. actionsForClip = actionsByClip[ clipUuid ];
  27153. if ( actionsForClip === undefined ) {
  27154. actionsForClip = {
  27155. knownActions: [ action ],
  27156. actionByRoot: {}
  27157. };
  27158. action._byClipCacheIndex = 0;
  27159. actionsByClip[ clipUuid ] = actionsForClip;
  27160. } else {
  27161. var knownActions = actionsForClip.knownActions;
  27162. action._byClipCacheIndex = knownActions.length;
  27163. knownActions.push( action );
  27164. }
  27165. action._cacheIndex = actions.length;
  27166. actions.push( action );
  27167. actionsForClip.actionByRoot[ rootUuid ] = action;
  27168. },
  27169. _removeInactiveAction: function ( action ) {
  27170. var actions = this._actions,
  27171. lastInactiveAction = actions[ actions.length - 1 ],
  27172. cacheIndex = action._cacheIndex;
  27173. lastInactiveAction._cacheIndex = cacheIndex;
  27174. actions[ cacheIndex ] = lastInactiveAction;
  27175. actions.pop();
  27176. action._cacheIndex = null;
  27177. var clipUuid = action._clip.uuid,
  27178. actionsByClip = this._actionsByClip,
  27179. actionsForClip = actionsByClip[ clipUuid ],
  27180. knownActionsForClip = actionsForClip.knownActions,
  27181. lastKnownAction =
  27182. knownActionsForClip[ knownActionsForClip.length - 1 ],
  27183. byClipCacheIndex = action._byClipCacheIndex;
  27184. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  27185. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  27186. knownActionsForClip.pop();
  27187. action._byClipCacheIndex = null;
  27188. var actionByRoot = actionsForClip.actionByRoot,
  27189. rootUuid = ( actions._localRoot || this._root ).uuid;
  27190. delete actionByRoot[ rootUuid ];
  27191. if ( knownActionsForClip.length === 0 ) {
  27192. delete actionsByClip[ clipUuid ];
  27193. }
  27194. this._removeInactiveBindingsForAction( action );
  27195. },
  27196. _removeInactiveBindingsForAction: function ( action ) {
  27197. var bindings = action._propertyBindings;
  27198. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  27199. var binding = bindings[ i ];
  27200. if ( -- binding.referenceCount === 0 ) {
  27201. this._removeInactiveBinding( binding );
  27202. }
  27203. }
  27204. },
  27205. _lendAction: function ( action ) {
  27206. // [ active actions | inactive actions ]
  27207. // [ active actions >| inactive actions ]
  27208. // s a
  27209. // <-swap->
  27210. // a s
  27211. var actions = this._actions,
  27212. prevIndex = action._cacheIndex,
  27213. lastActiveIndex = this._nActiveActions ++,
  27214. firstInactiveAction = actions[ lastActiveIndex ];
  27215. action._cacheIndex = lastActiveIndex;
  27216. actions[ lastActiveIndex ] = action;
  27217. firstInactiveAction._cacheIndex = prevIndex;
  27218. actions[ prevIndex ] = firstInactiveAction;
  27219. },
  27220. _takeBackAction: function ( action ) {
  27221. // [ active actions | inactive actions ]
  27222. // [ active actions |< inactive actions ]
  27223. // a s
  27224. // <-swap->
  27225. // s a
  27226. var actions = this._actions,
  27227. prevIndex = action._cacheIndex,
  27228. firstInactiveIndex = -- this._nActiveActions,
  27229. lastActiveAction = actions[ firstInactiveIndex ];
  27230. action._cacheIndex = firstInactiveIndex;
  27231. actions[ firstInactiveIndex ] = action;
  27232. lastActiveAction._cacheIndex = prevIndex;
  27233. actions[ prevIndex ] = lastActiveAction;
  27234. },
  27235. // Memory management for PropertyMixer objects
  27236. _addInactiveBinding: function ( binding, rootUuid, trackName ) {
  27237. var bindingsByRoot = this._bindingsByRootAndName,
  27238. bindingByName = bindingsByRoot[ rootUuid ],
  27239. bindings = this._bindings;
  27240. if ( bindingByName === undefined ) {
  27241. bindingByName = {};
  27242. bindingsByRoot[ rootUuid ] = bindingByName;
  27243. }
  27244. bindingByName[ trackName ] = binding;
  27245. binding._cacheIndex = bindings.length;
  27246. bindings.push( binding );
  27247. },
  27248. _removeInactiveBinding: function ( binding ) {
  27249. var bindings = this._bindings,
  27250. propBinding = binding.binding,
  27251. rootUuid = propBinding.rootNode.uuid,
  27252. trackName = propBinding.path,
  27253. bindingsByRoot = this._bindingsByRootAndName,
  27254. bindingByName = bindingsByRoot[ rootUuid ],
  27255. lastInactiveBinding = bindings[ bindings.length - 1 ],
  27256. cacheIndex = binding._cacheIndex;
  27257. lastInactiveBinding._cacheIndex = cacheIndex;
  27258. bindings[ cacheIndex ] = lastInactiveBinding;
  27259. bindings.pop();
  27260. delete bindingByName[ trackName ];
  27261. remove_empty_map: {
  27262. for ( var _ in bindingByName ) break remove_empty_map;
  27263. delete bindingsByRoot[ rootUuid ];
  27264. }
  27265. },
  27266. _lendBinding: function ( binding ) {
  27267. var bindings = this._bindings,
  27268. prevIndex = binding._cacheIndex,
  27269. lastActiveIndex = this._nActiveBindings ++,
  27270. firstInactiveBinding = bindings[ lastActiveIndex ];
  27271. binding._cacheIndex = lastActiveIndex;
  27272. bindings[ lastActiveIndex ] = binding;
  27273. firstInactiveBinding._cacheIndex = prevIndex;
  27274. bindings[ prevIndex ] = firstInactiveBinding;
  27275. },
  27276. _takeBackBinding: function ( binding ) {
  27277. var bindings = this._bindings,
  27278. prevIndex = binding._cacheIndex,
  27279. firstInactiveIndex = -- this._nActiveBindings,
  27280. lastActiveBinding = bindings[ firstInactiveIndex ];
  27281. binding._cacheIndex = firstInactiveIndex;
  27282. bindings[ firstInactiveIndex ] = binding;
  27283. lastActiveBinding._cacheIndex = prevIndex;
  27284. bindings[ prevIndex ] = lastActiveBinding;
  27285. },
  27286. // Memory management of Interpolants for weight and time scale
  27287. _lendControlInterpolant: function () {
  27288. var interpolants = this._controlInterpolants,
  27289. lastActiveIndex = this._nActiveControlInterpolants ++,
  27290. interpolant = interpolants[ lastActiveIndex ];
  27291. if ( interpolant === undefined ) {
  27292. interpolant = new LinearInterpolant(
  27293. new Float32Array( 2 ), new Float32Array( 2 ),
  27294. 1, this._controlInterpolantsResultBuffer );
  27295. interpolant.__cacheIndex = lastActiveIndex;
  27296. interpolants[ lastActiveIndex ] = interpolant;
  27297. }
  27298. return interpolant;
  27299. },
  27300. _takeBackControlInterpolant: function ( interpolant ) {
  27301. var interpolants = this._controlInterpolants,
  27302. prevIndex = interpolant.__cacheIndex,
  27303. firstInactiveIndex = -- this._nActiveControlInterpolants,
  27304. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  27305. interpolant.__cacheIndex = firstInactiveIndex;
  27306. interpolants[ firstInactiveIndex ] = interpolant;
  27307. lastActiveInterpolant.__cacheIndex = prevIndex;
  27308. interpolants[ prevIndex ] = lastActiveInterpolant;
  27309. },
  27310. _controlInterpolantsResultBuffer: new Float32Array( 1 )
  27311. } );
  27312. Object.assign( AnimationMixer.prototype, EventDispatcher.prototype );
  27313. /**
  27314. * @author mrdoob / http://mrdoob.com/
  27315. */
  27316. function Uniform( value ) {
  27317. if ( typeof value === 'string' ) {
  27318. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  27319. value = arguments[ 1 ];
  27320. }
  27321. this.value = value;
  27322. }
  27323. Uniform.prototype.clone = function () {
  27324. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  27325. };
  27326. /**
  27327. * @author benaadams / https://twitter.com/ben_a_adams
  27328. */
  27329. function InstancedBufferGeometry() {
  27330. BufferGeometry.call( this );
  27331. this.type = 'InstancedBufferGeometry';
  27332. this.maxInstancedCount = undefined;
  27333. }
  27334. InstancedBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  27335. InstancedBufferGeometry.prototype.constructor = InstancedBufferGeometry;
  27336. InstancedBufferGeometry.prototype.isInstancedBufferGeometry = true;
  27337. InstancedBufferGeometry.prototype.addGroup = function ( start, count, materialIndex ) {
  27338. this.groups.push( {
  27339. start: start,
  27340. count: count,
  27341. materialIndex: materialIndex
  27342. } );
  27343. };
  27344. InstancedBufferGeometry.prototype.copy = function ( source ) {
  27345. var index = source.index;
  27346. if ( index !== null ) {
  27347. this.setIndex( index.clone() );
  27348. }
  27349. var attributes = source.attributes;
  27350. for ( var name in attributes ) {
  27351. var attribute = attributes[ name ];
  27352. this.addAttribute( name, attribute.clone() );
  27353. }
  27354. var groups = source.groups;
  27355. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  27356. var group = groups[ i ];
  27357. this.addGroup( group.start, group.count, group.materialIndex );
  27358. }
  27359. return this;
  27360. };
  27361. /**
  27362. * @author benaadams / https://twitter.com/ben_a_adams
  27363. */
  27364. function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) {
  27365. this.uuid = _Math.generateUUID();
  27366. this.data = interleavedBuffer;
  27367. this.itemSize = itemSize;
  27368. this.offset = offset;
  27369. this.normalized = normalized === true;
  27370. }
  27371. InterleavedBufferAttribute.prototype = {
  27372. constructor: InterleavedBufferAttribute,
  27373. isInterleavedBufferAttribute: true,
  27374. get count() {
  27375. return this.data.count;
  27376. },
  27377. get array() {
  27378. return this.data.array;
  27379. },
  27380. setX: function ( index, x ) {
  27381. this.data.array[ index * this.data.stride + this.offset ] = x;
  27382. return this;
  27383. },
  27384. setY: function ( index, y ) {
  27385. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  27386. return this;
  27387. },
  27388. setZ: function ( index, z ) {
  27389. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  27390. return this;
  27391. },
  27392. setW: function ( index, w ) {
  27393. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  27394. return this;
  27395. },
  27396. getX: function ( index ) {
  27397. return this.data.array[ index * this.data.stride + this.offset ];
  27398. },
  27399. getY: function ( index ) {
  27400. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  27401. },
  27402. getZ: function ( index ) {
  27403. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  27404. },
  27405. getW: function ( index ) {
  27406. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  27407. },
  27408. setXY: function ( index, x, y ) {
  27409. index = index * this.data.stride + this.offset;
  27410. this.data.array[ index + 0 ] = x;
  27411. this.data.array[ index + 1 ] = y;
  27412. return this;
  27413. },
  27414. setXYZ: function ( index, x, y, z ) {
  27415. index = index * this.data.stride + this.offset;
  27416. this.data.array[ index + 0 ] = x;
  27417. this.data.array[ index + 1 ] = y;
  27418. this.data.array[ index + 2 ] = z;
  27419. return this;
  27420. },
  27421. setXYZW: function ( index, x, y, z, w ) {
  27422. index = index * this.data.stride + this.offset;
  27423. this.data.array[ index + 0 ] = x;
  27424. this.data.array[ index + 1 ] = y;
  27425. this.data.array[ index + 2 ] = z;
  27426. this.data.array[ index + 3 ] = w;
  27427. return this;
  27428. }
  27429. };
  27430. /**
  27431. * @author benaadams / https://twitter.com/ben_a_adams
  27432. */
  27433. function InterleavedBuffer( array, stride ) {
  27434. this.uuid = _Math.generateUUID();
  27435. this.array = array;
  27436. this.stride = stride;
  27437. this.count = array !== undefined ? array.length / stride : 0;
  27438. this.dynamic = false;
  27439. this.updateRange = { offset: 0, count: - 1 };
  27440. this.onUploadCallback = function () {};
  27441. this.version = 0;
  27442. }
  27443. InterleavedBuffer.prototype = {
  27444. constructor: InterleavedBuffer,
  27445. isInterleavedBuffer: true,
  27446. set needsUpdate( value ) {
  27447. if ( value === true ) this.version ++;
  27448. },
  27449. setArray: function ( array ) {
  27450. if ( Array.isArray( array ) ) {
  27451. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  27452. }
  27453. this.count = array !== undefined ? array.length / this.stride : 0;
  27454. this.array = array;
  27455. },
  27456. setDynamic: function ( value ) {
  27457. this.dynamic = value;
  27458. return this;
  27459. },
  27460. copy: function ( source ) {
  27461. this.array = new source.array.constructor( source.array );
  27462. this.count = source.count;
  27463. this.stride = source.stride;
  27464. this.dynamic = source.dynamic;
  27465. return this;
  27466. },
  27467. copyAt: function ( index1, attribute, index2 ) {
  27468. index1 *= this.stride;
  27469. index2 *= attribute.stride;
  27470. for ( var i = 0, l = this.stride; i < l; i ++ ) {
  27471. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  27472. }
  27473. return this;
  27474. },
  27475. set: function ( value, offset ) {
  27476. if ( offset === undefined ) offset = 0;
  27477. this.array.set( value, offset );
  27478. return this;
  27479. },
  27480. clone: function () {
  27481. return new this.constructor().copy( this );
  27482. },
  27483. onUpload: function ( callback ) {
  27484. this.onUploadCallback = callback;
  27485. return this;
  27486. }
  27487. };
  27488. /**
  27489. * @author benaadams / https://twitter.com/ben_a_adams
  27490. */
  27491. function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) {
  27492. InterleavedBuffer.call( this, array, stride );
  27493. this.meshPerAttribute = meshPerAttribute || 1;
  27494. }
  27495. InstancedInterleavedBuffer.prototype = Object.create( InterleavedBuffer.prototype );
  27496. InstancedInterleavedBuffer.prototype.constructor = InstancedInterleavedBuffer;
  27497. InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true;
  27498. InstancedInterleavedBuffer.prototype.copy = function ( source ) {
  27499. InterleavedBuffer.prototype.copy.call( this, source );
  27500. this.meshPerAttribute = source.meshPerAttribute;
  27501. return this;
  27502. };
  27503. /**
  27504. * @author benaadams / https://twitter.com/ben_a_adams
  27505. */
  27506. function InstancedBufferAttribute( array, itemSize, meshPerAttribute ) {
  27507. BufferAttribute.call( this, array, itemSize );
  27508. this.meshPerAttribute = meshPerAttribute || 1;
  27509. }
  27510. InstancedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  27511. InstancedBufferAttribute.prototype.constructor = InstancedBufferAttribute;
  27512. InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true;
  27513. InstancedBufferAttribute.prototype.copy = function ( source ) {
  27514. BufferAttribute.prototype.copy.call( this, source );
  27515. this.meshPerAttribute = source.meshPerAttribute;
  27516. return this;
  27517. };
  27518. /**
  27519. * @author mrdoob / http://mrdoob.com/
  27520. * @author bhouston / http://clara.io/
  27521. * @author stephomi / http://stephaneginier.com/
  27522. */
  27523. function Raycaster( origin, direction, near, far ) {
  27524. this.ray = new Ray( origin, direction );
  27525. // direction is assumed to be normalized (for accurate distance calculations)
  27526. this.near = near || 0;
  27527. this.far = far || Infinity;
  27528. this.params = {
  27529. Mesh: {},
  27530. Line: {},
  27531. LOD: {},
  27532. Points: { threshold: 1 },
  27533. Sprite: {}
  27534. };
  27535. Object.defineProperties( this.params, {
  27536. PointCloud: {
  27537. get: function () {
  27538. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  27539. return this.Points;
  27540. }
  27541. }
  27542. } );
  27543. }
  27544. function ascSort( a, b ) {
  27545. return a.distance - b.distance;
  27546. }
  27547. function intersectObject( object, raycaster, intersects, recursive ) {
  27548. if ( object.visible === false ) return;
  27549. object.raycast( raycaster, intersects );
  27550. if ( recursive === true ) {
  27551. var children = object.children;
  27552. for ( var i = 0, l = children.length; i < l; i ++ ) {
  27553. intersectObject( children[ i ], raycaster, intersects, true );
  27554. }
  27555. }
  27556. }
  27557. //
  27558. Raycaster.prototype = {
  27559. constructor: Raycaster,
  27560. linePrecision: 1,
  27561. set: function ( origin, direction ) {
  27562. // direction is assumed to be normalized (for accurate distance calculations)
  27563. this.ray.set( origin, direction );
  27564. },
  27565. setFromCamera: function ( coords, camera ) {
  27566. if ( (camera && camera.isPerspectiveCamera) ) {
  27567. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  27568. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  27569. } else if ( (camera && camera.isOrthographicCamera) ) {
  27570. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  27571. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  27572. } else {
  27573. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  27574. }
  27575. },
  27576. intersectObject: function ( object, recursive ) {
  27577. var intersects = [];
  27578. intersectObject( object, this, intersects, recursive );
  27579. intersects.sort( ascSort );
  27580. return intersects;
  27581. },
  27582. intersectObjects: function ( objects, recursive ) {
  27583. var intersects = [];
  27584. if ( Array.isArray( objects ) === false ) {
  27585. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  27586. return intersects;
  27587. }
  27588. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  27589. intersectObject( objects[ i ], this, intersects, recursive );
  27590. }
  27591. intersects.sort( ascSort );
  27592. return intersects;
  27593. }
  27594. };
  27595. /**
  27596. * @author alteredq / http://alteredqualia.com/
  27597. */
  27598. function Clock( autoStart ) {
  27599. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  27600. this.startTime = 0;
  27601. this.oldTime = 0;
  27602. this.elapsedTime = 0;
  27603. this.running = false;
  27604. }
  27605. Clock.prototype = {
  27606. constructor: Clock,
  27607. start: function () {
  27608. this.startTime = ( performance || Date ).now();
  27609. this.oldTime = this.startTime;
  27610. this.elapsedTime = 0;
  27611. this.running = true;
  27612. },
  27613. stop: function () {
  27614. this.getElapsedTime();
  27615. this.running = false;
  27616. },
  27617. getElapsedTime: function () {
  27618. this.getDelta();
  27619. return this.elapsedTime;
  27620. },
  27621. getDelta: function () {
  27622. var diff = 0;
  27623. if ( this.autoStart && ! this.running ) {
  27624. this.start();
  27625. }
  27626. if ( this.running ) {
  27627. var newTime = ( performance || Date ).now();
  27628. diff = ( newTime - this.oldTime ) / 1000;
  27629. this.oldTime = newTime;
  27630. this.elapsedTime += diff;
  27631. }
  27632. return diff;
  27633. }
  27634. };
  27635. /**
  27636. * @author bhouston / http://clara.io
  27637. * @author WestLangley / http://github.com/WestLangley
  27638. *
  27639. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  27640. *
  27641. * The poles (phi) are at the positive and negative y axis.
  27642. * The equator starts at positive z.
  27643. */
  27644. function Spherical( radius, phi, theta ) {
  27645. this.radius = ( radius !== undefined ) ? radius : 1.0;
  27646. this.phi = ( phi !== undefined ) ? phi : 0; // up / down towards top and bottom pole
  27647. this.theta = ( theta !== undefined ) ? theta : 0; // around the equator of the sphere
  27648. return this;
  27649. }
  27650. Spherical.prototype = {
  27651. constructor: Spherical,
  27652. set: function ( radius, phi, theta ) {
  27653. this.radius = radius;
  27654. this.phi = phi;
  27655. this.theta = theta;
  27656. return this;
  27657. },
  27658. clone: function () {
  27659. return new this.constructor().copy( this );
  27660. },
  27661. copy: function ( other ) {
  27662. this.radius = other.radius;
  27663. this.phi = other.phi;
  27664. this.theta = other.theta;
  27665. return this;
  27666. },
  27667. // restrict phi to be betwee EPS and PI-EPS
  27668. makeSafe: function() {
  27669. var EPS = 0.000001;
  27670. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  27671. return this;
  27672. },
  27673. setFromVector3: function( vec3 ) {
  27674. this.radius = vec3.length();
  27675. if ( this.radius === 0 ) {
  27676. this.theta = 0;
  27677. this.phi = 0;
  27678. } else {
  27679. this.theta = Math.atan2( vec3.x, vec3.z ); // equator angle around y-up axis
  27680. this.phi = Math.acos( _Math.clamp( vec3.y / this.radius, - 1, 1 ) ); // polar angle
  27681. }
  27682. return this;
  27683. }
  27684. };
  27685. /**
  27686. * @author Mugen87 / https://github.com/Mugen87
  27687. *
  27688. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  27689. *
  27690. */
  27691. function Cylindrical( radius, theta, y ) {
  27692. this.radius = ( radius !== undefined ) ? radius : 1.0; // distance from the origin to a point in the x-z plane
  27693. this.theta = ( theta !== undefined ) ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  27694. this.y = ( y !== undefined ) ? y : 0; // height above the x-z plane
  27695. return this;
  27696. }
  27697. Cylindrical.prototype = {
  27698. constructor: Cylindrical,
  27699. set: function ( radius, theta, y ) {
  27700. this.radius = radius;
  27701. this.theta = theta;
  27702. this.y = y;
  27703. return this;
  27704. },
  27705. clone: function () {
  27706. return new this.constructor().copy( this );
  27707. },
  27708. copy: function ( other ) {
  27709. this.radius = other.radius;
  27710. this.theta = other.theta;
  27711. this.y = other.y;
  27712. return this;
  27713. },
  27714. setFromVector3: function( vec3 ) {
  27715. this.radius = Math.sqrt( vec3.x * vec3.x + vec3.z * vec3.z );
  27716. this.theta = Math.atan2( vec3.x, vec3.z );
  27717. this.y = vec3.y;
  27718. return this;
  27719. }
  27720. };
  27721. /**
  27722. * @author alteredq / http://alteredqualia.com/
  27723. */
  27724. function MorphBlendMesh( geometry, material ) {
  27725. Mesh.call( this, geometry, material );
  27726. this.animationsMap = {};
  27727. this.animationsList = [];
  27728. // prepare default animation
  27729. // (all frames played together in 1 second)
  27730. var numFrames = this.geometry.morphTargets.length;
  27731. var name = "__default";
  27732. var startFrame = 0;
  27733. var endFrame = numFrames - 1;
  27734. var fps = numFrames / 1;
  27735. this.createAnimation( name, startFrame, endFrame, fps );
  27736. this.setAnimationWeight( name, 1 );
  27737. }
  27738. MorphBlendMesh.prototype = Object.create( Mesh.prototype );
  27739. MorphBlendMesh.prototype.constructor = MorphBlendMesh;
  27740. MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  27741. var animation = {
  27742. start: start,
  27743. end: end,
  27744. length: end - start + 1,
  27745. fps: fps,
  27746. duration: ( end - start ) / fps,
  27747. lastFrame: 0,
  27748. currentFrame: 0,
  27749. active: false,
  27750. time: 0,
  27751. direction: 1,
  27752. weight: 1,
  27753. directionBackwards: false,
  27754. mirroredLoop: false
  27755. };
  27756. this.animationsMap[ name ] = animation;
  27757. this.animationsList.push( animation );
  27758. };
  27759. MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  27760. var pattern = /([a-z]+)_?(\d+)/i;
  27761. var firstAnimation, frameRanges = {};
  27762. var geometry = this.geometry;
  27763. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  27764. var morph = geometry.morphTargets[ i ];
  27765. var chunks = morph.name.match( pattern );
  27766. if ( chunks && chunks.length > 1 ) {
  27767. var name = chunks[ 1 ];
  27768. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity };
  27769. var range = frameRanges[ name ];
  27770. if ( i < range.start ) range.start = i;
  27771. if ( i > range.end ) range.end = i;
  27772. if ( ! firstAnimation ) firstAnimation = name;
  27773. }
  27774. }
  27775. for ( var name in frameRanges ) {
  27776. var range = frameRanges[ name ];
  27777. this.createAnimation( name, range.start, range.end, fps );
  27778. }
  27779. this.firstAnimation = firstAnimation;
  27780. };
  27781. MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  27782. var animation = this.animationsMap[ name ];
  27783. if ( animation ) {
  27784. animation.direction = 1;
  27785. animation.directionBackwards = false;
  27786. }
  27787. };
  27788. MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  27789. var animation = this.animationsMap[ name ];
  27790. if ( animation ) {
  27791. animation.direction = - 1;
  27792. animation.directionBackwards = true;
  27793. }
  27794. };
  27795. MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  27796. var animation = this.animationsMap[ name ];
  27797. if ( animation ) {
  27798. animation.fps = fps;
  27799. animation.duration = ( animation.end - animation.start ) / animation.fps;
  27800. }
  27801. };
  27802. MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  27803. var animation = this.animationsMap[ name ];
  27804. if ( animation ) {
  27805. animation.duration = duration;
  27806. animation.fps = ( animation.end - animation.start ) / animation.duration;
  27807. }
  27808. };
  27809. MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  27810. var animation = this.animationsMap[ name ];
  27811. if ( animation ) {
  27812. animation.weight = weight;
  27813. }
  27814. };
  27815. MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  27816. var animation = this.animationsMap[ name ];
  27817. if ( animation ) {
  27818. animation.time = time;
  27819. }
  27820. };
  27821. MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  27822. var time = 0;
  27823. var animation = this.animationsMap[ name ];
  27824. if ( animation ) {
  27825. time = animation.time;
  27826. }
  27827. return time;
  27828. };
  27829. MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  27830. var duration = - 1;
  27831. var animation = this.animationsMap[ name ];
  27832. if ( animation ) {
  27833. duration = animation.duration;
  27834. }
  27835. return duration;
  27836. };
  27837. MorphBlendMesh.prototype.playAnimation = function ( name ) {
  27838. var animation = this.animationsMap[ name ];
  27839. if ( animation ) {
  27840. animation.time = 0;
  27841. animation.active = true;
  27842. } else {
  27843. console.warn( "THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()" );
  27844. }
  27845. };
  27846. MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  27847. var animation = this.animationsMap[ name ];
  27848. if ( animation ) {
  27849. animation.active = false;
  27850. }
  27851. };
  27852. MorphBlendMesh.prototype.update = function ( delta ) {
  27853. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  27854. var animation = this.animationsList[ i ];
  27855. if ( ! animation.active ) continue;
  27856. var frameTime = animation.duration / animation.length;
  27857. animation.time += animation.direction * delta;
  27858. if ( animation.mirroredLoop ) {
  27859. if ( animation.time > animation.duration || animation.time < 0 ) {
  27860. animation.direction *= - 1;
  27861. if ( animation.time > animation.duration ) {
  27862. animation.time = animation.duration;
  27863. animation.directionBackwards = true;
  27864. }
  27865. if ( animation.time < 0 ) {
  27866. animation.time = 0;
  27867. animation.directionBackwards = false;
  27868. }
  27869. }
  27870. } else {
  27871. animation.time = animation.time % animation.duration;
  27872. if ( animation.time < 0 ) animation.time += animation.duration;
  27873. }
  27874. var keyframe = animation.start + _Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  27875. var weight = animation.weight;
  27876. if ( keyframe !== animation.currentFrame ) {
  27877. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  27878. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  27879. this.morphTargetInfluences[ keyframe ] = 0;
  27880. animation.lastFrame = animation.currentFrame;
  27881. animation.currentFrame = keyframe;
  27882. }
  27883. var mix = ( animation.time % frameTime ) / frameTime;
  27884. if ( animation.directionBackwards ) mix = 1 - mix;
  27885. if ( animation.currentFrame !== animation.lastFrame ) {
  27886. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  27887. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  27888. } else {
  27889. this.morphTargetInfluences[ animation.currentFrame ] = weight;
  27890. }
  27891. }
  27892. };
  27893. /**
  27894. * @author alteredq / http://alteredqualia.com/
  27895. */
  27896. function ImmediateRenderObject( material ) {
  27897. Object3D.call( this );
  27898. this.material = material;
  27899. this.render = function ( renderCallback ) {};
  27900. }
  27901. ImmediateRenderObject.prototype = Object.create( Object3D.prototype );
  27902. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  27903. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  27904. /**
  27905. * @author mrdoob / http://mrdoob.com/
  27906. * @author WestLangley / http://github.com/WestLangley
  27907. */
  27908. function VertexNormalsHelper( object, size, hex, linewidth ) {
  27909. this.object = object;
  27910. this.size = ( size !== undefined ) ? size : 1;
  27911. var color = ( hex !== undefined ) ? hex : 0xff0000;
  27912. var width = ( linewidth !== undefined ) ? linewidth : 1;
  27913. //
  27914. var nNormals = 0;
  27915. var objGeometry = this.object.geometry;
  27916. if ( objGeometry && objGeometry.isGeometry ) {
  27917. nNormals = objGeometry.faces.length * 3;
  27918. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  27919. nNormals = objGeometry.attributes.normal.count;
  27920. }
  27921. //
  27922. var geometry = new BufferGeometry();
  27923. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  27924. geometry.addAttribute( 'position', positions );
  27925. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  27926. //
  27927. this.matrixAutoUpdate = false;
  27928. this.update();
  27929. }
  27930. VertexNormalsHelper.prototype = Object.create( LineSegments.prototype );
  27931. VertexNormalsHelper.prototype.constructor = VertexNormalsHelper;
  27932. VertexNormalsHelper.prototype.update = ( function () {
  27933. var v1 = new Vector3();
  27934. var v2 = new Vector3();
  27935. var normalMatrix = new Matrix3();
  27936. return function update() {
  27937. var keys = [ 'a', 'b', 'c' ];
  27938. this.object.updateMatrixWorld( true );
  27939. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  27940. var matrixWorld = this.object.matrixWorld;
  27941. var position = this.geometry.attributes.position;
  27942. //
  27943. var objGeometry = this.object.geometry;
  27944. if ( objGeometry && objGeometry.isGeometry ) {
  27945. var vertices = objGeometry.vertices;
  27946. var faces = objGeometry.faces;
  27947. var idx = 0;
  27948. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  27949. var face = faces[ i ];
  27950. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  27951. var vertex = vertices[ face[ keys[ j ] ] ];
  27952. var normal = face.vertexNormals[ j ];
  27953. v1.copy( vertex ).applyMatrix4( matrixWorld );
  27954. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  27955. position.setXYZ( idx, v1.x, v1.y, v1.z );
  27956. idx = idx + 1;
  27957. position.setXYZ( idx, v2.x, v2.y, v2.z );
  27958. idx = idx + 1;
  27959. }
  27960. }
  27961. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  27962. var objPos = objGeometry.attributes.position;
  27963. var objNorm = objGeometry.attributes.normal;
  27964. var idx = 0;
  27965. // for simplicity, ignore index and drawcalls, and render every normal
  27966. for ( var j = 0, jl = objPos.count; j < jl; j ++ ) {
  27967. v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld );
  27968. v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) );
  27969. v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  27970. position.setXYZ( idx, v1.x, v1.y, v1.z );
  27971. idx = idx + 1;
  27972. position.setXYZ( idx, v2.x, v2.y, v2.z );
  27973. idx = idx + 1;
  27974. }
  27975. }
  27976. position.needsUpdate = true;
  27977. return this;
  27978. };
  27979. }() );
  27980. /**
  27981. * @author alteredq / http://alteredqualia.com/
  27982. * @author mrdoob / http://mrdoob.com/
  27983. * @author WestLangley / http://github.com/WestLangley
  27984. */
  27985. function SpotLightHelper( light ) {
  27986. Object3D.call( this );
  27987. this.light = light;
  27988. this.light.updateMatrixWorld();
  27989. this.matrix = light.matrixWorld;
  27990. this.matrixAutoUpdate = false;
  27991. var geometry = new BufferGeometry();
  27992. var positions = [
  27993. 0, 0, 0, 0, 0, 1,
  27994. 0, 0, 0, 1, 0, 1,
  27995. 0, 0, 0, - 1, 0, 1,
  27996. 0, 0, 0, 0, 1, 1,
  27997. 0, 0, 0, 0, - 1, 1
  27998. ];
  27999. for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  28000. var p1 = ( i / l ) * Math.PI * 2;
  28001. var p2 = ( j / l ) * Math.PI * 2;
  28002. positions.push(
  28003. Math.cos( p1 ), Math.sin( p1 ), 1,
  28004. Math.cos( p2 ), Math.sin( p2 ), 1
  28005. );
  28006. }
  28007. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28008. var material = new LineBasicMaterial( { fog: false } );
  28009. this.cone = new LineSegments( geometry, material );
  28010. this.add( this.cone );
  28011. this.update();
  28012. }
  28013. SpotLightHelper.prototype = Object.create( Object3D.prototype );
  28014. SpotLightHelper.prototype.constructor = SpotLightHelper;
  28015. SpotLightHelper.prototype.dispose = function () {
  28016. this.cone.geometry.dispose();
  28017. this.cone.material.dispose();
  28018. };
  28019. SpotLightHelper.prototype.update = function () {
  28020. var vector = new Vector3();
  28021. var vector2 = new Vector3();
  28022. return function update() {
  28023. var coneLength = this.light.distance ? this.light.distance : 1000;
  28024. var coneWidth = coneLength * Math.tan( this.light.angle );
  28025. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  28026. vector.setFromMatrixPosition( this.light.matrixWorld );
  28027. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  28028. this.cone.lookAt( vector2.sub( vector ) );
  28029. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  28030. };
  28031. }();
  28032. /**
  28033. * @author Sean Griffin / http://twitter.com/sgrif
  28034. * @author Michael Guerrero / http://realitymeltdown.com
  28035. * @author mrdoob / http://mrdoob.com/
  28036. * @author ikerr / http://verold.com
  28037. * @author Mugen87 / https://github.com/Mugen87
  28038. */
  28039. function SkeletonHelper( object ) {
  28040. this.bones = this.getBoneList( object );
  28041. var geometry = new BufferGeometry();
  28042. var vertices = [];
  28043. var colors = [];
  28044. var color1 = new Color( 0, 0, 1 );
  28045. var color2 = new Color( 0, 1, 0 );
  28046. for ( var i = 0; i < this.bones.length; i ++ ) {
  28047. var bone = this.bones[ i ];
  28048. if ( bone.parent && bone.parent.isBone ) {
  28049. vertices.push( 0, 0, 0 );
  28050. vertices.push( 0, 0, 0 );
  28051. colors.push( color1.r, color1.g, color1.b );
  28052. colors.push( color2.r, color2.g, color2.b );
  28053. }
  28054. }
  28055. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28056. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28057. var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  28058. LineSegments.call( this, geometry, material );
  28059. this.root = object;
  28060. this.matrix = object.matrixWorld;
  28061. this.matrixAutoUpdate = false;
  28062. this.update();
  28063. }
  28064. SkeletonHelper.prototype = Object.create( LineSegments.prototype );
  28065. SkeletonHelper.prototype.constructor = SkeletonHelper;
  28066. SkeletonHelper.prototype.getBoneList = function( object ) {
  28067. var boneList = [];
  28068. if ( object && object.isBone ) {
  28069. boneList.push( object );
  28070. }
  28071. for ( var i = 0; i < object.children.length; i ++ ) {
  28072. boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) );
  28073. }
  28074. return boneList;
  28075. };
  28076. SkeletonHelper.prototype.update = function () {
  28077. var vector = new Vector3();
  28078. var boneMatrix = new Matrix4();
  28079. var matrixWorldInv = new Matrix4();
  28080. return function update() {
  28081. var geometry = this.geometry;
  28082. var position = geometry.getAttribute( 'position' );
  28083. matrixWorldInv.getInverse( this.root.matrixWorld );
  28084. for ( var i = 0, j = 0; i < this.bones.length; i ++ ) {
  28085. var bone = this.bones[ i ];
  28086. if ( bone.parent && bone.parent.isBone ) {
  28087. boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
  28088. vector.setFromMatrixPosition( boneMatrix );
  28089. position.setXYZ( j, vector.x, vector.y, vector.z );
  28090. boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
  28091. vector.setFromMatrixPosition( boneMatrix );
  28092. position.setXYZ( j + 1, vector.x, vector.y, vector.z );
  28093. j += 2;
  28094. }
  28095. }
  28096. geometry.getAttribute( 'position' ).needsUpdate = true;
  28097. };
  28098. }();
  28099. /**
  28100. * @author alteredq / http://alteredqualia.com/
  28101. * @author mrdoob / http://mrdoob.com/
  28102. */
  28103. function PointLightHelper( light, sphereSize ) {
  28104. this.light = light;
  28105. this.light.updateMatrixWorld();
  28106. var geometry = new SphereBufferGeometry( sphereSize, 4, 2 );
  28107. var material = new MeshBasicMaterial( { wireframe: true, fog: false } );
  28108. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  28109. Mesh.call( this, geometry, material );
  28110. this.matrix = this.light.matrixWorld;
  28111. this.matrixAutoUpdate = false;
  28112. /*
  28113. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  28114. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  28115. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  28116. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  28117. var d = light.distance;
  28118. if ( d === 0.0 ) {
  28119. this.lightDistance.visible = false;
  28120. } else {
  28121. this.lightDistance.scale.set( d, d, d );
  28122. }
  28123. this.add( this.lightDistance );
  28124. */
  28125. }
  28126. PointLightHelper.prototype = Object.create( Mesh.prototype );
  28127. PointLightHelper.prototype.constructor = PointLightHelper;
  28128. PointLightHelper.prototype.dispose = function () {
  28129. this.geometry.dispose();
  28130. this.material.dispose();
  28131. };
  28132. PointLightHelper.prototype.update = function () {
  28133. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  28134. /*
  28135. var d = this.light.distance;
  28136. if ( d === 0.0 ) {
  28137. this.lightDistance.visible = false;
  28138. } else {
  28139. this.lightDistance.visible = true;
  28140. this.lightDistance.scale.set( d, d, d );
  28141. }
  28142. */
  28143. };
  28144. /**
  28145. * @author abelnation / http://github.com/abelnation
  28146. * @author Mugen87 / http://github.com/Mugen87
  28147. */
  28148. function RectAreaLightHelper( light ) {
  28149. Object3D.call( this );
  28150. this.light = light;
  28151. this.light.updateMatrixWorld();
  28152. var materialFront = new MeshBasicMaterial( {
  28153. color: light.color,
  28154. fog: false
  28155. } );
  28156. var materialBack = new MeshBasicMaterial( {
  28157. color: light.color,
  28158. fog: false,
  28159. wireframe: true
  28160. } );
  28161. var geometry = new BufferGeometry();
  28162. geometry.addAttribute( 'position', new BufferAttribute( new Float32Array( 6 * 3 ), 3 ) );
  28163. // shows the "front" of the light, e.g. where light comes from
  28164. this.add( new Mesh( geometry, materialFront ) );
  28165. // shows the "back" of the light, which does not emit light
  28166. this.add( new Mesh( geometry, materialBack ) );
  28167. this.update();
  28168. }
  28169. RectAreaLightHelper.prototype = Object.create( Object3D.prototype );
  28170. RectAreaLightHelper.prototype.constructor = RectAreaLightHelper;
  28171. RectAreaLightHelper.prototype.dispose = function () {
  28172. this.children[ 0 ].geometry.dispose();
  28173. this.children[ 0 ].material.dispose();
  28174. this.children[ 1 ].geometry.dispose();
  28175. this.children[ 1 ].material.dispose();
  28176. };
  28177. RectAreaLightHelper.prototype.update = function () {
  28178. var vector1 = new Vector3();
  28179. var vector2 = new Vector3();
  28180. return function update() {
  28181. var mesh1 = this.children[ 0 ];
  28182. var mesh2 = this.children[ 1 ];
  28183. if ( this.light.target ) {
  28184. vector1.setFromMatrixPosition( this.light.matrixWorld );
  28185. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  28186. var lookVec = vector2.clone().sub( vector1 );
  28187. mesh1.lookAt( lookVec );
  28188. mesh2.lookAt( lookVec );
  28189. }
  28190. // update materials
  28191. mesh1.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  28192. mesh2.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  28193. // calculate new dimensions of the helper
  28194. var hx = this.light.width * 0.5;
  28195. var hy = this.light.height * 0.5;
  28196. // because the buffer attribute is shared over both geometries, we only have to update once
  28197. var position = mesh1.geometry.getAttribute( 'position' );
  28198. var array = position.array;
  28199. // first face
  28200. array[ 0 ] = hx; array[ 1 ] = - hy; array[ 2 ] = 0;
  28201. array[ 3 ] = hx; array[ 4 ] = hy; array[ 5 ] = 0;
  28202. array[ 6 ] = - hx; array[ 7 ] = hy; array[ 8 ] = 0;
  28203. // second face
  28204. array[ 9 ] = - hx; array[ 10 ] = hy; array[ 11 ] = 0;
  28205. array[ 12 ] = - hx; array[ 13 ] = - hy; array[ 14 ] = 0;
  28206. array[ 15 ] = hx; array[ 16 ] = - hy; array[ 17 ] = 0;
  28207. position.needsUpdate = true;
  28208. };
  28209. }();
  28210. /**
  28211. * @author alteredq / http://alteredqualia.com/
  28212. * @author mrdoob / http://mrdoob.com/
  28213. * @author Mugen87 / https://github.com/Mugen87
  28214. */
  28215. function HemisphereLightHelper( light, size ) {
  28216. Object3D.call( this );
  28217. this.light = light;
  28218. this.light.updateMatrixWorld();
  28219. this.matrix = light.matrixWorld;
  28220. this.matrixAutoUpdate = false;
  28221. var geometry = new OctahedronBufferGeometry( size );
  28222. geometry.rotateY( Math.PI * 0.5 );
  28223. var material = new MeshBasicMaterial( { vertexColors: VertexColors, wireframe: true } );
  28224. var position = geometry.getAttribute( 'position' );
  28225. var colors = new Float32Array( position.count * 3 );
  28226. geometry.addAttribute( 'color', new BufferAttribute( colors, 3 ) );
  28227. this.add( new Mesh( geometry, material ) );
  28228. this.update();
  28229. }
  28230. HemisphereLightHelper.prototype = Object.create( Object3D.prototype );
  28231. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  28232. HemisphereLightHelper.prototype.dispose = function () {
  28233. this.children[ 0 ].geometry.dispose();
  28234. this.children[ 0 ].material.dispose();
  28235. };
  28236. HemisphereLightHelper.prototype.update = function () {
  28237. var vector = new Vector3();
  28238. var color1 = new Color();
  28239. var color2 = new Color();
  28240. return function update() {
  28241. var mesh = this.children[ 0 ];
  28242. var colors = mesh.geometry.getAttribute( 'color' );
  28243. color1.copy( this.light.color ).multiplyScalar( this.light.intensity );
  28244. color2.copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  28245. for ( var i = 0, l = colors.count; i < l; i ++ ) {
  28246. var color = ( i < ( l / 2 ) ) ? color1 : color2;
  28247. colors.setXYZ( i, color.r, color.g, color.b );
  28248. }
  28249. mesh.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  28250. colors.needsUpdate = true;
  28251. };
  28252. }();
  28253. /**
  28254. * @author mrdoob / http://mrdoob.com/
  28255. */
  28256. function GridHelper( size, divisions, color1, color2 ) {
  28257. size = size || 10;
  28258. divisions = divisions || 10;
  28259. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  28260. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  28261. var center = divisions / 2;
  28262. var step = size / divisions;
  28263. var halfSize = size / 2;
  28264. var vertices = [], colors = [];
  28265. for ( var i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  28266. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  28267. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  28268. var color = i === center ? color1 : color2;
  28269. color.toArray( colors, j ); j += 3;
  28270. color.toArray( colors, j ); j += 3;
  28271. color.toArray( colors, j ); j += 3;
  28272. color.toArray( colors, j ); j += 3;
  28273. }
  28274. var geometry = new BufferGeometry();
  28275. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28276. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28277. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  28278. LineSegments.call( this, geometry, material );
  28279. }
  28280. GridHelper.prototype = Object.create( LineSegments.prototype );
  28281. GridHelper.prototype.constructor = GridHelper;
  28282. /**
  28283. * @author mrdoob / http://mrdoob.com/
  28284. * @author Mugen87 / http://github.com/Mugen87
  28285. * @author Hectate / http://www.github.com/Hectate
  28286. */
  28287. function PolarGridHelper( radius, radials, circles, divisions, color1, color2 ) {
  28288. radius = radius || 10;
  28289. radials = radials || 16;
  28290. circles = circles || 8;
  28291. divisions = divisions || 64;
  28292. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  28293. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  28294. var vertices = [];
  28295. var colors = [];
  28296. var x, z;
  28297. var v, i, j, r, color;
  28298. // create the radials
  28299. for ( i = 0; i <= radials; i ++ ) {
  28300. v = ( i / radials ) * ( Math.PI * 2 );
  28301. x = Math.sin( v ) * radius;
  28302. z = Math.cos( v ) * radius;
  28303. vertices.push( 0, 0, 0 );
  28304. vertices.push( x, 0, z );
  28305. color = ( i & 1 ) ? color1 : color2;
  28306. colors.push( color.r, color.g, color.b );
  28307. colors.push( color.r, color.g, color.b );
  28308. }
  28309. // create the circles
  28310. for ( i = 0; i <= circles; i ++ ) {
  28311. color = ( i & 1 ) ? color1 : color2;
  28312. r = radius - ( radius / circles * i );
  28313. for ( j = 0; j < divisions; j ++ ) {
  28314. // first vertex
  28315. v = ( j / divisions ) * ( Math.PI * 2 );
  28316. x = Math.sin( v ) * r;
  28317. z = Math.cos( v ) * r;
  28318. vertices.push( x, 0, z );
  28319. colors.push( color.r, color.g, color.b );
  28320. // second vertex
  28321. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  28322. x = Math.sin( v ) * r;
  28323. z = Math.cos( v ) * r;
  28324. vertices.push( x, 0, z );
  28325. colors.push( color.r, color.g, color.b );
  28326. }
  28327. }
  28328. var geometry = new BufferGeometry();
  28329. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28330. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28331. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  28332. LineSegments.call( this, geometry, material );
  28333. }
  28334. PolarGridHelper.prototype = Object.create( LineSegments.prototype );
  28335. PolarGridHelper.prototype.constructor = PolarGridHelper;
  28336. /**
  28337. * @author mrdoob / http://mrdoob.com/
  28338. * @author WestLangley / http://github.com/WestLangley
  28339. */
  28340. function FaceNormalsHelper( object, size, hex, linewidth ) {
  28341. // FaceNormalsHelper only supports THREE.Geometry
  28342. this.object = object;
  28343. this.size = ( size !== undefined ) ? size : 1;
  28344. var color = ( hex !== undefined ) ? hex : 0xffff00;
  28345. var width = ( linewidth !== undefined ) ? linewidth : 1;
  28346. //
  28347. var nNormals = 0;
  28348. var objGeometry = this.object.geometry;
  28349. if ( objGeometry && objGeometry.isGeometry ) {
  28350. nNormals = objGeometry.faces.length;
  28351. } else {
  28352. console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' );
  28353. }
  28354. //
  28355. var geometry = new BufferGeometry();
  28356. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  28357. geometry.addAttribute( 'position', positions );
  28358. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  28359. //
  28360. this.matrixAutoUpdate = false;
  28361. this.update();
  28362. }
  28363. FaceNormalsHelper.prototype = Object.create( LineSegments.prototype );
  28364. FaceNormalsHelper.prototype.constructor = FaceNormalsHelper;
  28365. FaceNormalsHelper.prototype.update = ( function () {
  28366. var v1 = new Vector3();
  28367. var v2 = new Vector3();
  28368. var normalMatrix = new Matrix3();
  28369. return function update() {
  28370. this.object.updateMatrixWorld( true );
  28371. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  28372. var matrixWorld = this.object.matrixWorld;
  28373. var position = this.geometry.attributes.position;
  28374. //
  28375. var objGeometry = this.object.geometry;
  28376. var vertices = objGeometry.vertices;
  28377. var faces = objGeometry.faces;
  28378. var idx = 0;
  28379. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  28380. var face = faces[ i ];
  28381. var normal = face.normal;
  28382. v1.copy( vertices[ face.a ] )
  28383. .add( vertices[ face.b ] )
  28384. .add( vertices[ face.c ] )
  28385. .divideScalar( 3 )
  28386. .applyMatrix4( matrixWorld );
  28387. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  28388. position.setXYZ( idx, v1.x, v1.y, v1.z );
  28389. idx = idx + 1;
  28390. position.setXYZ( idx, v2.x, v2.y, v2.z );
  28391. idx = idx + 1;
  28392. }
  28393. position.needsUpdate = true;
  28394. return this;
  28395. };
  28396. }() );
  28397. /**
  28398. * @author alteredq / http://alteredqualia.com/
  28399. * @author mrdoob / http://mrdoob.com/
  28400. * @author WestLangley / http://github.com/WestLangley
  28401. */
  28402. function DirectionalLightHelper( light, size ) {
  28403. Object3D.call( this );
  28404. this.light = light;
  28405. this.light.updateMatrixWorld();
  28406. this.matrix = light.matrixWorld;
  28407. this.matrixAutoUpdate = false;
  28408. if ( size === undefined ) size = 1;
  28409. var geometry = new BufferGeometry();
  28410. geometry.addAttribute( 'position', new Float32BufferAttribute( [
  28411. - size, size, 0,
  28412. size, size, 0,
  28413. size, - size, 0,
  28414. - size, - size, 0,
  28415. - size, size, 0
  28416. ], 3 ) );
  28417. var material = new LineBasicMaterial( { fog: false } );
  28418. this.add( new Line( geometry, material ) );
  28419. geometry = new BufferGeometry();
  28420. geometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  28421. this.add( new Line( geometry, material ));
  28422. this.update();
  28423. }
  28424. DirectionalLightHelper.prototype = Object.create( Object3D.prototype );
  28425. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  28426. DirectionalLightHelper.prototype.dispose = function () {
  28427. var lightPlane = this.children[ 0 ];
  28428. var targetLine = this.children[ 1 ];
  28429. lightPlane.geometry.dispose();
  28430. lightPlane.material.dispose();
  28431. targetLine.geometry.dispose();
  28432. targetLine.material.dispose();
  28433. };
  28434. DirectionalLightHelper.prototype.update = function () {
  28435. var v1 = new Vector3();
  28436. var v2 = new Vector3();
  28437. var v3 = new Vector3();
  28438. return function update() {
  28439. v1.setFromMatrixPosition( this.light.matrixWorld );
  28440. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  28441. v3.subVectors( v2, v1 );
  28442. var lightPlane = this.children[ 0 ];
  28443. var targetLine = this.children[ 1 ];
  28444. lightPlane.lookAt( v3 );
  28445. lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  28446. targetLine.lookAt( v3 );
  28447. targetLine.scale.z = v3.length();
  28448. };
  28449. }();
  28450. /**
  28451. * @author alteredq / http://alteredqualia.com/
  28452. * @author Mugen87 / https://github.com/Mugen87
  28453. *
  28454. * - shows frustum, line of sight and up of the camera
  28455. * - suitable for fast updates
  28456. * - based on frustum visualization in lightgl.js shadowmap example
  28457. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  28458. */
  28459. function CameraHelper( camera ) {
  28460. var geometry = new BufferGeometry();
  28461. var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: FaceColors } );
  28462. var vertices = [];
  28463. var colors = [];
  28464. var pointMap = {};
  28465. // colors
  28466. var colorFrustum = new Color( 0xffaa00 );
  28467. var colorCone = new Color( 0xff0000 );
  28468. var colorUp = new Color( 0x00aaff );
  28469. var colorTarget = new Color( 0xffffff );
  28470. var colorCross = new Color( 0x333333 );
  28471. // near
  28472. addLine( "n1", "n2", colorFrustum );
  28473. addLine( "n2", "n4", colorFrustum );
  28474. addLine( "n4", "n3", colorFrustum );
  28475. addLine( "n3", "n1", colorFrustum );
  28476. // far
  28477. addLine( "f1", "f2", colorFrustum );
  28478. addLine( "f2", "f4", colorFrustum );
  28479. addLine( "f4", "f3", colorFrustum );
  28480. addLine( "f3", "f1", colorFrustum );
  28481. // sides
  28482. addLine( "n1", "f1", colorFrustum );
  28483. addLine( "n2", "f2", colorFrustum );
  28484. addLine( "n3", "f3", colorFrustum );
  28485. addLine( "n4", "f4", colorFrustum );
  28486. // cone
  28487. addLine( "p", "n1", colorCone );
  28488. addLine( "p", "n2", colorCone );
  28489. addLine( "p", "n3", colorCone );
  28490. addLine( "p", "n4", colorCone );
  28491. // up
  28492. addLine( "u1", "u2", colorUp );
  28493. addLine( "u2", "u3", colorUp );
  28494. addLine( "u3", "u1", colorUp );
  28495. // target
  28496. addLine( "c", "t", colorTarget );
  28497. addLine( "p", "c", colorCross );
  28498. // cross
  28499. addLine( "cn1", "cn2", colorCross );
  28500. addLine( "cn3", "cn4", colorCross );
  28501. addLine( "cf1", "cf2", colorCross );
  28502. addLine( "cf3", "cf4", colorCross );
  28503. function addLine( a, b, color ) {
  28504. addPoint( a, color );
  28505. addPoint( b, color );
  28506. }
  28507. function addPoint( id, color ) {
  28508. vertices.push( 0, 0, 0 );
  28509. colors.push( color.r, color.g, color.b );
  28510. if ( pointMap[ id ] === undefined ) {
  28511. pointMap[ id ] = [];
  28512. }
  28513. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  28514. }
  28515. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28516. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28517. LineSegments.call( this, geometry, material );
  28518. this.camera = camera;
  28519. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  28520. this.matrix = camera.matrixWorld;
  28521. this.matrixAutoUpdate = false;
  28522. this.pointMap = pointMap;
  28523. this.update();
  28524. }
  28525. CameraHelper.prototype = Object.create( LineSegments.prototype );
  28526. CameraHelper.prototype.constructor = CameraHelper;
  28527. CameraHelper.prototype.update = function () {
  28528. var geometry, pointMap;
  28529. var vector = new Vector3();
  28530. var camera = new Camera();
  28531. function setPoint( point, x, y, z ) {
  28532. vector.set( x, y, z ).unproject( camera );
  28533. var points = pointMap[ point ];
  28534. if ( points !== undefined ) {
  28535. var position = geometry.getAttribute( 'position' );
  28536. for ( var i = 0, l = points.length; i < l; i ++ ) {
  28537. position.setXYZ( points[ i ], vector.x, vector.y, vector.z );
  28538. }
  28539. }
  28540. }
  28541. return function update() {
  28542. geometry = this.geometry;
  28543. pointMap = this.pointMap;
  28544. var w = 1, h = 1;
  28545. // we need just camera projection matrix
  28546. // world matrix must be identity
  28547. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  28548. // center / target
  28549. setPoint( "c", 0, 0, - 1 );
  28550. setPoint( "t", 0, 0, 1 );
  28551. // near
  28552. setPoint( "n1", - w, - h, - 1 );
  28553. setPoint( "n2", w, - h, - 1 );
  28554. setPoint( "n3", - w, h, - 1 );
  28555. setPoint( "n4", w, h, - 1 );
  28556. // far
  28557. setPoint( "f1", - w, - h, 1 );
  28558. setPoint( "f2", w, - h, 1 );
  28559. setPoint( "f3", - w, h, 1 );
  28560. setPoint( "f4", w, h, 1 );
  28561. // up
  28562. setPoint( "u1", w * 0.7, h * 1.1, - 1 );
  28563. setPoint( "u2", - w * 0.7, h * 1.1, - 1 );
  28564. setPoint( "u3", 0, h * 2, - 1 );
  28565. // cross
  28566. setPoint( "cf1", - w, 0, 1 );
  28567. setPoint( "cf2", w, 0, 1 );
  28568. setPoint( "cf3", 0, - h, 1 );
  28569. setPoint( "cf4", 0, h, 1 );
  28570. setPoint( "cn1", - w, 0, - 1 );
  28571. setPoint( "cn2", w, 0, - 1 );
  28572. setPoint( "cn3", 0, - h, - 1 );
  28573. setPoint( "cn4", 0, h, - 1 );
  28574. geometry.getAttribute( 'position' ).needsUpdate = true;
  28575. };
  28576. }();
  28577. /**
  28578. * @author mrdoob / http://mrdoob.com/
  28579. */
  28580. function BoxHelper( object, color ) {
  28581. if ( color === undefined ) color = 0xffff00;
  28582. 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 ] );
  28583. var positions = new Float32Array( 8 * 3 );
  28584. var geometry = new BufferGeometry();
  28585. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  28586. geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) );
  28587. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  28588. if ( object !== undefined ) {
  28589. this.update( object );
  28590. }
  28591. }
  28592. BoxHelper.prototype = Object.create( LineSegments.prototype );
  28593. BoxHelper.prototype.constructor = BoxHelper;
  28594. BoxHelper.prototype.update = ( function () {
  28595. var box = new Box3();
  28596. return function update( object ) {
  28597. if ( object && object.isBox3 ) {
  28598. box.copy( object );
  28599. } else {
  28600. box.setFromObject( object );
  28601. }
  28602. if ( box.isEmpty() ) return;
  28603. var min = box.min;
  28604. var max = box.max;
  28605. /*
  28606. 5____4
  28607. 1/___0/|
  28608. | 6__|_7
  28609. 2/___3/
  28610. 0: max.x, max.y, max.z
  28611. 1: min.x, max.y, max.z
  28612. 2: min.x, min.y, max.z
  28613. 3: max.x, min.y, max.z
  28614. 4: max.x, max.y, min.z
  28615. 5: min.x, max.y, min.z
  28616. 6: min.x, min.y, min.z
  28617. 7: max.x, min.y, min.z
  28618. */
  28619. var position = this.geometry.attributes.position;
  28620. var array = position.array;
  28621. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  28622. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  28623. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  28624. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  28625. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  28626. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  28627. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  28628. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  28629. position.needsUpdate = true;
  28630. this.geometry.computeBoundingSphere();
  28631. };
  28632. } )();
  28633. /**
  28634. * @author WestLangley / http://github.com/WestLangley
  28635. * @author zz85 / http://github.com/zz85
  28636. * @author bhouston / http://clara.io
  28637. *
  28638. * Creates an arrow for visualizing directions
  28639. *
  28640. * Parameters:
  28641. * dir - Vector3
  28642. * origin - Vector3
  28643. * length - Number
  28644. * color - color in hex value
  28645. * headLength - Number
  28646. * headWidth - Number
  28647. */
  28648. var lineGeometry;
  28649. var coneGeometry;
  28650. function ArrowHelper( dir, origin, length, color, headLength, headWidth ) {
  28651. // dir is assumed to be normalized
  28652. Object3D.call( this );
  28653. if ( color === undefined ) color = 0xffff00;
  28654. if ( length === undefined ) length = 1;
  28655. if ( headLength === undefined ) headLength = 0.2 * length;
  28656. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  28657. if ( lineGeometry === undefined ) {
  28658. lineGeometry = new BufferGeometry();
  28659. lineGeometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  28660. coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 );
  28661. coneGeometry.translate( 0, - 0.5, 0 );
  28662. }
  28663. this.position.copy( origin );
  28664. this.line = new Line( lineGeometry, new LineBasicMaterial( { color: color } ) );
  28665. this.line.matrixAutoUpdate = false;
  28666. this.add( this.line );
  28667. this.cone = new Mesh( coneGeometry, new MeshBasicMaterial( { color: color } ) );
  28668. this.cone.matrixAutoUpdate = false;
  28669. this.add( this.cone );
  28670. this.setDirection( dir );
  28671. this.setLength( length, headLength, headWidth );
  28672. }
  28673. ArrowHelper.prototype = Object.create( Object3D.prototype );
  28674. ArrowHelper.prototype.constructor = ArrowHelper;
  28675. ArrowHelper.prototype.setDirection = ( function () {
  28676. var axis = new Vector3();
  28677. var radians;
  28678. return function setDirection( dir ) {
  28679. // dir is assumed to be normalized
  28680. if ( dir.y > 0.99999 ) {
  28681. this.quaternion.set( 0, 0, 0, 1 );
  28682. } else if ( dir.y < - 0.99999 ) {
  28683. this.quaternion.set( 1, 0, 0, 0 );
  28684. } else {
  28685. axis.set( dir.z, 0, - dir.x ).normalize();
  28686. radians = Math.acos( dir.y );
  28687. this.quaternion.setFromAxisAngle( axis, radians );
  28688. }
  28689. };
  28690. }() );
  28691. ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  28692. if ( headLength === undefined ) headLength = 0.2 * length;
  28693. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  28694. this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 );
  28695. this.line.updateMatrix();
  28696. this.cone.scale.set( headWidth, headLength, headWidth );
  28697. this.cone.position.y = length;
  28698. this.cone.updateMatrix();
  28699. };
  28700. ArrowHelper.prototype.setColor = function ( color ) {
  28701. this.line.material.color.copy( color );
  28702. this.cone.material.color.copy( color );
  28703. };
  28704. /**
  28705. * @author sroucheray / http://sroucheray.org/
  28706. * @author mrdoob / http://mrdoob.com/
  28707. */
  28708. function AxisHelper( size ) {
  28709. size = size || 1;
  28710. var vertices = [
  28711. 0, 0, 0, size, 0, 0,
  28712. 0, 0, 0, 0, size, 0,
  28713. 0, 0, 0, 0, 0, size
  28714. ];
  28715. var colors = [
  28716. 1, 0, 0, 1, 0.6, 0,
  28717. 0, 1, 0, 0.6, 1, 0,
  28718. 0, 0, 1, 0, 0.6, 1
  28719. ];
  28720. var geometry = new BufferGeometry();
  28721. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28722. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28723. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  28724. LineSegments.call( this, geometry, material );
  28725. }
  28726. AxisHelper.prototype = Object.create( LineSegments.prototype );
  28727. AxisHelper.prototype.constructor = AxisHelper;
  28728. /**
  28729. * @author zz85 https://github.com/zz85
  28730. *
  28731. * Centripetal CatmullRom Curve - which is useful for avoiding
  28732. * cusps and self-intersections in non-uniform catmull rom curves.
  28733. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  28734. *
  28735. * curve.type accepts centripetal(default), chordal and catmullrom
  28736. * curve.tension is used for catmullrom which defaults to 0.5
  28737. */
  28738. /*
  28739. Based on an optimized c++ solution in
  28740. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  28741. - http://ideone.com/NoEbVM
  28742. This CubicPoly class could be used for reusing some variables and calculations,
  28743. but for three.js curve use, it could be possible inlined and flatten into a single function call
  28744. which can be placed in CurveUtils.
  28745. */
  28746. function CubicPoly() {
  28747. var c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  28748. /*
  28749. * Compute coefficients for a cubic polynomial
  28750. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  28751. * such that
  28752. * p(0) = x0, p(1) = x1
  28753. * and
  28754. * p'(0) = t0, p'(1) = t1.
  28755. */
  28756. function init( x0, x1, t0, t1 ) {
  28757. c0 = x0;
  28758. c1 = t0;
  28759. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  28760. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  28761. }
  28762. return {
  28763. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  28764. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  28765. },
  28766. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  28767. // compute tangents when parameterized in [t1,t2]
  28768. var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  28769. var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  28770. // rescale tangents for parametrization in [0,1]
  28771. t1 *= dt1;
  28772. t2 *= dt1;
  28773. init( x1, x2, t1, t2 );
  28774. },
  28775. calc: function ( t ) {
  28776. var t2 = t * t;
  28777. var t3 = t2 * t;
  28778. return c0 + c1 * t + c2 * t2 + c3 * t3;
  28779. }
  28780. };
  28781. }
  28782. //
  28783. var tmp = new Vector3();
  28784. var px = new CubicPoly();
  28785. var py = new CubicPoly();
  28786. var pz = new CubicPoly();
  28787. function CatmullRomCurve3( p /* array of Vector3 */ ) {
  28788. this.points = p || [];
  28789. this.closed = false;
  28790. }
  28791. CatmullRomCurve3.prototype = Object.create( Curve.prototype );
  28792. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  28793. CatmullRomCurve3.prototype.getPoint = function ( t ) {
  28794. var points = this.points;
  28795. var l = points.length;
  28796. if ( l < 2 ) console.log( 'duh, you need at least 2 points' );
  28797. var point = ( l - ( this.closed ? 0 : 1 ) ) * t;
  28798. var intPoint = Math.floor( point );
  28799. var weight = point - intPoint;
  28800. if ( this.closed ) {
  28801. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  28802. } else if ( weight === 0 && intPoint === l - 1 ) {
  28803. intPoint = l - 2;
  28804. weight = 1;
  28805. }
  28806. var p0, p1, p2, p3; // 4 points
  28807. if ( this.closed || intPoint > 0 ) {
  28808. p0 = points[ ( intPoint - 1 ) % l ];
  28809. } else {
  28810. // extrapolate first point
  28811. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  28812. p0 = tmp;
  28813. }
  28814. p1 = points[ intPoint % l ];
  28815. p2 = points[ ( intPoint + 1 ) % l ];
  28816. if ( this.closed || intPoint + 2 < l ) {
  28817. p3 = points[ ( intPoint + 2 ) % l ];
  28818. } else {
  28819. // extrapolate last point
  28820. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  28821. p3 = tmp;
  28822. }
  28823. if ( this.type === undefined || this.type === 'centripetal' || this.type === 'chordal' ) {
  28824. // init Centripetal / Chordal Catmull-Rom
  28825. var pow = this.type === 'chordal' ? 0.5 : 0.25;
  28826. var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  28827. var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  28828. var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  28829. // safety check for repeated points
  28830. if ( dt1 < 1e-4 ) dt1 = 1.0;
  28831. if ( dt0 < 1e-4 ) dt0 = dt1;
  28832. if ( dt2 < 1e-4 ) dt2 = dt1;
  28833. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  28834. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  28835. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  28836. } else if ( this.type === 'catmullrom' ) {
  28837. var tension = this.tension !== undefined ? this.tension : 0.5;
  28838. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, tension );
  28839. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, tension );
  28840. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, tension );
  28841. }
  28842. return new Vector3( px.calc( weight ), py.calc( weight ), pz.calc( weight ) );
  28843. };
  28844. function CubicBezierCurve3( v0, v1, v2, v3 ) {
  28845. this.v0 = v0;
  28846. this.v1 = v1;
  28847. this.v2 = v2;
  28848. this.v3 = v3;
  28849. }
  28850. CubicBezierCurve3.prototype = Object.create( Curve.prototype );
  28851. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  28852. CubicBezierCurve3.prototype.getPoint = function ( t ) {
  28853. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  28854. return new Vector3(
  28855. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  28856. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  28857. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  28858. );
  28859. };
  28860. function QuadraticBezierCurve3( v0, v1, v2 ) {
  28861. this.v0 = v0;
  28862. this.v1 = v1;
  28863. this.v2 = v2;
  28864. }
  28865. QuadraticBezierCurve3.prototype = Object.create( Curve.prototype );
  28866. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  28867. QuadraticBezierCurve3.prototype.getPoint = function ( t ) {
  28868. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  28869. return new Vector3(
  28870. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  28871. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  28872. QuadraticBezier( t, v0.z, v1.z, v2.z )
  28873. );
  28874. };
  28875. function LineCurve3( v1, v2 ) {
  28876. this.v1 = v1;
  28877. this.v2 = v2;
  28878. }
  28879. LineCurve3.prototype = Object.create( Curve.prototype );
  28880. LineCurve3.prototype.constructor = LineCurve3;
  28881. LineCurve3.prototype.getPoint = function ( t ) {
  28882. if ( t === 1 ) {
  28883. return this.v2.clone();
  28884. }
  28885. var vector = new Vector3();
  28886. vector.subVectors( this.v2, this.v1 ); // diff
  28887. vector.multiplyScalar( t );
  28888. vector.add( this.v1 );
  28889. return vector;
  28890. };
  28891. function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  28892. EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  28893. }
  28894. ArcCurve.prototype = Object.create( EllipseCurve.prototype );
  28895. ArcCurve.prototype.constructor = ArcCurve;
  28896. /**
  28897. * @author alteredq / http://alteredqualia.com/
  28898. */
  28899. var SceneUtils = {
  28900. createMultiMaterialObject: function ( geometry, materials ) {
  28901. var group = new Group();
  28902. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  28903. group.add( new Mesh( geometry, materials[ i ] ) );
  28904. }
  28905. return group;
  28906. },
  28907. detach: function ( child, parent, scene ) {
  28908. child.applyMatrix( parent.matrixWorld );
  28909. parent.remove( child );
  28910. scene.add( child );
  28911. },
  28912. attach: function ( child, scene, parent ) {
  28913. var matrixWorldInverse = new Matrix4();
  28914. matrixWorldInverse.getInverse( parent.matrixWorld );
  28915. child.applyMatrix( matrixWorldInverse );
  28916. scene.remove( child );
  28917. parent.add( child );
  28918. }
  28919. };
  28920. /**
  28921. * @author mrdoob / http://mrdoob.com/
  28922. */
  28923. function Face4( a, b, c, d, normal, color, materialIndex ) {
  28924. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  28925. return new Face3( a, b, c, normal, color, materialIndex );
  28926. }
  28927. var LineStrip = 0;
  28928. var LinePieces = 1;
  28929. function MeshFaceMaterial( materials ) {
  28930. console.warn( 'THREE.MeshFaceMaterial has been renamed to THREE.MultiMaterial.' );
  28931. return new MultiMaterial( materials );
  28932. }
  28933. function PointCloud( geometry, material ) {
  28934. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  28935. return new Points( geometry, material );
  28936. }
  28937. function Particle( material ) {
  28938. console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
  28939. return new Sprite( material );
  28940. }
  28941. function ParticleSystem( geometry, material ) {
  28942. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  28943. return new Points( geometry, material );
  28944. }
  28945. function PointCloudMaterial( parameters ) {
  28946. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  28947. return new PointsMaterial( parameters );
  28948. }
  28949. function ParticleBasicMaterial( parameters ) {
  28950. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  28951. return new PointsMaterial( parameters );
  28952. }
  28953. function ParticleSystemMaterial( parameters ) {
  28954. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  28955. return new PointsMaterial( parameters );
  28956. }
  28957. function Vertex( x, y, z ) {
  28958. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  28959. return new Vector3( x, y, z );
  28960. }
  28961. //
  28962. function DynamicBufferAttribute( array, itemSize ) {
  28963. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' );
  28964. return new BufferAttribute( array, itemSize ).setDynamic( true );
  28965. }
  28966. function Int8Attribute( array, itemSize ) {
  28967. console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
  28968. return new Int8BufferAttribute( array, itemSize );
  28969. }
  28970. function Uint8Attribute( array, itemSize ) {
  28971. console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
  28972. return new Uint8BufferAttribute( array, itemSize );
  28973. }
  28974. function Uint8ClampedAttribute( array, itemSize ) {
  28975. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
  28976. return new Uint8ClampedBufferAttribute( array, itemSize );
  28977. }
  28978. function Int16Attribute( array, itemSize ) {
  28979. console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
  28980. return new Int16BufferAttribute( array, itemSize );
  28981. }
  28982. function Uint16Attribute( array, itemSize ) {
  28983. console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
  28984. return new Uint16BufferAttribute( array, itemSize );
  28985. }
  28986. function Int32Attribute( array, itemSize ) {
  28987. console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
  28988. return new Int32BufferAttribute( array, itemSize );
  28989. }
  28990. function Uint32Attribute( array, itemSize ) {
  28991. console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
  28992. return new Uint32BufferAttribute( array, itemSize );
  28993. }
  28994. function Float32Attribute( array, itemSize ) {
  28995. console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
  28996. return new Float32BufferAttribute( array, itemSize );
  28997. }
  28998. function Float64Attribute( array, itemSize ) {
  28999. console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
  29000. return new Float64BufferAttribute( array, itemSize );
  29001. }
  29002. //
  29003. Curve.create = function ( construct, getPoint ) {
  29004. console.log( 'THREE.Curve.create() has been deprecated' );
  29005. construct.prototype = Object.create( Curve.prototype );
  29006. construct.prototype.constructor = construct;
  29007. construct.prototype.getPoint = getPoint;
  29008. return construct;
  29009. };
  29010. //
  29011. function ClosedSplineCurve3( points ) {
  29012. console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  29013. CatmullRomCurve3.call( this, points );
  29014. this.type = 'catmullrom';
  29015. this.closed = true;
  29016. }
  29017. ClosedSplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  29018. //
  29019. function SplineCurve3( points ) {
  29020. console.warn( 'THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  29021. CatmullRomCurve3.call( this, points );
  29022. this.type = 'catmullrom';
  29023. }
  29024. SplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  29025. //
  29026. function Spline( points ) {
  29027. console.warn( 'THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.' );
  29028. CatmullRomCurve3.call( this, points );
  29029. this.type = 'catmullrom';
  29030. }
  29031. Spline.prototype = Object.create( CatmullRomCurve3.prototype );
  29032. Object.assign( Spline.prototype, {
  29033. initFromArray: function ( a ) {
  29034. console.error( 'THREE.Spline: .initFromArray() has been removed.' );
  29035. },
  29036. getControlPointsArray: function ( optionalTarget ) {
  29037. console.error( 'THREE.Spline: .getControlPointsArray() has been removed.' );
  29038. },
  29039. reparametrizeByArcLength: function ( samplingCoef ) {
  29040. console.error( 'THREE.Spline: .reparametrizeByArcLength() has been removed.' );
  29041. }
  29042. } );
  29043. //
  29044. function BoundingBoxHelper( object, color ) {
  29045. console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
  29046. return new BoxHelper( object, color );
  29047. }
  29048. function EdgesHelper( object, hex ) {
  29049. console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
  29050. return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  29051. }
  29052. GridHelper.prototype.setColors = function () {
  29053. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  29054. };
  29055. function WireframeHelper( object, hex ) {
  29056. console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
  29057. return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  29058. }
  29059. //
  29060. function XHRLoader( manager ) {
  29061. console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
  29062. return new FileLoader( manager );
  29063. }
  29064. function BinaryTextureLoader( manager ) {
  29065. console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' );
  29066. return new DataTextureLoader( manager );
  29067. }
  29068. //
  29069. Object.assign( Box2.prototype, {
  29070. center: function ( optionalTarget ) {
  29071. console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
  29072. return this.getCenter( optionalTarget );
  29073. },
  29074. empty: function () {
  29075. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  29076. return this.isEmpty();
  29077. },
  29078. isIntersectionBox: function ( box ) {
  29079. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  29080. return this.intersectsBox( box );
  29081. },
  29082. size: function ( optionalTarget ) {
  29083. console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
  29084. return this.getSize( optionalTarget );
  29085. }
  29086. } );
  29087. Object.assign( Box3.prototype, {
  29088. center: function ( optionalTarget ) {
  29089. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  29090. return this.getCenter( optionalTarget );
  29091. },
  29092. empty: function () {
  29093. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  29094. return this.isEmpty();
  29095. },
  29096. isIntersectionBox: function ( box ) {
  29097. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  29098. return this.intersectsBox( box );
  29099. },
  29100. isIntersectionSphere: function ( sphere ) {
  29101. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  29102. return this.intersectsSphere( sphere );
  29103. },
  29104. size: function ( optionalTarget ) {
  29105. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  29106. return this.getSize( optionalTarget );
  29107. }
  29108. } );
  29109. Line3.prototype.center = function ( optionalTarget ) {
  29110. console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
  29111. return this.getCenter( optionalTarget );
  29112. };
  29113. _Math.random16 = function () {
  29114. console.warn( 'THREE.Math.random16() has been deprecated. Use Math.random() instead.' );
  29115. return Math.random();
  29116. };
  29117. Object.assign( Matrix3.prototype, {
  29118. flattenToArrayOffset: function ( array, offset ) {
  29119. console.warn( "THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  29120. return this.toArray( array, offset );
  29121. },
  29122. multiplyVector3: function ( vector ) {
  29123. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  29124. return vector.applyMatrix3( this );
  29125. },
  29126. multiplyVector3Array: function ( a ) {
  29127. console.warn( 'THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  29128. return this.applyToVector3Array( a );
  29129. },
  29130. applyToBuffer: function( buffer, offset, length ) {
  29131. console.warn( 'THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  29132. return this.applyToBufferAttribute( buffer );
  29133. },
  29134. applyToVector3Array: function( array, offset, length ) {
  29135. console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' );
  29136. }
  29137. } );
  29138. Object.assign( Matrix4.prototype, {
  29139. extractPosition: function ( m ) {
  29140. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  29141. return this.copyPosition( m );
  29142. },
  29143. flattenToArrayOffset: function ( array, offset ) {
  29144. console.warn( "THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  29145. return this.toArray( array, offset );
  29146. },
  29147. getPosition: function () {
  29148. var v1;
  29149. return function getPosition() {
  29150. if ( v1 === undefined ) v1 = new Vector3();
  29151. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  29152. return v1.setFromMatrixColumn( this, 3 );
  29153. };
  29154. }(),
  29155. setRotationFromQuaternion: function ( q ) {
  29156. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  29157. return this.makeRotationFromQuaternion( q );
  29158. },
  29159. multiplyVector3: function ( vector ) {
  29160. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  29161. return vector.applyMatrix4( this );
  29162. },
  29163. multiplyVector4: function ( vector ) {
  29164. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  29165. return vector.applyMatrix4( this );
  29166. },
  29167. multiplyVector3Array: function ( a ) {
  29168. console.warn( 'THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  29169. return this.applyToVector3Array( a );
  29170. },
  29171. rotateAxis: function ( v ) {
  29172. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  29173. v.transformDirection( this );
  29174. },
  29175. crossVector: function ( vector ) {
  29176. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  29177. return vector.applyMatrix4( this );
  29178. },
  29179. translate: function () {
  29180. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  29181. },
  29182. rotateX: function () {
  29183. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  29184. },
  29185. rotateY: function () {
  29186. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  29187. },
  29188. rotateZ: function () {
  29189. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  29190. },
  29191. rotateByAxis: function () {
  29192. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  29193. },
  29194. applyToBuffer: function( buffer, offset, length ) {
  29195. console.warn( 'THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  29196. return this.applyToBufferAttribute( buffer );
  29197. },
  29198. applyToVector3Array: function( array, offset, length ) {
  29199. console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' );
  29200. },
  29201. makeFrustum: function( left, right, bottom, top, near, far ) {
  29202. console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' );
  29203. return this.makePerspective( left, right, top, bottom, near, far );
  29204. }
  29205. } );
  29206. Plane.prototype.isIntersectionLine = function ( line ) {
  29207. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  29208. return this.intersectsLine( line );
  29209. };
  29210. Quaternion.prototype.multiplyVector3 = function ( vector ) {
  29211. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  29212. return vector.applyQuaternion( this );
  29213. };
  29214. Object.assign( Ray.prototype, {
  29215. isIntersectionBox: function ( box ) {
  29216. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  29217. return this.intersectsBox( box );
  29218. },
  29219. isIntersectionPlane: function ( plane ) {
  29220. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  29221. return this.intersectsPlane( plane );
  29222. },
  29223. isIntersectionSphere: function ( sphere ) {
  29224. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  29225. return this.intersectsSphere( sphere );
  29226. }
  29227. } );
  29228. Object.assign( Shape.prototype, {
  29229. extrude: function ( options ) {
  29230. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  29231. return new ExtrudeGeometry( this, options );
  29232. },
  29233. makeGeometry: function ( options ) {
  29234. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  29235. return new ShapeGeometry( this, options );
  29236. }
  29237. } );
  29238. Object.assign( Vector2.prototype, {
  29239. fromAttribute: function ( attribute, index, offset ) {
  29240. console.error( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  29241. return this.fromBufferAttribute( attribute, index, offset );
  29242. }
  29243. } );
  29244. Object.assign( Vector3.prototype, {
  29245. setEulerFromRotationMatrix: function () {
  29246. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  29247. },
  29248. setEulerFromQuaternion: function () {
  29249. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  29250. },
  29251. getPositionFromMatrix: function ( m ) {
  29252. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  29253. return this.setFromMatrixPosition( m );
  29254. },
  29255. getScaleFromMatrix: function ( m ) {
  29256. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  29257. return this.setFromMatrixScale( m );
  29258. },
  29259. getColumnFromMatrix: function ( index, matrix ) {
  29260. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  29261. return this.setFromMatrixColumn( matrix, index );
  29262. },
  29263. applyProjection: function ( m ) {
  29264. console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' );
  29265. return this.applyMatrix4( m );
  29266. },
  29267. fromAttribute: function ( attribute, index, offset ) {
  29268. console.error( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  29269. return this.fromBufferAttribute( attribute, index, offset );
  29270. }
  29271. } );
  29272. Object.assign( Vector4.prototype, {
  29273. fromAttribute: function ( attribute, index, offset ) {
  29274. console.error( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  29275. return this.fromBufferAttribute( attribute, index, offset );
  29276. }
  29277. } );
  29278. //
  29279. Geometry.prototype.computeTangents = function () {
  29280. console.warn( 'THREE.Geometry: .computeTangents() has been removed.' );
  29281. };
  29282. Object.assign( Object3D.prototype, {
  29283. getChildByName: function ( name ) {
  29284. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  29285. return this.getObjectByName( name );
  29286. },
  29287. renderDepth: function () {
  29288. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  29289. },
  29290. translate: function ( distance, axis ) {
  29291. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  29292. return this.translateOnAxis( axis, distance );
  29293. }
  29294. } );
  29295. Object.defineProperties( Object3D.prototype, {
  29296. eulerOrder: {
  29297. get: function () {
  29298. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  29299. return this.rotation.order;
  29300. },
  29301. set: function ( value ) {
  29302. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  29303. this.rotation.order = value;
  29304. }
  29305. },
  29306. useQuaternion: {
  29307. get: function () {
  29308. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  29309. },
  29310. set: function () {
  29311. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  29312. }
  29313. }
  29314. } );
  29315. Object.defineProperties( LOD.prototype, {
  29316. objects: {
  29317. get: function () {
  29318. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  29319. return this.levels;
  29320. }
  29321. }
  29322. } );
  29323. //
  29324. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  29325. console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " +
  29326. "Use .setFocalLength and .filmGauge for a photographic setup." );
  29327. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  29328. this.setFocalLength( focalLength );
  29329. };
  29330. //
  29331. Object.defineProperties( Light.prototype, {
  29332. onlyShadow: {
  29333. set: function () {
  29334. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  29335. }
  29336. },
  29337. shadowCameraFov: {
  29338. set: function ( value ) {
  29339. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  29340. this.shadow.camera.fov = value;
  29341. }
  29342. },
  29343. shadowCameraLeft: {
  29344. set: function ( value ) {
  29345. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  29346. this.shadow.camera.left = value;
  29347. }
  29348. },
  29349. shadowCameraRight: {
  29350. set: function ( value ) {
  29351. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  29352. this.shadow.camera.right = value;
  29353. }
  29354. },
  29355. shadowCameraTop: {
  29356. set: function ( value ) {
  29357. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  29358. this.shadow.camera.top = value;
  29359. }
  29360. },
  29361. shadowCameraBottom: {
  29362. set: function ( value ) {
  29363. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  29364. this.shadow.camera.bottom = value;
  29365. }
  29366. },
  29367. shadowCameraNear: {
  29368. set: function ( value ) {
  29369. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  29370. this.shadow.camera.near = value;
  29371. }
  29372. },
  29373. shadowCameraFar: {
  29374. set: function ( value ) {
  29375. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  29376. this.shadow.camera.far = value;
  29377. }
  29378. },
  29379. shadowCameraVisible: {
  29380. set: function () {
  29381. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  29382. }
  29383. },
  29384. shadowBias: {
  29385. set: function ( value ) {
  29386. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  29387. this.shadow.bias = value;
  29388. }
  29389. },
  29390. shadowDarkness: {
  29391. set: function () {
  29392. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  29393. }
  29394. },
  29395. shadowMapWidth: {
  29396. set: function ( value ) {
  29397. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  29398. this.shadow.mapSize.width = value;
  29399. }
  29400. },
  29401. shadowMapHeight: {
  29402. set: function ( value ) {
  29403. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  29404. this.shadow.mapSize.height = value;
  29405. }
  29406. }
  29407. } );
  29408. //
  29409. Object.defineProperties( BufferAttribute.prototype, {
  29410. length: {
  29411. get: function () {
  29412. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  29413. return this.array.length;
  29414. }
  29415. }
  29416. } );
  29417. Object.assign( BufferGeometry.prototype, {
  29418. addIndex: function ( index ) {
  29419. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  29420. this.setIndex( index );
  29421. },
  29422. addDrawCall: function ( start, count, indexOffset ) {
  29423. if ( indexOffset !== undefined ) {
  29424. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  29425. }
  29426. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  29427. this.addGroup( start, count );
  29428. },
  29429. clearDrawCalls: function () {
  29430. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  29431. this.clearGroups();
  29432. },
  29433. computeTangents: function () {
  29434. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  29435. },
  29436. computeOffsets: function () {
  29437. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  29438. }
  29439. } );
  29440. Object.defineProperties( BufferGeometry.prototype, {
  29441. drawcalls: {
  29442. get: function () {
  29443. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  29444. return this.groups;
  29445. }
  29446. },
  29447. offsets: {
  29448. get: function () {
  29449. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  29450. return this.groups;
  29451. }
  29452. }
  29453. } );
  29454. //
  29455. Object.defineProperties( Uniform.prototype, {
  29456. dynamic: {
  29457. set: function () {
  29458. console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' );
  29459. }
  29460. },
  29461. onUpdate: {
  29462. value: function () {
  29463. console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
  29464. return this;
  29465. }
  29466. }
  29467. } );
  29468. //
  29469. Object.defineProperties( Material.prototype, {
  29470. wrapAround: {
  29471. get: function () {
  29472. console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' );
  29473. },
  29474. set: function () {
  29475. console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' );
  29476. }
  29477. },
  29478. wrapRGB: {
  29479. get: function () {
  29480. console.warn( 'THREE.' + this.type + ': .wrapRGB has been removed.' );
  29481. return new Color();
  29482. }
  29483. }
  29484. } );
  29485. Object.defineProperties( MeshPhongMaterial.prototype, {
  29486. metal: {
  29487. get: function () {
  29488. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  29489. return false;
  29490. },
  29491. set: function () {
  29492. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  29493. }
  29494. }
  29495. } );
  29496. Object.defineProperties( ShaderMaterial.prototype, {
  29497. derivatives: {
  29498. get: function () {
  29499. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  29500. return this.extensions.derivatives;
  29501. },
  29502. set: function ( value ) {
  29503. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  29504. this.extensions.derivatives = value;
  29505. }
  29506. }
  29507. } );
  29508. //
  29509. Object.assign( WebGLRenderer.prototype, {
  29510. supportsFloatTextures: function () {
  29511. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  29512. return this.extensions.get( 'OES_texture_float' );
  29513. },
  29514. supportsHalfFloatTextures: function () {
  29515. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  29516. return this.extensions.get( 'OES_texture_half_float' );
  29517. },
  29518. supportsStandardDerivatives: function () {
  29519. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  29520. return this.extensions.get( 'OES_standard_derivatives' );
  29521. },
  29522. supportsCompressedTextureS3TC: function () {
  29523. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  29524. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  29525. },
  29526. supportsCompressedTexturePVRTC: function () {
  29527. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  29528. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  29529. },
  29530. supportsBlendMinMax: function () {
  29531. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  29532. return this.extensions.get( 'EXT_blend_minmax' );
  29533. },
  29534. supportsVertexTextures: function () {
  29535. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  29536. return this.capabilities.vertexTextures;
  29537. },
  29538. supportsInstancedArrays: function () {
  29539. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  29540. return this.extensions.get( 'ANGLE_instanced_arrays' );
  29541. },
  29542. enableScissorTest: function ( boolean ) {
  29543. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  29544. this.setScissorTest( boolean );
  29545. },
  29546. initMaterial: function () {
  29547. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  29548. },
  29549. addPrePlugin: function () {
  29550. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  29551. },
  29552. addPostPlugin: function () {
  29553. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  29554. },
  29555. updateShadowMap: function () {
  29556. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  29557. }
  29558. } );
  29559. Object.defineProperties( WebGLRenderer.prototype, {
  29560. shadowMapEnabled: {
  29561. get: function () {
  29562. return this.shadowMap.enabled;
  29563. },
  29564. set: function ( value ) {
  29565. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  29566. this.shadowMap.enabled = value;
  29567. }
  29568. },
  29569. shadowMapType: {
  29570. get: function () {
  29571. return this.shadowMap.type;
  29572. },
  29573. set: function ( value ) {
  29574. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  29575. this.shadowMap.type = value;
  29576. }
  29577. },
  29578. shadowMapCullFace: {
  29579. get: function () {
  29580. return this.shadowMap.cullFace;
  29581. },
  29582. set: function ( value ) {
  29583. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.' );
  29584. this.shadowMap.cullFace = value;
  29585. }
  29586. }
  29587. } );
  29588. Object.defineProperties( WebGLShadowMap.prototype, {
  29589. cullFace: {
  29590. get: function () {
  29591. return this.renderReverseSided ? CullFaceFront : CullFaceBack;
  29592. },
  29593. set: function ( cullFace ) {
  29594. var value = ( cullFace !== CullFaceBack );
  29595. console.warn( "WebGLRenderer: .shadowMap.cullFace is deprecated. Set .shadowMap.renderReverseSided to " + value + "." );
  29596. this.renderReverseSided = value;
  29597. }
  29598. }
  29599. } );
  29600. //
  29601. Object.defineProperties( WebGLRenderTarget.prototype, {
  29602. wrapS: {
  29603. get: function () {
  29604. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  29605. return this.texture.wrapS;
  29606. },
  29607. set: function ( value ) {
  29608. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  29609. this.texture.wrapS = value;
  29610. }
  29611. },
  29612. wrapT: {
  29613. get: function () {
  29614. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  29615. return this.texture.wrapT;
  29616. },
  29617. set: function ( value ) {
  29618. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  29619. this.texture.wrapT = value;
  29620. }
  29621. },
  29622. magFilter: {
  29623. get: function () {
  29624. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  29625. return this.texture.magFilter;
  29626. },
  29627. set: function ( value ) {
  29628. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  29629. this.texture.magFilter = value;
  29630. }
  29631. },
  29632. minFilter: {
  29633. get: function () {
  29634. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  29635. return this.texture.minFilter;
  29636. },
  29637. set: function ( value ) {
  29638. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  29639. this.texture.minFilter = value;
  29640. }
  29641. },
  29642. anisotropy: {
  29643. get: function () {
  29644. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  29645. return this.texture.anisotropy;
  29646. },
  29647. set: function ( value ) {
  29648. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  29649. this.texture.anisotropy = value;
  29650. }
  29651. },
  29652. offset: {
  29653. get: function () {
  29654. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  29655. return this.texture.offset;
  29656. },
  29657. set: function ( value ) {
  29658. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  29659. this.texture.offset = value;
  29660. }
  29661. },
  29662. repeat: {
  29663. get: function () {
  29664. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  29665. return this.texture.repeat;
  29666. },
  29667. set: function ( value ) {
  29668. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  29669. this.texture.repeat = value;
  29670. }
  29671. },
  29672. format: {
  29673. get: function () {
  29674. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  29675. return this.texture.format;
  29676. },
  29677. set: function ( value ) {
  29678. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  29679. this.texture.format = value;
  29680. }
  29681. },
  29682. type: {
  29683. get: function () {
  29684. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  29685. return this.texture.type;
  29686. },
  29687. set: function ( value ) {
  29688. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  29689. this.texture.type = value;
  29690. }
  29691. },
  29692. generateMipmaps: {
  29693. get: function () {
  29694. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  29695. return this.texture.generateMipmaps;
  29696. },
  29697. set: function ( value ) {
  29698. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  29699. this.texture.generateMipmaps = value;
  29700. }
  29701. }
  29702. } );
  29703. //
  29704. Audio.prototype.load = function ( file ) {
  29705. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  29706. var scope = this;
  29707. var audioLoader = new AudioLoader();
  29708. audioLoader.load( file, function ( buffer ) {
  29709. scope.setBuffer( buffer );
  29710. } );
  29711. return this;
  29712. };
  29713. AudioAnalyser.prototype.getData = function () {
  29714. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  29715. return this.getFrequencyData();
  29716. };
  29717. //
  29718. var GeometryUtils = {
  29719. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  29720. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  29721. var matrix;
  29722. if ( geometry2.isMesh ) {
  29723. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  29724. matrix = geometry2.matrix;
  29725. geometry2 = geometry2.geometry;
  29726. }
  29727. geometry1.merge( geometry2, matrix, materialIndexOffset );
  29728. },
  29729. center: function ( geometry ) {
  29730. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  29731. return geometry.center();
  29732. }
  29733. };
  29734. var ImageUtils = {
  29735. crossOrigin: undefined,
  29736. loadTexture: function ( url, mapping, onLoad, onError ) {
  29737. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  29738. var loader = new TextureLoader();
  29739. loader.setCrossOrigin( this.crossOrigin );
  29740. var texture = loader.load( url, onLoad, undefined, onError );
  29741. if ( mapping ) texture.mapping = mapping;
  29742. return texture;
  29743. },
  29744. loadTextureCube: function ( urls, mapping, onLoad, onError ) {
  29745. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  29746. var loader = new CubeTextureLoader();
  29747. loader.setCrossOrigin( this.crossOrigin );
  29748. var texture = loader.load( urls, onLoad, undefined, onError );
  29749. if ( mapping ) texture.mapping = mapping;
  29750. return texture;
  29751. },
  29752. loadCompressedTexture: function () {
  29753. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  29754. },
  29755. loadCompressedTextureCube: function () {
  29756. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  29757. }
  29758. };
  29759. //
  29760. function Projector() {
  29761. console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' );
  29762. this.projectVector = function ( vector, camera ) {
  29763. console.warn( 'THREE.Projector: .projectVector() is now vector.project().' );
  29764. vector.project( camera );
  29765. };
  29766. this.unprojectVector = function ( vector, camera ) {
  29767. console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' );
  29768. vector.unproject( camera );
  29769. };
  29770. this.pickingRay = function () {
  29771. console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' );
  29772. };
  29773. }
  29774. //
  29775. function CanvasRenderer() {
  29776. console.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' );
  29777. this.domElement = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  29778. this.clear = function () {};
  29779. this.render = function () {};
  29780. this.setClearColor = function () {};
  29781. this.setSize = function () {};
  29782. }
  29783. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  29784. exports.WebGLRenderTarget = WebGLRenderTarget;
  29785. exports.WebGLRenderer = WebGLRenderer;
  29786. exports.ShaderLib = ShaderLib;
  29787. exports.UniformsLib = UniformsLib;
  29788. exports.UniformsUtils = UniformsUtils;
  29789. exports.ShaderChunk = ShaderChunk;
  29790. exports.FogExp2 = FogExp2;
  29791. exports.Fog = Fog;
  29792. exports.Scene = Scene;
  29793. exports.LensFlare = LensFlare;
  29794. exports.Sprite = Sprite;
  29795. exports.LOD = LOD;
  29796. exports.SkinnedMesh = SkinnedMesh;
  29797. exports.Skeleton = Skeleton;
  29798. exports.Bone = Bone;
  29799. exports.Mesh = Mesh;
  29800. exports.LineSegments = LineSegments;
  29801. exports.Line = Line;
  29802. exports.Points = Points;
  29803. exports.Group = Group;
  29804. exports.VideoTexture = VideoTexture;
  29805. exports.DataTexture = DataTexture;
  29806. exports.CompressedTexture = CompressedTexture;
  29807. exports.CubeTexture = CubeTexture;
  29808. exports.CanvasTexture = CanvasTexture;
  29809. exports.DepthTexture = DepthTexture;
  29810. exports.Texture = Texture;
  29811. exports.CompressedTextureLoader = CompressedTextureLoader;
  29812. exports.DataTextureLoader = DataTextureLoader;
  29813. exports.CubeTextureLoader = CubeTextureLoader;
  29814. exports.TextureLoader = TextureLoader;
  29815. exports.ObjectLoader = ObjectLoader;
  29816. exports.MaterialLoader = MaterialLoader;
  29817. exports.BufferGeometryLoader = BufferGeometryLoader;
  29818. exports.DefaultLoadingManager = DefaultLoadingManager;
  29819. exports.LoadingManager = LoadingManager;
  29820. exports.JSONLoader = JSONLoader;
  29821. exports.ImageLoader = ImageLoader;
  29822. exports.FontLoader = FontLoader;
  29823. exports.FileLoader = FileLoader;
  29824. exports.Loader = Loader;
  29825. exports.Cache = Cache;
  29826. exports.AudioLoader = AudioLoader;
  29827. exports.SpotLightShadow = SpotLightShadow;
  29828. exports.SpotLight = SpotLight;
  29829. exports.PointLight = PointLight;
  29830. exports.RectAreaLight = RectAreaLight;
  29831. exports.HemisphereLight = HemisphereLight;
  29832. exports.DirectionalLightShadow = DirectionalLightShadow;
  29833. exports.DirectionalLight = DirectionalLight;
  29834. exports.AmbientLight = AmbientLight;
  29835. exports.LightShadow = LightShadow;
  29836. exports.Light = Light;
  29837. exports.StereoCamera = StereoCamera;
  29838. exports.PerspectiveCamera = PerspectiveCamera;
  29839. exports.OrthographicCamera = OrthographicCamera;
  29840. exports.CubeCamera = CubeCamera;
  29841. exports.Camera = Camera;
  29842. exports.AudioListener = AudioListener;
  29843. exports.PositionalAudio = PositionalAudio;
  29844. exports.AudioContext = AudioContext;
  29845. exports.AudioAnalyser = AudioAnalyser;
  29846. exports.Audio = Audio;
  29847. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  29848. exports.StringKeyframeTrack = StringKeyframeTrack;
  29849. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  29850. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  29851. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  29852. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  29853. exports.PropertyMixer = PropertyMixer;
  29854. exports.PropertyBinding = PropertyBinding;
  29855. exports.KeyframeTrack = KeyframeTrack;
  29856. exports.AnimationUtils = AnimationUtils;
  29857. exports.AnimationObjectGroup = AnimationObjectGroup;
  29858. exports.AnimationMixer = AnimationMixer;
  29859. exports.AnimationClip = AnimationClip;
  29860. exports.Uniform = Uniform;
  29861. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  29862. exports.BufferGeometry = BufferGeometry;
  29863. exports.GeometryIdCount = GeometryIdCount;
  29864. exports.Geometry = Geometry;
  29865. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  29866. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  29867. exports.InterleavedBuffer = InterleavedBuffer;
  29868. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  29869. exports.Face3 = Face3;
  29870. exports.Object3D = Object3D;
  29871. exports.Raycaster = Raycaster;
  29872. exports.Layers = Layers;
  29873. exports.EventDispatcher = EventDispatcher;
  29874. exports.Clock = Clock;
  29875. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  29876. exports.LinearInterpolant = LinearInterpolant;
  29877. exports.DiscreteInterpolant = DiscreteInterpolant;
  29878. exports.CubicInterpolant = CubicInterpolant;
  29879. exports.Interpolant = Interpolant;
  29880. exports.Triangle = Triangle;
  29881. exports.Math = _Math;
  29882. exports.Spherical = Spherical;
  29883. exports.Cylindrical = Cylindrical;
  29884. exports.Plane = Plane;
  29885. exports.Frustum = Frustum;
  29886. exports.Sphere = Sphere;
  29887. exports.Ray = Ray;
  29888. exports.Matrix4 = Matrix4;
  29889. exports.Matrix3 = Matrix3;
  29890. exports.Box3 = Box3;
  29891. exports.Box2 = Box2;
  29892. exports.Line3 = Line3;
  29893. exports.Euler = Euler;
  29894. exports.Vector4 = Vector4;
  29895. exports.Vector3 = Vector3;
  29896. exports.Vector2 = Vector2;
  29897. exports.Quaternion = Quaternion;
  29898. exports.Color = Color;
  29899. exports.MorphBlendMesh = MorphBlendMesh;
  29900. exports.ImmediateRenderObject = ImmediateRenderObject;
  29901. exports.VertexNormalsHelper = VertexNormalsHelper;
  29902. exports.SpotLightHelper = SpotLightHelper;
  29903. exports.SkeletonHelper = SkeletonHelper;
  29904. exports.PointLightHelper = PointLightHelper;
  29905. exports.RectAreaLightHelper = RectAreaLightHelper;
  29906. exports.HemisphereLightHelper = HemisphereLightHelper;
  29907. exports.GridHelper = GridHelper;
  29908. exports.PolarGridHelper = PolarGridHelper;
  29909. exports.FaceNormalsHelper = FaceNormalsHelper;
  29910. exports.DirectionalLightHelper = DirectionalLightHelper;
  29911. exports.CameraHelper = CameraHelper;
  29912. exports.BoxHelper = BoxHelper;
  29913. exports.ArrowHelper = ArrowHelper;
  29914. exports.AxisHelper = AxisHelper;
  29915. exports.CatmullRomCurve3 = CatmullRomCurve3;
  29916. exports.CubicBezierCurve3 = CubicBezierCurve3;
  29917. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  29918. exports.LineCurve3 = LineCurve3;
  29919. exports.ArcCurve = ArcCurve;
  29920. exports.EllipseCurve = EllipseCurve;
  29921. exports.SplineCurve = SplineCurve;
  29922. exports.CubicBezierCurve = CubicBezierCurve;
  29923. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  29924. exports.LineCurve = LineCurve;
  29925. exports.Shape = Shape;
  29926. exports.Path = Path;
  29927. exports.ShapePath = ShapePath;
  29928. exports.Font = Font;
  29929. exports.CurvePath = CurvePath;
  29930. exports.Curve = Curve;
  29931. exports.ShapeUtils = ShapeUtils;
  29932. exports.SceneUtils = SceneUtils;
  29933. exports.WireframeGeometry = WireframeGeometry;
  29934. exports.ParametricGeometry = ParametricGeometry;
  29935. exports.ParametricBufferGeometry = ParametricBufferGeometry;
  29936. exports.TetrahedronGeometry = TetrahedronGeometry;
  29937. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  29938. exports.OctahedronGeometry = OctahedronGeometry;
  29939. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  29940. exports.IcosahedronGeometry = IcosahedronGeometry;
  29941. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  29942. exports.DodecahedronGeometry = DodecahedronGeometry;
  29943. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  29944. exports.PolyhedronGeometry = PolyhedronGeometry;
  29945. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  29946. exports.TubeGeometry = TubeGeometry;
  29947. exports.TubeBufferGeometry = TubeBufferGeometry;
  29948. exports.TorusKnotGeometry = TorusKnotGeometry;
  29949. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  29950. exports.TorusGeometry = TorusGeometry;
  29951. exports.TorusBufferGeometry = TorusBufferGeometry;
  29952. exports.TextGeometry = TextGeometry;
  29953. exports.SphereGeometry = SphereGeometry;
  29954. exports.SphereBufferGeometry = SphereBufferGeometry;
  29955. exports.RingGeometry = RingGeometry;
  29956. exports.RingBufferGeometry = RingBufferGeometry;
  29957. exports.PlaneGeometry = PlaneGeometry;
  29958. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  29959. exports.LatheGeometry = LatheGeometry;
  29960. exports.LatheBufferGeometry = LatheBufferGeometry;
  29961. exports.ShapeGeometry = ShapeGeometry;
  29962. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  29963. exports.ExtrudeGeometry = ExtrudeGeometry;
  29964. exports.EdgesGeometry = EdgesGeometry;
  29965. exports.ConeGeometry = ConeGeometry;
  29966. exports.ConeBufferGeometry = ConeBufferGeometry;
  29967. exports.CylinderGeometry = CylinderGeometry;
  29968. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  29969. exports.CircleGeometry = CircleGeometry;
  29970. exports.CircleBufferGeometry = CircleBufferGeometry;
  29971. exports.BoxGeometry = BoxGeometry;
  29972. exports.BoxBufferGeometry = BoxBufferGeometry;
  29973. exports.ShadowMaterial = ShadowMaterial;
  29974. exports.SpriteMaterial = SpriteMaterial;
  29975. exports.RawShaderMaterial = RawShaderMaterial;
  29976. exports.ShaderMaterial = ShaderMaterial;
  29977. exports.PointsMaterial = PointsMaterial;
  29978. exports.MultiMaterial = MultiMaterial;
  29979. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  29980. exports.MeshStandardMaterial = MeshStandardMaterial;
  29981. exports.MeshPhongMaterial = MeshPhongMaterial;
  29982. exports.MeshToonMaterial = MeshToonMaterial;
  29983. exports.MeshNormalMaterial = MeshNormalMaterial;
  29984. exports.MeshLambertMaterial = MeshLambertMaterial;
  29985. exports.MeshDepthMaterial = MeshDepthMaterial;
  29986. exports.MeshBasicMaterial = MeshBasicMaterial;
  29987. exports.LineDashedMaterial = LineDashedMaterial;
  29988. exports.LineBasicMaterial = LineBasicMaterial;
  29989. exports.Material = Material;
  29990. exports.Float64BufferAttribute = Float64BufferAttribute;
  29991. exports.Float32BufferAttribute = Float32BufferAttribute;
  29992. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  29993. exports.Int32BufferAttribute = Int32BufferAttribute;
  29994. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  29995. exports.Int16BufferAttribute = Int16BufferAttribute;
  29996. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  29997. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  29998. exports.Int8BufferAttribute = Int8BufferAttribute;
  29999. exports.BufferAttribute = BufferAttribute;
  30000. exports.REVISION = REVISION;
  30001. exports.MOUSE = MOUSE;
  30002. exports.CullFaceNone = CullFaceNone;
  30003. exports.CullFaceBack = CullFaceBack;
  30004. exports.CullFaceFront = CullFaceFront;
  30005. exports.CullFaceFrontBack = CullFaceFrontBack;
  30006. exports.FrontFaceDirectionCW = FrontFaceDirectionCW;
  30007. exports.FrontFaceDirectionCCW = FrontFaceDirectionCCW;
  30008. exports.BasicShadowMap = BasicShadowMap;
  30009. exports.PCFShadowMap = PCFShadowMap;
  30010. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  30011. exports.FrontSide = FrontSide;
  30012. exports.BackSide = BackSide;
  30013. exports.DoubleSide = DoubleSide;
  30014. exports.FlatShading = FlatShading;
  30015. exports.SmoothShading = SmoothShading;
  30016. exports.NoColors = NoColors;
  30017. exports.FaceColors = FaceColors;
  30018. exports.VertexColors = VertexColors;
  30019. exports.NoBlending = NoBlending;
  30020. exports.NormalBlending = NormalBlending;
  30021. exports.AdditiveBlending = AdditiveBlending;
  30022. exports.SubtractiveBlending = SubtractiveBlending;
  30023. exports.MultiplyBlending = MultiplyBlending;
  30024. exports.CustomBlending = CustomBlending;
  30025. exports.AddEquation = AddEquation;
  30026. exports.SubtractEquation = SubtractEquation;
  30027. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  30028. exports.MinEquation = MinEquation;
  30029. exports.MaxEquation = MaxEquation;
  30030. exports.ZeroFactor = ZeroFactor;
  30031. exports.OneFactor = OneFactor;
  30032. exports.SrcColorFactor = SrcColorFactor;
  30033. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  30034. exports.SrcAlphaFactor = SrcAlphaFactor;
  30035. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  30036. exports.DstAlphaFactor = DstAlphaFactor;
  30037. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  30038. exports.DstColorFactor = DstColorFactor;
  30039. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  30040. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  30041. exports.NeverDepth = NeverDepth;
  30042. exports.AlwaysDepth = AlwaysDepth;
  30043. exports.LessDepth = LessDepth;
  30044. exports.LessEqualDepth = LessEqualDepth;
  30045. exports.EqualDepth = EqualDepth;
  30046. exports.GreaterEqualDepth = GreaterEqualDepth;
  30047. exports.GreaterDepth = GreaterDepth;
  30048. exports.NotEqualDepth = NotEqualDepth;
  30049. exports.MultiplyOperation = MultiplyOperation;
  30050. exports.MixOperation = MixOperation;
  30051. exports.AddOperation = AddOperation;
  30052. exports.NoToneMapping = NoToneMapping;
  30053. exports.LinearToneMapping = LinearToneMapping;
  30054. exports.ReinhardToneMapping = ReinhardToneMapping;
  30055. exports.Uncharted2ToneMapping = Uncharted2ToneMapping;
  30056. exports.CineonToneMapping = CineonToneMapping;
  30057. exports.UVMapping = UVMapping;
  30058. exports.CubeReflectionMapping = CubeReflectionMapping;
  30059. exports.CubeRefractionMapping = CubeRefractionMapping;
  30060. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  30061. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  30062. exports.SphericalReflectionMapping = SphericalReflectionMapping;
  30063. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  30064. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  30065. exports.RepeatWrapping = RepeatWrapping;
  30066. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  30067. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  30068. exports.NearestFilter = NearestFilter;
  30069. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  30070. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  30071. exports.LinearFilter = LinearFilter;
  30072. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  30073. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  30074. exports.UnsignedByteType = UnsignedByteType;
  30075. exports.ByteType = ByteType;
  30076. exports.ShortType = ShortType;
  30077. exports.UnsignedShortType = UnsignedShortType;
  30078. exports.IntType = IntType;
  30079. exports.UnsignedIntType = UnsignedIntType;
  30080. exports.FloatType = FloatType;
  30081. exports.HalfFloatType = HalfFloatType;
  30082. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  30083. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  30084. exports.UnsignedShort565Type = UnsignedShort565Type;
  30085. exports.UnsignedInt248Type = UnsignedInt248Type;
  30086. exports.AlphaFormat = AlphaFormat;
  30087. exports.RGBFormat = RGBFormat;
  30088. exports.RGBAFormat = RGBAFormat;
  30089. exports.LuminanceFormat = LuminanceFormat;
  30090. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  30091. exports.RGBEFormat = RGBEFormat;
  30092. exports.DepthFormat = DepthFormat;
  30093. exports.DepthStencilFormat = DepthStencilFormat;
  30094. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  30095. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  30096. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  30097. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  30098. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  30099. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  30100. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  30101. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  30102. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  30103. exports.LoopOnce = LoopOnce;
  30104. exports.LoopRepeat = LoopRepeat;
  30105. exports.LoopPingPong = LoopPingPong;
  30106. exports.InterpolateDiscrete = InterpolateDiscrete;
  30107. exports.InterpolateLinear = InterpolateLinear;
  30108. exports.InterpolateSmooth = InterpolateSmooth;
  30109. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  30110. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  30111. exports.WrapAroundEnding = WrapAroundEnding;
  30112. exports.TrianglesDrawMode = TrianglesDrawMode;
  30113. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  30114. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  30115. exports.LinearEncoding = LinearEncoding;
  30116. exports.sRGBEncoding = sRGBEncoding;
  30117. exports.GammaEncoding = GammaEncoding;
  30118. exports.RGBEEncoding = RGBEEncoding;
  30119. exports.LogLuvEncoding = LogLuvEncoding;
  30120. exports.RGBM7Encoding = RGBM7Encoding;
  30121. exports.RGBM16Encoding = RGBM16Encoding;
  30122. exports.RGBDEncoding = RGBDEncoding;
  30123. exports.BasicDepthPacking = BasicDepthPacking;
  30124. exports.RGBADepthPacking = RGBADepthPacking;
  30125. exports.CubeGeometry = BoxGeometry;
  30126. exports.Face4 = Face4;
  30127. exports.LineStrip = LineStrip;
  30128. exports.LinePieces = LinePieces;
  30129. exports.MeshFaceMaterial = MeshFaceMaterial;
  30130. exports.PointCloud = PointCloud;
  30131. exports.Particle = Particle;
  30132. exports.ParticleSystem = ParticleSystem;
  30133. exports.PointCloudMaterial = PointCloudMaterial;
  30134. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  30135. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  30136. exports.Vertex = Vertex;
  30137. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  30138. exports.Int8Attribute = Int8Attribute;
  30139. exports.Uint8Attribute = Uint8Attribute;
  30140. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  30141. exports.Int16Attribute = Int16Attribute;
  30142. exports.Uint16Attribute = Uint16Attribute;
  30143. exports.Int32Attribute = Int32Attribute;
  30144. exports.Uint32Attribute = Uint32Attribute;
  30145. exports.Float32Attribute = Float32Attribute;
  30146. exports.Float64Attribute = Float64Attribute;
  30147. exports.ClosedSplineCurve3 = ClosedSplineCurve3;
  30148. exports.SplineCurve3 = SplineCurve3;
  30149. exports.Spline = Spline;
  30150. exports.BoundingBoxHelper = BoundingBoxHelper;
  30151. exports.EdgesHelper = EdgesHelper;
  30152. exports.WireframeHelper = WireframeHelper;
  30153. exports.XHRLoader = XHRLoader;
  30154. exports.BinaryTextureLoader = BinaryTextureLoader;
  30155. exports.GeometryUtils = GeometryUtils;
  30156. exports.ImageUtils = ImageUtils;
  30157. exports.Projector = Projector;
  30158. exports.CanvasRenderer = CanvasRenderer;
  30159. Object.defineProperty(exports, '__esModule', { value: true });
  30160. })));
  30161. },{}],42:[function(_dereq_,module,exports){
  30162. /**
  30163. * @author Michael Guerrero / http://realitymeltdown.com
  30164. */
  30165. THREE.BlendCharacter = function () {
  30166. this.weightSchedule = [];
  30167. this.warpSchedule = [];
  30168. this.load = function ( url, onLoad ) {
  30169. var scope = this;
  30170. var loader = new THREE.ObjectLoader();
  30171. loader.load( url, function( loadedObject ) {
  30172. // The exporter does not currently allow exporting a skinned mesh by itself
  30173. // so we must fish it out of the hierarchy it is embedded in (scene)
  30174. loadedObject.traverse( function( object ) {
  30175. if ( object instanceof THREE.SkinnedMesh ) {
  30176. scope.skinnedMesh = object;
  30177. }
  30178. } );
  30179. THREE.SkinnedMesh.call( scope, scope.skinnedMesh.geometry, scope.skinnedMesh.material );
  30180. // If we didn't successfully find the mesh, bail out
  30181. if ( scope.skinnedMesh == undefined ) {
  30182. console.log( 'unable to find skinned mesh in ' + url );
  30183. return;
  30184. }
  30185. scope.material.skinning = true;
  30186. scope.mixer = new THREE.AnimationMixer( scope );
  30187. // Create the animations
  30188. for ( var i = 0; i < scope.geometry.animations.length; ++ i ) {
  30189. scope.mixer.clipAction( scope.geometry.animations[ i ] );
  30190. }
  30191. // Loading is complete, fire the callback
  30192. if ( onLoad !== undefined ) onLoad();
  30193. } );
  30194. };
  30195. this.loadJSON = function ( url, onLoad ) {
  30196. var scope = this;
  30197. var loader = new THREE.JSONLoader();
  30198. loader.load( url, function( geometry, materials ) {
  30199. var originalMaterial = materials[ 0 ];
  30200. originalMaterial.skinning = true;
  30201. THREE.SkinnedMesh.call( scope, geometry, originalMaterial );
  30202. var mixer = new THREE.AnimationMixer( scope );
  30203. scope.mixer = mixer;
  30204. // Create the animations
  30205. for ( var i = 0; i < geometry.animations.length; ++ i ) {
  30206. mixer.clipAction( geometry.animations[ i ] );
  30207. }
  30208. // Loading is complete, fire the callback
  30209. if ( onLoad !== undefined ) onLoad();
  30210. } );
  30211. };
  30212. this.update = function( dt ) {
  30213. this.mixer.update( dt );
  30214. };
  30215. this.play = function( animName, weight ) {
  30216. //console.log("play('%s', %f)", animName, weight);
  30217. return this.mixer.clipAction( animName ).
  30218. setEffectiveWeight( weight ).play();
  30219. };
  30220. this.crossfade = function( fromAnimName, toAnimName, duration ) {
  30221. this.mixer.stopAllAction();
  30222. var fromAction = this.play( fromAnimName, 1 );
  30223. var toAction = this.play( toAnimName, 1 );
  30224. fromAction.crossFadeTo( toAction, duration, false );
  30225. };
  30226. this.warp = function( fromAnimName, toAnimName, duration ) {
  30227. this.mixer.stopAllAction();
  30228. var fromAction = this.play( fromAnimName, 1 );
  30229. var toAction = this.play( toAnimName, 1 );
  30230. fromAction.crossFadeTo( toAction, duration, true );
  30231. };
  30232. this.applyWeight = function( animName, weight ) {
  30233. this.mixer.clipAction( animName ).setEffectiveWeight( weight );
  30234. };
  30235. this.getWeight = function( animName ) {
  30236. return this.mixer.clipAction( animName ).getEffectiveWeight();
  30237. };
  30238. this.pauseAll = function() {
  30239. this.mixer.timeScale = 0;
  30240. };
  30241. this.unPauseAll = function() {
  30242. this.mixer.timeScale = 1;
  30243. };
  30244. this.stopAll = function() {
  30245. this.mixer.stopAllAction();
  30246. };
  30247. this.showModel = function( boolean ) {
  30248. this.visible = boolean;
  30249. };
  30250. };
  30251. THREE.BlendCharacter.prototype = Object.create( THREE.SkinnedMesh.prototype );
  30252. THREE.BlendCharacter.prototype.constructor = THREE.BlendCharacter;
  30253. THREE.BlendCharacter.prototype.getForward = function() {
  30254. var forward = new THREE.Vector3();
  30255. return function() {
  30256. // pull the character's forward basis vector out of the matrix
  30257. forward.set(
  30258. - this.matrix.elements[ 8 ],
  30259. - this.matrix.elements[ 9 ],
  30260. - this.matrix.elements[ 10 ]
  30261. );
  30262. return forward;
  30263. }
  30264. };
  30265. },{}],43:[function(_dereq_,module,exports){
  30266. /**
  30267. * @author Tim Knip / http://www.floorplanner.com/ / tim at floorplanner.com
  30268. * @author Tony Parisi / http://www.tonyparisi.com/
  30269. */
  30270. THREE.ColladaLoader = function () {
  30271. var COLLADA = null;
  30272. var scene = null;
  30273. var visualScene;
  30274. var kinematicsModel;
  30275. var readyCallbackFunc = null;
  30276. var sources = {};
  30277. var images = {};
  30278. var animations = {};
  30279. var controllers = {};
  30280. var geometries = {};
  30281. var materials = {};
  30282. var effects = {};
  30283. var cameras = {};
  30284. var lights = {};
  30285. var animData;
  30286. var kinematics;
  30287. var visualScenes;
  30288. var kinematicsModels;
  30289. var baseUrl;
  30290. var morphs;
  30291. var skins;
  30292. var flip_uv = true;
  30293. var preferredShading = THREE.SmoothShading;
  30294. var options = {
  30295. // Force Geometry to always be centered at the local origin of the
  30296. // containing Mesh.
  30297. centerGeometry: false,
  30298. // Axis conversion is done for geometries, animations, and controllers.
  30299. // If we ever pull cameras or lights out of the COLLADA file, they'll
  30300. // need extra work.
  30301. convertUpAxis: false,
  30302. subdivideFaces: true,
  30303. upAxis: 'Y',
  30304. // For reflective or refractive materials we'll use this cubemap
  30305. defaultEnvMap: null
  30306. };
  30307. var colladaUnit = 1.0;
  30308. var colladaUp = 'Y';
  30309. var upConversion = null;
  30310. function load ( url, readyCallback, progressCallback, failCallback ) {
  30311. var length = 0;
  30312. if ( document.implementation && document.implementation.createDocument ) {
  30313. var request = new XMLHttpRequest();
  30314. request.onreadystatechange = function() {
  30315. if ( request.readyState === 4 ) {
  30316. if ( request.status === 0 || request.status === 200 ) {
  30317. if ( request.response ) {
  30318. readyCallbackFunc = readyCallback;
  30319. parse( request.response, undefined, url );
  30320. } else {
  30321. if ( failCallback ) {
  30322. failCallback( { type: 'error', url: url } );
  30323. } else {
  30324. console.error( "ColladaLoader: Empty or non-existing file (" + url + ")" );
  30325. }
  30326. }
  30327. }else{
  30328. if( failCallback ){
  30329. failCallback( { type: 'error', url: url } );
  30330. }else{
  30331. console.error( 'ColladaLoader: Couldn\'t load "' + url + '" (' + request.status + ')' );
  30332. }
  30333. }
  30334. } else if ( request.readyState === 3 ) {
  30335. if ( progressCallback ) {
  30336. if ( length === 0 ) {
  30337. length = request.getResponseHeader( "Content-Length" );
  30338. }
  30339. progressCallback( { total: length, loaded: request.responseText.length } );
  30340. }
  30341. }
  30342. };
  30343. request.open( "GET", url, true );
  30344. request.send( null );
  30345. } else {
  30346. alert( "Don't know how to parse XML!" );
  30347. }
  30348. }
  30349. function parse( text, callBack, url ) {
  30350. COLLADA = new DOMParser().parseFromString( text, 'text/xml' );
  30351. callBack = callBack || readyCallbackFunc;
  30352. if ( url !== undefined ) {
  30353. var parts = url.split( '/' );
  30354. parts.pop();
  30355. baseUrl = ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  30356. }
  30357. parseAsset();
  30358. setUpConversion();
  30359. images = parseLib( "library_images image", _Image, "image" );
  30360. materials = parseLib( "library_materials material", Material, "material" );
  30361. effects = parseLib( "library_effects effect", Effect, "effect" );
  30362. geometries = parseLib( "library_geometries geometry", Geometry, "geometry" );
  30363. cameras = parseLib( "library_cameras camera", Camera, "camera" );
  30364. lights = parseLib( "library_lights light", Light, "light" );
  30365. controllers = parseLib( "library_controllers controller", Controller, "controller" );
  30366. animations = parseLib( "library_animations animation", Animation, "animation" );
  30367. visualScenes = parseLib( "library_visual_scenes visual_scene", VisualScene, "visual_scene" );
  30368. kinematicsModels = parseLib( "library_kinematics_models kinematics_model", KinematicsModel, "kinematics_model" );
  30369. morphs = [];
  30370. skins = [];
  30371. visualScene = parseScene();
  30372. scene = new THREE.Group();
  30373. for ( var i = 0; i < visualScene.nodes.length; i ++ ) {
  30374. scene.add( createSceneGraph( visualScene.nodes[ i ] ) );
  30375. }
  30376. // unit conversion
  30377. scene.scale.multiplyScalar( colladaUnit );
  30378. createAnimations();
  30379. kinematicsModel = parseKinematicsModel();
  30380. createKinematics();
  30381. var result = {
  30382. scene: scene,
  30383. morphs: morphs,
  30384. skins: skins,
  30385. animations: animData,
  30386. kinematics: kinematics,
  30387. dae: {
  30388. images: images,
  30389. materials: materials,
  30390. cameras: cameras,
  30391. lights: lights,
  30392. effects: effects,
  30393. geometries: geometries,
  30394. controllers: controllers,
  30395. animations: animations,
  30396. visualScenes: visualScenes,
  30397. visualScene: visualScene,
  30398. scene: visualScene,
  30399. kinematicsModels: kinematicsModels,
  30400. kinematicsModel: kinematicsModel
  30401. }
  30402. };
  30403. if ( callBack ) {
  30404. callBack( result );
  30405. }
  30406. return result;
  30407. }
  30408. function setPreferredShading ( shading ) {
  30409. preferredShading = shading;
  30410. }
  30411. function parseAsset () {
  30412. var elements = COLLADA.querySelectorAll('asset');
  30413. var element = elements[0];
  30414. if ( element && element.childNodes ) {
  30415. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  30416. var child = element.childNodes[ i ];
  30417. switch ( child.nodeName ) {
  30418. case 'unit':
  30419. var meter = child.getAttribute( 'meter' );
  30420. if ( meter ) {
  30421. colladaUnit = parseFloat( meter );
  30422. }
  30423. break;
  30424. case 'up_axis':
  30425. colladaUp = child.textContent.charAt(0);
  30426. break;
  30427. }
  30428. }
  30429. }
  30430. }
  30431. function parseLib ( q, classSpec, prefix ) {
  30432. var elements = COLLADA.querySelectorAll(q);
  30433. var lib = {};
  30434. var i = 0;
  30435. var elementsLength = elements.length;
  30436. for ( var j = 0; j < elementsLength; j ++ ) {
  30437. var element = elements[j];
  30438. var daeElement = ( new classSpec() ).parse( element );
  30439. if ( !daeElement.id || daeElement.id.length === 0 ) daeElement.id = prefix + ( i ++ );
  30440. lib[ daeElement.id ] = daeElement;
  30441. }
  30442. return lib;
  30443. }
  30444. function parseScene() {
  30445. var sceneElement = COLLADA.querySelectorAll('scene instance_visual_scene')[0];
  30446. if ( sceneElement ) {
  30447. var url = sceneElement.getAttribute( 'url' ).replace( /^#/, '' );
  30448. return visualScenes[ url.length > 0 ? url : 'visual_scene0' ];
  30449. } else {
  30450. return null;
  30451. }
  30452. }
  30453. function parseKinematicsModel() {
  30454. var kinematicsModelElement = COLLADA.querySelectorAll('instance_kinematics_model')[0];
  30455. if ( kinematicsModelElement ) {
  30456. var url = kinematicsModelElement.getAttribute( 'url' ).replace(/^#/, '');
  30457. return kinematicsModels[ url.length > 0 ? url : 'kinematics_model0' ];
  30458. } else {
  30459. return null;
  30460. }
  30461. }
  30462. function createAnimations() {
  30463. animData = [];
  30464. // fill in the keys
  30465. recurseHierarchy( scene );
  30466. }
  30467. function recurseHierarchy( node ) {
  30468. var n = visualScene.getChildById( node.colladaId, true ),
  30469. newData = null;
  30470. if ( n && n.keys ) {
  30471. newData = {
  30472. fps: 60,
  30473. hierarchy: [ {
  30474. node: n,
  30475. keys: n.keys,
  30476. sids: n.sids
  30477. } ],
  30478. node: node,
  30479. name: 'animation_' + node.name,
  30480. length: 0
  30481. };
  30482. animData.push(newData);
  30483. for ( var i = 0, il = n.keys.length; i < il; i ++ ) {
  30484. newData.length = Math.max( newData.length, n.keys[i].time );
  30485. }
  30486. } else {
  30487. newData = {
  30488. hierarchy: [ {
  30489. keys: [],
  30490. sids: []
  30491. } ]
  30492. }
  30493. }
  30494. for ( var i = 0, il = node.children.length; i < il; i ++ ) {
  30495. var d = recurseHierarchy( node.children[i] );
  30496. for ( var j = 0, jl = d.hierarchy.length; j < jl; j ++ ) {
  30497. newData.hierarchy.push( {
  30498. keys: [],
  30499. sids: []
  30500. } );
  30501. }
  30502. }
  30503. return newData;
  30504. }
  30505. function calcAnimationBounds () {
  30506. var start = 1000000;
  30507. var end = -start;
  30508. var frames = 0;
  30509. var ID;
  30510. for ( var id in animations ) {
  30511. var animation = animations[ id ];
  30512. ID = ID || animation.id;
  30513. for ( var i = 0; i < animation.sampler.length; i ++ ) {
  30514. var sampler = animation.sampler[ i ];
  30515. sampler.create();
  30516. start = Math.min( start, sampler.startTime );
  30517. end = Math.max( end, sampler.endTime );
  30518. frames = Math.max( frames, sampler.input.length );
  30519. }
  30520. }
  30521. return { start:start, end:end, frames:frames,ID:ID };
  30522. }
  30523. function createMorph ( geometry, ctrl ) {
  30524. var morphCtrl = ctrl instanceof InstanceController ? controllers[ ctrl.url ] : ctrl;
  30525. if ( !morphCtrl || !morphCtrl.morph ) {
  30526. console.log("could not find morph controller!");
  30527. return;
  30528. }
  30529. var morph = morphCtrl.morph;
  30530. for ( var i = 0; i < morph.targets.length; i ++ ) {
  30531. var target_id = morph.targets[ i ];
  30532. var daeGeometry = geometries[ target_id ];
  30533. if ( !daeGeometry.mesh ||
  30534. !daeGeometry.mesh.primitives ||
  30535. !daeGeometry.mesh.primitives.length ) {
  30536. continue;
  30537. }
  30538. var target = daeGeometry.mesh.primitives[ 0 ].geometry;
  30539. if ( target.vertices.length === geometry.vertices.length ) {
  30540. geometry.morphTargets.push( { name: "target_1", vertices: target.vertices } );
  30541. }
  30542. }
  30543. geometry.morphTargets.push( { name: "target_Z", vertices: geometry.vertices } );
  30544. }
  30545. function createSkin ( geometry, ctrl, applyBindShape ) {
  30546. var skinCtrl = controllers[ ctrl.url ];
  30547. if ( !skinCtrl || !skinCtrl.skin ) {
  30548. console.log( "could not find skin controller!" );
  30549. return;
  30550. }
  30551. if ( !ctrl.skeleton || !ctrl.skeleton.length ) {
  30552. console.log( "could not find the skeleton for the skin!" );
  30553. return;
  30554. }
  30555. var skin = skinCtrl.skin;
  30556. var skeleton = visualScene.getChildById( ctrl.skeleton[ 0 ] );
  30557. var hierarchy = [];
  30558. applyBindShape = applyBindShape !== undefined ? applyBindShape : true;
  30559. var bones = [];
  30560. geometry.skinWeights = [];
  30561. geometry.skinIndices = [];
  30562. //createBones( geometry.bones, skin, hierarchy, skeleton, null, -1 );
  30563. //createWeights( skin, geometry.bones, geometry.skinIndices, geometry.skinWeights );
  30564. /*
  30565. geometry.animation = {
  30566. name: 'take_001',
  30567. fps: 30,
  30568. length: 2,
  30569. JIT: true,
  30570. hierarchy: hierarchy
  30571. };
  30572. */
  30573. if ( applyBindShape ) {
  30574. for ( var i = 0; i < geometry.vertices.length; i ++ ) {
  30575. geometry.vertices[ i ].applyMatrix4( skin.bindShapeMatrix );
  30576. }
  30577. }
  30578. }
  30579. function setupSkeleton ( node, bones, frame, parent ) {
  30580. node.world = node.world || new THREE.Matrix4();
  30581. node.localworld = node.localworld || new THREE.Matrix4();
  30582. node.world.copy( node.matrix );
  30583. node.localworld.copy( node.matrix );
  30584. if ( node.channels && node.channels.length ) {
  30585. var channel = node.channels[ 0 ];
  30586. var m = channel.sampler.output[ frame ];
  30587. if ( m instanceof THREE.Matrix4 ) {
  30588. node.world.copy( m );
  30589. node.localworld.copy(m);
  30590. if (frame === 0)
  30591. node.matrix.copy(m);
  30592. }
  30593. }
  30594. if ( parent ) {
  30595. node.world.multiplyMatrices( parent, node.world );
  30596. }
  30597. bones.push( node );
  30598. for ( var i = 0; i < node.nodes.length; i ++ ) {
  30599. setupSkeleton( node.nodes[ i ], bones, frame, node.world );
  30600. }
  30601. }
  30602. function setupSkinningMatrices ( bones, skin ) {
  30603. // FIXME: this is dumb...
  30604. for ( var i = 0; i < bones.length; i ++ ) {
  30605. var bone = bones[ i ];
  30606. var found = -1;
  30607. if ( bone.type != 'JOINT' ) continue;
  30608. for ( var j = 0; j < skin.joints.length; j ++ ) {
  30609. if ( bone.sid === skin.joints[ j ] ) {
  30610. found = j;
  30611. break;
  30612. }
  30613. }
  30614. if ( found >= 0 ) {
  30615. var inv = skin.invBindMatrices[ found ];
  30616. bone.invBindMatrix = inv;
  30617. bone.skinningMatrix = new THREE.Matrix4();
  30618. bone.skinningMatrix.multiplyMatrices(bone.world, inv); // (IBMi * JMi)
  30619. bone.animatrix = new THREE.Matrix4();
  30620. bone.animatrix.copy(bone.localworld);
  30621. bone.weights = [];
  30622. for ( var j = 0; j < skin.weights.length; j ++ ) {
  30623. for (var k = 0; k < skin.weights[ j ].length; k ++ ) {
  30624. var w = skin.weights[ j ][ k ];
  30625. if ( w.joint === found ) {
  30626. bone.weights.push( w );
  30627. }
  30628. }
  30629. }
  30630. } else {
  30631. console.warn( "ColladaLoader: Could not find joint '" + bone.sid + "'." );
  30632. bone.skinningMatrix = new THREE.Matrix4();
  30633. bone.weights = [];
  30634. }
  30635. }
  30636. }
  30637. //Walk the Collada tree and flatten the bones into a list, extract the position, quat and scale from the matrix
  30638. function flattenSkeleton(skeleton) {
  30639. var list = [];
  30640. var walk = function(parentid, node, list) {
  30641. var bone = {};
  30642. bone.name = node.sid;
  30643. bone.parent = parentid;
  30644. bone.matrix = node.matrix;
  30645. var data = [ new THREE.Vector3(),new THREE.Quaternion(),new THREE.Vector3() ];
  30646. bone.matrix.decompose(data[0], data[1], data[2]);
  30647. bone.pos = [ data[0].x,data[0].y,data[0].z ];
  30648. bone.scl = [ data[2].x,data[2].y,data[2].z ];
  30649. bone.rotq = [ data[1].x,data[1].y,data[1].z,data[1].w ];
  30650. list.push(bone);
  30651. for (var i in node.nodes) {
  30652. walk(node.sid, node.nodes[i], list);
  30653. }
  30654. };
  30655. walk(-1, skeleton, list);
  30656. return list;
  30657. }
  30658. //Move the vertices into the pose that is proper for the start of the animation
  30659. function skinToBindPose(geometry,skeleton,skinController) {
  30660. var bones = [];
  30661. setupSkeleton( skeleton, bones, -1 );
  30662. setupSkinningMatrices( bones, skinController.skin );
  30663. var v = new THREE.Vector3();
  30664. var skinned = [];
  30665. for (var i = 0; i < geometry.vertices.length; i ++) {
  30666. skinned.push(new THREE.Vector3());
  30667. }
  30668. for ( i = 0; i < bones.length; i ++ ) {
  30669. if ( bones[ i ].type != 'JOINT' ) continue;
  30670. for ( var j = 0; j < bones[ i ].weights.length; j ++ ) {
  30671. var w = bones[ i ].weights[ j ];
  30672. var vidx = w.index;
  30673. var weight = w.weight;
  30674. var o = geometry.vertices[vidx];
  30675. var s = skinned[vidx];
  30676. v.x = o.x;
  30677. v.y = o.y;
  30678. v.z = o.z;
  30679. v.applyMatrix4( bones[i].skinningMatrix );
  30680. s.x += (v.x * weight);
  30681. s.y += (v.y * weight);
  30682. s.z += (v.z * weight);
  30683. }
  30684. }
  30685. for (var i = 0; i < geometry.vertices.length; i ++) {
  30686. geometry.vertices[i] = skinned[i];
  30687. }
  30688. }
  30689. function applySkin ( geometry, instanceCtrl, frame ) {
  30690. var skinController = controllers[ instanceCtrl.url ];
  30691. frame = frame !== undefined ? frame : 40;
  30692. if ( !skinController || !skinController.skin ) {
  30693. console.log( 'ColladaLoader: Could not find skin controller.' );
  30694. return;
  30695. }
  30696. if ( !instanceCtrl.skeleton || !instanceCtrl.skeleton.length ) {
  30697. console.log( 'ColladaLoader: Could not find the skeleton for the skin. ' );
  30698. return;
  30699. }
  30700. var animationBounds = calcAnimationBounds();
  30701. var skeleton = visualScene.getChildById( instanceCtrl.skeleton[0], true ) || visualScene.getChildBySid( instanceCtrl.skeleton[0], true );
  30702. //flatten the skeleton into a list of bones
  30703. var bonelist = flattenSkeleton(skeleton);
  30704. var joints = skinController.skin.joints;
  30705. //sort that list so that the order reflects the order in the joint list
  30706. var sortedbones = [];
  30707. for (var i = 0; i < joints.length; i ++) {
  30708. for (var j = 0; j < bonelist.length; j ++) {
  30709. if (bonelist[j].name === joints[i]) {
  30710. sortedbones[i] = bonelist[j];
  30711. }
  30712. }
  30713. }
  30714. //hook up the parents by index instead of name
  30715. for (var i = 0; i < sortedbones.length; i ++) {
  30716. for (var j = 0; j < sortedbones.length; j ++) {
  30717. if (sortedbones[i].parent === sortedbones[j].name) {
  30718. sortedbones[i].parent = j;
  30719. }
  30720. }
  30721. }
  30722. var i, j, w, vidx, weight;
  30723. var v = new THREE.Vector3(), o, s;
  30724. // move vertices to bind shape
  30725. for ( i = 0; i < geometry.vertices.length; i ++ ) {
  30726. geometry.vertices[i].applyMatrix4( skinController.skin.bindShapeMatrix );
  30727. }
  30728. var skinIndices = [];
  30729. var skinWeights = [];
  30730. var weights = skinController.skin.weights;
  30731. // hook up the skin weights
  30732. // TODO - this might be a good place to choose greatest 4 weights
  30733. for ( var i =0; i < weights.length; i ++ ) {
  30734. 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);
  30735. 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);
  30736. skinIndices.push(indicies);
  30737. skinWeights.push(weight);
  30738. }
  30739. geometry.skinIndices = skinIndices;
  30740. geometry.skinWeights = skinWeights;
  30741. geometry.bones = sortedbones;
  30742. // process animation, or simply pose the rig if no animation
  30743. //create an animation for the animated bones
  30744. //NOTE: this has no effect when using morphtargets
  30745. var animationdata = { "name":animationBounds.ID,"fps":30,"length":animationBounds.frames / 30,"hierarchy":[] };
  30746. for (var j = 0; j < sortedbones.length; j ++) {
  30747. animationdata.hierarchy.push({ parent:sortedbones[j].parent, name:sortedbones[j].name, keys:[] });
  30748. }
  30749. console.log( 'ColladaLoader:', animationBounds.ID + ' has ' + sortedbones.length + ' bones.' );
  30750. skinToBindPose(geometry, skeleton, skinController);
  30751. for ( frame = 0; frame < animationBounds.frames; frame ++ ) {
  30752. var bones = [];
  30753. var skinned = [];
  30754. // process the frame and setup the rig with a fresh
  30755. // transform, possibly from the bone's animation channel(s)
  30756. setupSkeleton( skeleton, bones, frame );
  30757. setupSkinningMatrices( bones, skinController.skin );
  30758. for (var i = 0; i < bones.length; i ++) {
  30759. for (var j = 0; j < animationdata.hierarchy.length; j ++) {
  30760. if (animationdata.hierarchy[j].name === bones[i].sid) {
  30761. var key = {};
  30762. key.time = (frame / 30);
  30763. key.matrix = bones[i].animatrix;
  30764. if (frame === 0)
  30765. bones[i].matrix = key.matrix;
  30766. var data = [ new THREE.Vector3(),new THREE.Quaternion(),new THREE.Vector3() ];
  30767. key.matrix.decompose(data[0], data[1], data[2]);
  30768. key.pos = [ data[0].x,data[0].y,data[0].z ];
  30769. key.scl = [ data[2].x,data[2].y,data[2].z ];
  30770. key.rot = data[1];
  30771. animationdata.hierarchy[j].keys.push(key);
  30772. }
  30773. }
  30774. }
  30775. geometry.animation = animationdata;
  30776. }
  30777. }
  30778. function createKinematics() {
  30779. if ( kinematicsModel && kinematicsModel.joints.length === 0 ) {
  30780. kinematics = undefined;
  30781. return;
  30782. }
  30783. var jointMap = {};
  30784. var _addToMap = function( jointIndex, parentVisualElement ) {
  30785. var parentVisualElementId = parentVisualElement.getAttribute( 'id' );
  30786. var colladaNode = visualScene.getChildById( parentVisualElementId, true );
  30787. var joint = kinematicsModel.joints[ jointIndex ];
  30788. scene.traverse(function( node ) {
  30789. if ( node.colladaId == parentVisualElementId ) {
  30790. jointMap[ jointIndex ] = {
  30791. node: node,
  30792. transforms: colladaNode.transforms,
  30793. joint: joint,
  30794. position: joint.zeroPosition
  30795. };
  30796. }
  30797. });
  30798. };
  30799. kinematics = {
  30800. joints: kinematicsModel && kinematicsModel.joints,
  30801. getJointValue: function( jointIndex ) {
  30802. var jointData = jointMap[ jointIndex ];
  30803. if ( jointData ) {
  30804. return jointData.position;
  30805. } else {
  30806. console.log( 'getJointValue: joint ' + jointIndex + ' doesn\'t exist' );
  30807. }
  30808. },
  30809. setJointValue: function( jointIndex, value ) {
  30810. var jointData = jointMap[ jointIndex ];
  30811. if ( jointData ) {
  30812. var joint = jointData.joint;
  30813. if ( value > joint.limits.max || value < joint.limits.min ) {
  30814. console.log( 'setJointValue: joint ' + jointIndex + ' value ' + value + ' outside of limits (min: ' + joint.limits.min + ', max: ' + joint.limits.max + ')' );
  30815. } else if ( joint.static ) {
  30816. console.log( 'setJointValue: joint ' + jointIndex + ' is static' );
  30817. } else {
  30818. var threejsNode = jointData.node;
  30819. var axis = joint.axis;
  30820. var transforms = jointData.transforms;
  30821. var matrix = new THREE.Matrix4();
  30822. for (i = 0; i < transforms.length; i ++ ) {
  30823. var transform = transforms[ i ];
  30824. // kinda ghetto joint detection
  30825. if ( transform.sid && transform.sid.indexOf( 'joint' + jointIndex ) !== -1 ) {
  30826. // apply actual joint value here
  30827. switch ( joint.type ) {
  30828. case 'revolute':
  30829. matrix.multiply( m1.makeRotationAxis( axis, THREE.Math.degToRad(value) ) );
  30830. break;
  30831. case 'prismatic':
  30832. matrix.multiply( m1.makeTranslation(axis.x * value, axis.y * value, axis.z * value ) );
  30833. break;
  30834. default:
  30835. console.warn( 'setJointValue: unknown joint type: ' + joint.type );
  30836. break;
  30837. }
  30838. } else {
  30839. var m1 = new THREE.Matrix4();
  30840. switch ( transform.type ) {
  30841. case 'matrix':
  30842. matrix.multiply( transform.obj );
  30843. break;
  30844. case 'translate':
  30845. matrix.multiply( m1.makeTranslation( transform.obj.x, transform.obj.y, transform.obj.z ) );
  30846. break;
  30847. case 'rotate':
  30848. matrix.multiply( m1.makeRotationAxis( transform.obj, transform.angle ) );
  30849. break;
  30850. }
  30851. }
  30852. }
  30853. // apply the matrix to the threejs node
  30854. var elementsFloat32Arr = matrix.elements;
  30855. var elements = Array.prototype.slice.call( elementsFloat32Arr );
  30856. var elementsRowMajor = [
  30857. elements[ 0 ],
  30858. elements[ 4 ],
  30859. elements[ 8 ],
  30860. elements[ 12 ],
  30861. elements[ 1 ],
  30862. elements[ 5 ],
  30863. elements[ 9 ],
  30864. elements[ 13 ],
  30865. elements[ 2 ],
  30866. elements[ 6 ],
  30867. elements[ 10 ],
  30868. elements[ 14 ],
  30869. elements[ 3 ],
  30870. elements[ 7 ],
  30871. elements[ 11 ],
  30872. elements[ 15 ]
  30873. ];
  30874. threejsNode.matrix.set.apply( threejsNode.matrix, elementsRowMajor );
  30875. threejsNode.matrix.decompose( threejsNode.position, threejsNode.quaternion, threejsNode.scale );
  30876. }
  30877. } else {
  30878. console.log( 'setJointValue: joint ' + jointIndex + ' doesn\'t exist' );
  30879. }
  30880. }
  30881. };
  30882. var element = COLLADA.querySelector('scene instance_kinematics_scene');
  30883. if ( element ) {
  30884. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  30885. var child = element.childNodes[ i ];
  30886. if ( child.nodeType != 1 ) continue;
  30887. switch ( child.nodeName ) {
  30888. case 'bind_joint_axis':
  30889. var visualTarget = child.getAttribute( 'target' ).split( '/' ).pop();
  30890. var axis = child.querySelector('axis param').textContent;
  30891. var jointIndex = parseInt( axis.split( 'joint' ).pop().split( '.' )[0] );
  30892. var visualTargetElement = COLLADA.querySelector( '[sid="' + visualTarget + '"]' );
  30893. if ( visualTargetElement ) {
  30894. var parentVisualElement = visualTargetElement.parentElement;
  30895. _addToMap(jointIndex, parentVisualElement);
  30896. }
  30897. break;
  30898. default:
  30899. break;
  30900. }
  30901. }
  30902. }
  30903. }
  30904. function createSceneGraph ( node, parent ) {
  30905. var obj = new THREE.Object3D();
  30906. var skinned = false;
  30907. var skinController;
  30908. var morphController;
  30909. var i, j;
  30910. // FIXME: controllers
  30911. for ( i = 0; i < node.controllers.length; i ++ ) {
  30912. var controller = controllers[ node.controllers[ i ].url ];
  30913. switch ( controller.type ) {
  30914. case 'skin':
  30915. if ( geometries[ controller.skin.source ] ) {
  30916. var inst_geom = new InstanceGeometry();
  30917. inst_geom.url = controller.skin.source;
  30918. inst_geom.instance_material = node.controllers[ i ].instance_material;
  30919. node.geometries.push( inst_geom );
  30920. skinned = true;
  30921. skinController = node.controllers[ i ];
  30922. } else if ( controllers[ controller.skin.source ] ) {
  30923. // urgh: controller can be chained
  30924. // handle the most basic case...
  30925. var second = controllers[ controller.skin.source ];
  30926. morphController = second;
  30927. // skinController = node.controllers[i];
  30928. if ( second.morph && geometries[ second.morph.source ] ) {
  30929. var inst_geom = new InstanceGeometry();
  30930. inst_geom.url = second.morph.source;
  30931. inst_geom.instance_material = node.controllers[ i ].instance_material;
  30932. node.geometries.push( inst_geom );
  30933. }
  30934. }
  30935. break;
  30936. case 'morph':
  30937. if ( geometries[ controller.morph.source ] ) {
  30938. var inst_geom = new InstanceGeometry();
  30939. inst_geom.url = controller.morph.source;
  30940. inst_geom.instance_material = node.controllers[ i ].instance_material;
  30941. node.geometries.push( inst_geom );
  30942. morphController = node.controllers[ i ];
  30943. }
  30944. console.log( 'ColladaLoader: Morph-controller partially supported.' );
  30945. default:
  30946. break;
  30947. }
  30948. }
  30949. // geometries
  30950. var double_sided_materials = {};
  30951. for ( i = 0; i < node.geometries.length; i ++ ) {
  30952. var instance_geometry = node.geometries[i];
  30953. var instance_materials = instance_geometry.instance_material;
  30954. var geometry = geometries[ instance_geometry.url ];
  30955. var used_materials = {};
  30956. var used_materials_array = [];
  30957. var num_materials = 0;
  30958. var first_material;
  30959. if ( geometry ) {
  30960. if ( !geometry.mesh || !geometry.mesh.primitives )
  30961. continue;
  30962. if ( obj.name.length === 0 ) {
  30963. obj.name = geometry.id;
  30964. }
  30965. // collect used fx for this geometry-instance
  30966. if ( instance_materials ) {
  30967. for ( j = 0; j < instance_materials.length; j ++ ) {
  30968. var instance_material = instance_materials[ j ];
  30969. var mat = materials[ instance_material.target ];
  30970. var effect_id = mat.instance_effect.url;
  30971. var shader = effects[ effect_id ].shader;
  30972. var material3js = shader.material;
  30973. if ( geometry.doubleSided ) {
  30974. if ( !( instance_material.symbol in double_sided_materials ) ) {
  30975. var _copied_material = material3js.clone();
  30976. _copied_material.side = THREE.DoubleSide;
  30977. double_sided_materials[ instance_material.symbol ] = _copied_material;
  30978. }
  30979. material3js = double_sided_materials[ instance_material.symbol ];
  30980. }
  30981. material3js.opacity = !material3js.opacity ? 1 : material3js.opacity;
  30982. used_materials[ instance_material.symbol ] = num_materials;
  30983. used_materials_array.push( material3js );
  30984. first_material = material3js;
  30985. first_material.name = mat.name === null || mat.name === '' ? mat.id : mat.name;
  30986. num_materials ++;
  30987. }
  30988. }
  30989. var mesh;
  30990. var material = first_material || new THREE.MeshLambertMaterial( { color: 0xdddddd, side: geometry.doubleSided ? THREE.DoubleSide : THREE.FrontSide } );
  30991. var geom = geometry.mesh.geometry3js;
  30992. if ( num_materials > 1 ) {
  30993. material = new THREE.MultiMaterial( used_materials_array );
  30994. for ( j = 0; j < geom.faces.length; j ++ ) {
  30995. var face = geom.faces[ j ];
  30996. face.materialIndex = used_materials[ face.daeMaterial ]
  30997. }
  30998. }
  30999. if ( skinController !== undefined ) {
  31000. applySkin( geom, skinController );
  31001. if ( geom.morphTargets.length > 0 ) {
  31002. material.morphTargets = true;
  31003. material.skinning = false;
  31004. } else {
  31005. material.morphTargets = false;
  31006. material.skinning = true;
  31007. }
  31008. mesh = new THREE.SkinnedMesh( geom, material, false );
  31009. //mesh.skeleton = skinController.skeleton;
  31010. //mesh.skinController = controllers[ skinController.url ];
  31011. //mesh.skinInstanceController = skinController;
  31012. mesh.name = 'skin_' + skins.length;
  31013. //mesh.animationHandle.setKey(0);
  31014. skins.push( mesh );
  31015. } else if ( morphController !== undefined ) {
  31016. createMorph( geom, morphController );
  31017. material.morphTargets = true;
  31018. mesh = new THREE.Mesh( geom, material );
  31019. mesh.name = 'morph_' + morphs.length;
  31020. morphs.push( mesh );
  31021. } else {
  31022. if ( geom.isLineStrip === true ) {
  31023. mesh = new THREE.Line( geom );
  31024. } else {
  31025. mesh = new THREE.Mesh( geom, material );
  31026. }
  31027. }
  31028. obj.add(mesh);
  31029. }
  31030. }
  31031. for ( i = 0; i < node.cameras.length; i ++ ) {
  31032. var instance_camera = node.cameras[i];
  31033. var cparams = cameras[instance_camera.url];
  31034. var cam = new THREE.PerspectiveCamera(cparams.yfov, parseFloat(cparams.aspect_ratio),
  31035. parseFloat(cparams.znear), parseFloat(cparams.zfar));
  31036. obj.add(cam);
  31037. }
  31038. for ( i = 0; i < node.lights.length; i ++ ) {
  31039. var light = null;
  31040. var instance_light = node.lights[i];
  31041. var lparams = lights[instance_light.url];
  31042. if ( lparams && lparams.technique ) {
  31043. var color = lparams.color.getHex();
  31044. var intensity = lparams.intensity;
  31045. var distance = lparams.distance;
  31046. var angle = lparams.falloff_angle;
  31047. switch ( lparams.technique ) {
  31048. case 'directional':
  31049. light = new THREE.DirectionalLight( color, intensity, distance );
  31050. light.position.set(0, 0, 1);
  31051. break;
  31052. case 'point':
  31053. light = new THREE.PointLight( color, intensity, distance );
  31054. break;
  31055. case 'spot':
  31056. light = new THREE.SpotLight( color, intensity, distance, angle );
  31057. light.position.set(0, 0, 1);
  31058. break;
  31059. case 'ambient':
  31060. light = new THREE.AmbientLight( color );
  31061. break;
  31062. }
  31063. }
  31064. if (light) {
  31065. obj.add(light);
  31066. }
  31067. }
  31068. obj.name = node.name || node.id || "";
  31069. obj.colladaId = node.id || "";
  31070. obj.layer = node.layer || "";
  31071. obj.matrix = node.matrix;
  31072. obj.matrix.decompose( obj.position, obj.quaternion, obj.scale );
  31073. if ( options.centerGeometry && obj.geometry ) {
  31074. var delta = obj.geometry.center();
  31075. delta.multiply( obj.scale );
  31076. delta.applyQuaternion( obj.quaternion );
  31077. obj.position.sub( delta );
  31078. }
  31079. for ( i = 0; i < node.nodes.length; i ++ ) {
  31080. obj.add( createSceneGraph( node.nodes[i], node ) );
  31081. }
  31082. return obj;
  31083. }
  31084. function getJointId( skin, id ) {
  31085. for ( var i = 0; i < skin.joints.length; i ++ ) {
  31086. if ( skin.joints[ i ] === id ) {
  31087. return i;
  31088. }
  31089. }
  31090. }
  31091. function getLibraryNode( id ) {
  31092. var nodes = COLLADA.querySelectorAll('library_nodes node');
  31093. for ( var i = 0; i < nodes.length; i++ ) {
  31094. var attObj = nodes[i].attributes.getNamedItem('id');
  31095. if ( attObj && attObj.value === id ) {
  31096. return nodes[i];
  31097. }
  31098. }
  31099. return undefined;
  31100. }
  31101. function getChannelsForNode ( node ) {
  31102. var channels = [];
  31103. var startTime = 1000000;
  31104. var endTime = -1000000;
  31105. for ( var id in animations ) {
  31106. var animation = animations[id];
  31107. for ( var i = 0; i < animation.channel.length; i ++ ) {
  31108. var channel = animation.channel[i];
  31109. var sampler = animation.sampler[i];
  31110. var id = channel.target.split('/')[0];
  31111. if ( id == node.id ) {
  31112. sampler.create();
  31113. channel.sampler = sampler;
  31114. startTime = Math.min(startTime, sampler.startTime);
  31115. endTime = Math.max(endTime, sampler.endTime);
  31116. channels.push(channel);
  31117. }
  31118. }
  31119. }
  31120. if ( channels.length ) {
  31121. node.startTime = startTime;
  31122. node.endTime = endTime;
  31123. }
  31124. return channels;
  31125. }
  31126. function calcFrameDuration( node ) {
  31127. var minT = 10000000;
  31128. for ( var i = 0; i < node.channels.length; i ++ ) {
  31129. var sampler = node.channels[i].sampler;
  31130. for ( var j = 0; j < sampler.input.length - 1; j ++ ) {
  31131. var t0 = sampler.input[ j ];
  31132. var t1 = sampler.input[ j + 1 ];
  31133. minT = Math.min( minT, t1 - t0 );
  31134. }
  31135. }
  31136. return minT;
  31137. }
  31138. function calcMatrixAt( node, t ) {
  31139. var animated = {};
  31140. var i, j;
  31141. for ( i = 0; i < node.channels.length; i ++ ) {
  31142. var channel = node.channels[ i ];
  31143. animated[ channel.sid ] = channel;
  31144. }
  31145. var matrix = new THREE.Matrix4();
  31146. for ( i = 0; i < node.transforms.length; i ++ ) {
  31147. var transform = node.transforms[ i ];
  31148. var channel = animated[ transform.sid ];
  31149. if ( channel !== undefined ) {
  31150. var sampler = channel.sampler;
  31151. var value;
  31152. for ( j = 0; j < sampler.input.length - 1; j ++ ) {
  31153. if ( sampler.input[ j + 1 ] > t ) {
  31154. value = sampler.output[ j ];
  31155. //console.log(value.flatten)
  31156. break;
  31157. }
  31158. }
  31159. if ( value !== undefined ) {
  31160. if ( value instanceof THREE.Matrix4 ) {
  31161. matrix.multiplyMatrices( matrix, value );
  31162. } else {
  31163. // FIXME: handle other types
  31164. matrix.multiplyMatrices( matrix, transform.matrix );
  31165. }
  31166. } else {
  31167. matrix.multiplyMatrices( matrix, transform.matrix );
  31168. }
  31169. } else {
  31170. matrix.multiplyMatrices( matrix, transform.matrix );
  31171. }
  31172. }
  31173. return matrix;
  31174. }
  31175. function bakeAnimations ( node ) {
  31176. if ( node.channels && node.channels.length ) {
  31177. var keys = [],
  31178. sids = [];
  31179. for ( var i = 0, il = node.channels.length; i < il; i ++ ) {
  31180. var channel = node.channels[i],
  31181. fullSid = channel.fullSid,
  31182. sampler = channel.sampler,
  31183. input = sampler.input,
  31184. transform = node.getTransformBySid( channel.sid ),
  31185. member;
  31186. if ( channel.arrIndices ) {
  31187. member = [];
  31188. for ( var j = 0, jl = channel.arrIndices.length; j < jl; j ++ ) {
  31189. member[ j ] = getConvertedIndex( channel.arrIndices[ j ] );
  31190. }
  31191. } else {
  31192. member = getConvertedMember( channel.member );
  31193. }
  31194. if ( transform ) {
  31195. if ( sids.indexOf( fullSid ) === -1 ) {
  31196. sids.push( fullSid );
  31197. }
  31198. for ( var j = 0, jl = input.length; j < jl; j ++ ) {
  31199. var time = input[j],
  31200. data = sampler.getData( transform.type, j, member ),
  31201. key = findKey( keys, time );
  31202. if ( !key ) {
  31203. key = new Key( time );
  31204. var timeNdx = findTimeNdx( keys, time );
  31205. keys.splice( timeNdx === -1 ? keys.length : timeNdx, 0, key );
  31206. }
  31207. key.addTarget( fullSid, transform, member, data );
  31208. }
  31209. } else {
  31210. console.log( 'Could not find transform "' + channel.sid + '" in node ' + node.id );
  31211. }
  31212. }
  31213. // post process
  31214. for ( var i = 0; i < sids.length; i ++ ) {
  31215. var sid = sids[ i ];
  31216. for ( var j = 0; j < keys.length; j ++ ) {
  31217. var key = keys[ j ];
  31218. if ( !key.hasTarget( sid ) ) {
  31219. interpolateKeys( keys, key, j, sid );
  31220. }
  31221. }
  31222. }
  31223. node.keys = keys;
  31224. node.sids = sids;
  31225. }
  31226. }
  31227. function findKey ( keys, time) {
  31228. var retVal = null;
  31229. for ( var i = 0, il = keys.length; i < il && retVal === null; i ++ ) {
  31230. var key = keys[i];
  31231. if ( key.time === time ) {
  31232. retVal = key;
  31233. } else if ( key.time > time ) {
  31234. break;
  31235. }
  31236. }
  31237. return retVal;
  31238. }
  31239. function findTimeNdx ( keys, time) {
  31240. var ndx = -1;
  31241. for ( var i = 0, il = keys.length; i < il && ndx === -1; i ++ ) {
  31242. var key = keys[i];
  31243. if ( key.time >= time ) {
  31244. ndx = i;
  31245. }
  31246. }
  31247. return ndx;
  31248. }
  31249. function interpolateKeys ( keys, key, ndx, fullSid ) {
  31250. var prevKey = getPrevKeyWith( keys, fullSid, ndx ? ndx - 1 : 0 ),
  31251. nextKey = getNextKeyWith( keys, fullSid, ndx + 1 );
  31252. if ( prevKey && nextKey ) {
  31253. var scale = (key.time - prevKey.time) / (nextKey.time - prevKey.time),
  31254. prevTarget = prevKey.getTarget( fullSid ),
  31255. nextData = nextKey.getTarget( fullSid ).data,
  31256. prevData = prevTarget.data,
  31257. data;
  31258. if ( prevTarget.type === 'matrix' ) {
  31259. data = prevData;
  31260. } else if ( prevData.length ) {
  31261. data = [];
  31262. for ( var i = 0; i < prevData.length; ++ i ) {
  31263. data[ i ] = prevData[ i ] + ( nextData[ i ] - prevData[ i ] ) * scale;
  31264. }
  31265. } else {
  31266. data = prevData + ( nextData - prevData ) * scale;
  31267. }
  31268. key.addTarget( fullSid, prevTarget.transform, prevTarget.member, data );
  31269. }
  31270. }
  31271. // Get next key with given sid
  31272. function getNextKeyWith( keys, fullSid, ndx ) {
  31273. for ( ; ndx < keys.length; ndx ++ ) {
  31274. var key = keys[ ndx ];
  31275. if ( key.hasTarget( fullSid ) ) {
  31276. return key;
  31277. }
  31278. }
  31279. return null;
  31280. }
  31281. // Get previous key with given sid
  31282. function getPrevKeyWith( keys, fullSid, ndx ) {
  31283. ndx = ndx >= 0 ? ndx : ndx + keys.length;
  31284. for ( ; ndx >= 0; ndx -- ) {
  31285. var key = keys[ ndx ];
  31286. if ( key.hasTarget( fullSid ) ) {
  31287. return key;
  31288. }
  31289. }
  31290. return null;
  31291. }
  31292. function _Image() {
  31293. this.id = "";
  31294. this.init_from = "";
  31295. }
  31296. _Image.prototype.parse = function(element) {
  31297. this.id = element.getAttribute('id');
  31298. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  31299. var child = element.childNodes[ i ];
  31300. if ( child.nodeName === 'init_from' ) {
  31301. this.init_from = child.textContent;
  31302. }
  31303. }
  31304. return this;
  31305. };
  31306. function Controller() {
  31307. this.id = "";
  31308. this.name = "";
  31309. this.type = "";
  31310. this.skin = null;
  31311. this.morph = null;
  31312. }
  31313. Controller.prototype.parse = function( element ) {
  31314. this.id = element.getAttribute('id');
  31315. this.name = element.getAttribute('name');
  31316. this.type = "none";
  31317. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  31318. var child = element.childNodes[ i ];
  31319. switch ( child.nodeName ) {
  31320. case 'skin':
  31321. this.skin = (new Skin()).parse(child);
  31322. this.type = child.nodeName;
  31323. break;
  31324. case 'morph':
  31325. this.morph = (new Morph()).parse(child);
  31326. this.type = child.nodeName;
  31327. break;
  31328. default:
  31329. break;
  31330. }
  31331. }
  31332. return this;
  31333. };
  31334. function Morph() {
  31335. this.method = null;
  31336. this.source = null;
  31337. this.targets = null;
  31338. this.weights = null;
  31339. }
  31340. Morph.prototype.parse = function( element ) {
  31341. var sources = {};
  31342. var inputs = [];
  31343. var i;
  31344. this.method = element.getAttribute( 'method' );
  31345. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  31346. for ( i = 0; i < element.childNodes.length; i ++ ) {
  31347. var child = element.childNodes[ i ];
  31348. if ( child.nodeType != 1 ) continue;
  31349. switch ( child.nodeName ) {
  31350. case 'source':
  31351. var source = ( new Source() ).parse( child );
  31352. sources[ source.id ] = source;
  31353. break;
  31354. case 'targets':
  31355. inputs = this.parseInputs( child );
  31356. break;
  31357. default:
  31358. console.log( child.nodeName );
  31359. break;
  31360. }
  31361. }
  31362. for ( i = 0; i < inputs.length; i ++ ) {
  31363. var input = inputs[ i ];
  31364. var source = sources[ input.source ];
  31365. switch ( input.semantic ) {
  31366. case 'MORPH_TARGET':
  31367. this.targets = source.read();
  31368. break;
  31369. case 'MORPH_WEIGHT':
  31370. this.weights = source.read();
  31371. break;
  31372. default:
  31373. break;
  31374. }
  31375. }
  31376. return this;
  31377. };
  31378. Morph.prototype.parseInputs = function(element) {
  31379. var inputs = [];
  31380. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  31381. var child = element.childNodes[i];
  31382. if ( child.nodeType != 1) continue;
  31383. switch ( child.nodeName ) {
  31384. case 'input':
  31385. inputs.push( (new Input()).parse(child) );
  31386. break;
  31387. default:
  31388. break;
  31389. }
  31390. }
  31391. return inputs;
  31392. };
  31393. function Skin() {
  31394. this.source = "";
  31395. this.bindShapeMatrix = null;
  31396. this.invBindMatrices = [];
  31397. this.joints = [];
  31398. this.weights = [];
  31399. }
  31400. Skin.prototype.parse = function( element ) {
  31401. var sources = {};
  31402. var joints, weights;
  31403. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  31404. this.invBindMatrices = [];
  31405. this.joints = [];
  31406. this.weights = [];
  31407. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  31408. var child = element.childNodes[i];
  31409. if ( child.nodeType != 1 ) continue;
  31410. switch ( child.nodeName ) {
  31411. case 'bind_shape_matrix':
  31412. var f = _floats(child.textContent);
  31413. this.bindShapeMatrix = getConvertedMat4( f );
  31414. break;
  31415. case 'source':
  31416. var src = new Source().parse(child);
  31417. sources[ src.id ] = src;
  31418. break;
  31419. case 'joints':
  31420. joints = child;
  31421. break;
  31422. case 'vertex_weights':
  31423. weights = child;
  31424. break;
  31425. default:
  31426. console.log( child.nodeName );
  31427. break;
  31428. }
  31429. }
  31430. this.parseJoints( joints, sources );
  31431. this.parseWeights( weights, sources );
  31432. return this;
  31433. };
  31434. Skin.prototype.parseJoints = function ( element, sources ) {
  31435. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  31436. var child = element.childNodes[ i ];
  31437. if ( child.nodeType != 1 ) continue;
  31438. switch ( child.nodeName ) {
  31439. case 'input':
  31440. var input = ( new Input() ).parse( child );
  31441. var source = sources[ input.source ];
  31442. if ( input.semantic === 'JOINT' ) {
  31443. this.joints = source.read();
  31444. } else if ( input.semantic === 'INV_BIND_MATRIX' ) {
  31445. this.invBindMatrices = source.read();
  31446. }
  31447. break;
  31448. default:
  31449. break;
  31450. }
  31451. }
  31452. };
  31453. Skin.prototype.parseWeights = function ( element, sources ) {
  31454. var v, vcount, inputs = [];
  31455. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  31456. var child = element.childNodes[ i ];
  31457. if ( child.nodeType != 1 ) continue;
  31458. switch ( child.nodeName ) {
  31459. case 'input':
  31460. inputs.push( ( new Input() ).parse( child ) );
  31461. break;
  31462. case 'v':
  31463. v = _ints( child.textContent );
  31464. break;
  31465. case 'vcount':
  31466. vcount = _ints( child.textContent );
  31467. break;
  31468. default:
  31469. break;
  31470. }
  31471. }
  31472. var index = 0;
  31473. for ( var i = 0; i < vcount.length; i ++ ) {
  31474. var numBones = vcount[i];
  31475. var vertex_weights = [];
  31476. for ( var j = 0; j < numBones; j ++ ) {
  31477. var influence = {};
  31478. for ( var k = 0; k < inputs.length; k ++ ) {
  31479. var input = inputs[ k ];
  31480. var value = v[ index + input.offset ];
  31481. switch ( input.semantic ) {
  31482. case 'JOINT':
  31483. influence.joint = value;//this.joints[value];
  31484. break;
  31485. case 'WEIGHT':
  31486. influence.weight = sources[ input.source ].data[ value ];
  31487. break;
  31488. default:
  31489. break;
  31490. }
  31491. }
  31492. vertex_weights.push( influence );
  31493. index += inputs.length;
  31494. }
  31495. for ( var j = 0; j < vertex_weights.length; j ++ ) {
  31496. vertex_weights[ j ].index = i;
  31497. }
  31498. this.weights.push( vertex_weights );
  31499. }
  31500. };
  31501. function VisualScene () {
  31502. this.id = "";
  31503. this.name = "";
  31504. this.nodes = [];
  31505. this.scene = new THREE.Group();
  31506. }
  31507. VisualScene.prototype.getChildById = function( id, recursive ) {
  31508. for ( var i = 0; i < this.nodes.length; i ++ ) {
  31509. var node = this.nodes[ i ].getChildById( id, recursive );
  31510. if ( node ) {
  31511. return node;
  31512. }
  31513. }
  31514. return null;
  31515. };
  31516. VisualScene.prototype.getChildBySid = function( sid, recursive ) {
  31517. for ( var i = 0; i < this.nodes.length; i ++ ) {
  31518. var node = this.nodes[ i ].getChildBySid( sid, recursive );
  31519. if ( node ) {
  31520. return node;
  31521. }
  31522. }
  31523. return null;
  31524. };
  31525. VisualScene.prototype.parse = function( element ) {
  31526. this.id = element.getAttribute( 'id' );
  31527. this.name = element.getAttribute( 'name' );
  31528. this.nodes = [];
  31529. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  31530. var child = element.childNodes[ i ];
  31531. if ( child.nodeType != 1 ) continue;
  31532. switch ( child.nodeName ) {
  31533. case 'node':
  31534. this.nodes.push( ( new Node() ).parse( child ) );
  31535. break;
  31536. default:
  31537. break;
  31538. }
  31539. }
  31540. return this;
  31541. };
  31542. function Node() {
  31543. this.id = "";
  31544. this.name = "";
  31545. this.sid = "";
  31546. this.nodes = [];
  31547. this.controllers = [];
  31548. this.transforms = [];
  31549. this.geometries = [];
  31550. this.channels = [];
  31551. this.matrix = new THREE.Matrix4();
  31552. }
  31553. Node.prototype.getChannelForTransform = function( transformSid ) {
  31554. for ( var i = 0; i < this.channels.length; i ++ ) {
  31555. var channel = this.channels[i];
  31556. var parts = channel.target.split('/');
  31557. var id = parts.shift();
  31558. var sid = parts.shift();
  31559. var dotSyntax = (sid.indexOf(".") >= 0);
  31560. var arrSyntax = (sid.indexOf("(") >= 0);
  31561. var arrIndices;
  31562. var member;
  31563. if ( dotSyntax ) {
  31564. parts = sid.split(".");
  31565. sid = parts.shift();
  31566. member = parts.shift();
  31567. } else if ( arrSyntax ) {
  31568. arrIndices = sid.split("(");
  31569. sid = arrIndices.shift();
  31570. for ( var j = 0; j < arrIndices.length; j ++ ) {
  31571. arrIndices[ j ] = parseInt( arrIndices[ j ].replace( /\)/, '' ) );
  31572. }
  31573. }
  31574. if ( sid === transformSid ) {
  31575. channel.info = { sid: sid, dotSyntax: dotSyntax, arrSyntax: arrSyntax, arrIndices: arrIndices };
  31576. return channel;
  31577. }
  31578. }
  31579. return null;
  31580. };
  31581. Node.prototype.getChildById = function ( id, recursive ) {
  31582. if ( this.id === id ) {
  31583. return this;
  31584. }
  31585. if ( recursive ) {
  31586. for ( var i = 0; i < this.nodes.length; i ++ ) {
  31587. var n = this.nodes[ i ].getChildById( id, recursive );
  31588. if ( n ) {
  31589. return n;
  31590. }
  31591. }
  31592. }
  31593. return null;
  31594. };
  31595. Node.prototype.getChildBySid = function ( sid, recursive ) {
  31596. if ( this.sid === sid ) {
  31597. return this;
  31598. }
  31599. if ( recursive ) {
  31600. for ( var i = 0; i < this.nodes.length; i ++ ) {
  31601. var n = this.nodes[ i ].getChildBySid( sid, recursive );
  31602. if ( n ) {
  31603. return n;
  31604. }
  31605. }
  31606. }
  31607. return null;
  31608. };
  31609. Node.prototype.getTransformBySid = function ( sid ) {
  31610. for ( var i = 0; i < this.transforms.length; i ++ ) {
  31611. if ( this.transforms[ i ].sid === sid ) return this.transforms[ i ];
  31612. }
  31613. return null;
  31614. };
  31615. Node.prototype.parse = function( element ) {
  31616. var url;
  31617. this.id = element.getAttribute('id');
  31618. this.sid = element.getAttribute('sid');
  31619. this.name = element.getAttribute('name');
  31620. this.type = element.getAttribute('type');
  31621. this.layer = element.getAttribute('layer');
  31622. this.type = this.type === 'JOINT' ? this.type : 'NODE';
  31623. this.nodes = [];
  31624. this.transforms = [];
  31625. this.geometries = [];
  31626. this.cameras = [];
  31627. this.lights = [];
  31628. this.controllers = [];
  31629. this.matrix = new THREE.Matrix4();
  31630. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  31631. var child = element.childNodes[ i ];
  31632. if ( child.nodeType != 1 ) continue;
  31633. switch ( child.nodeName ) {
  31634. case 'node':
  31635. this.nodes.push( ( new Node() ).parse( child ) );
  31636. break;
  31637. case 'instance_camera':
  31638. this.cameras.push( ( new InstanceCamera() ).parse( child ) );
  31639. break;
  31640. case 'instance_controller':
  31641. this.controllers.push( ( new InstanceController() ).parse( child ) );
  31642. break;
  31643. case 'instance_geometry':
  31644. this.geometries.push( ( new InstanceGeometry() ).parse( child ) );
  31645. break;
  31646. case 'instance_light':
  31647. this.lights.push( ( new InstanceLight() ).parse( child ) );
  31648. break;
  31649. case 'instance_node':
  31650. url = child.getAttribute( 'url' ).replace( /^#/, '' );
  31651. var iNode = getLibraryNode( url );
  31652. if ( iNode ) {
  31653. this.nodes.push( ( new Node() ).parse( iNode )) ;
  31654. }
  31655. break;
  31656. case 'rotate':
  31657. case 'translate':
  31658. case 'scale':
  31659. case 'matrix':
  31660. case 'lookat':
  31661. case 'skew':
  31662. this.transforms.push( ( new Transform() ).parse( child ) );
  31663. break;
  31664. case 'extra':
  31665. break;
  31666. default:
  31667. console.log( child.nodeName );
  31668. break;
  31669. }
  31670. }
  31671. this.channels = getChannelsForNode( this );
  31672. bakeAnimations( this );
  31673. this.updateMatrix();
  31674. return this;
  31675. };
  31676. Node.prototype.updateMatrix = function () {
  31677. this.matrix.identity();
  31678. for ( var i = 0; i < this.transforms.length; i ++ ) {
  31679. this.transforms[ i ].apply( this.matrix );
  31680. }
  31681. };
  31682. function Transform () {
  31683. this.sid = "";
  31684. this.type = "";
  31685. this.data = [];
  31686. this.obj = null;
  31687. }
  31688. Transform.prototype.parse = function ( element ) {
  31689. this.sid = element.getAttribute( 'sid' );
  31690. this.type = element.nodeName;
  31691. this.data = _floats( element.textContent );
  31692. this.convert();
  31693. return this;
  31694. };
  31695. Transform.prototype.convert = function () {
  31696. switch ( this.type ) {
  31697. case 'matrix':
  31698. this.obj = getConvertedMat4( this.data );
  31699. break;
  31700. case 'rotate':
  31701. this.angle = THREE.Math.degToRad( this.data[3] );
  31702. case 'translate':
  31703. fixCoords( this.data, -1 );
  31704. this.obj = new THREE.Vector3( this.data[ 0 ], this.data[ 1 ], this.data[ 2 ] );
  31705. break;
  31706. case 'scale':
  31707. fixCoords( this.data, 1 );
  31708. this.obj = new THREE.Vector3( this.data[ 0 ], this.data[ 1 ], this.data[ 2 ] );
  31709. break;
  31710. default:
  31711. console.log( 'Can not convert Transform of type ' + this.type );
  31712. break;
  31713. }
  31714. };
  31715. Transform.prototype.apply = function () {
  31716. var m1 = new THREE.Matrix4();
  31717. return function ( matrix ) {
  31718. switch ( this.type ) {
  31719. case 'matrix':
  31720. matrix.multiply( this.obj );
  31721. break;
  31722. case 'translate':
  31723. matrix.multiply( m1.makeTranslation( this.obj.x, this.obj.y, this.obj.z ) );
  31724. break;
  31725. case 'rotate':
  31726. matrix.multiply( m1.makeRotationAxis( this.obj, this.angle ) );
  31727. break;
  31728. case 'scale':
  31729. matrix.scale( this.obj );
  31730. break;
  31731. }
  31732. };
  31733. }();
  31734. Transform.prototype.update = function ( data, member ) {
  31735. var members = [ 'X', 'Y', 'Z', 'ANGLE' ];
  31736. switch ( this.type ) {
  31737. case 'matrix':
  31738. if ( ! member ) {
  31739. this.obj.copy( data );
  31740. } else if ( member.length === 1 ) {
  31741. switch ( member[ 0 ] ) {
  31742. case 0:
  31743. this.obj.n11 = data[ 0 ];
  31744. this.obj.n21 = data[ 1 ];
  31745. this.obj.n31 = data[ 2 ];
  31746. this.obj.n41 = data[ 3 ];
  31747. break;
  31748. case 1:
  31749. this.obj.n12 = data[ 0 ];
  31750. this.obj.n22 = data[ 1 ];
  31751. this.obj.n32 = data[ 2 ];
  31752. this.obj.n42 = data[ 3 ];
  31753. break;
  31754. case 2:
  31755. this.obj.n13 = data[ 0 ];
  31756. this.obj.n23 = data[ 1 ];
  31757. this.obj.n33 = data[ 2 ];
  31758. this.obj.n43 = data[ 3 ];
  31759. break;
  31760. case 3:
  31761. this.obj.n14 = data[ 0 ];
  31762. this.obj.n24 = data[ 1 ];
  31763. this.obj.n34 = data[ 2 ];
  31764. this.obj.n44 = data[ 3 ];
  31765. break;
  31766. }
  31767. } else if ( member.length === 2 ) {
  31768. var propName = 'n' + ( member[ 0 ] + 1 ) + ( member[ 1 ] + 1 );
  31769. this.obj[ propName ] = data;
  31770. } else {
  31771. console.log('Incorrect addressing of matrix in transform.');
  31772. }
  31773. break;
  31774. case 'translate':
  31775. case 'scale':
  31776. if ( Object.prototype.toString.call( member ) === '[object Array]' ) {
  31777. member = members[ member[ 0 ] ];
  31778. }
  31779. switch ( member ) {
  31780. case 'X':
  31781. this.obj.x = data;
  31782. break;
  31783. case 'Y':
  31784. this.obj.y = data;
  31785. break;
  31786. case 'Z':
  31787. this.obj.z = data;
  31788. break;
  31789. default:
  31790. this.obj.x = data[ 0 ];
  31791. this.obj.y = data[ 1 ];
  31792. this.obj.z = data[ 2 ];
  31793. break;
  31794. }
  31795. break;
  31796. case 'rotate':
  31797. if ( Object.prototype.toString.call( member ) === '[object Array]' ) {
  31798. member = members[ member[ 0 ] ];
  31799. }
  31800. switch ( member ) {
  31801. case 'X':
  31802. this.obj.x = data;
  31803. break;
  31804. case 'Y':
  31805. this.obj.y = data;
  31806. break;
  31807. case 'Z':
  31808. this.obj.z = data;
  31809. break;
  31810. case 'ANGLE':
  31811. this.angle = THREE.Math.degToRad( data );
  31812. break;
  31813. default:
  31814. this.obj.x = data[ 0 ];
  31815. this.obj.y = data[ 1 ];
  31816. this.obj.z = data[ 2 ];
  31817. this.angle = THREE.Math.degToRad( data[ 3 ] );
  31818. break;
  31819. }
  31820. break;
  31821. }
  31822. };
  31823. function InstanceController() {
  31824. this.url = "";
  31825. this.skeleton = [];
  31826. this.instance_material = [];
  31827. }
  31828. InstanceController.prototype.parse = function ( element ) {
  31829. this.url = element.getAttribute('url').replace(/^#/, '');
  31830. this.skeleton = [];
  31831. this.instance_material = [];
  31832. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  31833. var child = element.childNodes[ i ];
  31834. if ( child.nodeType !== 1 ) continue;
  31835. switch ( child.nodeName ) {
  31836. case 'skeleton':
  31837. this.skeleton.push( child.textContent.replace(/^#/, '') );
  31838. break;
  31839. case 'bind_material':
  31840. var instances = child.querySelectorAll('instance_material');
  31841. for ( var j = 0; j < instances.length; j ++ ) {
  31842. var instance = instances[j];
  31843. this.instance_material.push( (new InstanceMaterial()).parse(instance) );
  31844. }
  31845. break;
  31846. case 'extra':
  31847. break;
  31848. default:
  31849. break;
  31850. }
  31851. }
  31852. return this;
  31853. };
  31854. function InstanceMaterial () {
  31855. this.symbol = "";
  31856. this.target = "";
  31857. }
  31858. InstanceMaterial.prototype.parse = function ( element ) {
  31859. this.symbol = element.getAttribute('symbol');
  31860. this.target = element.getAttribute('target').replace(/^#/, '');
  31861. return this;
  31862. };
  31863. function InstanceGeometry() {
  31864. this.url = "";
  31865. this.instance_material = [];
  31866. }
  31867. InstanceGeometry.prototype.parse = function ( element ) {
  31868. this.url = element.getAttribute('url').replace(/^#/, '');
  31869. this.instance_material = [];
  31870. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  31871. var child = element.childNodes[i];
  31872. if ( child.nodeType != 1 ) continue;
  31873. if ( child.nodeName === 'bind_material' ) {
  31874. var instances = child.querySelectorAll('instance_material');
  31875. for ( var j = 0; j < instances.length; j ++ ) {
  31876. var instance = instances[j];
  31877. this.instance_material.push( (new InstanceMaterial()).parse(instance) );
  31878. }
  31879. break;
  31880. }
  31881. }
  31882. return this;
  31883. };
  31884. function Geometry() {
  31885. this.id = "";
  31886. this.mesh = null;
  31887. }
  31888. Geometry.prototype.parse = function ( element ) {
  31889. this.id = element.getAttribute('id');
  31890. extractDoubleSided( this, element );
  31891. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  31892. var child = element.childNodes[i];
  31893. switch ( child.nodeName ) {
  31894. case 'mesh':
  31895. this.mesh = (new Mesh(this)).parse(child);
  31896. break;
  31897. case 'extra':
  31898. // console.log( child );
  31899. break;
  31900. default:
  31901. break;
  31902. }
  31903. }
  31904. return this;
  31905. };
  31906. function Mesh( geometry ) {
  31907. this.geometry = geometry.id;
  31908. this.primitives = [];
  31909. this.vertices = null;
  31910. this.geometry3js = null;
  31911. }
  31912. Mesh.prototype.parse = function ( element ) {
  31913. this.primitives = [];
  31914. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  31915. var child = element.childNodes[ i ];
  31916. switch ( child.nodeName ) {
  31917. case 'source':
  31918. _source( child );
  31919. break;
  31920. case 'vertices':
  31921. this.vertices = ( new Vertices() ).parse( child );
  31922. break;
  31923. case 'linestrips':
  31924. this.primitives.push( ( new LineStrips().parse( child ) ) );
  31925. break;
  31926. case 'triangles':
  31927. this.primitives.push( ( new Triangles().parse( child ) ) );
  31928. break;
  31929. case 'polygons':
  31930. this.primitives.push( ( new Polygons().parse( child ) ) );
  31931. break;
  31932. case 'polylist':
  31933. this.primitives.push( ( new Polylist().parse( child ) ) );
  31934. break;
  31935. default:
  31936. break;
  31937. }
  31938. }
  31939. this.geometry3js = new THREE.Geometry();
  31940. if ( this.vertices === null ) {
  31941. // TODO (mrdoob): Study case when this is null (carrier.dae)
  31942. return this;
  31943. }
  31944. var vertexData = sources[ this.vertices.input['POSITION'].source ].data;
  31945. for ( var i = 0; i < vertexData.length; i += 3 ) {
  31946. this.geometry3js.vertices.push( getConvertedVec3( vertexData, i ).clone() );
  31947. }
  31948. for ( var i = 0; i < this.primitives.length; i ++ ) {
  31949. var primitive = this.primitives[ i ];
  31950. primitive.setVertices( this.vertices );
  31951. this.handlePrimitive( primitive, this.geometry3js );
  31952. }
  31953. if ( this.geometry3js.calcNormals ) {
  31954. this.geometry3js.computeVertexNormals();
  31955. delete this.geometry3js.calcNormals;
  31956. }
  31957. return this;
  31958. };
  31959. Mesh.prototype.handlePrimitive = function ( primitive, geom ) {
  31960. if ( primitive instanceof LineStrips ) {
  31961. // TODO: Handle indices. Maybe easier with BufferGeometry?
  31962. geom.isLineStrip = true;
  31963. return;
  31964. }
  31965. var j, k, pList = primitive.p, inputs = primitive.inputs;
  31966. var input, index, idx32;
  31967. var source, numParams;
  31968. var vcIndex = 0, vcount = 3, maxOffset = 0;
  31969. var texture_sets = [];
  31970. for ( j = 0; j < inputs.length; j ++ ) {
  31971. input = inputs[ j ];
  31972. var offset = input.offset + 1;
  31973. maxOffset = (maxOffset < offset) ? offset : maxOffset;
  31974. switch ( input.semantic ) {
  31975. case 'TEXCOORD':
  31976. texture_sets.push( input.set );
  31977. break;
  31978. }
  31979. }
  31980. for ( var pCount = 0; pCount < pList.length; ++ pCount ) {
  31981. var p = pList[ pCount ], i = 0;
  31982. while ( i < p.length ) {
  31983. var vs = [];
  31984. var ns = [];
  31985. var ts = null;
  31986. var cs = [];
  31987. if ( primitive.vcount ) {
  31988. vcount = primitive.vcount.length ? primitive.vcount[ vcIndex ++ ] : primitive.vcount;
  31989. } else {
  31990. vcount = p.length / maxOffset;
  31991. }
  31992. for ( j = 0; j < vcount; j ++ ) {
  31993. for ( k = 0; k < inputs.length; k ++ ) {
  31994. input = inputs[ k ];
  31995. source = sources[ input.source ];
  31996. index = p[ i + ( j * maxOffset ) + input.offset ];
  31997. numParams = source.accessor.params.length;
  31998. idx32 = index * numParams;
  31999. switch ( input.semantic ) {
  32000. case 'VERTEX':
  32001. vs.push( index );
  32002. break;
  32003. case 'NORMAL':
  32004. ns.push( getConvertedVec3( source.data, idx32 ) );
  32005. break;
  32006. case 'TEXCOORD':
  32007. ts = ts || { };
  32008. if ( ts[ input.set ] === undefined ) ts[ input.set ] = [];
  32009. // invert the V
  32010. ts[ input.set ].push( new THREE.Vector2( source.data[ idx32 ], source.data[ idx32 + 1 ] ) );
  32011. break;
  32012. case 'COLOR':
  32013. cs.push( new THREE.Color().setRGB( source.data[ idx32 ], source.data[ idx32 + 1 ], source.data[ idx32 + 2 ] ) );
  32014. break;
  32015. default:
  32016. break;
  32017. }
  32018. }
  32019. }
  32020. if ( ns.length === 0 ) {
  32021. // check the vertices inputs
  32022. input = this.vertices.input.NORMAL;
  32023. if ( input ) {
  32024. source = sources[ input.source ];
  32025. numParams = source.accessor.params.length;
  32026. for ( var ndx = 0, len = vs.length; ndx < len; ndx ++ ) {
  32027. ns.push( getConvertedVec3( source.data, vs[ ndx ] * numParams ) );
  32028. }
  32029. } else {
  32030. geom.calcNormals = true;
  32031. }
  32032. }
  32033. if ( !ts ) {
  32034. ts = { };
  32035. // check the vertices inputs
  32036. input = this.vertices.input.TEXCOORD;
  32037. if ( input ) {
  32038. texture_sets.push( input.set );
  32039. source = sources[ input.source ];
  32040. numParams = source.accessor.params.length;
  32041. for ( var ndx = 0, len = vs.length; ndx < len; ndx ++ ) {
  32042. idx32 = vs[ ndx ] * numParams;
  32043. if ( ts[ input.set ] === undefined ) ts[ input.set ] = [ ];
  32044. // invert the V
  32045. ts[ input.set ].push( new THREE.Vector2( source.data[ idx32 ], 1.0 - source.data[ idx32 + 1 ] ) );
  32046. }
  32047. }
  32048. }
  32049. if ( cs.length === 0 ) {
  32050. // check the vertices inputs
  32051. input = this.vertices.input.COLOR;
  32052. if ( input ) {
  32053. source = sources[ input.source ];
  32054. numParams = source.accessor.params.length;
  32055. for ( var ndx = 0, len = vs.length; ndx < len; ndx ++ ) {
  32056. idx32 = vs[ ndx ] * numParams;
  32057. cs.push( new THREE.Color().setRGB( source.data[ idx32 ], source.data[ idx32 + 1 ], source.data[ idx32 + 2 ] ) );
  32058. }
  32059. }
  32060. }
  32061. var face = null, faces = [], uv, uvArr;
  32062. if ( vcount === 3 ) {
  32063. faces.push( new THREE.Face3( vs[0], vs[1], vs[2], ns, cs.length ? cs : new THREE.Color() ) );
  32064. } else if ( vcount === 4 ) {
  32065. 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() ) );
  32066. 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() ) );
  32067. } else if ( vcount > 4 && options.subdivideFaces ) {
  32068. var clr = cs.length ? cs : new THREE.Color(),
  32069. vec1, vec2, vec3, v1, v2, norm;
  32070. // subdivide into multiple Face3s
  32071. for ( k = 1; k < vcount - 1; ) {
  32072. faces.push( new THREE.Face3( vs[0], vs[k], vs[k + 1], ns.length ? [ ns[0].clone(), ns[k ++].clone(), ns[k].clone() ] : [], clr ) );
  32073. }
  32074. }
  32075. if ( faces.length ) {
  32076. for ( var ndx = 0, len = faces.length; ndx < len; ndx ++ ) {
  32077. face = faces[ndx];
  32078. face.daeMaterial = primitive.material;
  32079. geom.faces.push( face );
  32080. for ( k = 0; k < texture_sets.length; k ++ ) {
  32081. uv = ts[ texture_sets[k] ];
  32082. if ( vcount > 4 ) {
  32083. // Grab the right UVs for the vertices in this face
  32084. uvArr = [ uv[0], uv[ndx + 1], uv[ndx + 2] ];
  32085. } else if ( vcount === 4 ) {
  32086. if ( ndx === 0 ) {
  32087. uvArr = [ uv[0], uv[1], uv[3] ];
  32088. } else {
  32089. uvArr = [ uv[1].clone(), uv[2], uv[3].clone() ];
  32090. }
  32091. } else {
  32092. uvArr = [ uv[0], uv[1], uv[2] ];
  32093. }
  32094. if ( geom.faceVertexUvs[k] === undefined ) {
  32095. geom.faceVertexUvs[k] = [];
  32096. }
  32097. geom.faceVertexUvs[k].push( uvArr );
  32098. }
  32099. }
  32100. } else {
  32101. console.log( 'dropped face with vcount ' + vcount + ' for geometry with id: ' + geom.id );
  32102. }
  32103. i += maxOffset * vcount;
  32104. }
  32105. }
  32106. };
  32107. function Polygons () {
  32108. this.material = "";
  32109. this.count = 0;
  32110. this.inputs = [];
  32111. this.vcount = null;
  32112. this.p = [];
  32113. this.geometry = new THREE.Geometry();
  32114. }
  32115. Polygons.prototype.setVertices = function ( vertices ) {
  32116. for ( var i = 0; i < this.inputs.length; i ++ ) {
  32117. if ( this.inputs[ i ].source === vertices.id ) {
  32118. this.inputs[ i ].source = vertices.input[ 'POSITION' ].source;
  32119. }
  32120. }
  32121. };
  32122. Polygons.prototype.parse = function ( element ) {
  32123. this.material = element.getAttribute( 'material' );
  32124. this.count = _attr_as_int( element, 'count', 0 );
  32125. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32126. var child = element.childNodes[ i ];
  32127. switch ( child.nodeName ) {
  32128. case 'input':
  32129. this.inputs.push( ( new Input() ).parse( element.childNodes[ i ] ) );
  32130. break;
  32131. case 'vcount':
  32132. this.vcount = _ints( child.textContent );
  32133. break;
  32134. case 'p':
  32135. this.p.push( _ints( child.textContent ) );
  32136. break;
  32137. case 'ph':
  32138. console.warn( 'polygon holes not yet supported!' );
  32139. break;
  32140. default:
  32141. break;
  32142. }
  32143. }
  32144. return this;
  32145. };
  32146. function Polylist () {
  32147. Polygons.call( this );
  32148. this.vcount = [];
  32149. }
  32150. Polylist.prototype = Object.create( Polygons.prototype );
  32151. Polylist.prototype.constructor = Polylist;
  32152. function LineStrips() {
  32153. Polygons.call( this );
  32154. this.vcount = 1;
  32155. }
  32156. LineStrips.prototype = Object.create( Polygons.prototype );
  32157. LineStrips.prototype.constructor = LineStrips;
  32158. function Triangles () {
  32159. Polygons.call( this );
  32160. this.vcount = 3;
  32161. }
  32162. Triangles.prototype = Object.create( Polygons.prototype );
  32163. Triangles.prototype.constructor = Triangles;
  32164. function Accessor() {
  32165. this.source = "";
  32166. this.count = 0;
  32167. this.stride = 0;
  32168. this.params = [];
  32169. }
  32170. Accessor.prototype.parse = function ( element ) {
  32171. this.params = [];
  32172. this.source = element.getAttribute( 'source' );
  32173. this.count = _attr_as_int( element, 'count', 0 );
  32174. this.stride = _attr_as_int( element, 'stride', 0 );
  32175. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32176. var child = element.childNodes[ i ];
  32177. if ( child.nodeName === 'param' ) {
  32178. var param = {};
  32179. param[ 'name' ] = child.getAttribute( 'name' );
  32180. param[ 'type' ] = child.getAttribute( 'type' );
  32181. this.params.push( param );
  32182. }
  32183. }
  32184. return this;
  32185. };
  32186. function Vertices() {
  32187. this.input = {};
  32188. }
  32189. Vertices.prototype.parse = function ( element ) {
  32190. this.id = element.getAttribute('id');
  32191. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32192. if ( element.childNodes[i].nodeName === 'input' ) {
  32193. var input = ( new Input() ).parse( element.childNodes[ i ] );
  32194. this.input[ input.semantic ] = input;
  32195. }
  32196. }
  32197. return this;
  32198. };
  32199. function Input () {
  32200. this.semantic = "";
  32201. this.offset = 0;
  32202. this.source = "";
  32203. this.set = 0;
  32204. }
  32205. Input.prototype.parse = function ( element ) {
  32206. this.semantic = element.getAttribute('semantic');
  32207. this.source = element.getAttribute('source').replace(/^#/, '');
  32208. this.set = _attr_as_int(element, 'set', -1);
  32209. this.offset = _attr_as_int(element, 'offset', 0);
  32210. if ( this.semantic === 'TEXCOORD' && this.set < 0 ) {
  32211. this.set = 0;
  32212. }
  32213. return this;
  32214. };
  32215. function Source ( id ) {
  32216. this.id = id;
  32217. this.type = null;
  32218. }
  32219. Source.prototype.parse = function ( element ) {
  32220. this.id = element.getAttribute( 'id' );
  32221. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32222. var child = element.childNodes[i];
  32223. switch ( child.nodeName ) {
  32224. case 'bool_array':
  32225. this.data = _bools( child.textContent );
  32226. this.type = child.nodeName;
  32227. break;
  32228. case 'float_array':
  32229. this.data = _floats( child.textContent );
  32230. this.type = child.nodeName;
  32231. break;
  32232. case 'int_array':
  32233. this.data = _ints( child.textContent );
  32234. this.type = child.nodeName;
  32235. break;
  32236. case 'IDREF_array':
  32237. case 'Name_array':
  32238. this.data = _strings( child.textContent );
  32239. this.type = child.nodeName;
  32240. break;
  32241. case 'technique_common':
  32242. for ( var j = 0; j < child.childNodes.length; j ++ ) {
  32243. if ( child.childNodes[ j ].nodeName === 'accessor' ) {
  32244. this.accessor = ( new Accessor() ).parse( child.childNodes[ j ] );
  32245. break;
  32246. }
  32247. }
  32248. break;
  32249. default:
  32250. // console.log(child.nodeName);
  32251. break;
  32252. }
  32253. }
  32254. return this;
  32255. };
  32256. Source.prototype.read = function () {
  32257. var result = [];
  32258. //for (var i = 0; i < this.accessor.params.length; i++) {
  32259. var param = this.accessor.params[ 0 ];
  32260. //console.log(param.name + " " + param.type);
  32261. switch ( param.type ) {
  32262. case 'IDREF':
  32263. case 'Name': case 'name':
  32264. case 'float':
  32265. return this.data;
  32266. case 'float4x4':
  32267. for ( var j = 0; j < this.data.length; j += 16 ) {
  32268. var s = this.data.slice( j, j + 16 );
  32269. var m = getConvertedMat4( s );
  32270. result.push( m );
  32271. }
  32272. break;
  32273. default:
  32274. console.log( 'ColladaLoader: Source: Read dont know how to read ' + param.type + '.' );
  32275. break;
  32276. }
  32277. //}
  32278. return result;
  32279. };
  32280. function Material () {
  32281. this.id = "";
  32282. this.name = "";
  32283. this.instance_effect = null;
  32284. }
  32285. Material.prototype.parse = function ( element ) {
  32286. this.id = element.getAttribute( 'id' );
  32287. this.name = element.getAttribute( 'name' );
  32288. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32289. if ( element.childNodes[ i ].nodeName === 'instance_effect' ) {
  32290. this.instance_effect = ( new InstanceEffect() ).parse( element.childNodes[ i ] );
  32291. break;
  32292. }
  32293. }
  32294. return this;
  32295. };
  32296. function ColorOrTexture () {
  32297. this.color = new THREE.Color();
  32298. this.color.setRGB( Math.random(), Math.random(), Math.random() );
  32299. this.color.a = 1.0;
  32300. this.texture = null;
  32301. this.texcoord = null;
  32302. this.texOpts = null;
  32303. }
  32304. ColorOrTexture.prototype.isColor = function () {
  32305. return ( this.texture === null );
  32306. };
  32307. ColorOrTexture.prototype.isTexture = function () {
  32308. return ( this.texture != null );
  32309. };
  32310. ColorOrTexture.prototype.parse = function ( element ) {
  32311. if (element.nodeName === 'transparent') {
  32312. this.opaque = element.getAttribute('opaque');
  32313. }
  32314. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32315. var child = element.childNodes[ i ];
  32316. if ( child.nodeType != 1 ) continue;
  32317. switch ( child.nodeName ) {
  32318. case 'color':
  32319. var rgba = _floats( child.textContent );
  32320. this.color = new THREE.Color();
  32321. this.color.setRGB( rgba[0], rgba[1], rgba[2] );
  32322. this.color.a = rgba[3];
  32323. break;
  32324. case 'texture':
  32325. this.texture = child.getAttribute('texture');
  32326. this.texcoord = child.getAttribute('texcoord');
  32327. // Defaults from:
  32328. // https://collada.org/mediawiki/index.php/Maya_texture_placement_MAYA_extension
  32329. this.texOpts = {
  32330. offsetU: 0,
  32331. offsetV: 0,
  32332. repeatU: 1,
  32333. repeatV: 1,
  32334. wrapU: 1,
  32335. wrapV: 1
  32336. };
  32337. this.parseTexture( child );
  32338. break;
  32339. default:
  32340. break;
  32341. }
  32342. }
  32343. return this;
  32344. };
  32345. ColorOrTexture.prototype.parseTexture = function ( element ) {
  32346. if ( ! element.childNodes ) return this;
  32347. // This should be supported by Maya, 3dsMax, and MotionBuilder
  32348. if ( element.childNodes[1] && element.childNodes[1].nodeName === 'extra' ) {
  32349. element = element.childNodes[1];
  32350. if ( element.childNodes[1] && element.childNodes[1].nodeName === 'technique' ) {
  32351. element = element.childNodes[1];
  32352. }
  32353. }
  32354. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32355. var child = element.childNodes[ i ];
  32356. switch ( child.nodeName ) {
  32357. case 'offsetU':
  32358. case 'offsetV':
  32359. case 'repeatU':
  32360. case 'repeatV':
  32361. this.texOpts[ child.nodeName ] = parseFloat( child.textContent );
  32362. break;
  32363. case 'wrapU':
  32364. case 'wrapV':
  32365. // some dae have a value of true which becomes NaN via parseInt
  32366. if ( child.textContent.toUpperCase() === 'TRUE' ) {
  32367. this.texOpts[ child.nodeName ] = 1;
  32368. } else {
  32369. this.texOpts[ child.nodeName ] = parseInt( child.textContent );
  32370. }
  32371. break;
  32372. default:
  32373. this.texOpts[ child.nodeName ] = child.textContent;
  32374. break;
  32375. }
  32376. }
  32377. return this;
  32378. };
  32379. function Shader ( type, effect ) {
  32380. this.type = type;
  32381. this.effect = effect;
  32382. this.material = null;
  32383. }
  32384. Shader.prototype.parse = function ( element ) {
  32385. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32386. var child = element.childNodes[ i ];
  32387. if ( child.nodeType != 1 ) continue;
  32388. switch ( child.nodeName ) {
  32389. case 'emission':
  32390. case 'diffuse':
  32391. case 'specular':
  32392. case 'transparent':
  32393. this[ child.nodeName ] = ( new ColorOrTexture() ).parse( child );
  32394. break;
  32395. case 'bump':
  32396. // If 'bumptype' is 'heightfield', create a 'bump' property
  32397. // Else if 'bumptype' is 'normalmap', create a 'normal' property
  32398. // (Default to 'bump')
  32399. var bumpType = child.getAttribute( 'bumptype' );
  32400. if ( bumpType ) {
  32401. if ( bumpType.toLowerCase() === "heightfield" ) {
  32402. this[ 'bump' ] = ( new ColorOrTexture() ).parse( child );
  32403. } else if ( bumpType.toLowerCase() === "normalmap" ) {
  32404. this[ 'normal' ] = ( new ColorOrTexture() ).parse( child );
  32405. } else {
  32406. console.error( "Shader.prototype.parse: Invalid value for attribute 'bumptype' (" + bumpType + ") - valid bumptypes are 'HEIGHTFIELD' and 'NORMALMAP' - defaulting to 'HEIGHTFIELD'" );
  32407. this[ 'bump' ] = ( new ColorOrTexture() ).parse( child );
  32408. }
  32409. } else {
  32410. console.warn( "Shader.prototype.parse: Attribute 'bumptype' missing from bump node - defaulting to 'HEIGHTFIELD'" );
  32411. this[ 'bump' ] = ( new ColorOrTexture() ).parse( child );
  32412. }
  32413. break;
  32414. case 'shininess':
  32415. case 'reflectivity':
  32416. case 'index_of_refraction':
  32417. case 'transparency':
  32418. var f = child.querySelectorAll('float');
  32419. if ( f.length > 0 )
  32420. this[ child.nodeName ] = parseFloat( f[ 0 ].textContent );
  32421. break;
  32422. default:
  32423. break;
  32424. }
  32425. }
  32426. this.create();
  32427. return this;
  32428. };
  32429. Shader.prototype.create = function() {
  32430. var props = {};
  32431. var transparent = false;
  32432. if (this['transparency'] !== undefined && this['transparent'] !== undefined) {
  32433. // convert transparent color RBG to average value
  32434. var transparentColor = this['transparent'];
  32435. var transparencyLevel = (this.transparent.color.r + this.transparent.color.g + this.transparent.color.b) / 3 * this.transparency;
  32436. if (transparencyLevel > 0) {
  32437. transparent = true;
  32438. props[ 'transparent' ] = true;
  32439. props[ 'opacity' ] = 1 - transparencyLevel;
  32440. }
  32441. }
  32442. var keys = {
  32443. 'diffuse':'map',
  32444. 'ambient':'lightMap',
  32445. 'specular':'specularMap',
  32446. 'emission':'emissionMap',
  32447. 'bump':'bumpMap',
  32448. 'normal':'normalMap'
  32449. };
  32450. for ( var prop in this ) {
  32451. switch ( prop ) {
  32452. case 'ambient':
  32453. case 'emission':
  32454. case 'diffuse':
  32455. case 'specular':
  32456. case 'bump':
  32457. case 'normal':
  32458. var cot = this[ prop ];
  32459. if ( cot instanceof ColorOrTexture ) {
  32460. if ( cot.isTexture() ) {
  32461. var samplerId = cot.texture;
  32462. var sampler = this.effect.sampler[samplerId];
  32463. if ( sampler !== undefined && sampler.source !== undefined ) {
  32464. var surface = this.effect.surface[sampler.source];
  32465. if ( surface !== undefined ) {
  32466. var image = images[ surface.init_from ];
  32467. if ( image ) {
  32468. var url = baseUrl + image.init_from;
  32469. var texture;
  32470. var loader = THREE.Loader.Handlers.get( url );
  32471. if ( loader !== null ) {
  32472. texture = loader.load( url );
  32473. } else {
  32474. texture = new THREE.Texture();
  32475. loadTextureImage( texture, url );
  32476. }
  32477. if ( sampler.wrap_s === "MIRROR" ) {
  32478. texture.wrapS = THREE.MirroredRepeatWrapping;
  32479. } else if ( sampler.wrap_s === "WRAP" || cot.texOpts.wrapU ) {
  32480. texture.wrapS = THREE.RepeatWrapping;
  32481. } else {
  32482. texture.wrapS = THREE.ClampToEdgeWrapping;
  32483. }
  32484. if ( sampler.wrap_t === "MIRROR" ) {
  32485. texture.wrapT = THREE.MirroredRepeatWrapping;
  32486. } else if ( sampler.wrap_t === "WRAP" || cot.texOpts.wrapV ) {
  32487. texture.wrapT = THREE.RepeatWrapping;
  32488. } else {
  32489. texture.wrapT = THREE.ClampToEdgeWrapping;
  32490. }
  32491. texture.offset.x = cot.texOpts.offsetU;
  32492. texture.offset.y = cot.texOpts.offsetV;
  32493. texture.repeat.x = cot.texOpts.repeatU;
  32494. texture.repeat.y = cot.texOpts.repeatV;
  32495. props[keys[prop]] = texture;
  32496. // Texture with baked lighting?
  32497. if (prop === 'emission') props['emissive'] = 0xffffff;
  32498. }
  32499. }
  32500. }
  32501. } else if ( prop === 'diffuse' || !transparent ) {
  32502. if ( prop === 'emission' ) {
  32503. props[ 'emissive' ] = cot.color.getHex();
  32504. } else {
  32505. props[ prop ] = cot.color.getHex();
  32506. }
  32507. }
  32508. }
  32509. break;
  32510. case 'shininess':
  32511. props[ prop ] = this[ prop ];
  32512. break;
  32513. case 'reflectivity':
  32514. props[ prop ] = this[ prop ];
  32515. if ( props[ prop ] > 0.0 ) props['envMap'] = options.defaultEnvMap;
  32516. props['combine'] = THREE.MixOperation; //mix regular shading with reflective component
  32517. break;
  32518. case 'index_of_refraction':
  32519. props[ 'refractionRatio' ] = this[ prop ]; //TODO: "index_of_refraction" becomes "refractionRatio" in shader, but I'm not sure if the two are actually comparable
  32520. if ( this[ prop ] !== 1.0 ) props['envMap'] = options.defaultEnvMap;
  32521. break;
  32522. case 'transparency':
  32523. // gets figured out up top
  32524. break;
  32525. default:
  32526. break;
  32527. }
  32528. }
  32529. props[ 'shading' ] = preferredShading;
  32530. props[ 'side' ] = this.effect.doubleSided ? THREE.DoubleSide : THREE.FrontSide;
  32531. if ( props.diffuse !== undefined ) {
  32532. props.color = props.diffuse;
  32533. delete props.diffuse;
  32534. }
  32535. switch ( this.type ) {
  32536. case 'constant':
  32537. if (props.emissive != undefined) props.color = props.emissive;
  32538. this.material = new THREE.MeshBasicMaterial( props );
  32539. break;
  32540. case 'phong':
  32541. case 'blinn':
  32542. this.material = new THREE.MeshPhongMaterial( props );
  32543. break;
  32544. case 'lambert':
  32545. default:
  32546. this.material = new THREE.MeshLambertMaterial( props );
  32547. break;
  32548. }
  32549. return this.material;
  32550. };
  32551. function Surface ( effect ) {
  32552. this.effect = effect;
  32553. this.init_from = null;
  32554. this.format = null;
  32555. }
  32556. Surface.prototype.parse = function ( element ) {
  32557. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32558. var child = element.childNodes[ i ];
  32559. if ( child.nodeType != 1 ) continue;
  32560. switch ( child.nodeName ) {
  32561. case 'init_from':
  32562. this.init_from = child.textContent;
  32563. break;
  32564. case 'format':
  32565. this.format = child.textContent;
  32566. break;
  32567. default:
  32568. console.log( "unhandled Surface prop: " + child.nodeName );
  32569. break;
  32570. }
  32571. }
  32572. return this;
  32573. };
  32574. function Sampler2D ( effect ) {
  32575. this.effect = effect;
  32576. this.source = null;
  32577. this.wrap_s = null;
  32578. this.wrap_t = null;
  32579. this.minfilter = null;
  32580. this.magfilter = null;
  32581. this.mipfilter = null;
  32582. }
  32583. Sampler2D.prototype.parse = function ( element ) {
  32584. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32585. var child = element.childNodes[ i ];
  32586. if ( child.nodeType != 1 ) continue;
  32587. switch ( child.nodeName ) {
  32588. case 'source':
  32589. this.source = child.textContent;
  32590. break;
  32591. case 'minfilter':
  32592. this.minfilter = child.textContent;
  32593. break;
  32594. case 'magfilter':
  32595. this.magfilter = child.textContent;
  32596. break;
  32597. case 'mipfilter':
  32598. this.mipfilter = child.textContent;
  32599. break;
  32600. case 'wrap_s':
  32601. this.wrap_s = child.textContent;
  32602. break;
  32603. case 'wrap_t':
  32604. this.wrap_t = child.textContent;
  32605. break;
  32606. default:
  32607. console.log( "unhandled Sampler2D prop: " + child.nodeName );
  32608. break;
  32609. }
  32610. }
  32611. return this;
  32612. };
  32613. function Effect () {
  32614. this.id = "";
  32615. this.name = "";
  32616. this.shader = null;
  32617. this.surface = {};
  32618. this.sampler = {};
  32619. }
  32620. Effect.prototype.create = function () {
  32621. if ( this.shader === null ) {
  32622. return null;
  32623. }
  32624. };
  32625. Effect.prototype.parse = function ( element ) {
  32626. this.id = element.getAttribute( 'id' );
  32627. this.name = element.getAttribute( 'name' );
  32628. extractDoubleSided( this, element );
  32629. this.shader = null;
  32630. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32631. var child = element.childNodes[ i ];
  32632. if ( child.nodeType != 1 ) continue;
  32633. switch ( child.nodeName ) {
  32634. case 'profile_COMMON':
  32635. this.parseTechnique( this.parseProfileCOMMON( child ) );
  32636. break;
  32637. default:
  32638. break;
  32639. }
  32640. }
  32641. return this;
  32642. };
  32643. Effect.prototype.parseNewparam = function ( element ) {
  32644. var sid = element.getAttribute( 'sid' );
  32645. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32646. var child = element.childNodes[ i ];
  32647. if ( child.nodeType != 1 ) continue;
  32648. switch ( child.nodeName ) {
  32649. case 'surface':
  32650. this.surface[sid] = ( new Surface( this ) ).parse( child );
  32651. break;
  32652. case 'sampler2D':
  32653. this.sampler[sid] = ( new Sampler2D( this ) ).parse( child );
  32654. break;
  32655. case 'extra':
  32656. break;
  32657. default:
  32658. console.log( child.nodeName );
  32659. break;
  32660. }
  32661. }
  32662. };
  32663. Effect.prototype.parseProfileCOMMON = function ( element ) {
  32664. var technique;
  32665. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32666. var child = element.childNodes[ i ];
  32667. if ( child.nodeType != 1 ) continue;
  32668. switch ( child.nodeName ) {
  32669. case 'profile_COMMON':
  32670. this.parseProfileCOMMON( child );
  32671. break;
  32672. case 'technique':
  32673. technique = child;
  32674. break;
  32675. case 'newparam':
  32676. this.parseNewparam( child );
  32677. break;
  32678. case 'image':
  32679. var _image = ( new _Image() ).parse( child );
  32680. images[ _image.id ] = _image;
  32681. break;
  32682. case 'extra':
  32683. break;
  32684. default:
  32685. console.log( child.nodeName );
  32686. break;
  32687. }
  32688. }
  32689. return technique;
  32690. };
  32691. Effect.prototype.parseTechnique = function ( element ) {
  32692. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32693. var child = element.childNodes[i];
  32694. if ( child.nodeType != 1 ) continue;
  32695. switch ( child.nodeName ) {
  32696. case 'constant':
  32697. case 'lambert':
  32698. case 'blinn':
  32699. case 'phong':
  32700. this.shader = ( new Shader( child.nodeName, this ) ).parse( child );
  32701. break;
  32702. case 'extra':
  32703. this.parseExtra(child);
  32704. break;
  32705. default:
  32706. break;
  32707. }
  32708. }
  32709. };
  32710. Effect.prototype.parseExtra = function ( element ) {
  32711. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32712. var child = element.childNodes[i];
  32713. if ( child.nodeType != 1 ) continue;
  32714. switch ( child.nodeName ) {
  32715. case 'technique':
  32716. this.parseExtraTechnique( child );
  32717. break;
  32718. default:
  32719. break;
  32720. }
  32721. }
  32722. };
  32723. Effect.prototype.parseExtraTechnique = function ( element ) {
  32724. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32725. var child = element.childNodes[i];
  32726. if ( child.nodeType != 1 ) continue;
  32727. switch ( child.nodeName ) {
  32728. case 'bump':
  32729. this.shader.parse( element );
  32730. break;
  32731. default:
  32732. break;
  32733. }
  32734. }
  32735. };
  32736. function InstanceEffect () {
  32737. this.url = "";
  32738. }
  32739. InstanceEffect.prototype.parse = function ( element ) {
  32740. this.url = element.getAttribute( 'url' ).replace( /^#/, '' );
  32741. return this;
  32742. };
  32743. function Animation() {
  32744. this.id = "";
  32745. this.name = "";
  32746. this.source = {};
  32747. this.sampler = [];
  32748. this.channel = [];
  32749. }
  32750. Animation.prototype.parse = function ( element ) {
  32751. this.id = element.getAttribute( 'id' );
  32752. this.name = element.getAttribute( 'name' );
  32753. this.source = {};
  32754. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32755. var child = element.childNodes[ i ];
  32756. if ( child.nodeType != 1 ) continue;
  32757. switch ( child.nodeName ) {
  32758. case 'animation':
  32759. var anim = ( new Animation() ).parse( child );
  32760. for ( var src in anim.source ) {
  32761. this.source[ src ] = anim.source[ src ];
  32762. }
  32763. for ( var j = 0; j < anim.channel.length; j ++ ) {
  32764. this.channel.push( anim.channel[ j ] );
  32765. this.sampler.push( anim.sampler[ j ] );
  32766. }
  32767. break;
  32768. case 'source':
  32769. var src = ( new Source() ).parse( child );
  32770. this.source[ src.id ] = src;
  32771. break;
  32772. case 'sampler':
  32773. this.sampler.push( ( new Sampler( this ) ).parse( child ) );
  32774. break;
  32775. case 'channel':
  32776. this.channel.push( ( new Channel( this ) ).parse( child ) );
  32777. break;
  32778. default:
  32779. break;
  32780. }
  32781. }
  32782. return this;
  32783. };
  32784. function Channel( animation ) {
  32785. this.animation = animation;
  32786. this.source = "";
  32787. this.target = "";
  32788. this.fullSid = null;
  32789. this.sid = null;
  32790. this.dotSyntax = null;
  32791. this.arrSyntax = null;
  32792. this.arrIndices = null;
  32793. this.member = null;
  32794. }
  32795. Channel.prototype.parse = function ( element ) {
  32796. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  32797. this.target = element.getAttribute( 'target' );
  32798. var parts = this.target.split( '/' );
  32799. var id = parts.shift();
  32800. var sid = parts.shift();
  32801. var dotSyntax = ( sid.indexOf(".") >= 0 );
  32802. var arrSyntax = ( sid.indexOf("(") >= 0 );
  32803. if ( dotSyntax ) {
  32804. parts = sid.split(".");
  32805. this.sid = parts.shift();
  32806. this.member = parts.shift();
  32807. } else if ( arrSyntax ) {
  32808. var arrIndices = sid.split("(");
  32809. this.sid = arrIndices.shift();
  32810. for (var j = 0; j < arrIndices.length; j ++ ) {
  32811. arrIndices[j] = parseInt( arrIndices[j].replace(/\)/, '') );
  32812. }
  32813. this.arrIndices = arrIndices;
  32814. } else {
  32815. this.sid = sid;
  32816. }
  32817. this.fullSid = sid;
  32818. this.dotSyntax = dotSyntax;
  32819. this.arrSyntax = arrSyntax;
  32820. return this;
  32821. };
  32822. function Sampler ( animation ) {
  32823. this.id = "";
  32824. this.animation = animation;
  32825. this.inputs = [];
  32826. this.input = null;
  32827. this.output = null;
  32828. this.strideOut = null;
  32829. this.interpolation = null;
  32830. this.startTime = null;
  32831. this.endTime = null;
  32832. this.duration = 0;
  32833. }
  32834. Sampler.prototype.parse = function ( element ) {
  32835. this.id = element.getAttribute( 'id' );
  32836. this.inputs = [];
  32837. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32838. var child = element.childNodes[ i ];
  32839. if ( child.nodeType != 1 ) continue;
  32840. switch ( child.nodeName ) {
  32841. case 'input':
  32842. this.inputs.push( (new Input()).parse( child ) );
  32843. break;
  32844. default:
  32845. break;
  32846. }
  32847. }
  32848. return this;
  32849. };
  32850. Sampler.prototype.create = function () {
  32851. for ( var i = 0; i < this.inputs.length; i ++ ) {
  32852. var input = this.inputs[ i ];
  32853. var source = this.animation.source[ input.source ];
  32854. switch ( input.semantic ) {
  32855. case 'INPUT':
  32856. this.input = source.read();
  32857. break;
  32858. case 'OUTPUT':
  32859. this.output = source.read();
  32860. this.strideOut = source.accessor.stride;
  32861. break;
  32862. case 'INTERPOLATION':
  32863. this.interpolation = source.read();
  32864. break;
  32865. case 'IN_TANGENT':
  32866. break;
  32867. case 'OUT_TANGENT':
  32868. break;
  32869. default:
  32870. console.log(input.semantic);
  32871. break;
  32872. }
  32873. }
  32874. this.startTime = 0;
  32875. this.endTime = 0;
  32876. this.duration = 0;
  32877. if ( this.input.length ) {
  32878. this.startTime = 100000000;
  32879. this.endTime = -100000000;
  32880. for ( var i = 0; i < this.input.length; i ++ ) {
  32881. this.startTime = Math.min( this.startTime, this.input[ i ] );
  32882. this.endTime = Math.max( this.endTime, this.input[ i ] );
  32883. }
  32884. this.duration = this.endTime - this.startTime;
  32885. }
  32886. };
  32887. Sampler.prototype.getData = function ( type, ndx, member ) {
  32888. var data;
  32889. if ( type === 'matrix' && this.strideOut === 16 ) {
  32890. data = this.output[ ndx ];
  32891. } else if ( this.strideOut > 1 ) {
  32892. data = [];
  32893. ndx *= this.strideOut;
  32894. for ( var i = 0; i < this.strideOut; ++ i ) {
  32895. data[ i ] = this.output[ ndx + i ];
  32896. }
  32897. if ( this.strideOut === 3 ) {
  32898. switch ( type ) {
  32899. case 'rotate':
  32900. case 'translate':
  32901. fixCoords( data, -1 );
  32902. break;
  32903. case 'scale':
  32904. fixCoords( data, 1 );
  32905. break;
  32906. }
  32907. } else if ( this.strideOut === 4 && type === 'matrix' ) {
  32908. fixCoords( data, -1 );
  32909. }
  32910. } else {
  32911. data = this.output[ ndx ];
  32912. if ( member && type === 'translate' ) {
  32913. data = getConvertedTranslation( member, data );
  32914. }
  32915. }
  32916. return data;
  32917. };
  32918. function Key ( time ) {
  32919. this.targets = [];
  32920. this.time = time;
  32921. }
  32922. Key.prototype.addTarget = function ( fullSid, transform, member, data ) {
  32923. this.targets.push( {
  32924. sid: fullSid,
  32925. member: member,
  32926. transform: transform,
  32927. data: data
  32928. } );
  32929. };
  32930. Key.prototype.apply = function ( opt_sid ) {
  32931. for ( var i = 0; i < this.targets.length; ++ i ) {
  32932. var target = this.targets[ i ];
  32933. if ( !opt_sid || target.sid === opt_sid ) {
  32934. target.transform.update( target.data, target.member );
  32935. }
  32936. }
  32937. };
  32938. Key.prototype.getTarget = function ( fullSid ) {
  32939. for ( var i = 0; i < this.targets.length; ++ i ) {
  32940. if ( this.targets[ i ].sid === fullSid ) {
  32941. return this.targets[ i ];
  32942. }
  32943. }
  32944. return null;
  32945. };
  32946. Key.prototype.hasTarget = function ( fullSid ) {
  32947. for ( var i = 0; i < this.targets.length; ++ i ) {
  32948. if ( this.targets[ i ].sid === fullSid ) {
  32949. return true;
  32950. }
  32951. }
  32952. return false;
  32953. };
  32954. // TODO: Currently only doing linear interpolation. Should support full COLLADA spec.
  32955. Key.prototype.interpolate = function ( nextKey, time ) {
  32956. for ( var i = 0, l = this.targets.length; i < l; i ++ ) {
  32957. var target = this.targets[ i ],
  32958. nextTarget = nextKey.getTarget( target.sid ),
  32959. data;
  32960. if ( target.transform.type !== 'matrix' && nextTarget ) {
  32961. var scale = ( time - this.time ) / ( nextKey.time - this.time ),
  32962. nextData = nextTarget.data,
  32963. prevData = target.data;
  32964. if ( scale < 0 ) scale = 0;
  32965. if ( scale > 1 ) scale = 1;
  32966. if ( prevData.length ) {
  32967. data = [];
  32968. for ( var j = 0; j < prevData.length; ++ j ) {
  32969. data[ j ] = prevData[ j ] + ( nextData[ j ] - prevData[ j ] ) * scale;
  32970. }
  32971. } else {
  32972. data = prevData + ( nextData - prevData ) * scale;
  32973. }
  32974. } else {
  32975. data = target.data;
  32976. }
  32977. target.transform.update( data, target.member );
  32978. }
  32979. };
  32980. // Camera
  32981. function Camera() {
  32982. this.id = "";
  32983. this.name = "";
  32984. this.technique = "";
  32985. }
  32986. Camera.prototype.parse = function ( element ) {
  32987. this.id = element.getAttribute( 'id' );
  32988. this.name = element.getAttribute( 'name' );
  32989. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32990. var child = element.childNodes[ i ];
  32991. if ( child.nodeType != 1 ) continue;
  32992. switch ( child.nodeName ) {
  32993. case 'optics':
  32994. this.parseOptics( child );
  32995. break;
  32996. default:
  32997. break;
  32998. }
  32999. }
  33000. return this;
  33001. };
  33002. Camera.prototype.parseOptics = function ( element ) {
  33003. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33004. if ( element.childNodes[ i ].nodeName === 'technique_common' ) {
  33005. var technique = element.childNodes[ i ];
  33006. for ( var j = 0; j < technique.childNodes.length; j ++ ) {
  33007. this.technique = technique.childNodes[ j ].nodeName;
  33008. if ( this.technique === 'perspective' ) {
  33009. var perspective = technique.childNodes[ j ];
  33010. for ( var k = 0; k < perspective.childNodes.length; k ++ ) {
  33011. var param = perspective.childNodes[ k ];
  33012. switch ( param.nodeName ) {
  33013. case 'yfov':
  33014. this.yfov = param.textContent;
  33015. break;
  33016. case 'xfov':
  33017. this.xfov = param.textContent;
  33018. break;
  33019. case 'znear':
  33020. this.znear = param.textContent;
  33021. break;
  33022. case 'zfar':
  33023. this.zfar = param.textContent;
  33024. break;
  33025. case 'aspect_ratio':
  33026. this.aspect_ratio = param.textContent;
  33027. break;
  33028. }
  33029. }
  33030. } else if ( this.technique === 'orthographic' ) {
  33031. var orthographic = technique.childNodes[ j ];
  33032. for ( var k = 0; k < orthographic.childNodes.length; k ++ ) {
  33033. var param = orthographic.childNodes[ k ];
  33034. switch ( param.nodeName ) {
  33035. case 'xmag':
  33036. this.xmag = param.textContent;
  33037. break;
  33038. case 'ymag':
  33039. this.ymag = param.textContent;
  33040. break;
  33041. case 'znear':
  33042. this.znear = param.textContent;
  33043. break;
  33044. case 'zfar':
  33045. this.zfar = param.textContent;
  33046. break;
  33047. case 'aspect_ratio':
  33048. this.aspect_ratio = param.textContent;
  33049. break;
  33050. }
  33051. }
  33052. }
  33053. }
  33054. }
  33055. }
  33056. return this;
  33057. };
  33058. function InstanceCamera() {
  33059. this.url = "";
  33060. }
  33061. InstanceCamera.prototype.parse = function ( element ) {
  33062. this.url = element.getAttribute('url').replace(/^#/, '');
  33063. return this;
  33064. };
  33065. // Light
  33066. function Light() {
  33067. this.id = "";
  33068. this.name = "";
  33069. this.technique = "";
  33070. }
  33071. Light.prototype.parse = function ( element ) {
  33072. this.id = element.getAttribute( 'id' );
  33073. this.name = element.getAttribute( 'name' );
  33074. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33075. var child = element.childNodes[ i ];
  33076. if ( child.nodeType != 1 ) continue;
  33077. switch ( child.nodeName ) {
  33078. case 'technique_common':
  33079. this.parseCommon( child );
  33080. break;
  33081. case 'technique':
  33082. this.parseTechnique( child );
  33083. break;
  33084. default:
  33085. break;
  33086. }
  33087. }
  33088. return this;
  33089. };
  33090. Light.prototype.parseCommon = function ( element ) {
  33091. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33092. switch ( element.childNodes[ i ].nodeName ) {
  33093. case 'directional':
  33094. case 'point':
  33095. case 'spot':
  33096. case 'ambient':
  33097. this.technique = element.childNodes[ i ].nodeName;
  33098. var light = element.childNodes[ i ];
  33099. for ( var j = 0; j < light.childNodes.length; j ++ ) {
  33100. var child = light.childNodes[j];
  33101. switch ( child.nodeName ) {
  33102. case 'color':
  33103. var rgba = _floats( child.textContent );
  33104. this.color = new THREE.Color(0);
  33105. this.color.setRGB( rgba[0], rgba[1], rgba[2] );
  33106. this.color.a = rgba[3];
  33107. break;
  33108. case 'falloff_angle':
  33109. this.falloff_angle = parseFloat( child.textContent );
  33110. break;
  33111. case 'quadratic_attenuation':
  33112. var f = parseFloat( child.textContent );
  33113. this.distance = f ? Math.sqrt( 1 / f ) : 0;
  33114. }
  33115. }
  33116. }
  33117. }
  33118. return this;
  33119. };
  33120. Light.prototype.parseTechnique = function ( element ) {
  33121. this.profile = element.getAttribute( 'profile' );
  33122. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33123. var child = element.childNodes[ i ];
  33124. switch ( child.nodeName ) {
  33125. case 'intensity':
  33126. this.intensity = parseFloat(child.textContent);
  33127. break;
  33128. }
  33129. }
  33130. return this;
  33131. };
  33132. function InstanceLight() {
  33133. this.url = "";
  33134. }
  33135. InstanceLight.prototype.parse = function ( element ) {
  33136. this.url = element.getAttribute('url').replace(/^#/, '');
  33137. return this;
  33138. };
  33139. function KinematicsModel( ) {
  33140. this.id = '';
  33141. this.name = '';
  33142. this.joints = [];
  33143. this.links = [];
  33144. }
  33145. KinematicsModel.prototype.parse = function( element ) {
  33146. this.id = element.getAttribute('id');
  33147. this.name = element.getAttribute('name');
  33148. this.joints = [];
  33149. this.links = [];
  33150. for (var i = 0; i < element.childNodes.length; i ++ ) {
  33151. var child = element.childNodes[ i ];
  33152. if ( child.nodeType != 1 ) continue;
  33153. switch ( child.nodeName ) {
  33154. case 'technique_common':
  33155. this.parseCommon(child);
  33156. break;
  33157. default:
  33158. break;
  33159. }
  33160. }
  33161. return this;
  33162. };
  33163. KinematicsModel.prototype.parseCommon = function( element ) {
  33164. for (var i = 0; i < element.childNodes.length; i ++ ) {
  33165. var child = element.childNodes[ i ];
  33166. if ( child.nodeType != 1 ) continue;
  33167. switch ( element.childNodes[ i ].nodeName ) {
  33168. case 'joint':
  33169. this.joints.push( (new Joint()).parse(child) );
  33170. break;
  33171. case 'link':
  33172. this.links.push( (new Link()).parse(child) );
  33173. break;
  33174. default:
  33175. break;
  33176. }
  33177. }
  33178. return this;
  33179. };
  33180. function Joint( ) {
  33181. this.sid = '';
  33182. this.name = '';
  33183. this.axis = new THREE.Vector3();
  33184. this.limits = {
  33185. min: 0,
  33186. max: 0
  33187. };
  33188. this.type = '';
  33189. this.static = false;
  33190. this.zeroPosition = 0.0;
  33191. this.middlePosition = 0.0;
  33192. }
  33193. Joint.prototype.parse = function( element ) {
  33194. this.sid = element.getAttribute('sid');
  33195. this.name = element.getAttribute('name');
  33196. this.axis = new THREE.Vector3();
  33197. this.limits = {
  33198. min: 0,
  33199. max: 0
  33200. };
  33201. this.type = '';
  33202. this.static = false;
  33203. this.zeroPosition = 0.0;
  33204. this.middlePosition = 0.0;
  33205. var axisElement = element.querySelector('axis');
  33206. var _axis = _floats(axisElement.textContent);
  33207. this.axis = getConvertedVec3(_axis, 0);
  33208. var min = element.querySelector('limits min') ? parseFloat(element.querySelector('limits min').textContent) : -360;
  33209. var max = element.querySelector('limits max') ? parseFloat(element.querySelector('limits max').textContent) : 360;
  33210. this.limits = {
  33211. min: min,
  33212. max: max
  33213. };
  33214. var jointTypes = [ 'prismatic', 'revolute' ];
  33215. for (var i = 0; i < jointTypes.length; i ++ ) {
  33216. var type = jointTypes[ i ];
  33217. var jointElement = element.querySelector(type);
  33218. if ( jointElement ) {
  33219. this.type = type;
  33220. }
  33221. }
  33222. // if the min is equal to or somehow greater than the max, consider the joint static
  33223. if ( this.limits.min >= this.limits.max ) {
  33224. this.static = true;
  33225. }
  33226. this.middlePosition = (this.limits.min + this.limits.max) / 2.0;
  33227. return this;
  33228. };
  33229. function Link( ) {
  33230. this.sid = '';
  33231. this.name = '';
  33232. this.transforms = [];
  33233. this.attachments = [];
  33234. }
  33235. Link.prototype.parse = function( element ) {
  33236. this.sid = element.getAttribute('sid');
  33237. this.name = element.getAttribute('name');
  33238. this.transforms = [];
  33239. this.attachments = [];
  33240. for (var i = 0; i < element.childNodes.length; i ++ ) {
  33241. var child = element.childNodes[ i ];
  33242. if ( child.nodeType != 1 ) continue;
  33243. switch ( child.nodeName ) {
  33244. case 'attachment_full':
  33245. this.attachments.push( (new Attachment()).parse(child) );
  33246. break;
  33247. case 'rotate':
  33248. case 'translate':
  33249. case 'matrix':
  33250. this.transforms.push( (new Transform()).parse(child) );
  33251. break;
  33252. default:
  33253. break;
  33254. }
  33255. }
  33256. return this;
  33257. };
  33258. function Attachment( ) {
  33259. this.joint = '';
  33260. this.transforms = [];
  33261. this.links = [];
  33262. }
  33263. Attachment.prototype.parse = function( element ) {
  33264. this.joint = element.getAttribute('joint').split('/').pop();
  33265. this.links = [];
  33266. for (var i = 0; i < element.childNodes.length; i ++ ) {
  33267. var child = element.childNodes[ i ];
  33268. if ( child.nodeType != 1 ) continue;
  33269. switch ( child.nodeName ) {
  33270. case 'link':
  33271. this.links.push( (new Link()).parse(child) );
  33272. break;
  33273. case 'rotate':
  33274. case 'translate':
  33275. case 'matrix':
  33276. this.transforms.push( (new Transform()).parse(child) );
  33277. break;
  33278. default:
  33279. break;
  33280. }
  33281. }
  33282. return this;
  33283. };
  33284. function _source( element ) {
  33285. var id = element.getAttribute( 'id' );
  33286. if ( sources[ id ] != undefined ) {
  33287. return sources[ id ];
  33288. }
  33289. sources[ id ] = ( new Source(id )).parse( element );
  33290. return sources[ id ];
  33291. }
  33292. function _nsResolver( nsPrefix ) {
  33293. if ( nsPrefix === "dae" ) {
  33294. return "http://www.collada.org/2005/11/COLLADASchema";
  33295. }
  33296. return null;
  33297. }
  33298. function _bools( str ) {
  33299. var raw = _strings( str );
  33300. var data = [];
  33301. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  33302. data.push( (raw[i] === 'true' || raw[i] === '1') ? true : false );
  33303. }
  33304. return data;
  33305. }
  33306. function _floats( str ) {
  33307. var raw = _strings(str);
  33308. var data = [];
  33309. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  33310. data.push( parseFloat( raw[ i ] ) );
  33311. }
  33312. return data;
  33313. }
  33314. function _ints( str ) {
  33315. var raw = _strings( str );
  33316. var data = [];
  33317. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  33318. data.push( parseInt( raw[ i ], 10 ) );
  33319. }
  33320. return data;
  33321. }
  33322. function _strings( str ) {
  33323. return ( str.length > 0 ) ? _trimString( str ).split( /\s+/ ) : [];
  33324. }
  33325. function _trimString( str ) {
  33326. return str.replace( /^\s+/, "" ).replace( /\s+$/, "" );
  33327. }
  33328. function _attr_as_float( element, name, defaultValue ) {
  33329. if ( element.hasAttribute( name ) ) {
  33330. return parseFloat( element.getAttribute( name ) );
  33331. } else {
  33332. return defaultValue;
  33333. }
  33334. }
  33335. function _attr_as_int( element, name, defaultValue ) {
  33336. if ( element.hasAttribute( name ) ) {
  33337. return parseInt( element.getAttribute( name ), 10) ;
  33338. } else {
  33339. return defaultValue;
  33340. }
  33341. }
  33342. function _attr_as_string( element, name, defaultValue ) {
  33343. if ( element.hasAttribute( name ) ) {
  33344. return element.getAttribute( name );
  33345. } else {
  33346. return defaultValue;
  33347. }
  33348. }
  33349. function _format_float( f, num ) {
  33350. if ( f === undefined ) {
  33351. var s = '0.';
  33352. while ( s.length < num + 2 ) {
  33353. s += '0';
  33354. }
  33355. return s;
  33356. }
  33357. num = num || 2;
  33358. var parts = f.toString().split( '.' );
  33359. parts[ 1 ] = parts.length > 1 ? parts[ 1 ].substr( 0, num ) : "0";
  33360. while ( parts[ 1 ].length < num ) {
  33361. parts[ 1 ] += '0';
  33362. }
  33363. return parts.join( '.' );
  33364. }
  33365. function loadTextureImage ( texture, url ) {
  33366. var loader = new THREE.ImageLoader();
  33367. loader.load( url, function ( image ) {
  33368. texture.image = image;
  33369. texture.needsUpdate = true;
  33370. } );
  33371. }
  33372. function extractDoubleSided( obj, element ) {
  33373. obj.doubleSided = false;
  33374. var node = element.querySelectorAll('extra double_sided')[0];
  33375. if ( node ) {
  33376. if ( node && parseInt( node.textContent, 10 ) === 1 ) {
  33377. obj.doubleSided = true;
  33378. }
  33379. }
  33380. }
  33381. // Up axis conversion
  33382. function setUpConversion() {
  33383. if ( options.convertUpAxis !== true || colladaUp === options.upAxis ) {
  33384. upConversion = null;
  33385. } else {
  33386. switch ( colladaUp ) {
  33387. case 'X':
  33388. upConversion = options.upAxis === 'Y' ? 'XtoY' : 'XtoZ';
  33389. break;
  33390. case 'Y':
  33391. upConversion = options.upAxis === 'X' ? 'YtoX' : 'YtoZ';
  33392. break;
  33393. case 'Z':
  33394. upConversion = options.upAxis === 'X' ? 'ZtoX' : 'ZtoY';
  33395. break;
  33396. }
  33397. }
  33398. }
  33399. function fixCoords( data, sign ) {
  33400. if ( options.convertUpAxis !== true || colladaUp === options.upAxis ) {
  33401. return;
  33402. }
  33403. switch ( upConversion ) {
  33404. case 'XtoY':
  33405. var tmp = data[ 0 ];
  33406. data[ 0 ] = sign * data[ 1 ];
  33407. data[ 1 ] = tmp;
  33408. break;
  33409. case 'XtoZ':
  33410. var tmp = data[ 2 ];
  33411. data[ 2 ] = data[ 1 ];
  33412. data[ 1 ] = data[ 0 ];
  33413. data[ 0 ] = tmp;
  33414. break;
  33415. case 'YtoX':
  33416. var tmp = data[ 0 ];
  33417. data[ 0 ] = data[ 1 ];
  33418. data[ 1 ] = sign * tmp;
  33419. break;
  33420. case 'YtoZ':
  33421. var tmp = data[ 1 ];
  33422. data[ 1 ] = sign * data[ 2 ];
  33423. data[ 2 ] = tmp;
  33424. break;
  33425. case 'ZtoX':
  33426. var tmp = data[ 0 ];
  33427. data[ 0 ] = data[ 1 ];
  33428. data[ 1 ] = data[ 2 ];
  33429. data[ 2 ] = tmp;
  33430. break;
  33431. case 'ZtoY':
  33432. var tmp = data[ 1 ];
  33433. data[ 1 ] = data[ 2 ];
  33434. data[ 2 ] = sign * tmp;
  33435. break;
  33436. }
  33437. }
  33438. function getConvertedTranslation( axis, data ) {
  33439. if ( options.convertUpAxis !== true || colladaUp === options.upAxis ) {
  33440. return data;
  33441. }
  33442. switch ( axis ) {
  33443. case 'X':
  33444. data = upConversion === 'XtoY' ? data * -1 : data;
  33445. break;
  33446. case 'Y':
  33447. data = upConversion === 'YtoZ' || upConversion === 'YtoX' ? data * -1 : data;
  33448. break;
  33449. case 'Z':
  33450. data = upConversion === 'ZtoY' ? data * -1 : data ;
  33451. break;
  33452. default:
  33453. break;
  33454. }
  33455. return data;
  33456. }
  33457. function getConvertedVec3( data, offset ) {
  33458. var arr = [ data[ offset ], data[ offset + 1 ], data[ offset + 2 ] ];
  33459. fixCoords( arr, -1 );
  33460. return new THREE.Vector3( arr[ 0 ], arr[ 1 ], arr[ 2 ] );
  33461. }
  33462. function getConvertedMat4( data ) {
  33463. if ( options.convertUpAxis ) {
  33464. // First fix rotation and scale
  33465. // Columns first
  33466. var arr = [ data[ 0 ], data[ 4 ], data[ 8 ] ];
  33467. fixCoords( arr, -1 );
  33468. data[ 0 ] = arr[ 0 ];
  33469. data[ 4 ] = arr[ 1 ];
  33470. data[ 8 ] = arr[ 2 ];
  33471. arr = [ data[ 1 ], data[ 5 ], data[ 9 ] ];
  33472. fixCoords( arr, -1 );
  33473. data[ 1 ] = arr[ 0 ];
  33474. data[ 5 ] = arr[ 1 ];
  33475. data[ 9 ] = arr[ 2 ];
  33476. arr = [ data[ 2 ], data[ 6 ], data[ 10 ] ];
  33477. fixCoords( arr, -1 );
  33478. data[ 2 ] = arr[ 0 ];
  33479. data[ 6 ] = arr[ 1 ];
  33480. data[ 10 ] = arr[ 2 ];
  33481. // Rows second
  33482. arr = [ data[ 0 ], data[ 1 ], data[ 2 ] ];
  33483. fixCoords( arr, -1 );
  33484. data[ 0 ] = arr[ 0 ];
  33485. data[ 1 ] = arr[ 1 ];
  33486. data[ 2 ] = arr[ 2 ];
  33487. arr = [ data[ 4 ], data[ 5 ], data[ 6 ] ];
  33488. fixCoords( arr, -1 );
  33489. data[ 4 ] = arr[ 0 ];
  33490. data[ 5 ] = arr[ 1 ];
  33491. data[ 6 ] = arr[ 2 ];
  33492. arr = [ data[ 8 ], data[ 9 ], data[ 10 ] ];
  33493. fixCoords( arr, -1 );
  33494. data[ 8 ] = arr[ 0 ];
  33495. data[ 9 ] = arr[ 1 ];
  33496. data[ 10 ] = arr[ 2 ];
  33497. // Now fix translation
  33498. arr = [ data[ 3 ], data[ 7 ], data[ 11 ] ];
  33499. fixCoords( arr, -1 );
  33500. data[ 3 ] = arr[ 0 ];
  33501. data[ 7 ] = arr[ 1 ];
  33502. data[ 11 ] = arr[ 2 ];
  33503. }
  33504. return new THREE.Matrix4().set(
  33505. data[0], data[1], data[2], data[3],
  33506. data[4], data[5], data[6], data[7],
  33507. data[8], data[9], data[10], data[11],
  33508. data[12], data[13], data[14], data[15]
  33509. );
  33510. }
  33511. function getConvertedIndex( index ) {
  33512. if ( index > -1 && index < 3 ) {
  33513. var members = [ 'X', 'Y', 'Z' ],
  33514. indices = { X: 0, Y: 1, Z: 2 };
  33515. index = getConvertedMember( members[ index ] );
  33516. index = indices[ index ];
  33517. }
  33518. return index;
  33519. }
  33520. function getConvertedMember( member ) {
  33521. if ( options.convertUpAxis ) {
  33522. switch ( member ) {
  33523. case 'X':
  33524. switch ( upConversion ) {
  33525. case 'XtoY':
  33526. case 'XtoZ':
  33527. case 'YtoX':
  33528. member = 'Y';
  33529. break;
  33530. case 'ZtoX':
  33531. member = 'Z';
  33532. break;
  33533. }
  33534. break;
  33535. case 'Y':
  33536. switch ( upConversion ) {
  33537. case 'XtoY':
  33538. case 'YtoX':
  33539. case 'ZtoX':
  33540. member = 'X';
  33541. break;
  33542. case 'XtoZ':
  33543. case 'YtoZ':
  33544. case 'ZtoY':
  33545. member = 'Z';
  33546. break;
  33547. }
  33548. break;
  33549. case 'Z':
  33550. switch ( upConversion ) {
  33551. case 'XtoZ':
  33552. member = 'X';
  33553. break;
  33554. case 'YtoZ':
  33555. case 'ZtoX':
  33556. case 'ZtoY':
  33557. member = 'Y';
  33558. break;
  33559. }
  33560. break;
  33561. }
  33562. }
  33563. return member;
  33564. }
  33565. return {
  33566. load: load,
  33567. parse: parse,
  33568. setPreferredShading: setPreferredShading,
  33569. applySkin: applySkin,
  33570. geometries : geometries,
  33571. options: options
  33572. };
  33573. };
  33574. },{}],44:[function(_dereq_,module,exports){
  33575. /**
  33576. * @author Rich Tibbett / https://github.com/richtr
  33577. * @author mrdoob / http://mrdoob.com/
  33578. * @author Tony Parisi / http://www.tonyparisi.com/
  33579. * @author Takahiro / https://github.com/takahirox
  33580. */
  33581. THREE.GLTFLoader = ( function () {
  33582. function GLTFLoader( manager ) {
  33583. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  33584. }
  33585. GLTFLoader.prototype = {
  33586. constructor: GLTFLoader,
  33587. load: function ( url, onLoad, onProgress, onError ) {
  33588. var scope = this;
  33589. var path = this.path && ( typeof this.path === "string" ) ? this.path : THREE.Loader.prototype.extractUrlBase( url );
  33590. var loader = new THREE.FileLoader( scope.manager );
  33591. loader.setResponseType( 'arraybuffer' );
  33592. loader.load( url, function ( data ) {
  33593. scope.parse( data, onLoad, path );
  33594. }, onProgress, onError );
  33595. },
  33596. setCrossOrigin: function ( value ) {
  33597. this.crossOrigin = value;
  33598. },
  33599. setPath: function ( value ) {
  33600. this.path = value;
  33601. },
  33602. parse: function ( data, callback, path ) {
  33603. var content;
  33604. var extensions = {};
  33605. var magic = convertUint8ArrayToString( new Uint8Array( data, 0, 4 ) );
  33606. if ( magic === BINARY_EXTENSION_HEADER_DEFAULTS.magic ) {
  33607. extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
  33608. content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content;
  33609. } else {
  33610. content = convertUint8ArrayToString( new Uint8Array( data ) );
  33611. }
  33612. var json = JSON.parse( content );
  33613. if ( json.extensionsUsed && json.extensionsUsed.indexOf( EXTENSIONS.KHR_MATERIALS_COMMON ) >= 0 ) {
  33614. extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ] = new GLTFMaterialsCommonExtension( json );
  33615. }
  33616. console.time( 'GLTFLoader' );
  33617. var parser = new GLTFParser( json, extensions, {
  33618. path: path || this.path,
  33619. crossOrigin: this.crossOrigin
  33620. } );
  33621. parser.parse( function ( scene, scenes, cameras, animations ) {
  33622. console.timeEnd( 'GLTFLoader' );
  33623. var glTF = {
  33624. "scene": scene,
  33625. "scenes": scenes,
  33626. "cameras": cameras,
  33627. "animations": animations
  33628. };
  33629. callback( glTF );
  33630. } );
  33631. }
  33632. };
  33633. /* GLTFREGISTRY */
  33634. function GLTFRegistry() {
  33635. var objects = {};
  33636. return {
  33637. get: function ( key ) {
  33638. return objects[ key ];
  33639. },
  33640. add: function ( key, object ) {
  33641. objects[ key ] = object;
  33642. },
  33643. remove: function ( key ) {
  33644. delete objects[ key ];
  33645. },
  33646. removeAll: function () {
  33647. objects = {};
  33648. },
  33649. update: function ( scene, camera ) {
  33650. // update scene graph
  33651. scene.updateMatrixWorld();
  33652. // update camera matrices and frustum
  33653. camera.updateMatrixWorld();
  33654. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  33655. for ( var name in objects ) {
  33656. var object = objects[ name ];
  33657. if ( object.update ) {
  33658. object.update( scene, camera );
  33659. }
  33660. }
  33661. }
  33662. };
  33663. }
  33664. /* GLTFSHADERS */
  33665. GLTFLoader.Shaders = new GLTFRegistry();
  33666. /* GLTFSHADER */
  33667. function GLTFShader( targetNode, allNodes ) {
  33668. var boundUniforms = {};
  33669. // bind each uniform to its source node
  33670. var uniforms = targetNode.material.uniforms;
  33671. for ( var uniformId in uniforms ) {
  33672. var uniform = uniforms[ uniformId ];
  33673. if ( uniform.semantic ) {
  33674. var sourceNodeRef = uniform.node;
  33675. var sourceNode = targetNode;
  33676. if ( sourceNodeRef ) {
  33677. sourceNode = allNodes[ sourceNodeRef ];
  33678. }
  33679. boundUniforms[ uniformId ] = {
  33680. semantic: uniform.semantic,
  33681. sourceNode: sourceNode,
  33682. targetNode: targetNode,
  33683. uniform: uniform
  33684. };
  33685. }
  33686. }
  33687. this.boundUniforms = boundUniforms;
  33688. this._m4 = new THREE.Matrix4();
  33689. }
  33690. // Update - update all the uniform values
  33691. GLTFShader.prototype.update = function ( scene, camera ) {
  33692. var boundUniforms = this.boundUniforms;
  33693. for ( var name in boundUniforms ) {
  33694. var boundUniform = boundUniforms[ name ];
  33695. switch ( boundUniform.semantic ) {
  33696. case "MODELVIEW":
  33697. var m4 = boundUniform.uniform.value;
  33698. m4.multiplyMatrices( camera.matrixWorldInverse, boundUniform.sourceNode.matrixWorld );
  33699. break;
  33700. case "MODELVIEWINVERSETRANSPOSE":
  33701. var m3 = boundUniform.uniform.value;
  33702. this._m4.multiplyMatrices( camera.matrixWorldInverse, boundUniform.sourceNode.matrixWorld );
  33703. m3.getNormalMatrix( this._m4 );
  33704. break;
  33705. case "PROJECTION":
  33706. var m4 = boundUniform.uniform.value;
  33707. m4.copy( camera.projectionMatrix );
  33708. break;
  33709. case "JOINTMATRIX":
  33710. var m4v = boundUniform.uniform.value;
  33711. for ( var mi = 0; mi < m4v.length; mi ++ ) {
  33712. // So it goes like this:
  33713. // SkinnedMesh world matrix is already baked into MODELVIEW;
  33714. // transform joints to local space,
  33715. // then transform using joint's inverse
  33716. m4v[ mi ]
  33717. .getInverse( boundUniform.sourceNode.matrixWorld )
  33718. .multiply( boundUniform.targetNode.skeleton.bones[ mi ].matrixWorld )
  33719. .multiply( boundUniform.targetNode.skeleton.boneInverses[ mi ] )
  33720. .multiply( boundUniform.targetNode.bindMatrix );
  33721. }
  33722. break;
  33723. default :
  33724. console.warn( "Unhandled shader semantic: " + boundUniform.semantic );
  33725. break;
  33726. }
  33727. }
  33728. };
  33729. /* ANIMATION */
  33730. GLTFLoader.Animations = {
  33731. update: function () {
  33732. console.warn( 'THREE.GLTFLoader.Animation has been deprecated. Use THREE.AnimationMixer instead.' );
  33733. }
  33734. };
  33735. /*********************************/
  33736. /********** EXTENSIONS ***********/
  33737. /*********************************/
  33738. var EXTENSIONS = {
  33739. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  33740. KHR_MATERIALS_COMMON: 'KHR_materials_common'
  33741. };
  33742. /* MATERIALS COMMON EXTENSION */
  33743. function GLTFMaterialsCommonExtension( json ) {
  33744. this.name = EXTENSIONS.KHR_MATERIALS_COMMON;
  33745. this.lights = {};
  33746. var lights = json.extensions && json.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ].lights;
  33747. for ( var lightId in lights ) {
  33748. var light = lights[ lightId ];
  33749. var lightNode;
  33750. var lightParams = light[ light.type ];
  33751. var color = new THREE.Color().fromArray( lightParams.color );
  33752. switch ( light.type ) {
  33753. case "directional":
  33754. lightNode = new THREE.DirectionalLight( color );
  33755. lightNode.position.set( 0, 0, 1 );
  33756. break;
  33757. case "point":
  33758. lightNode = new THREE.PointLight( color );
  33759. break;
  33760. case "spot":
  33761. lightNode = new THREE.SpotLight( color );
  33762. lightNode.position.set( 0, 0, 1 );
  33763. break;
  33764. case "ambient":
  33765. lightNode = new THREE.AmbientLight( color );
  33766. break;
  33767. }
  33768. if ( lightNode ) {
  33769. this.lights[ lightId ] = lightNode;
  33770. }
  33771. }
  33772. }
  33773. /* BINARY EXTENSION */
  33774. var BINARY_EXTENSION_BUFFER_NAME = 'binary_glTF';
  33775. var BINARY_EXTENSION_HEADER_DEFAULTS = { magic: 'glTF', version: 1, contentFormat: 0 };
  33776. var BINARY_EXTENSION_HEADER_LENGTH = 20;
  33777. function GLTFBinaryExtension( data ) {
  33778. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  33779. var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
  33780. var header = {
  33781. magic: convertUint8ArrayToString( new Uint8Array( data.slice( 0, 4 ) ) ),
  33782. version: headerView.getUint32( 4, true ),
  33783. length: headerView.getUint32( 8, true ),
  33784. contentLength: headerView.getUint32( 12, true ),
  33785. contentFormat: headerView.getUint32( 16, true )
  33786. };
  33787. for ( var key in BINARY_EXTENSION_HEADER_DEFAULTS ) {
  33788. var value = BINARY_EXTENSION_HEADER_DEFAULTS[ key ];
  33789. if ( header[ key ] !== value ) {
  33790. throw new Error( 'Unsupported glTF-Binary header: Expected "%s" to be "%s".', key, value );
  33791. }
  33792. }
  33793. var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH, header.contentLength );
  33794. this.header = header;
  33795. this.content = convertUint8ArrayToString( contentArray );
  33796. this.body = data.slice( BINARY_EXTENSION_HEADER_LENGTH + header.contentLength, header.length );
  33797. }
  33798. GLTFBinaryExtension.prototype.loadShader = function ( shader, bufferViews ) {
  33799. var bufferView = bufferViews[ shader.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].bufferView ];
  33800. var array = new Uint8Array( bufferView );
  33801. return convertUint8ArrayToString( array );
  33802. };
  33803. GLTFBinaryExtension.prototype.loadTextureSourceUri = function ( source, bufferViews ) {
  33804. var metadata = source.extensions[ EXTENSIONS.KHR_BINARY_GLTF ];
  33805. var bufferView = bufferViews[ metadata.bufferView ];
  33806. var stringData = convertUint8ArrayToString( new Uint8Array( bufferView ) );
  33807. return 'data:' + metadata.mimeType + ';base64,' + btoa( stringData );
  33808. };
  33809. /*********************************/
  33810. /********** INTERNALS ************/
  33811. /*********************************/
  33812. /* CONSTANTS */
  33813. var WEBGL_CONSTANTS = {
  33814. FLOAT: 5126,
  33815. //FLOAT_MAT2: 35674,
  33816. FLOAT_MAT3: 35675,
  33817. FLOAT_MAT4: 35676,
  33818. FLOAT_VEC2: 35664,
  33819. FLOAT_VEC3: 35665,
  33820. FLOAT_VEC4: 35666,
  33821. LINEAR: 9729,
  33822. REPEAT: 10497,
  33823. SAMPLER_2D: 35678,
  33824. TRIANGLES: 4,
  33825. LINES: 1,
  33826. UNSIGNED_BYTE: 5121,
  33827. UNSIGNED_SHORT: 5123,
  33828. VERTEX_SHADER: 35633,
  33829. FRAGMENT_SHADER: 35632
  33830. };
  33831. var WEBGL_TYPE = {
  33832. 5126: Number,
  33833. //35674: THREE.Matrix2,
  33834. 35675: THREE.Matrix3,
  33835. 35676: THREE.Matrix4,
  33836. 35664: THREE.Vector2,
  33837. 35665: THREE.Vector3,
  33838. 35666: THREE.Vector4,
  33839. 35678: THREE.Texture
  33840. };
  33841. var WEBGL_COMPONENT_TYPES = {
  33842. 5120: Int8Array,
  33843. 5121: Uint8Array,
  33844. 5122: Int16Array,
  33845. 5123: Uint16Array,
  33846. 5125: Uint32Array,
  33847. 5126: Float32Array
  33848. };
  33849. var WEBGL_FILTERS = {
  33850. 9728: THREE.NearestFilter,
  33851. 9729: THREE.LinearFilter,
  33852. 9984: THREE.NearestMipMapNearestFilter,
  33853. 9985: THREE.LinearMipMapNearestFilter,
  33854. 9986: THREE.NearestMipMapLinearFilter,
  33855. 9987: THREE.LinearMipMapLinearFilter
  33856. };
  33857. var WEBGL_WRAPPINGS = {
  33858. 33071: THREE.ClampToEdgeWrapping,
  33859. 33648: THREE.MirroredRepeatWrapping,
  33860. 10497: THREE.RepeatWrapping
  33861. };
  33862. var WEBGL_TEXTURE_FORMATS = {
  33863. 6406: THREE.AlphaFormat,
  33864. 6407: THREE.RGBFormat,
  33865. 6408: THREE.RGBAFormat,
  33866. 6409: THREE.LuminanceFormat,
  33867. 6410: THREE.LuminanceAlphaFormat
  33868. };
  33869. var WEBGL_TEXTURE_DATATYPES = {
  33870. 5121: THREE.UnsignedByteType,
  33871. 32819: THREE.UnsignedShort4444Type,
  33872. 32820: THREE.UnsignedShort5551Type,
  33873. 33635: THREE.UnsignedShort565Type
  33874. };
  33875. var WEBGL_SIDES = {
  33876. 1028: THREE.BackSide, // Culling front
  33877. 1029: THREE.FrontSide // Culling back
  33878. //1032: THREE.NoSide // Culling front and back, what to do?
  33879. };
  33880. var WEBGL_DEPTH_FUNCS = {
  33881. 512: THREE.NeverDepth,
  33882. 513: THREE.LessDepth,
  33883. 514: THREE.EqualDepth,
  33884. 515: THREE.LessEqualDepth,
  33885. 516: THREE.GreaterEqualDepth,
  33886. 517: THREE.NotEqualDepth,
  33887. 518: THREE.GreaterEqualDepth,
  33888. 519: THREE.AlwaysDepth
  33889. };
  33890. var WEBGL_BLEND_EQUATIONS = {
  33891. 32774: THREE.AddEquation,
  33892. 32778: THREE.SubtractEquation,
  33893. 32779: THREE.ReverseSubtractEquation
  33894. };
  33895. var WEBGL_BLEND_FUNCS = {
  33896. 0: THREE.ZeroFactor,
  33897. 1: THREE.OneFactor,
  33898. 768: THREE.SrcColorFactor,
  33899. 769: THREE.OneMinusSrcColorFactor,
  33900. 770: THREE.SrcAlphaFactor,
  33901. 771: THREE.OneMinusSrcAlphaFactor,
  33902. 772: THREE.DstAlphaFactor,
  33903. 773: THREE.OneMinusDstAlphaFactor,
  33904. 774: THREE.DstColorFactor,
  33905. 775: THREE.OneMinusDstColorFactor,
  33906. 776: THREE.SrcAlphaSaturateFactor
  33907. // The followings are not supported by Three.js yet
  33908. //32769: CONSTANT_COLOR,
  33909. //32770: ONE_MINUS_CONSTANT_COLOR,
  33910. //32771: CONSTANT_ALPHA,
  33911. //32772: ONE_MINUS_CONSTANT_COLOR
  33912. };
  33913. var WEBGL_TYPE_SIZES = {
  33914. 'SCALAR': 1,
  33915. 'VEC2': 2,
  33916. 'VEC3': 3,
  33917. 'VEC4': 4,
  33918. 'MAT2': 4,
  33919. 'MAT3': 9,
  33920. 'MAT4': 16
  33921. };
  33922. var PATH_PROPERTIES = {
  33923. scale: 'scale',
  33924. translation: 'position',
  33925. rotation: 'quaternion'
  33926. };
  33927. var INTERPOLATION = {
  33928. LINEAR: THREE.InterpolateLinear,
  33929. STEP: THREE.InterpolateDiscrete
  33930. };
  33931. var STATES_ENABLES = {
  33932. 2884: 'CULL_FACE',
  33933. 2929: 'DEPTH_TEST',
  33934. 3042: 'BLEND',
  33935. 3089: 'SCISSOR_TEST',
  33936. 32823: 'POLYGON_OFFSET_FILL',
  33937. 32926: 'SAMPLE_ALPHA_TO_COVERAGE'
  33938. };
  33939. /* UTILITY FUNCTIONS */
  33940. function _each( object, callback, thisObj ) {
  33941. if ( !object ) {
  33942. return Promise.resolve();
  33943. }
  33944. var results;
  33945. var fns = [];
  33946. if ( Object.prototype.toString.call( object ) === '[object Array]' ) {
  33947. results = [];
  33948. var length = object.length;
  33949. for ( var idx = 0; idx < length; idx ++ ) {
  33950. var value = callback.call( thisObj || this, object[ idx ], idx );
  33951. if ( value ) {
  33952. fns.push( value );
  33953. if ( value instanceof Promise ) {
  33954. value.then( function( key, value ) {
  33955. results[ idx ] = value;
  33956. }.bind( this, key ));
  33957. } else {
  33958. results[ idx ] = value;
  33959. }
  33960. }
  33961. }
  33962. } else {
  33963. results = {};
  33964. for ( var key in object ) {
  33965. if ( object.hasOwnProperty( key ) ) {
  33966. var value = callback.call( thisObj || this, object[ key ], key );
  33967. if ( value ) {
  33968. fns.push( value );
  33969. if ( value instanceof Promise ) {
  33970. value.then( function( key, value ) {
  33971. results[ key ] = value;
  33972. }.bind( this, key ));
  33973. } else {
  33974. results[ key ] = value;
  33975. }
  33976. }
  33977. }
  33978. }
  33979. }
  33980. return Promise.all( fns ).then( function() {
  33981. return results;
  33982. });
  33983. }
  33984. function resolveURL( url, path ) {
  33985. // Invalid URL
  33986. if ( typeof url !== 'string' || url === '' )
  33987. return '';
  33988. // Absolute URL
  33989. if ( /^https?:\/\//i.test( url ) ) {
  33990. return url;
  33991. }
  33992. // Data URI
  33993. if ( /^data:.*,.*$/i.test( url ) ) {
  33994. return url;
  33995. }
  33996. // Relative URL
  33997. return ( path || '' ) + url;
  33998. }
  33999. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  34000. // throws a "maximum call stack size exceeded" error for large arrays.
  34001. function convertUint8ArrayToString( array ) {
  34002. var s = '';
  34003. for ( var i = 0; i < array.length; i ++ ) {
  34004. s += String.fromCharCode( array[ i ] );
  34005. }
  34006. return s;
  34007. }
  34008. // Three.js seems too dependent on attribute names so globally
  34009. // replace those in the shader code
  34010. function replaceTHREEShaderAttributes( shaderText, technique ) {
  34011. // Expected technique attributes
  34012. var attributes = {};
  34013. for ( var attributeId in technique.attributes ) {
  34014. var pname = technique.attributes[ attributeId ];
  34015. var param = technique.parameters[ pname ];
  34016. var atype = param.type;
  34017. var semantic = param.semantic;
  34018. attributes[ attributeId ] = {
  34019. type: atype,
  34020. semantic: semantic
  34021. };
  34022. }
  34023. // Figure out which attributes to change in technique
  34024. var shaderParams = technique.parameters;
  34025. var shaderAttributes = technique.attributes;
  34026. var params = {};
  34027. for ( var attributeId in attributes ) {
  34028. var pname = shaderAttributes[ attributeId ];
  34029. var shaderParam = shaderParams[ pname ];
  34030. var semantic = shaderParam.semantic;
  34031. if ( semantic ) {
  34032. params[ attributeId ] = shaderParam;
  34033. }
  34034. }
  34035. for ( var pname in params ) {
  34036. var param = params[ pname ];
  34037. var semantic = param.semantic;
  34038. var regEx = new RegExp( "\\b" + pname + "\\b", "g" );
  34039. switch ( semantic ) {
  34040. case "POSITION":
  34041. shaderText = shaderText.replace( regEx, 'position' );
  34042. break;
  34043. case "NORMAL":
  34044. shaderText = shaderText.replace( regEx, 'normal' );
  34045. break;
  34046. case 'TEXCOORD_0':
  34047. case 'TEXCOORD0':
  34048. case 'TEXCOORD':
  34049. shaderText = shaderText.replace( regEx, 'uv' );
  34050. break;
  34051. case 'COLOR_0':
  34052. case 'COLOR0':
  34053. case 'COLOR':
  34054. shaderText = shaderText.replace( regEx, 'color' );
  34055. break;
  34056. case "WEIGHT":
  34057. shaderText = shaderText.replace( regEx, 'skinWeight' );
  34058. break;
  34059. case "JOINT":
  34060. shaderText = shaderText.replace( regEx, 'skinIndex' );
  34061. break;
  34062. }
  34063. }
  34064. return shaderText;
  34065. }
  34066. function createDefaultMaterial() {
  34067. return new THREE.MeshPhongMaterial( {
  34068. color: 0x00000,
  34069. emissive: 0x888888,
  34070. specular: 0x000000,
  34071. shininess: 0,
  34072. transparent: false,
  34073. depthTest: true,
  34074. side: THREE.FrontSide
  34075. } );
  34076. }
  34077. // Deferred constructor for RawShaderMaterial types
  34078. function DeferredShaderMaterial( params ) {
  34079. this.isDeferredShaderMaterial = true;
  34080. this.params = params;
  34081. }
  34082. DeferredShaderMaterial.prototype.create = function () {
  34083. var uniforms = THREE.UniformsUtils.clone( this.params.uniforms );
  34084. for ( var uniformId in this.params.uniforms ) {
  34085. var originalUniform = this.params.uniforms[ uniformId ];
  34086. if ( originalUniform.value instanceof THREE.Texture ) {
  34087. uniforms[ uniformId ].value = originalUniform.value;
  34088. uniforms[ uniformId ].value.needsUpdate = true;
  34089. }
  34090. uniforms[ uniformId ].semantic = originalUniform.semantic;
  34091. uniforms[ uniformId ].node = originalUniform.node;
  34092. }
  34093. this.params.uniforms = uniforms;
  34094. return new THREE.RawShaderMaterial( this.params );
  34095. };
  34096. /* GLTF PARSER */
  34097. function GLTFParser( json, extensions, options ) {
  34098. this.json = json || {};
  34099. this.extensions = extensions || {};
  34100. this.options = options || {};
  34101. // loader object cache
  34102. this.cache = new GLTFRegistry();
  34103. }
  34104. GLTFParser.prototype._withDependencies = function ( dependencies ) {
  34105. var _dependencies = {};
  34106. for ( var i = 0; i < dependencies.length; i ++ ) {
  34107. var dependency = dependencies[ i ];
  34108. var fnName = "load" + dependency.charAt( 0 ).toUpperCase() + dependency.slice( 1 );
  34109. var cached = this.cache.get( dependency );
  34110. if ( cached !== undefined ) {
  34111. _dependencies[ dependency ] = cached;
  34112. } else if ( this[ fnName ] ) {
  34113. var fn = this[ fnName ]();
  34114. this.cache.add( dependency, fn );
  34115. _dependencies[ dependency ] = fn;
  34116. }
  34117. }
  34118. return _each( _dependencies, function ( dependency ) {
  34119. return dependency;
  34120. } );
  34121. };
  34122. GLTFParser.prototype.parse = function ( callback ) {
  34123. var json = this.json;
  34124. // Clear the loader cache
  34125. this.cache.removeAll();
  34126. // Fire the callback on complete
  34127. this._withDependencies( [
  34128. "scenes",
  34129. "cameras",
  34130. "animations"
  34131. ] ).then( function ( dependencies ) {
  34132. var scene = dependencies.scenes[ json.scene ];
  34133. var scenes = [];
  34134. for ( var name in dependencies.scenes ) {
  34135. scenes.push( dependencies.scenes[ name ] );
  34136. }
  34137. var cameras = [];
  34138. for ( var name in dependencies.cameras ) {
  34139. var camera = dependencies.cameras[ name ];
  34140. cameras.push( camera );
  34141. }
  34142. var animations = [];
  34143. for ( var name in dependencies.animations ) {
  34144. animations.push( dependencies.animations[ name ] );
  34145. }
  34146. callback( scene, scenes, cameras, animations );
  34147. } );
  34148. };
  34149. GLTFParser.prototype.loadShaders = function () {
  34150. var json = this.json;
  34151. var extensions = this.extensions;
  34152. var options = this.options;
  34153. return this._withDependencies( [
  34154. "bufferViews"
  34155. ] ).then( function ( dependencies ) {
  34156. return _each( json.shaders, function ( shader ) {
  34157. if ( shader.extensions && shader.extensions[ EXTENSIONS.KHR_BINARY_GLTF ] ) {
  34158. return extensions[ EXTENSIONS.KHR_BINARY_GLTF ].loadShader( shader, dependencies.bufferViews );
  34159. }
  34160. return new Promise( function ( resolve ) {
  34161. var loader = new THREE.FileLoader();
  34162. loader.setResponseType( 'text' );
  34163. loader.load( resolveURL( shader.uri, options.path ), function ( shaderText ) {
  34164. resolve( shaderText );
  34165. } );
  34166. } );
  34167. } );
  34168. } );
  34169. };
  34170. GLTFParser.prototype.loadBuffers = function () {
  34171. var json = this.json;
  34172. var extensions = this.extensions;
  34173. var options = this.options;
  34174. return _each( json.buffers, function ( buffer, name ) {
  34175. if ( name === BINARY_EXTENSION_BUFFER_NAME ) {
  34176. return extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body;
  34177. }
  34178. if ( buffer.type === 'arraybuffer' || buffer.type === undefined ) {
  34179. return new Promise( function ( resolve ) {
  34180. var loader = new THREE.FileLoader();
  34181. loader.setResponseType( 'arraybuffer' );
  34182. loader.load( resolveURL( buffer.uri, options.path ), function ( buffer ) {
  34183. resolve( buffer );
  34184. } );
  34185. } );
  34186. } else {
  34187. console.warn( 'THREE.GLTFLoader: ' + buffer.type + ' buffer type is not supported' );
  34188. }
  34189. } );
  34190. };
  34191. GLTFParser.prototype.loadBufferViews = function () {
  34192. var json = this.json;
  34193. return this._withDependencies( [
  34194. "buffers"
  34195. ] ).then( function ( dependencies ) {
  34196. return _each( json.bufferViews, function ( bufferView ) {
  34197. var arraybuffer = dependencies.buffers[ bufferView.buffer ];
  34198. return arraybuffer.slice( bufferView.byteOffset, bufferView.byteOffset + bufferView.byteLength );
  34199. } );
  34200. } );
  34201. };
  34202. GLTFParser.prototype.loadAccessors = function () {
  34203. var json = this.json;
  34204. return this._withDependencies( [
  34205. "bufferViews"
  34206. ] ).then( function ( dependencies ) {
  34207. return _each( json.accessors, function ( accessor ) {
  34208. var arraybuffer = dependencies.bufferViews[ accessor.bufferView ];
  34209. var itemSize = WEBGL_TYPE_SIZES[ accessor.type ];
  34210. var TypedArray = WEBGL_COMPONENT_TYPES[ accessor.componentType ];
  34211. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  34212. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  34213. var itemBytes = elementBytes * itemSize;
  34214. // The buffer is not interleaved if the stride is the item size in bytes.
  34215. if ( accessor.byteStride && accessor.byteStride !== itemBytes ) {
  34216. // Use the full buffer if it's interleaved.
  34217. var array = new TypedArray( arraybuffer );
  34218. // Integer parameters to IB/IBA are in array elements, not bytes.
  34219. var ib = new THREE.InterleavedBuffer( array, accessor.byteStride / elementBytes );
  34220. return new THREE.InterleavedBufferAttribute( ib, itemSize, accessor.byteOffset / elementBytes );
  34221. } else {
  34222. array = new TypedArray( arraybuffer, accessor.byteOffset, accessor.count * itemSize );
  34223. return new THREE.BufferAttribute( array, itemSize );
  34224. }
  34225. } );
  34226. } );
  34227. };
  34228. GLTFParser.prototype.loadTextures = function () {
  34229. var json = this.json;
  34230. var extensions = this.extensions;
  34231. var options = this.options;
  34232. return this._withDependencies( [
  34233. "bufferViews"
  34234. ] ).then( function ( dependencies ) {
  34235. return _each( json.textures, function ( texture ) {
  34236. if ( texture.source ) {
  34237. return new Promise( function ( resolve ) {
  34238. var source = json.images[ texture.source ];
  34239. var sourceUri = source.uri;
  34240. if ( source.extensions && source.extensions[ EXTENSIONS.KHR_BINARY_GLTF ] ) {
  34241. sourceUri = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].loadTextureSourceUri( source, dependencies.bufferViews );
  34242. }
  34243. var textureLoader = THREE.Loader.Handlers.get( sourceUri );
  34244. if ( textureLoader === null ) {
  34245. textureLoader = new THREE.TextureLoader();
  34246. }
  34247. textureLoader.setCrossOrigin( options.crossOrigin );
  34248. textureLoader.load( resolveURL( sourceUri, options.path ), function ( _texture ) {
  34249. _texture.flipY = false;
  34250. if ( texture.name !== undefined ) _texture.name = texture.name;
  34251. _texture.format = texture.format !== undefined ? WEBGL_TEXTURE_FORMATS[ texture.format ] : THREE.RGBAFormat;
  34252. if ( texture.internalFormat !== undefined && _texture.format !== WEBGL_TEXTURE_FORMATS[ texture.internalFormat ] ) {
  34253. console.warn( 'THREE.GLTFLoader: Three.js doesn\'t support texture internalFormat which is different from texture format. ' +
  34254. 'internalFormat will be forced to be the same value as format.' );
  34255. }
  34256. _texture.type = texture.type !== undefined ? WEBGL_TEXTURE_DATATYPES[ texture.type ] : THREE.UnsignedByteType;
  34257. if ( texture.sampler ) {
  34258. var sampler = json.samplers[ texture.sampler ];
  34259. _texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ];
  34260. _texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ];
  34261. _texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ];
  34262. _texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ];
  34263. }
  34264. resolve( _texture );
  34265. }, undefined, function () {
  34266. resolve();
  34267. } );
  34268. } );
  34269. }
  34270. } );
  34271. } );
  34272. };
  34273. GLTFParser.prototype.loadMaterials = function () {
  34274. var json = this.json;
  34275. return this._withDependencies( [
  34276. "shaders",
  34277. "textures"
  34278. ] ).then( function ( dependencies ) {
  34279. return _each( json.materials, function ( material ) {
  34280. var materialType;
  34281. var materialValues = {};
  34282. var materialParams = {};
  34283. var khr_material;
  34284. if ( material.extensions && material.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ] ) {
  34285. khr_material = material.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ];
  34286. }
  34287. if ( khr_material ) {
  34288. switch ( khr_material.technique ) {
  34289. case 'BLINN' :
  34290. case 'PHONG' :
  34291. materialType = THREE.MeshPhongMaterial;
  34292. break;
  34293. case 'LAMBERT' :
  34294. materialType = THREE.MeshLambertMaterial;
  34295. break;
  34296. case 'CONSTANT' :
  34297. default :
  34298. materialType = THREE.MeshBasicMaterial;
  34299. break;
  34300. }
  34301. Object.assign( materialValues, khr_material.values );
  34302. if ( khr_material.doubleSided || materialValues.doubleSided ) {
  34303. materialParams.side = THREE.DoubleSide;
  34304. }
  34305. if ( khr_material.transparent || materialValues.transparent ) {
  34306. materialParams.transparent = true;
  34307. materialParams.opacity = ( materialValues.transparency !== undefined ) ? materialValues.transparency : 1;
  34308. }
  34309. } else if ( material.technique === undefined ) {
  34310. materialType = THREE.MeshPhongMaterial;
  34311. Object.assign( materialValues, material.values );
  34312. } else {
  34313. materialType = DeferredShaderMaterial;
  34314. var technique = json.techniques[ material.technique ];
  34315. materialParams.uniforms = {};
  34316. var program = json.programs[ technique.program ];
  34317. if ( program ) {
  34318. materialParams.fragmentShader = dependencies.shaders[ program.fragmentShader ];
  34319. if ( ! materialParams.fragmentShader ) {
  34320. console.warn( "ERROR: Missing fragment shader definition:", program.fragmentShader );
  34321. materialType = THREE.MeshPhongMaterial;
  34322. }
  34323. var vertexShader = dependencies.shaders[ program.vertexShader ];
  34324. if ( ! vertexShader ) {
  34325. console.warn( "ERROR: Missing vertex shader definition:", program.vertexShader );
  34326. materialType = THREE.MeshPhongMaterial;
  34327. }
  34328. // IMPORTANT: FIX VERTEX SHADER ATTRIBUTE DEFINITIONS
  34329. materialParams.vertexShader = replaceTHREEShaderAttributes( vertexShader, technique );
  34330. var uniforms = technique.uniforms;
  34331. for ( var uniformId in uniforms ) {
  34332. var pname = uniforms[ uniformId ];
  34333. var shaderParam = technique.parameters[ pname ];
  34334. var ptype = shaderParam.type;
  34335. if ( WEBGL_TYPE[ ptype ] ) {
  34336. var pcount = shaderParam.count;
  34337. var value;
  34338. if ( material.values !== undefined ) value = material.values[ pname ];
  34339. var uvalue = new WEBGL_TYPE[ ptype ]();
  34340. var usemantic = shaderParam.semantic;
  34341. var unode = shaderParam.node;
  34342. switch ( ptype ) {
  34343. case WEBGL_CONSTANTS.FLOAT:
  34344. uvalue = shaderParam.value;
  34345. if ( pname == "transparency" ) {
  34346. materialParams.transparent = true;
  34347. }
  34348. if ( value !== undefined ) {
  34349. uvalue = value;
  34350. }
  34351. break;
  34352. case WEBGL_CONSTANTS.FLOAT_VEC2:
  34353. case WEBGL_CONSTANTS.FLOAT_VEC3:
  34354. case WEBGL_CONSTANTS.FLOAT_VEC4:
  34355. case WEBGL_CONSTANTS.FLOAT_MAT3:
  34356. if ( shaderParam && shaderParam.value ) {
  34357. uvalue.fromArray( shaderParam.value );
  34358. }
  34359. if ( value ) {
  34360. uvalue.fromArray( value );
  34361. }
  34362. break;
  34363. case WEBGL_CONSTANTS.FLOAT_MAT2:
  34364. // what to do?
  34365. console.warn( "FLOAT_MAT2 is not a supported uniform type" );
  34366. break;
  34367. case WEBGL_CONSTANTS.FLOAT_MAT4:
  34368. if ( pcount ) {
  34369. uvalue = new Array( pcount );
  34370. for ( var mi = 0; mi < pcount; mi ++ ) {
  34371. uvalue[ mi ] = new WEBGL_TYPE[ ptype ]();
  34372. }
  34373. if ( shaderParam && shaderParam.value ) {
  34374. var m4v = shaderParam.value;
  34375. uvalue.fromArray( m4v );
  34376. }
  34377. if ( value ) {
  34378. uvalue.fromArray( value );
  34379. }
  34380. } else {
  34381. if ( shaderParam && shaderParam.value ) {
  34382. var m4 = shaderParam.value;
  34383. uvalue.fromArray( m4 );
  34384. }
  34385. if ( value ) {
  34386. uvalue.fromArray( value );
  34387. }
  34388. }
  34389. break;
  34390. case WEBGL_CONSTANTS.SAMPLER_2D:
  34391. if ( value !== undefined ) {
  34392. uvalue = dependencies.textures[ value ];
  34393. } else if ( shaderParam.value !== undefined ) {
  34394. uvalue = dependencies.textures[ shaderParam.value ];
  34395. } else {
  34396. uvalue = null;
  34397. }
  34398. break;
  34399. }
  34400. materialParams.uniforms[ uniformId ] = {
  34401. value: uvalue,
  34402. semantic: usemantic,
  34403. node: unode
  34404. };
  34405. } else {
  34406. throw new Error( "Unknown shader uniform param type: " + ptype );
  34407. }
  34408. }
  34409. var states = technique.states || {};
  34410. var enables = states.enable || [];
  34411. var functions = states.functions || {};
  34412. var enableCullFace = false;
  34413. var enableDepthTest = false;
  34414. var enableBlend = false;
  34415. for ( var i = 0, il = enables.length; i < il; i ++ ) {
  34416. var enable = enables[ i ];
  34417. switch ( STATES_ENABLES[ enable ] ) {
  34418. case 'CULL_FACE':
  34419. enableCullFace = true;
  34420. break;
  34421. case 'DEPTH_TEST':
  34422. enableDepthTest = true;
  34423. break;
  34424. case 'BLEND':
  34425. enableBlend = true;
  34426. break;
  34427. // TODO: implement
  34428. case 'SCISSOR_TEST':
  34429. case 'POLYGON_OFFSET_FILL':
  34430. case 'SAMPLE_ALPHA_TO_COVERAGE':
  34431. break;
  34432. default:
  34433. throw new Error( "Unknown technique.states.enable: " + enable );
  34434. }
  34435. }
  34436. if ( enableCullFace ) {
  34437. materialParams.side = functions.cullFace !== undefined ? WEBGL_SIDES[ functions.cullFace ] : THREE.FrontSide;
  34438. } else {
  34439. materialParams.side = THREE.DoubleSide;
  34440. }
  34441. materialParams.depthTest = enableDepthTest;
  34442. materialParams.depthFunc = functions.depthFunc !== undefined ? WEBGL_DEPTH_FUNCS[ functions.depthFunc ] : THREE.LessDepth;
  34443. materialParams.depthWrite = functions.depthMask !== undefined ? functions.depthMask[ 0 ] : true;
  34444. materialParams.blending = enableBlend ? THREE.CustomBlending : THREE.NoBlending;
  34445. materialParams.transparent = enableBlend;
  34446. var blendEquationSeparate = functions.blendEquationSeparate;
  34447. if ( blendEquationSeparate !== undefined ) {
  34448. materialParams.blendEquation = WEBGL_BLEND_EQUATIONS[ blendEquationSeparate[ 0 ] ];
  34449. materialParams.blendEquationAlpha = WEBGL_BLEND_EQUATIONS[ blendEquationSeparate[ 1 ] ];
  34450. } else {
  34451. materialParams.blendEquation = THREE.AddEquation;
  34452. materialParams.blendEquationAlpha = THREE.AddEquation;
  34453. }
  34454. var blendFuncSeparate = functions.blendFuncSeparate;
  34455. if ( blendFuncSeparate !== undefined ) {
  34456. materialParams.blendSrc = WEBGL_BLEND_FUNCS[ blendFuncSeparate[ 0 ] ];
  34457. materialParams.blendDst = WEBGL_BLEND_FUNCS[ blendFuncSeparate[ 1 ] ];
  34458. materialParams.blendSrcAlpha = WEBGL_BLEND_FUNCS[ blendFuncSeparate[ 2 ] ];
  34459. materialParams.blendDstAlpha = WEBGL_BLEND_FUNCS[ blendFuncSeparate[ 3 ] ];
  34460. } else {
  34461. materialParams.blendSrc = THREE.OneFactor;
  34462. materialParams.blendDst = THREE.ZeroFactor;
  34463. materialParams.blendSrcAlpha = THREE.OneFactor;
  34464. materialParams.blendDstAlpha = THREE.ZeroFactor;
  34465. }
  34466. }
  34467. }
  34468. if ( Array.isArray( materialValues.diffuse ) ) {
  34469. materialParams.color = new THREE.Color().fromArray( materialValues.diffuse );
  34470. } else if ( typeof( materialValues.diffuse ) === 'string' ) {
  34471. materialParams.map = dependencies.textures[ materialValues.diffuse ];
  34472. }
  34473. delete materialParams.diffuse;
  34474. if ( typeof( materialValues.reflective ) === 'string' ) {
  34475. materialParams.envMap = dependencies.textures[ materialValues.reflective ];
  34476. }
  34477. if ( typeof( materialValues.bump ) === 'string' ) {
  34478. materialParams.bumpMap = dependencies.textures[ materialValues.bump ];
  34479. }
  34480. if ( Array.isArray( materialValues.emission ) ) {
  34481. if ( materialType === THREE.MeshBasicMaterial ) {
  34482. materialParams.color = new THREE.Color().fromArray( materialValues.emission );
  34483. } else {
  34484. materialParams.emissive = new THREE.Color().fromArray( materialValues.emission );
  34485. }
  34486. } else if ( typeof( materialValues.emission ) === 'string' ) {
  34487. if ( materialType === THREE.MeshBasicMaterial ) {
  34488. materialParams.map = dependencies.textures[ materialValues.emission ];
  34489. } else {
  34490. materialParams.emissiveMap = dependencies.textures[ materialValues.emission ];
  34491. }
  34492. }
  34493. if ( Array.isArray( materialValues.specular ) ) {
  34494. materialParams.specular = new THREE.Color().fromArray( materialValues.specular );
  34495. } else if ( typeof( materialValues.specular ) === 'string' ) {
  34496. materialParams.specularMap = dependencies.textures[ materialValues.specular ];
  34497. }
  34498. if ( materialValues.shininess !== undefined ) {
  34499. materialParams.shininess = materialValues.shininess;
  34500. }
  34501. var _material = new materialType( materialParams );
  34502. if ( material.name !== undefined ) _material.name = material.name;
  34503. return _material;
  34504. } );
  34505. } );
  34506. };
  34507. GLTFParser.prototype.loadMeshes = function () {
  34508. var json = this.json;
  34509. return this._withDependencies( [
  34510. "accessors",
  34511. "materials"
  34512. ] ).then( function ( dependencies ) {
  34513. return _each( json.meshes, function ( mesh ) {
  34514. var group = new THREE.Object3D();
  34515. if ( mesh.name !== undefined ) group.name = mesh.name;
  34516. if ( mesh.extras ) group.userData = mesh.extras;
  34517. var primitives = mesh.primitives;
  34518. for ( var name in primitives ) {
  34519. var primitive = primitives[ name ];
  34520. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === undefined ) {
  34521. var geometry = new THREE.BufferGeometry();
  34522. var attributes = primitive.attributes;
  34523. for ( var attributeId in attributes ) {
  34524. var attributeEntry = attributes[ attributeId ];
  34525. if ( ! attributeEntry ) return;
  34526. var bufferAttribute = dependencies.accessors[ attributeEntry ];
  34527. switch ( attributeId ) {
  34528. case 'POSITION':
  34529. geometry.addAttribute( 'position', bufferAttribute );
  34530. break;
  34531. case 'NORMAL':
  34532. geometry.addAttribute( 'normal', bufferAttribute );
  34533. break;
  34534. case 'TEXCOORD_0':
  34535. case 'TEXCOORD0':
  34536. case 'TEXCOORD':
  34537. geometry.addAttribute( 'uv', bufferAttribute );
  34538. break;
  34539. case 'COLOR_0':
  34540. case 'COLOR0':
  34541. case 'COLOR':
  34542. geometry.addAttribute( 'color', bufferAttribute );
  34543. break;
  34544. case 'WEIGHT':
  34545. geometry.addAttribute( 'skinWeight', bufferAttribute );
  34546. break;
  34547. case 'JOINT':
  34548. geometry.addAttribute( 'skinIndex', bufferAttribute );
  34549. break;
  34550. }
  34551. }
  34552. if ( primitive.indices ) {
  34553. geometry.setIndex( dependencies.accessors[ primitive.indices ] );
  34554. }
  34555. var material = dependencies.materials !== undefined ? dependencies.materials[ primitive.material ] : createDefaultMaterial();
  34556. var meshNode = new THREE.Mesh( geometry, material );
  34557. meshNode.castShadow = true;
  34558. meshNode.name = ( name === "0" ? group.name : group.name + name );
  34559. if ( primitive.extras ) meshNode.userData = primitive.extras;
  34560. group.add( meshNode );
  34561. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  34562. var geometry = new THREE.BufferGeometry();
  34563. var attributes = primitive.attributes;
  34564. for ( var attributeId in attributes ) {
  34565. var attributeEntry = attributes[ attributeId ];
  34566. if ( ! attributeEntry ) return;
  34567. var bufferAttribute = dependencies.accessors[ attributeEntry ];
  34568. switch ( attributeId ) {
  34569. case 'POSITION':
  34570. geometry.addAttribute( 'position', bufferAttribute );
  34571. break;
  34572. case 'COLOR_0':
  34573. case 'COLOR0':
  34574. case 'COLOR':
  34575. geometry.addAttribute( 'color', bufferAttribute );
  34576. break;
  34577. }
  34578. }
  34579. var material = dependencies.materials[ primitive.material ];
  34580. var meshNode;
  34581. if ( primitive.indices ) {
  34582. geometry.setIndex( dependencies.accessors[ primitive.indices ] );
  34583. meshNode = new THREE.LineSegments( geometry, material );
  34584. } else {
  34585. meshNode = new THREE.Line( geometry, material );
  34586. }
  34587. meshNode.name = ( name === "0" ? group.name : group.name + name );
  34588. if ( primitive.extras ) meshNode.userData = primitive.extras;
  34589. group.add( meshNode );
  34590. } else {
  34591. console.warn( "Only triangular and line primitives are supported" );
  34592. }
  34593. }
  34594. return group;
  34595. } );
  34596. } );
  34597. };
  34598. GLTFParser.prototype.loadCameras = function () {
  34599. var json = this.json;
  34600. return _each( json.cameras, function ( camera ) {
  34601. if ( camera.type == "perspective" && camera.perspective ) {
  34602. var yfov = camera.perspective.yfov;
  34603. var xfov = camera.perspective.xfov;
  34604. var aspect_ratio = camera.perspective.aspect_ratio || 1;
  34605. // According to COLLADA spec...
  34606. // aspect_ratio = xfov / yfov
  34607. xfov = ( xfov === undefined && yfov ) ? yfov * aspect_ratio : xfov;
  34608. // According to COLLADA spec...
  34609. // aspect_ratio = xfov / yfov
  34610. // yfov = ( yfov === undefined && xfov ) ? xfov / aspect_ratio : yfov;
  34611. var _camera = new THREE.PerspectiveCamera( THREE.Math.radToDeg( xfov ), aspect_ratio, camera.perspective.znear || 1, camera.perspective.zfar || 2e6 );
  34612. if ( camera.name !== undefined ) _camera.name = camera.name;
  34613. if ( camera.extras ) _camera.userData = camera.extras;
  34614. return _camera;
  34615. } else if ( camera.type == "orthographic" && camera.orthographic ) {
  34616. var _camera = new THREE.OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, camera.orthographic.znear, camera.orthographic.zfar );
  34617. if ( camera.name !== undefined ) _camera.name = camera.name;
  34618. if ( camera.extras ) _camera.userData = camera.extras;
  34619. return _camera;
  34620. }
  34621. } );
  34622. };
  34623. GLTFParser.prototype.loadSkins = function () {
  34624. var json = this.json;
  34625. return this._withDependencies( [
  34626. "accessors"
  34627. ] ).then( function ( dependencies ) {
  34628. return _each( json.skins, function ( skin ) {
  34629. var _skin = {
  34630. bindShapeMatrix: new THREE.Matrix4().fromArray( skin.bindShapeMatrix ),
  34631. jointNames: skin.jointNames,
  34632. inverseBindMatrices: dependencies.accessors[ skin.inverseBindMatrices ]
  34633. };
  34634. return _skin;
  34635. } );
  34636. } );
  34637. };
  34638. GLTFParser.prototype.loadAnimations = function () {
  34639. var json = this.json;
  34640. return this._withDependencies( [
  34641. "accessors",
  34642. "nodes"
  34643. ] ).then( function ( dependencies ) {
  34644. return _each( json.animations, function ( animation, animationId ) {
  34645. var tracks = [];
  34646. for ( var channelId in animation.channels ) {
  34647. var channel = animation.channels[ channelId ];
  34648. var sampler = animation.samplers[ channel.sampler ];
  34649. if ( sampler ) {
  34650. var target = channel.target;
  34651. var name = target.id;
  34652. var input = animation.parameters !== undefined ? animation.parameters[ sampler.input ] : sampler.input;
  34653. var output = animation.parameters !== undefined ? animation.parameters[ sampler.output ] : sampler.output;
  34654. var inputAccessor = dependencies.accessors[ input ];
  34655. var outputAccessor = dependencies.accessors[ output ];
  34656. var node = dependencies.nodes[ name ];
  34657. if ( node ) {
  34658. node.updateMatrix();
  34659. node.matrixAutoUpdate = true;
  34660. var TypedKeyframeTrack = PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.rotation
  34661. ? THREE.QuaternionKeyframeTrack
  34662. : THREE.VectorKeyframeTrack;
  34663. var targetName = node.name ? node.name : node.uuid;
  34664. // KeyframeTrack.optimize() will modify given 'times' and 'values'
  34665. // buffers before creating a truncated copy to keep. Because buffers may
  34666. // be reused by other tracks, make copies here.
  34667. tracks.push( new TypedKeyframeTrack(
  34668. targetName + '.' + PATH_PROPERTIES[ target.path ],
  34669. THREE.AnimationUtils.arraySlice( inputAccessor.array, 0 ),
  34670. THREE.AnimationUtils.arraySlice( outputAccessor.array, 0 ),
  34671. INTERPOLATION[ sampler.interpolation ]
  34672. ) );
  34673. }
  34674. }
  34675. }
  34676. return new THREE.AnimationClip( "animation_" + animationId, undefined, tracks );
  34677. } );
  34678. } );
  34679. };
  34680. GLTFParser.prototype.loadNodes = function () {
  34681. var json = this.json;
  34682. var extensions = this.extensions;
  34683. var scope = this;
  34684. return _each( json.nodes, function ( node ) {
  34685. var matrix = new THREE.Matrix4();
  34686. var _node;
  34687. if ( node.jointName ) {
  34688. _node = new THREE.Bone();
  34689. _node.name = node.name !== undefined ? node.name : node.jointName;
  34690. _node.jointName = node.jointName;
  34691. } else {
  34692. _node = new THREE.Object3D();
  34693. if ( node.name !== undefined ) _node.name = node.name;
  34694. }
  34695. if ( node.extras ) _node.userData = node.extras;
  34696. if ( node.matrix !== undefined ) {
  34697. matrix.fromArray( node.matrix );
  34698. _node.applyMatrix( matrix );
  34699. } else {
  34700. if ( node.translation !== undefined ) {
  34701. _node.position.fromArray( node.translation );
  34702. }
  34703. if ( node.rotation !== undefined ) {
  34704. _node.quaternion.fromArray( node.rotation );
  34705. }
  34706. if ( node.scale !== undefined ) {
  34707. _node.scale.fromArray( node.scale );
  34708. }
  34709. }
  34710. return _node;
  34711. } ).then( function ( __nodes ) {
  34712. return scope._withDependencies( [
  34713. "meshes",
  34714. "skins",
  34715. "cameras"
  34716. ] ).then( function ( dependencies ) {
  34717. return _each( __nodes, function ( _node, nodeId ) {
  34718. var node = json.nodes[ nodeId ];
  34719. if ( node.meshes !== undefined ) {
  34720. for ( var meshId in node.meshes ) {
  34721. var mesh = node.meshes[ meshId ];
  34722. var group = dependencies.meshes[ mesh ];
  34723. if ( group === undefined ) {
  34724. console.warn( 'GLTFLoader: Couldn\'t find node "' + mesh + '".' );
  34725. continue;
  34726. }
  34727. for ( var childrenId in group.children ) {
  34728. var child = group.children[ childrenId ];
  34729. // clone Mesh to add to _node
  34730. var originalMaterial = child.material;
  34731. var originalGeometry = child.geometry;
  34732. var originalUserData = child.userData;
  34733. var originalName = child.name;
  34734. var material;
  34735. if ( originalMaterial.isDeferredShaderMaterial ) {
  34736. originalMaterial = material = originalMaterial.create();
  34737. } else {
  34738. material = originalMaterial;
  34739. }
  34740. switch ( child.type ) {
  34741. case 'LineSegments':
  34742. child = new THREE.LineSegments( originalGeometry, material );
  34743. break;
  34744. case 'Line':
  34745. child = new THREE.Line( originalGeometry, material );
  34746. break;
  34747. default:
  34748. child = new THREE.Mesh( originalGeometry, material );
  34749. }
  34750. child.castShadow = true;
  34751. child.userData = originalUserData;
  34752. child.name = originalName;
  34753. var skinEntry;
  34754. if ( node.skin ) {
  34755. skinEntry = dependencies.skins[ node.skin ];
  34756. }
  34757. // Replace Mesh with SkinnedMesh in library
  34758. if ( skinEntry ) {
  34759. var getJointNode = function ( jointId ) {
  34760. var keys = Object.keys( __nodes );
  34761. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  34762. var n = __nodes[ keys[ i ] ];
  34763. if ( n.jointName === jointId ) return n;
  34764. }
  34765. return null;
  34766. };
  34767. var geometry = originalGeometry;
  34768. var material = originalMaterial;
  34769. material.skinning = true;
  34770. child = new THREE.SkinnedMesh( geometry, material, false );
  34771. child.castShadow = true;
  34772. child.userData = originalUserData;
  34773. child.name = originalName;
  34774. var bones = [];
  34775. var boneInverses = [];
  34776. for ( var i = 0, l = skinEntry.jointNames.length; i < l; i ++ ) {
  34777. var jointId = skinEntry.jointNames[ i ];
  34778. var jointNode = getJointNode( jointId );
  34779. if ( jointNode ) {
  34780. bones.push( jointNode );
  34781. var m = skinEntry.inverseBindMatrices.array;
  34782. var mat = new THREE.Matrix4().fromArray( m, i * 16 );
  34783. boneInverses.push( mat );
  34784. } else {
  34785. console.warn( "WARNING: joint: ''" + jointId + "' could not be found" );
  34786. }
  34787. }
  34788. child.bind( new THREE.Skeleton( bones, boneInverses, false ), skinEntry.bindShapeMatrix );
  34789. var buildBoneGraph = function ( parentJson, parentObject, property ) {
  34790. var children = parentJson[ property ];
  34791. if ( children === undefined ) return;
  34792. for ( var i = 0, il = children.length; i < il; i ++ ) {
  34793. var nodeId = children[ i ];
  34794. var bone = __nodes[ nodeId ];
  34795. var boneJson = json.nodes[ nodeId ];
  34796. if ( bone !== undefined && bone.isBone === true && boneJson !== undefined ) {
  34797. parentObject.add( bone );
  34798. buildBoneGraph( boneJson, bone, 'children' );
  34799. }
  34800. }
  34801. };
  34802. buildBoneGraph( node, child, 'skeletons' );
  34803. }
  34804. _node.add( child );
  34805. }
  34806. }
  34807. }
  34808. if ( node.camera !== undefined ) {
  34809. var camera = dependencies.cameras[ node.camera ];
  34810. _node.add( camera );
  34811. }
  34812. if ( node.extensions
  34813. && node.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ]
  34814. && node.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ].light ) {
  34815. var extensionLights = extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ].lights;
  34816. var light = extensionLights[ node.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ].light ];
  34817. _node.add( light );
  34818. }
  34819. return _node;
  34820. } );
  34821. } );
  34822. } );
  34823. };
  34824. GLTFParser.prototype.loadScenes = function () {
  34825. var json = this.json;
  34826. // scene node hierachy builder
  34827. function buildNodeHierachy( nodeId, parentObject, allNodes ) {
  34828. var _node = allNodes[ nodeId ];
  34829. parentObject.add( _node );
  34830. var node = json.nodes[ nodeId ];
  34831. if ( node.children ) {
  34832. var children = node.children;
  34833. for ( var i = 0, l = children.length; i < l; i ++ ) {
  34834. var child = children[ i ];
  34835. buildNodeHierachy( child, _node, allNodes );
  34836. }
  34837. }
  34838. }
  34839. return this._withDependencies( [
  34840. "nodes"
  34841. ] ).then( function ( dependencies ) {
  34842. return _each( json.scenes, function ( scene ) {
  34843. var _scene = new THREE.Scene();
  34844. if ( scene.name !== undefined ) _scene.name = scene.name;
  34845. if ( scene.extras ) _scene.userData = scene.extras;
  34846. var nodes = scene.nodes;
  34847. for ( var i = 0, l = nodes.length; i < l; i ++ ) {
  34848. var nodeId = nodes[ i ];
  34849. buildNodeHierachy( nodeId, _scene, dependencies.nodes );
  34850. }
  34851. _scene.traverse( function ( child ) {
  34852. // Register raw material meshes with GLTFLoader.Shaders
  34853. if ( child.material && child.material.isRawShaderMaterial ) {
  34854. var xshader = new GLTFShader( child, dependencies.nodes );
  34855. GLTFLoader.Shaders.add( child.uuid, xshader );
  34856. }
  34857. } );
  34858. return _scene;
  34859. } );
  34860. } );
  34861. };
  34862. return GLTFLoader;
  34863. } )();
  34864. },{}],45:[function(_dereq_,module,exports){
  34865. /**
  34866. * Loads a Wavefront .mtl file specifying materials
  34867. *
  34868. * @author angelxuanchang
  34869. */
  34870. THREE.MTLLoader = function ( manager ) {
  34871. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  34872. };
  34873. THREE.MTLLoader.prototype = {
  34874. constructor: THREE.MTLLoader,
  34875. /**
  34876. * Loads and parses a MTL asset from a URL.
  34877. *
  34878. * @param {String} url - URL to the MTL file.
  34879. * @param {Function} [onLoad] - Callback invoked with the loaded object.
  34880. * @param {Function} [onProgress] - Callback for download progress.
  34881. * @param {Function} [onError] - Callback for download errors.
  34882. *
  34883. * @see setPath setTexturePath
  34884. *
  34885. * @note In order for relative texture references to resolve correctly
  34886. * you must call setPath and/or setTexturePath explicitly prior to load.
  34887. */
  34888. load: function ( url, onLoad, onProgress, onError ) {
  34889. var scope = this;
  34890. var loader = new THREE.FileLoader( this.manager );
  34891. loader.setPath( this.path );
  34892. loader.load( url, function ( text ) {
  34893. onLoad( scope.parse( text ) );
  34894. }, onProgress, onError );
  34895. },
  34896. /**
  34897. * Set base path for resolving references.
  34898. * If set this path will be prepended to each loaded and found reference.
  34899. *
  34900. * @see setTexturePath
  34901. * @param {String} path
  34902. *
  34903. * @example
  34904. * mtlLoader.setPath( 'assets/obj/' );
  34905. * mtlLoader.load( 'my.mtl', ... );
  34906. */
  34907. setPath: function ( path ) {
  34908. this.path = path;
  34909. },
  34910. /**
  34911. * Set base path for resolving texture references.
  34912. * If set this path will be prepended found texture reference.
  34913. * If not set and setPath is, it will be used as texture base path.
  34914. *
  34915. * @see setPath
  34916. * @param {String} path
  34917. *
  34918. * @example
  34919. * mtlLoader.setPath( 'assets/obj/' );
  34920. * mtlLoader.setTexturePath( 'assets/textures/' );
  34921. * mtlLoader.load( 'my.mtl', ... );
  34922. */
  34923. setTexturePath: function ( path ) {
  34924. this.texturePath = path;
  34925. },
  34926. setBaseUrl: function ( path ) {
  34927. console.warn( 'THREE.MTLLoader: .setBaseUrl() is deprecated. Use .setTexturePath( path ) for texture path or .setPath( path ) for general base path instead.' );
  34928. this.setTexturePath( path );
  34929. },
  34930. setCrossOrigin: function ( value ) {
  34931. this.crossOrigin = value;
  34932. },
  34933. setMaterialOptions: function ( value ) {
  34934. this.materialOptions = value;
  34935. },
  34936. /**
  34937. * Parses a MTL file.
  34938. *
  34939. * @param {String} text - Content of MTL file
  34940. * @return {THREE.MTLLoader.MaterialCreator}
  34941. *
  34942. * @see setPath setTexturePath
  34943. *
  34944. * @note In order for relative texture references to resolve correctly
  34945. * you must call setPath and/or setTexturePath explicitly prior to parse.
  34946. */
  34947. parse: function ( text ) {
  34948. var lines = text.split( '\n' );
  34949. var info = {};
  34950. var delimiter_pattern = /\s+/;
  34951. var materialsInfo = {};
  34952. for ( var i = 0; i < lines.length; i ++ ) {
  34953. var line = lines[ i ];
  34954. line = line.trim();
  34955. if ( line.length === 0 || line.charAt( 0 ) === '#' ) {
  34956. // Blank line or comment ignore
  34957. continue;
  34958. }
  34959. var pos = line.indexOf( ' ' );
  34960. var key = ( pos >= 0 ) ? line.substring( 0, pos ) : line;
  34961. key = key.toLowerCase();
  34962. var value = ( pos >= 0 ) ? line.substring( pos + 1 ) : '';
  34963. value = value.trim();
  34964. if ( key === 'newmtl' ) {
  34965. // New material
  34966. info = { name: value };
  34967. materialsInfo[ value ] = info;
  34968. } else if ( info ) {
  34969. if ( key === 'ka' || key === 'kd' || key === 'ks' ) {
  34970. var ss = value.split( delimiter_pattern, 3 );
  34971. info[ key ] = [ parseFloat( ss[ 0 ] ), parseFloat( ss[ 1 ] ), parseFloat( ss[ 2 ] ) ];
  34972. } else {
  34973. info[ key ] = value;
  34974. }
  34975. }
  34976. }
  34977. var materialCreator = new THREE.MTLLoader.MaterialCreator( this.texturePath || this.path, this.materialOptions );
  34978. materialCreator.setCrossOrigin( this.crossOrigin );
  34979. materialCreator.setManager( this.manager );
  34980. materialCreator.setMaterials( materialsInfo );
  34981. return materialCreator;
  34982. }
  34983. };
  34984. /**
  34985. * Create a new THREE-MTLLoader.MaterialCreator
  34986. * @param baseUrl - Url relative to which textures are loaded
  34987. * @param options - Set of options on how to construct the materials
  34988. * side: Which side to apply the material
  34989. * THREE.FrontSide (default), THREE.BackSide, THREE.DoubleSide
  34990. * wrap: What type of wrapping to apply for textures
  34991. * THREE.RepeatWrapping (default), THREE.ClampToEdgeWrapping, THREE.MirroredRepeatWrapping
  34992. * normalizeRGB: RGBs need to be normalized to 0-1 from 0-255
  34993. * Default: false, assumed to be already normalized
  34994. * ignoreZeroRGBs: Ignore values of RGBs (Ka,Kd,Ks) that are all 0's
  34995. * Default: false
  34996. * @constructor
  34997. */
  34998. THREE.MTLLoader.MaterialCreator = function ( baseUrl, options ) {
  34999. this.baseUrl = baseUrl || '';
  35000. this.options = options;
  35001. this.materialsInfo = {};
  35002. this.materials = {};
  35003. this.materialsArray = [];
  35004. this.nameLookup = {};
  35005. this.side = ( this.options && this.options.side ) ? this.options.side : THREE.FrontSide;
  35006. this.wrap = ( this.options && this.options.wrap ) ? this.options.wrap : THREE.RepeatWrapping;
  35007. };
  35008. THREE.MTLLoader.MaterialCreator.prototype = {
  35009. constructor: THREE.MTLLoader.MaterialCreator,
  35010. setCrossOrigin: function ( value ) {
  35011. this.crossOrigin = value;
  35012. },
  35013. setManager: function ( value ) {
  35014. this.manager = value;
  35015. },
  35016. setMaterials: function ( materialsInfo ) {
  35017. this.materialsInfo = this.convert( materialsInfo );
  35018. this.materials = {};
  35019. this.materialsArray = [];
  35020. this.nameLookup = {};
  35021. },
  35022. convert: function ( materialsInfo ) {
  35023. if ( ! this.options ) return materialsInfo;
  35024. var converted = {};
  35025. for ( var mn in materialsInfo ) {
  35026. // Convert materials info into normalized form based on options
  35027. var mat = materialsInfo[ mn ];
  35028. var covmat = {};
  35029. converted[ mn ] = covmat;
  35030. for ( var prop in mat ) {
  35031. var save = true;
  35032. var value = mat[ prop ];
  35033. var lprop = prop.toLowerCase();
  35034. switch ( lprop ) {
  35035. case 'kd':
  35036. case 'ka':
  35037. case 'ks':
  35038. // Diffuse color (color under white light) using RGB values
  35039. if ( this.options && this.options.normalizeRGB ) {
  35040. value = [ value[ 0 ] / 255, value[ 1 ] / 255, value[ 2 ] / 255 ];
  35041. }
  35042. if ( this.options && this.options.ignoreZeroRGBs ) {
  35043. if ( value[ 0 ] === 0 && value[ 1 ] === 0 && value[ 2 ] === 0 ) {
  35044. // ignore
  35045. save = false;
  35046. }
  35047. }
  35048. break;
  35049. default:
  35050. break;
  35051. }
  35052. if ( save ) {
  35053. covmat[ lprop ] = value;
  35054. }
  35055. }
  35056. }
  35057. return converted;
  35058. },
  35059. preload: function () {
  35060. for ( var mn in this.materialsInfo ) {
  35061. this.create( mn );
  35062. }
  35063. },
  35064. getIndex: function ( materialName ) {
  35065. return this.nameLookup[ materialName ];
  35066. },
  35067. getAsArray: function () {
  35068. var index = 0;
  35069. for ( var mn in this.materialsInfo ) {
  35070. this.materialsArray[ index ] = this.create( mn );
  35071. this.nameLookup[ mn ] = index;
  35072. index ++;
  35073. }
  35074. return this.materialsArray;
  35075. },
  35076. create: function ( materialName ) {
  35077. if ( this.materials[ materialName ] === undefined ) {
  35078. this.createMaterial_( materialName );
  35079. }
  35080. return this.materials[ materialName ];
  35081. },
  35082. createMaterial_: function ( materialName ) {
  35083. // Create material
  35084. var scope = this;
  35085. var mat = this.materialsInfo[ materialName ];
  35086. var params = {
  35087. name: materialName,
  35088. side: this.side
  35089. };
  35090. function resolveURL( baseUrl, url ) {
  35091. if ( typeof url !== 'string' || url === '' )
  35092. return '';
  35093. // Absolute URL
  35094. if ( /^https?:\/\//i.test( url ) ) return url;
  35095. return baseUrl + url;
  35096. }
  35097. function setMapForType( mapType, value ) {
  35098. if ( params[ mapType ] ) return; // Keep the first encountered texture
  35099. var texParams = scope.getTextureParams( value, params );
  35100. var map = scope.loadTexture( resolveURL( scope.baseUrl, texParams.url ) );
  35101. map.repeat.copy( texParams.scale );
  35102. map.offset.copy( texParams.offset );
  35103. map.wrapS = scope.wrap;
  35104. map.wrapT = scope.wrap;
  35105. params[ mapType ] = map;
  35106. }
  35107. for ( var prop in mat ) {
  35108. var value = mat[ prop ];
  35109. if ( value === '' ) continue;
  35110. switch ( prop.toLowerCase() ) {
  35111. // Ns is material specular exponent
  35112. case 'kd':
  35113. // Diffuse color (color under white light) using RGB values
  35114. params.color = new THREE.Color().fromArray( value );
  35115. break;
  35116. case 'ks':
  35117. // Specular color (color when light is reflected from shiny surface) using RGB values
  35118. params.specular = new THREE.Color().fromArray( value );
  35119. break;
  35120. case 'map_kd':
  35121. // Diffuse texture map
  35122. setMapForType( "map", value );
  35123. break;
  35124. case 'map_ks':
  35125. // Specular map
  35126. setMapForType( "specularMap", value );
  35127. break;
  35128. case 'map_bump':
  35129. case 'bump':
  35130. // Bump texture map
  35131. setMapForType( "bumpMap", value );
  35132. break;
  35133. case 'ns':
  35134. // The specular exponent (defines the focus of the specular highlight)
  35135. // A high exponent results in a tight, concentrated highlight. Ns values normally range from 0 to 1000.
  35136. params.shininess = parseFloat( value );
  35137. break;
  35138. case 'd':
  35139. if ( value < 1 ) {
  35140. params.opacity = value;
  35141. params.transparent = true;
  35142. }
  35143. break;
  35144. case 'Tr':
  35145. if ( value > 0 ) {
  35146. params.opacity = 1 - value;
  35147. params.transparent = true;
  35148. }
  35149. break;
  35150. default:
  35151. break;
  35152. }
  35153. }
  35154. this.materials[ materialName ] = new THREE.MeshPhongMaterial( params );
  35155. return this.materials[ materialName ];
  35156. },
  35157. getTextureParams: function ( value, matParams ) {
  35158. var texParams = {
  35159. scale: new THREE.Vector2( 1, 1 ),
  35160. offset: new THREE.Vector2( 0, 0 )
  35161. };
  35162. var items = value.split( /\s+/ );
  35163. var pos;
  35164. pos = items.indexOf( '-bm' );
  35165. if ( pos >= 0 ) {
  35166. matParams.bumpScale = parseFloat( items[ pos + 1 ] );
  35167. items.splice( pos, 2 );
  35168. }
  35169. pos = items.indexOf( '-s' );
  35170. if ( pos >= 0 ) {
  35171. texParams.scale.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  35172. items.splice( pos, 4 ); // we expect 3 parameters here!
  35173. }
  35174. pos = items.indexOf( '-o' );
  35175. if ( pos >= 0 ) {
  35176. texParams.offset.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  35177. items.splice( pos, 4 ); // we expect 3 parameters here!
  35178. }
  35179. texParams.url = items.join( ' ' ).trim();
  35180. return texParams;
  35181. },
  35182. loadTexture: function ( url, mapping, onLoad, onProgress, onError ) {
  35183. var texture;
  35184. var loader = THREE.Loader.Handlers.get( url );
  35185. var manager = ( this.manager !== undefined ) ? this.manager : THREE.DefaultLoadingManager;
  35186. if ( loader === null ) {
  35187. loader = new THREE.TextureLoader( manager );
  35188. }
  35189. if ( loader.setCrossOrigin ) loader.setCrossOrigin( this.crossOrigin );
  35190. texture = loader.load( url, onLoad, onProgress, onError );
  35191. if ( mapping !== undefined ) texture.mapping = mapping;
  35192. return texture;
  35193. }
  35194. };
  35195. },{}],46:[function(_dereq_,module,exports){
  35196. /**
  35197. * @author mrdoob / http://mrdoob.com/
  35198. */
  35199. THREE.OBJLoader = function ( manager ) {
  35200. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  35201. this.materials = null;
  35202. this.regexp = {
  35203. // v float float float
  35204. vertex_pattern : /^v\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)/,
  35205. // vn float float float
  35206. normal_pattern : /^vn\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)/,
  35207. // vt float float
  35208. uv_pattern : /^vt\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)/,
  35209. // f vertex vertex vertex
  35210. face_vertex : /^f\s+(-?\d+)\s+(-?\d+)\s+(-?\d+)(?:\s+(-?\d+))?/,
  35211. // f vertex/uv vertex/uv vertex/uv
  35212. face_vertex_uv : /^f\s+(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)(?:\s+(-?\d+)\/(-?\d+))?/,
  35213. // f vertex/uv/normal vertex/uv/normal vertex/uv/normal
  35214. face_vertex_uv_normal : /^f\s+(-?\d+)\/(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\/(-?\d+)(?:\s+(-?\d+)\/(-?\d+)\/(-?\d+))?/,
  35215. // f vertex//normal vertex//normal vertex//normal
  35216. face_vertex_normal : /^f\s+(-?\d+)\/\/(-?\d+)\s+(-?\d+)\/\/(-?\d+)\s+(-?\d+)\/\/(-?\d+)(?:\s+(-?\d+)\/\/(-?\d+))?/,
  35217. // o object_name | g group_name
  35218. object_pattern : /^[og]\s*(.+)?/,
  35219. // s boolean
  35220. smoothing_pattern : /^s\s+(\d+|on|off)/,
  35221. // mtllib file_reference
  35222. material_library_pattern : /^mtllib /,
  35223. // usemtl material_name
  35224. material_use_pattern : /^usemtl /
  35225. };
  35226. };
  35227. THREE.OBJLoader.prototype = {
  35228. constructor: THREE.OBJLoader,
  35229. load: function ( url, onLoad, onProgress, onError ) {
  35230. var scope = this;
  35231. var loader = new THREE.FileLoader( scope.manager );
  35232. loader.setPath( this.path );
  35233. loader.load( url, function ( text ) {
  35234. onLoad( scope.parse( text ) );
  35235. }, onProgress, onError );
  35236. },
  35237. setPath: function ( value ) {
  35238. this.path = value;
  35239. },
  35240. setMaterials: function ( materials ) {
  35241. this.materials = materials;
  35242. },
  35243. _createParserState : function () {
  35244. var state = {
  35245. objects : [],
  35246. object : {},
  35247. vertices : [],
  35248. normals : [],
  35249. uvs : [],
  35250. materialLibraries : [],
  35251. startObject: function ( name, fromDeclaration ) {
  35252. // If the current object (initial from reset) is not from a g/o declaration in the parsed
  35253. // file. We need to use it for the first parsed g/o to keep things in sync.
  35254. if ( this.object && this.object.fromDeclaration === false ) {
  35255. this.object.name = name;
  35256. this.object.fromDeclaration = ( fromDeclaration !== false );
  35257. return;
  35258. }
  35259. var previousMaterial = ( this.object && typeof this.object.currentMaterial === 'function' ? this.object.currentMaterial() : undefined );
  35260. if ( this.object && typeof this.object._finalize === 'function' ) {
  35261. this.object._finalize( true );
  35262. }
  35263. this.object = {
  35264. name : name || '',
  35265. fromDeclaration : ( fromDeclaration !== false ),
  35266. geometry : {
  35267. vertices : [],
  35268. normals : [],
  35269. uvs : []
  35270. },
  35271. materials : [],
  35272. smooth : true,
  35273. startMaterial : function( name, libraries ) {
  35274. var previous = this._finalize( false );
  35275. // New usemtl declaration overwrites an inherited material, except if faces were declared
  35276. // after the material, then it must be preserved for proper MultiMaterial continuation.
  35277. if ( previous && ( previous.inherited || previous.groupCount <= 0 ) ) {
  35278. this.materials.splice( previous.index, 1 );
  35279. }
  35280. var material = {
  35281. index : this.materials.length,
  35282. name : name || '',
  35283. mtllib : ( Array.isArray( libraries ) && libraries.length > 0 ? libraries[ libraries.length - 1 ] : '' ),
  35284. smooth : ( previous !== undefined ? previous.smooth : this.smooth ),
  35285. groupStart : ( previous !== undefined ? previous.groupEnd : 0 ),
  35286. groupEnd : -1,
  35287. groupCount : -1,
  35288. inherited : false,
  35289. clone : function( index ) {
  35290. var cloned = {
  35291. index : ( typeof index === 'number' ? index : this.index ),
  35292. name : this.name,
  35293. mtllib : this.mtllib,
  35294. smooth : this.smooth,
  35295. groupStart : 0,
  35296. groupEnd : -1,
  35297. groupCount : -1,
  35298. inherited : false
  35299. };
  35300. cloned.clone = this.clone.bind(cloned);
  35301. return cloned;
  35302. }
  35303. };
  35304. this.materials.push( material );
  35305. return material;
  35306. },
  35307. currentMaterial : function() {
  35308. if ( this.materials.length > 0 ) {
  35309. return this.materials[ this.materials.length - 1 ];
  35310. }
  35311. return undefined;
  35312. },
  35313. _finalize : function( end ) {
  35314. var lastMultiMaterial = this.currentMaterial();
  35315. if ( lastMultiMaterial && lastMultiMaterial.groupEnd === -1 ) {
  35316. lastMultiMaterial.groupEnd = this.geometry.vertices.length / 3;
  35317. lastMultiMaterial.groupCount = lastMultiMaterial.groupEnd - lastMultiMaterial.groupStart;
  35318. lastMultiMaterial.inherited = false;
  35319. }
  35320. // Ignore objects tail materials if no face declarations followed them before a new o/g started.
  35321. if ( end && this.materials.length > 1 ) {
  35322. for ( var mi = this.materials.length - 1; mi >= 0; mi-- ) {
  35323. if ( this.materials[mi].groupCount <= 0 ) {
  35324. this.materials.splice( mi, 1 );
  35325. }
  35326. }
  35327. }
  35328. // Guarantee at least one empty material, this makes the creation later more straight forward.
  35329. if ( end && this.materials.length === 0 ) {
  35330. this.materials.push({
  35331. name : '',
  35332. smooth : this.smooth
  35333. });
  35334. }
  35335. return lastMultiMaterial;
  35336. }
  35337. };
  35338. // Inherit previous objects material.
  35339. // Spec tells us that a declared material must be set to all objects until a new material is declared.
  35340. // If a usemtl declaration is encountered while this new object is being parsed, it will
  35341. // overwrite the inherited material. Exception being that there was already face declarations
  35342. // to the inherited material, then it will be preserved for proper MultiMaterial continuation.
  35343. if ( previousMaterial && previousMaterial.name && typeof previousMaterial.clone === "function" ) {
  35344. var declared = previousMaterial.clone( 0 );
  35345. declared.inherited = true;
  35346. this.object.materials.push( declared );
  35347. }
  35348. this.objects.push( this.object );
  35349. },
  35350. finalize : function() {
  35351. if ( this.object && typeof this.object._finalize === 'function' ) {
  35352. this.object._finalize( true );
  35353. }
  35354. },
  35355. parseVertexIndex: function ( value, len ) {
  35356. var index = parseInt( value, 10 );
  35357. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  35358. },
  35359. parseNormalIndex: function ( value, len ) {
  35360. var index = parseInt( value, 10 );
  35361. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  35362. },
  35363. parseUVIndex: function ( value, len ) {
  35364. var index = parseInt( value, 10 );
  35365. return ( index >= 0 ? index - 1 : index + len / 2 ) * 2;
  35366. },
  35367. addVertex: function ( a, b, c ) {
  35368. var src = this.vertices;
  35369. var dst = this.object.geometry.vertices;
  35370. dst.push( src[ a + 0 ] );
  35371. dst.push( src[ a + 1 ] );
  35372. dst.push( src[ a + 2 ] );
  35373. dst.push( src[ b + 0 ] );
  35374. dst.push( src[ b + 1 ] );
  35375. dst.push( src[ b + 2 ] );
  35376. dst.push( src[ c + 0 ] );
  35377. dst.push( src[ c + 1 ] );
  35378. dst.push( src[ c + 2 ] );
  35379. },
  35380. addVertexLine: function ( a ) {
  35381. var src = this.vertices;
  35382. var dst = this.object.geometry.vertices;
  35383. dst.push( src[ a + 0 ] );
  35384. dst.push( src[ a + 1 ] );
  35385. dst.push( src[ a + 2 ] );
  35386. },
  35387. addNormal : function ( a, b, c ) {
  35388. var src = this.normals;
  35389. var dst = this.object.geometry.normals;
  35390. dst.push( src[ a + 0 ] );
  35391. dst.push( src[ a + 1 ] );
  35392. dst.push( src[ a + 2 ] );
  35393. dst.push( src[ b + 0 ] );
  35394. dst.push( src[ b + 1 ] );
  35395. dst.push( src[ b + 2 ] );
  35396. dst.push( src[ c + 0 ] );
  35397. dst.push( src[ c + 1 ] );
  35398. dst.push( src[ c + 2 ] );
  35399. },
  35400. addUV: function ( a, b, c ) {
  35401. var src = this.uvs;
  35402. var dst = this.object.geometry.uvs;
  35403. dst.push( src[ a + 0 ] );
  35404. dst.push( src[ a + 1 ] );
  35405. dst.push( src[ b + 0 ] );
  35406. dst.push( src[ b + 1 ] );
  35407. dst.push( src[ c + 0 ] );
  35408. dst.push( src[ c + 1 ] );
  35409. },
  35410. addUVLine: function ( a ) {
  35411. var src = this.uvs;
  35412. var dst = this.object.geometry.uvs;
  35413. dst.push( src[ a + 0 ] );
  35414. dst.push( src[ a + 1 ] );
  35415. },
  35416. addFace: function ( a, b, c, d, ua, ub, uc, ud, na, nb, nc, nd ) {
  35417. var vLen = this.vertices.length;
  35418. var ia = this.parseVertexIndex( a, vLen );
  35419. var ib = this.parseVertexIndex( b, vLen );
  35420. var ic = this.parseVertexIndex( c, vLen );
  35421. var id;
  35422. if ( d === undefined ) {
  35423. this.addVertex( ia, ib, ic );
  35424. } else {
  35425. id = this.parseVertexIndex( d, vLen );
  35426. this.addVertex( ia, ib, id );
  35427. this.addVertex( ib, ic, id );
  35428. }
  35429. if ( ua !== undefined ) {
  35430. var uvLen = this.uvs.length;
  35431. ia = this.parseUVIndex( ua, uvLen );
  35432. ib = this.parseUVIndex( ub, uvLen );
  35433. ic = this.parseUVIndex( uc, uvLen );
  35434. if ( d === undefined ) {
  35435. this.addUV( ia, ib, ic );
  35436. } else {
  35437. id = this.parseUVIndex( ud, uvLen );
  35438. this.addUV( ia, ib, id );
  35439. this.addUV( ib, ic, id );
  35440. }
  35441. }
  35442. if ( na !== undefined ) {
  35443. // Normals are many times the same. If so, skip function call and parseInt.
  35444. var nLen = this.normals.length;
  35445. ia = this.parseNormalIndex( na, nLen );
  35446. ib = na === nb ? ia : this.parseNormalIndex( nb, nLen );
  35447. ic = na === nc ? ia : this.parseNormalIndex( nc, nLen );
  35448. if ( d === undefined ) {
  35449. this.addNormal( ia, ib, ic );
  35450. } else {
  35451. id = this.parseNormalIndex( nd, nLen );
  35452. this.addNormal( ia, ib, id );
  35453. this.addNormal( ib, ic, id );
  35454. }
  35455. }
  35456. },
  35457. addLineGeometry: function ( vertices, uvs ) {
  35458. this.object.geometry.type = 'Line';
  35459. var vLen = this.vertices.length;
  35460. var uvLen = this.uvs.length;
  35461. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  35462. this.addVertexLine( this.parseVertexIndex( vertices[ vi ], vLen ) );
  35463. }
  35464. for ( var uvi = 0, l = uvs.length; uvi < l; uvi ++ ) {
  35465. this.addUVLine( this.parseUVIndex( uvs[ uvi ], uvLen ) );
  35466. }
  35467. }
  35468. };
  35469. state.startObject( '', false );
  35470. return state;
  35471. },
  35472. parse: function ( text ) {
  35473. console.time( 'OBJLoader' );
  35474. var state = this._createParserState();
  35475. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  35476. // This is faster than String.split with regex that splits on both
  35477. text = text.replace( /\r\n/g, '\n' );
  35478. }
  35479. if ( text.indexOf( '\\\n' ) !== - 1) {
  35480. // join lines separated by a line continuation character (\)
  35481. text = text.replace( /\\\n/g, '' );
  35482. }
  35483. var lines = text.split( '\n' );
  35484. var line = '', lineFirstChar = '', lineSecondChar = '';
  35485. var lineLength = 0;
  35486. var result = [];
  35487. // Faster to just trim left side of the line. Use if available.
  35488. var trimLeft = ( typeof ''.trimLeft === 'function' );
  35489. for ( var i = 0, l = lines.length; i < l; i ++ ) {
  35490. line = lines[ i ];
  35491. line = trimLeft ? line.trimLeft() : line.trim();
  35492. lineLength = line.length;
  35493. if ( lineLength === 0 ) continue;
  35494. lineFirstChar = line.charAt( 0 );
  35495. // @todo invoke passed in handler if any
  35496. if ( lineFirstChar === '#' ) continue;
  35497. if ( lineFirstChar === 'v' ) {
  35498. lineSecondChar = line.charAt( 1 );
  35499. if ( lineSecondChar === ' ' && ( result = this.regexp.vertex_pattern.exec( line ) ) !== null ) {
  35500. // 0 1 2 3
  35501. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  35502. state.vertices.push(
  35503. parseFloat( result[ 1 ] ),
  35504. parseFloat( result[ 2 ] ),
  35505. parseFloat( result[ 3 ] )
  35506. );
  35507. } else if ( lineSecondChar === 'n' && ( result = this.regexp.normal_pattern.exec( line ) ) !== null ) {
  35508. // 0 1 2 3
  35509. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  35510. state.normals.push(
  35511. parseFloat( result[ 1 ] ),
  35512. parseFloat( result[ 2 ] ),
  35513. parseFloat( result[ 3 ] )
  35514. );
  35515. } else if ( lineSecondChar === 't' && ( result = this.regexp.uv_pattern.exec( line ) ) !== null ) {
  35516. // 0 1 2
  35517. // ["vt 0.1 0.2", "0.1", "0.2"]
  35518. state.uvs.push(
  35519. parseFloat( result[ 1 ] ),
  35520. parseFloat( result[ 2 ] )
  35521. );
  35522. } else {
  35523. throw new Error( "Unexpected vertex/normal/uv line: '" + line + "'" );
  35524. }
  35525. } else if ( lineFirstChar === "f" ) {
  35526. if ( ( result = this.regexp.face_vertex_uv_normal.exec( line ) ) !== null ) {
  35527. // f vertex/uv/normal vertex/uv/normal vertex/uv/normal
  35528. // 0 1 2 3 4 5 6 7 8 9 10 11 12
  35529. // ["f 1/1/1 2/2/2 3/3/3", "1", "1", "1", "2", "2", "2", "3", "3", "3", undefined, undefined, undefined]
  35530. state.addFace(
  35531. result[ 1 ], result[ 4 ], result[ 7 ], result[ 10 ],
  35532. result[ 2 ], result[ 5 ], result[ 8 ], result[ 11 ],
  35533. result[ 3 ], result[ 6 ], result[ 9 ], result[ 12 ]
  35534. );
  35535. } else if ( ( result = this.regexp.face_vertex_uv.exec( line ) ) !== null ) {
  35536. // f vertex/uv vertex/uv vertex/uv
  35537. // 0 1 2 3 4 5 6 7 8
  35538. // ["f 1/1 2/2 3/3", "1", "1", "2", "2", "3", "3", undefined, undefined]
  35539. state.addFace(
  35540. result[ 1 ], result[ 3 ], result[ 5 ], result[ 7 ],
  35541. result[ 2 ], result[ 4 ], result[ 6 ], result[ 8 ]
  35542. );
  35543. } else if ( ( result = this.regexp.face_vertex_normal.exec( line ) ) !== null ) {
  35544. // f vertex//normal vertex//normal vertex//normal
  35545. // 0 1 2 3 4 5 6 7 8
  35546. // ["f 1//1 2//2 3//3", "1", "1", "2", "2", "3", "3", undefined, undefined]
  35547. state.addFace(
  35548. result[ 1 ], result[ 3 ], result[ 5 ], result[ 7 ],
  35549. undefined, undefined, undefined, undefined,
  35550. result[ 2 ], result[ 4 ], result[ 6 ], result[ 8 ]
  35551. );
  35552. } else if ( ( result = this.regexp.face_vertex.exec( line ) ) !== null ) {
  35553. // f vertex vertex vertex
  35554. // 0 1 2 3 4
  35555. // ["f 1 2 3", "1", "2", "3", undefined]
  35556. state.addFace(
  35557. result[ 1 ], result[ 2 ], result[ 3 ], result[ 4 ]
  35558. );
  35559. } else {
  35560. throw new Error( "Unexpected face line: '" + line + "'" );
  35561. }
  35562. } else if ( lineFirstChar === "l" ) {
  35563. var lineParts = line.substring( 1 ).trim().split( " " );
  35564. var lineVertices = [], lineUVs = [];
  35565. if ( line.indexOf( "/" ) === - 1 ) {
  35566. lineVertices = lineParts;
  35567. } else {
  35568. for ( var li = 0, llen = lineParts.length; li < llen; li ++ ) {
  35569. var parts = lineParts[ li ].split( "/" );
  35570. if ( parts[ 0 ] !== "" ) lineVertices.push( parts[ 0 ] );
  35571. if ( parts[ 1 ] !== "" ) lineUVs.push( parts[ 1 ] );
  35572. }
  35573. }
  35574. state.addLineGeometry( lineVertices, lineUVs );
  35575. } else if ( ( result = this.regexp.object_pattern.exec( line ) ) !== null ) {
  35576. // o object_name
  35577. // or
  35578. // g group_name
  35579. // WORKAROUND: https://bugs.chromium.org/p/v8/issues/detail?id=2869
  35580. // var name = result[ 0 ].substr( 1 ).trim();
  35581. var name = ( " " + result[ 0 ].substr( 1 ).trim() ).substr( 1 );
  35582. state.startObject( name );
  35583. } else if ( this.regexp.material_use_pattern.test( line ) ) {
  35584. // material
  35585. state.object.startMaterial( line.substring( 7 ).trim(), state.materialLibraries );
  35586. } else if ( this.regexp.material_library_pattern.test( line ) ) {
  35587. // mtl file
  35588. state.materialLibraries.push( line.substring( 7 ).trim() );
  35589. } else if ( ( result = this.regexp.smoothing_pattern.exec( line ) ) !== null ) {
  35590. // smooth shading
  35591. // @todo Handle files that have varying smooth values for a set of faces inside one geometry,
  35592. // but does not define a usemtl for each face set.
  35593. // This should be detected and a dummy material created (later MultiMaterial and geometry groups).
  35594. // This requires some care to not create extra material on each smooth value for "normal" obj files.
  35595. // where explicit usemtl defines geometry groups.
  35596. // Example asset: examples/models/obj/cerberus/Cerberus.obj
  35597. var value = result[ 1 ].trim().toLowerCase();
  35598. state.object.smooth = ( value === '1' || value === 'on' );
  35599. var material = state.object.currentMaterial();
  35600. if ( material ) {
  35601. material.smooth = state.object.smooth;
  35602. }
  35603. } else {
  35604. // Handle null terminated files without exception
  35605. if ( line === '\0' ) continue;
  35606. throw new Error( "Unexpected line: '" + line + "'" );
  35607. }
  35608. }
  35609. state.finalize();
  35610. var container = new THREE.Group();
  35611. container.materialLibraries = [].concat( state.materialLibraries );
  35612. for ( var i = 0, l = state.objects.length; i < l; i ++ ) {
  35613. var object = state.objects[ i ];
  35614. var geometry = object.geometry;
  35615. var materials = object.materials;
  35616. var isLine = ( geometry.type === 'Line' );
  35617. // Skip o/g line declarations that did not follow with any faces
  35618. if ( geometry.vertices.length === 0 ) continue;
  35619. var buffergeometry = new THREE.BufferGeometry();
  35620. buffergeometry.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( geometry.vertices ), 3 ) );
  35621. if ( geometry.normals.length > 0 ) {
  35622. buffergeometry.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( geometry.normals ), 3 ) );
  35623. } else {
  35624. buffergeometry.computeVertexNormals();
  35625. }
  35626. if ( geometry.uvs.length > 0 ) {
  35627. buffergeometry.addAttribute( 'uv', new THREE.BufferAttribute( new Float32Array( geometry.uvs ), 2 ) );
  35628. }
  35629. // Create materials
  35630. var createdMaterials = [];
  35631. for ( var mi = 0, miLen = materials.length; mi < miLen ; mi++ ) {
  35632. var sourceMaterial = materials[mi];
  35633. var material = undefined;
  35634. if ( this.materials !== null ) {
  35635. material = this.materials.create( sourceMaterial.name );
  35636. // mtl etc. loaders probably can't create line materials correctly, copy properties to a line material.
  35637. if ( isLine && material && ! ( material instanceof THREE.LineBasicMaterial ) ) {
  35638. var materialLine = new THREE.LineBasicMaterial();
  35639. materialLine.copy( material );
  35640. material = materialLine;
  35641. }
  35642. }
  35643. if ( ! material ) {
  35644. material = ( ! isLine ? new THREE.MeshPhongMaterial() : new THREE.LineBasicMaterial() );
  35645. material.name = sourceMaterial.name;
  35646. }
  35647. material.shading = sourceMaterial.smooth ? THREE.SmoothShading : THREE.FlatShading;
  35648. createdMaterials.push(material);
  35649. }
  35650. // Create mesh
  35651. var mesh;
  35652. if ( createdMaterials.length > 1 ) {
  35653. for ( var mi = 0, miLen = materials.length; mi < miLen ; mi++ ) {
  35654. var sourceMaterial = materials[mi];
  35655. buffergeometry.addGroup( sourceMaterial.groupStart, sourceMaterial.groupCount, mi );
  35656. }
  35657. var multiMaterial = new THREE.MultiMaterial( createdMaterials );
  35658. mesh = ( ! isLine ? new THREE.Mesh( buffergeometry, multiMaterial ) : new THREE.LineSegments( buffergeometry, multiMaterial ) );
  35659. } else {
  35660. mesh = ( ! isLine ? new THREE.Mesh( buffergeometry, createdMaterials[ 0 ] ) : new THREE.LineSegments( buffergeometry, createdMaterials[ 0 ] ) );
  35661. }
  35662. mesh.name = object.name;
  35663. container.add( mesh );
  35664. }
  35665. console.timeEnd( 'OBJLoader' );
  35666. return container;
  35667. }
  35668. };
  35669. },{}],47:[function(_dereq_,module,exports){
  35670. exports = module.exports = trim;
  35671. function trim(str){
  35672. return str.replace(/^\s*|\s*$/g, '');
  35673. }
  35674. exports.left = function(str){
  35675. return str.replace(/^\s*/, '');
  35676. };
  35677. exports.right = function(str){
  35678. return str.replace(/\s*$/, '');
  35679. };
  35680. },{}],48:[function(_dereq_,module,exports){
  35681. /**
  35682. * Tween.js - Licensed under the MIT license
  35683. * https://github.com/sole/tween.js
  35684. * ----------------------------------------------
  35685. *
  35686. * See https://github.com/sole/tween.js/graphs/contributors for the full list of contributors.
  35687. * Thank you all, you're awesome!
  35688. */
  35689. // performance.now polyfill
  35690. ( function ( root ) {
  35691. if ( 'performance' in root === false ) {
  35692. root.performance = {};
  35693. }
  35694. // IE 8
  35695. Date.now = ( Date.now || function () {
  35696. return new Date().getTime();
  35697. } );
  35698. if ( 'now' in root.performance === false ) {
  35699. var offset = root.performance.timing && root.performance.timing.navigationStart ? performance.timing.navigationStart
  35700. : Date.now();
  35701. root.performance.now = function () {
  35702. return Date.now() - offset;
  35703. };
  35704. }
  35705. } )( this );
  35706. var TWEEN = TWEEN || ( function () {
  35707. var _tweens = [];
  35708. return {
  35709. REVISION: '14',
  35710. getAll: function () {
  35711. return _tweens;
  35712. },
  35713. removeAll: function () {
  35714. _tweens = [];
  35715. },
  35716. add: function ( tween ) {
  35717. _tweens.push( tween );
  35718. },
  35719. remove: function ( tween ) {
  35720. var i = _tweens.indexOf( tween );
  35721. if ( i !== -1 ) {
  35722. _tweens.splice( i, 1 );
  35723. }
  35724. },
  35725. update: function ( time ) {
  35726. if ( _tweens.length === 0 ) return false;
  35727. var i = 0;
  35728. time = time !== undefined ? time : window.performance.now();
  35729. while ( i < _tweens.length ) {
  35730. if ( _tweens[ i ].update( time ) ) {
  35731. i++;
  35732. } else {
  35733. _tweens.splice( i, 1 );
  35734. }
  35735. }
  35736. return true;
  35737. }
  35738. };
  35739. } )();
  35740. TWEEN.Tween = function ( object ) {
  35741. var _object = object;
  35742. var _valuesStart = {};
  35743. var _valuesEnd = {};
  35744. var _valuesStartRepeat = {};
  35745. var _duration = 1000;
  35746. var _repeat = 0;
  35747. var _yoyo = false;
  35748. var _isPlaying = false;
  35749. var _reversed = false;
  35750. var _delayTime = 0;
  35751. var _startTime = null;
  35752. var _easingFunction = TWEEN.Easing.Linear.None;
  35753. var _interpolationFunction = TWEEN.Interpolation.Linear;
  35754. var _chainedTweens = [];
  35755. var _onStartCallback = null;
  35756. var _onStartCallbackFired = false;
  35757. var _onUpdateCallback = null;
  35758. var _onCompleteCallback = null;
  35759. var _onStopCallback = null;
  35760. // Set all starting values present on the target object
  35761. for ( var field in object ) {
  35762. _valuesStart[ field ] = parseFloat(object[field], 10);
  35763. }
  35764. this.to = function ( properties, duration ) {
  35765. if ( duration !== undefined ) {
  35766. _duration = duration;
  35767. }
  35768. _valuesEnd = properties;
  35769. return this;
  35770. };
  35771. this.start = function ( time ) {
  35772. TWEEN.add( this );
  35773. _isPlaying = true;
  35774. _onStartCallbackFired = false;
  35775. _startTime = time !== undefined ? time : window.performance.now();
  35776. _startTime += _delayTime;
  35777. for ( var property in _valuesEnd ) {
  35778. // check if an Array was provided as property value
  35779. if ( _valuesEnd[ property ] instanceof Array ) {
  35780. if ( _valuesEnd[ property ].length === 0 ) {
  35781. continue;
  35782. }
  35783. // create a local copy of the Array with the start value at the front
  35784. _valuesEnd[ property ] = [ _object[ property ] ].concat( _valuesEnd[ property ] );
  35785. }
  35786. _valuesStart[ property ] = _object[ property ];
  35787. if( ( _valuesStart[ property ] instanceof Array ) === false ) {
  35788. _valuesStart[ property ] *= 1.0; // Ensures we're using numbers, not strings
  35789. }
  35790. _valuesStartRepeat[ property ] = _valuesStart[ property ] || 0;
  35791. }
  35792. return this;
  35793. };
  35794. this.stop = function () {
  35795. if ( !_isPlaying ) {
  35796. return this;
  35797. }
  35798. TWEEN.remove( this );
  35799. _isPlaying = false;
  35800. if ( _onStopCallback !== null ) {
  35801. _onStopCallback.call( _object );
  35802. }
  35803. this.stopChainedTweens();
  35804. return this;
  35805. };
  35806. this.stopChainedTweens = function () {
  35807. for ( var i = 0, numChainedTweens = _chainedTweens.length; i < numChainedTweens; i++ ) {
  35808. _chainedTweens[ i ].stop();
  35809. }
  35810. };
  35811. this.delay = function ( amount ) {
  35812. _delayTime = amount;
  35813. return this;
  35814. };
  35815. this.repeat = function ( times ) {
  35816. _repeat = times;
  35817. return this;
  35818. };
  35819. this.yoyo = function( yoyo ) {
  35820. _yoyo = yoyo;
  35821. return this;
  35822. };
  35823. this.easing = function ( easing ) {
  35824. _easingFunction = easing;
  35825. return this;
  35826. };
  35827. this.interpolation = function ( interpolation ) {
  35828. _interpolationFunction = interpolation;
  35829. return this;
  35830. };
  35831. this.chain = function () {
  35832. _chainedTweens = arguments;
  35833. return this;
  35834. };
  35835. this.onStart = function ( callback ) {
  35836. _onStartCallback = callback;
  35837. return this;
  35838. };
  35839. this.onUpdate = function ( callback ) {
  35840. _onUpdateCallback = callback;
  35841. return this;
  35842. };
  35843. this.onComplete = function ( callback ) {
  35844. _onCompleteCallback = callback;
  35845. return this;
  35846. };
  35847. this.onStop = function ( callback ) {
  35848. _onStopCallback = callback;
  35849. return this;
  35850. };
  35851. this.update = function ( time ) {
  35852. var property;
  35853. if ( time < _startTime ) {
  35854. return true;
  35855. }
  35856. if ( _onStartCallbackFired === false ) {
  35857. if ( _onStartCallback !== null ) {
  35858. _onStartCallback.call( _object );
  35859. }
  35860. _onStartCallbackFired = true;
  35861. }
  35862. var elapsed = ( time - _startTime ) / _duration;
  35863. elapsed = elapsed > 1 ? 1 : elapsed;
  35864. var value = _easingFunction( elapsed );
  35865. for ( property in _valuesEnd ) {
  35866. var start = _valuesStart[ property ] || 0;
  35867. var end = _valuesEnd[ property ];
  35868. if ( end instanceof Array ) {
  35869. _object[ property ] = _interpolationFunction( end, value );
  35870. } else {
  35871. // Parses relative end values with start as base (e.g.: +10, -3)
  35872. if ( typeof(end) === "string" ) {
  35873. end = start + parseFloat(end, 10);
  35874. }
  35875. // protect against non numeric properties.
  35876. if ( typeof(end) === "number" ) {
  35877. _object[ property ] = start + ( end - start ) * value;
  35878. }
  35879. }
  35880. }
  35881. if ( _onUpdateCallback !== null ) {
  35882. _onUpdateCallback.call( _object, value );
  35883. }
  35884. if ( elapsed == 1 ) {
  35885. if ( _repeat > 0 ) {
  35886. if( isFinite( _repeat ) ) {
  35887. _repeat--;
  35888. }
  35889. // reassign starting values, restart by making startTime = now
  35890. for( property in _valuesStartRepeat ) {
  35891. if ( typeof( _valuesEnd[ property ] ) === "string" ) {
  35892. _valuesStartRepeat[ property ] = _valuesStartRepeat[ property ] + parseFloat(_valuesEnd[ property ], 10);
  35893. }
  35894. if (_yoyo) {
  35895. var tmp = _valuesStartRepeat[ property ];
  35896. _valuesStartRepeat[ property ] = _valuesEnd[ property ];
  35897. _valuesEnd[ property ] = tmp;
  35898. }
  35899. _valuesStart[ property ] = _valuesStartRepeat[ property ];
  35900. }
  35901. if (_yoyo) {
  35902. _reversed = !_reversed;
  35903. }
  35904. _startTime = time + _delayTime;
  35905. return true;
  35906. } else {
  35907. if ( _onCompleteCallback !== null ) {
  35908. _onCompleteCallback.call( _object );
  35909. }
  35910. for ( var i = 0, numChainedTweens = _chainedTweens.length; i < numChainedTweens; i++ ) {
  35911. _chainedTweens[ i ].start( time );
  35912. }
  35913. return false;
  35914. }
  35915. }
  35916. return true;
  35917. };
  35918. };
  35919. TWEEN.Easing = {
  35920. Linear: {
  35921. None: function ( k ) {
  35922. return k;
  35923. }
  35924. },
  35925. Quadratic: {
  35926. In: function ( k ) {
  35927. return k * k;
  35928. },
  35929. Out: function ( k ) {
  35930. return k * ( 2 - k );
  35931. },
  35932. InOut: function ( k ) {
  35933. if ( ( k *= 2 ) < 1 ) return 0.5 * k * k;
  35934. return - 0.5 * ( --k * ( k - 2 ) - 1 );
  35935. }
  35936. },
  35937. Cubic: {
  35938. In: function ( k ) {
  35939. return k * k * k;
  35940. },
  35941. Out: function ( k ) {
  35942. return --k * k * k + 1;
  35943. },
  35944. InOut: function ( k ) {
  35945. if ( ( k *= 2 ) < 1 ) return 0.5 * k * k * k;
  35946. return 0.5 * ( ( k -= 2 ) * k * k + 2 );
  35947. }
  35948. },
  35949. Quartic: {
  35950. In: function ( k ) {
  35951. return k * k * k * k;
  35952. },
  35953. Out: function ( k ) {
  35954. return 1 - ( --k * k * k * k );
  35955. },
  35956. InOut: function ( k ) {
  35957. if ( ( k *= 2 ) < 1) return 0.5 * k * k * k * k;
  35958. return - 0.5 * ( ( k -= 2 ) * k * k * k - 2 );
  35959. }
  35960. },
  35961. Quintic: {
  35962. In: function ( k ) {
  35963. return k * k * k * k * k;
  35964. },
  35965. Out: function ( k ) {
  35966. return --k * k * k * k * k + 1;
  35967. },
  35968. InOut: function ( k ) {
  35969. if ( ( k *= 2 ) < 1 ) return 0.5 * k * k * k * k * k;
  35970. return 0.5 * ( ( k -= 2 ) * k * k * k * k + 2 );
  35971. }
  35972. },
  35973. Sinusoidal: {
  35974. In: function ( k ) {
  35975. return 1 - Math.cos( k * Math.PI / 2 );
  35976. },
  35977. Out: function ( k ) {
  35978. return Math.sin( k * Math.PI / 2 );
  35979. },
  35980. InOut: function ( k ) {
  35981. return 0.5 * ( 1 - Math.cos( Math.PI * k ) );
  35982. }
  35983. },
  35984. Exponential: {
  35985. In: function ( k ) {
  35986. return k === 0 ? 0 : Math.pow( 1024, k - 1 );
  35987. },
  35988. Out: function ( k ) {
  35989. return k === 1 ? 1 : 1 - Math.pow( 2, - 10 * k );
  35990. },
  35991. InOut: function ( k ) {
  35992. if ( k === 0 ) return 0;
  35993. if ( k === 1 ) return 1;
  35994. if ( ( k *= 2 ) < 1 ) return 0.5 * Math.pow( 1024, k - 1 );
  35995. return 0.5 * ( - Math.pow( 2, - 10 * ( k - 1 ) ) + 2 );
  35996. }
  35997. },
  35998. Circular: {
  35999. In: function ( k ) {
  36000. return 1 - Math.sqrt( 1 - k * k );
  36001. },
  36002. Out: function ( k ) {
  36003. return Math.sqrt( 1 - ( --k * k ) );
  36004. },
  36005. InOut: function ( k ) {
  36006. if ( ( k *= 2 ) < 1) return - 0.5 * ( Math.sqrt( 1 - k * k) - 1);
  36007. return 0.5 * ( Math.sqrt( 1 - ( k -= 2) * k) + 1);
  36008. }
  36009. },
  36010. Elastic: {
  36011. In: function ( k ) {
  36012. var s, a = 0.1, p = 0.4;
  36013. if ( k === 0 ) return 0;
  36014. if ( k === 1 ) return 1;
  36015. if ( !a || a < 1 ) { a = 1; s = p / 4; }
  36016. else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI );
  36017. return - ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) );
  36018. },
  36019. Out: function ( k ) {
  36020. var s, a = 0.1, p = 0.4;
  36021. if ( k === 0 ) return 0;
  36022. if ( k === 1 ) return 1;
  36023. if ( !a || a < 1 ) { a = 1; s = p / 4; }
  36024. else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI );
  36025. return ( a * Math.pow( 2, - 10 * k) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) + 1 );
  36026. },
  36027. InOut: function ( k ) {
  36028. var s, a = 0.1, p = 0.4;
  36029. if ( k === 0 ) return 0;
  36030. if ( k === 1 ) return 1;
  36031. if ( !a || a < 1 ) { a = 1; s = p / 4; }
  36032. else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI );
  36033. if ( ( k *= 2 ) < 1 ) return - 0.5 * ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) );
  36034. return a * Math.pow( 2, -10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) * 0.5 + 1;
  36035. }
  36036. },
  36037. Back: {
  36038. In: function ( k ) {
  36039. var s = 1.70158;
  36040. return k * k * ( ( s + 1 ) * k - s );
  36041. },
  36042. Out: function ( k ) {
  36043. var s = 1.70158;
  36044. return --k * k * ( ( s + 1 ) * k + s ) + 1;
  36045. },
  36046. InOut: function ( k ) {
  36047. var s = 1.70158 * 1.525;
  36048. if ( ( k *= 2 ) < 1 ) return 0.5 * ( k * k * ( ( s + 1 ) * k - s ) );
  36049. return 0.5 * ( ( k -= 2 ) * k * ( ( s + 1 ) * k + s ) + 2 );
  36050. }
  36051. },
  36052. Bounce: {
  36053. In: function ( k ) {
  36054. return 1 - TWEEN.Easing.Bounce.Out( 1 - k );
  36055. },
  36056. Out: function ( k ) {
  36057. if ( k < ( 1 / 2.75 ) ) {
  36058. return 7.5625 * k * k;
  36059. } else if ( k < ( 2 / 2.75 ) ) {
  36060. return 7.5625 * ( k -= ( 1.5 / 2.75 ) ) * k + 0.75;
  36061. } else if ( k < ( 2.5 / 2.75 ) ) {
  36062. return 7.5625 * ( k -= ( 2.25 / 2.75 ) ) * k + 0.9375;
  36063. } else {
  36064. return 7.5625 * ( k -= ( 2.625 / 2.75 ) ) * k + 0.984375;
  36065. }
  36066. },
  36067. InOut: function ( k ) {
  36068. if ( k < 0.5 ) return TWEEN.Easing.Bounce.In( k * 2 ) * 0.5;
  36069. return TWEEN.Easing.Bounce.Out( k * 2 - 1 ) * 0.5 + 0.5;
  36070. }
  36071. }
  36072. };
  36073. TWEEN.Interpolation = {
  36074. Linear: function ( v, k ) {
  36075. var m = v.length - 1, f = m * k, i = Math.floor( f ), fn = TWEEN.Interpolation.Utils.Linear;
  36076. if ( k < 0 ) return fn( v[ 0 ], v[ 1 ], f );
  36077. if ( k > 1 ) return fn( v[ m ], v[ m - 1 ], m - f );
  36078. return fn( v[ i ], v[ i + 1 > m ? m : i + 1 ], f - i );
  36079. },
  36080. Bezier: function ( v, k ) {
  36081. var b = 0, n = v.length - 1, pw = Math.pow, bn = TWEEN.Interpolation.Utils.Bernstein, i;
  36082. for ( i = 0; i <= n; i++ ) {
  36083. b += pw( 1 - k, n - i ) * pw( k, i ) * v[ i ] * bn( n, i );
  36084. }
  36085. return b;
  36086. },
  36087. CatmullRom: function ( v, k ) {
  36088. var m = v.length - 1, f = m * k, i = Math.floor( f ), fn = TWEEN.Interpolation.Utils.CatmullRom;
  36089. if ( v[ 0 ] === v[ m ] ) {
  36090. if ( k < 0 ) i = Math.floor( f = m * ( 1 + k ) );
  36091. return fn( v[ ( i - 1 + m ) % m ], v[ i ], v[ ( i + 1 ) % m ], v[ ( i + 2 ) % m ], f - i );
  36092. } else {
  36093. if ( k < 0 ) return v[ 0 ] - ( fn( v[ 0 ], v[ 0 ], v[ 1 ], v[ 1 ], -f ) - v[ 0 ] );
  36094. if ( k > 1 ) return v[ m ] - ( fn( v[ m ], v[ m ], v[ m - 1 ], v[ m - 1 ], f - m ) - v[ m ] );
  36095. 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 );
  36096. }
  36097. },
  36098. Utils: {
  36099. Linear: function ( p0, p1, t ) {
  36100. return ( p1 - p0 ) * t + p0;
  36101. },
  36102. Bernstein: function ( n , i ) {
  36103. var fc = TWEEN.Interpolation.Utils.Factorial;
  36104. return fc( n ) / fc( i ) / fc( n - i );
  36105. },
  36106. Factorial: ( function () {
  36107. var a = [ 1 ];
  36108. return function ( n ) {
  36109. var s = 1, i;
  36110. if ( a[ n ] ) return a[ n ];
  36111. for ( i = n; i > 1; i-- ) s *= i;
  36112. return a[ n ] = s;
  36113. };
  36114. } )(),
  36115. CatmullRom: function ( p0, p1, p2, p3, t ) {
  36116. var v0 = ( p2 - p0 ) * 0.5, v1 = ( p3 - p1 ) * 0.5, t2 = t * t, t3 = t * t2;
  36117. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  36118. }
  36119. }
  36120. };
  36121. // UMD (Universal Module Definition)
  36122. ( function ( root ) {
  36123. if ( typeof define === 'function' && define.amd ) {
  36124. // AMD
  36125. define( [], function () {
  36126. return TWEEN;
  36127. } );
  36128. } else if ( typeof exports === 'object' ) {
  36129. // Node.js
  36130. module.exports = TWEEN;
  36131. } else {
  36132. // Global variable
  36133. root.TWEEN = TWEEN;
  36134. }
  36135. } )( this );
  36136. },{}],49:[function(_dereq_,module,exports){
  36137. (function (global){
  36138. (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.WebVRPolyfill = 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 _dereq_=="function"&&_dereq_;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 _dereq_=="function"&&_dereq_;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
  36139. 'use strict';
  36140. var has = Object.prototype.hasOwnProperty
  36141. , prefix = '~';
  36142. /**
  36143. * Constructor to create a storage for our `EE` objects.
  36144. * An `Events` instance is a plain object whose properties are event names.
  36145. *
  36146. * @constructor
  36147. * @api private
  36148. */
  36149. function Events() {}
  36150. //
  36151. // We try to not inherit from `Object.prototype`. In some engines creating an
  36152. // instance in this way is faster than calling `Object.create(null)` directly.
  36153. // If `Object.create(null)` is not supported we prefix the event names with a
  36154. // character to make sure that the built-in object properties are not
  36155. // overridden or used as an attack vector.
  36156. //
  36157. if (Object.create) {
  36158. Events.prototype = Object.create(null);
  36159. //
  36160. // This hack is needed because the `__proto__` property is still inherited in
  36161. // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
  36162. //
  36163. if (!new Events().__proto__) prefix = false;
  36164. }
  36165. /**
  36166. * Representation of a single event listener.
  36167. *
  36168. * @param {Function} fn The listener function.
  36169. * @param {Mixed} context The context to invoke the listener with.
  36170. * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
  36171. * @constructor
  36172. * @api private
  36173. */
  36174. function EE(fn, context, once) {
  36175. this.fn = fn;
  36176. this.context = context;
  36177. this.once = once || false;
  36178. }
  36179. /**
  36180. * Minimal `EventEmitter` interface that is molded against the Node.js
  36181. * `EventEmitter` interface.
  36182. *
  36183. * @constructor
  36184. * @api public
  36185. */
  36186. function EventEmitter() {
  36187. this._events = new Events();
  36188. this._eventsCount = 0;
  36189. }
  36190. /**
  36191. * Return an array listing the events for which the emitter has registered
  36192. * listeners.
  36193. *
  36194. * @returns {Array}
  36195. * @api public
  36196. */
  36197. EventEmitter.prototype.eventNames = function eventNames() {
  36198. var names = []
  36199. , events
  36200. , name;
  36201. if (this._eventsCount === 0) return names;
  36202. for (name in (events = this._events)) {
  36203. if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
  36204. }
  36205. if (Object.getOwnPropertySymbols) {
  36206. return names.concat(Object.getOwnPropertySymbols(events));
  36207. }
  36208. return names;
  36209. };
  36210. /**
  36211. * Return the listeners registered for a given event.
  36212. *
  36213. * @param {String|Symbol} event The event name.
  36214. * @param {Boolean} exists Only check if there are listeners.
  36215. * @returns {Array|Boolean}
  36216. * @api public
  36217. */
  36218. EventEmitter.prototype.listeners = function listeners(event, exists) {
  36219. var evt = prefix ? prefix + event : event
  36220. , available = this._events[evt];
  36221. if (exists) return !!available;
  36222. if (!available) return [];
  36223. if (available.fn) return [available.fn];
  36224. for (var i = 0, l = available.length, ee = new Array(l); i < l; i++) {
  36225. ee[i] = available[i].fn;
  36226. }
  36227. return ee;
  36228. };
  36229. /**
  36230. * Calls each of the listeners registered for a given event.
  36231. *
  36232. * @param {String|Symbol} event The event name.
  36233. * @returns {Boolean} `true` if the event had listeners, else `false`.
  36234. * @api public
  36235. */
  36236. EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
  36237. var evt = prefix ? prefix + event : event;
  36238. if (!this._events[evt]) return false;
  36239. var listeners = this._events[evt]
  36240. , len = arguments.length
  36241. , args
  36242. , i;
  36243. if (listeners.fn) {
  36244. if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
  36245. switch (len) {
  36246. case 1: return listeners.fn.call(listeners.context), true;
  36247. case 2: return listeners.fn.call(listeners.context, a1), true;
  36248. case 3: return listeners.fn.call(listeners.context, a1, a2), true;
  36249. case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
  36250. case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
  36251. case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
  36252. }
  36253. for (i = 1, args = new Array(len -1); i < len; i++) {
  36254. args[i - 1] = arguments[i];
  36255. }
  36256. listeners.fn.apply(listeners.context, args);
  36257. } else {
  36258. var length = listeners.length
  36259. , j;
  36260. for (i = 0; i < length; i++) {
  36261. if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
  36262. switch (len) {
  36263. case 1: listeners[i].fn.call(listeners[i].context); break;
  36264. case 2: listeners[i].fn.call(listeners[i].context, a1); break;
  36265. case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
  36266. case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
  36267. default:
  36268. if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
  36269. args[j - 1] = arguments[j];
  36270. }
  36271. listeners[i].fn.apply(listeners[i].context, args);
  36272. }
  36273. }
  36274. }
  36275. return true;
  36276. };
  36277. /**
  36278. * Add a listener for a given event.
  36279. *
  36280. * @param {String|Symbol} event The event name.
  36281. * @param {Function} fn The listener function.
  36282. * @param {Mixed} [context=this] The context to invoke the listener with.
  36283. * @returns {EventEmitter} `this`.
  36284. * @api public
  36285. */
  36286. EventEmitter.prototype.on = function on(event, fn, context) {
  36287. var listener = new EE(fn, context || this)
  36288. , evt = prefix ? prefix + event : event;
  36289. if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++;
  36290. else if (!this._events[evt].fn) this._events[evt].push(listener);
  36291. else this._events[evt] = [this._events[evt], listener];
  36292. return this;
  36293. };
  36294. /**
  36295. * Add a one-time listener for a given event.
  36296. *
  36297. * @param {String|Symbol} event The event name.
  36298. * @param {Function} fn The listener function.
  36299. * @param {Mixed} [context=this] The context to invoke the listener with.
  36300. * @returns {EventEmitter} `this`.
  36301. * @api public
  36302. */
  36303. EventEmitter.prototype.once = function once(event, fn, context) {
  36304. var listener = new EE(fn, context || this, true)
  36305. , evt = prefix ? prefix + event : event;
  36306. if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++;
  36307. else if (!this._events[evt].fn) this._events[evt].push(listener);
  36308. else this._events[evt] = [this._events[evt], listener];
  36309. return this;
  36310. };
  36311. /**
  36312. * Remove the listeners of a given event.
  36313. *
  36314. * @param {String|Symbol} event The event name.
  36315. * @param {Function} fn Only remove the listeners that match this function.
  36316. * @param {Mixed} context Only remove the listeners that have this context.
  36317. * @param {Boolean} once Only remove one-time listeners.
  36318. * @returns {EventEmitter} `this`.
  36319. * @api public
  36320. */
  36321. EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
  36322. var evt = prefix ? prefix + event : event;
  36323. if (!this._events[evt]) return this;
  36324. if (!fn) {
  36325. if (--this._eventsCount === 0) this._events = new Events();
  36326. else delete this._events[evt];
  36327. return this;
  36328. }
  36329. var listeners = this._events[evt];
  36330. if (listeners.fn) {
  36331. if (
  36332. listeners.fn === fn
  36333. && (!once || listeners.once)
  36334. && (!context || listeners.context === context)
  36335. ) {
  36336. if (--this._eventsCount === 0) this._events = new Events();
  36337. else delete this._events[evt];
  36338. }
  36339. } else {
  36340. for (var i = 0, events = [], length = listeners.length; i < length; i++) {
  36341. if (
  36342. listeners[i].fn !== fn
  36343. || (once && !listeners[i].once)
  36344. || (context && listeners[i].context !== context)
  36345. ) {
  36346. events.push(listeners[i]);
  36347. }
  36348. }
  36349. //
  36350. // Reset the array, or remove it completely if we have no more listeners.
  36351. //
  36352. if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
  36353. else if (--this._eventsCount === 0) this._events = new Events();
  36354. else delete this._events[evt];
  36355. }
  36356. return this;
  36357. };
  36358. /**
  36359. * Remove all listeners, or those of the specified event.
  36360. *
  36361. * @param {String|Symbol} [event] The event name.
  36362. * @returns {EventEmitter} `this`.
  36363. * @api public
  36364. */
  36365. EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
  36366. var evt;
  36367. if (event) {
  36368. evt = prefix ? prefix + event : event;
  36369. if (this._events[evt]) {
  36370. if (--this._eventsCount === 0) this._events = new Events();
  36371. else delete this._events[evt];
  36372. }
  36373. } else {
  36374. this._events = new Events();
  36375. this._eventsCount = 0;
  36376. }
  36377. return this;
  36378. };
  36379. //
  36380. // Alias methods names because people roll like that.
  36381. //
  36382. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  36383. EventEmitter.prototype.addListener = EventEmitter.prototype.on;
  36384. //
  36385. // This function doesn't apply anymore.
  36386. //
  36387. EventEmitter.prototype.setMaxListeners = function setMaxListeners() {
  36388. return this;
  36389. };
  36390. //
  36391. // Expose the prefix.
  36392. //
  36393. EventEmitter.prefixed = prefix;
  36394. //
  36395. // Allow `EventEmitter` to be imported as module namespace.
  36396. //
  36397. EventEmitter.EventEmitter = EventEmitter;
  36398. //
  36399. // Expose the module.
  36400. //
  36401. if ('undefined' !== typeof module) {
  36402. module.exports = EventEmitter;
  36403. }
  36404. },{}],2:[function(_dereq_,module,exports){
  36405. 'use strict';
  36406. /* eslint-disable no-unused-vars */
  36407. var hasOwnProperty = Object.prototype.hasOwnProperty;
  36408. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  36409. function toObject(val) {
  36410. if (val === null || val === undefined) {
  36411. throw new TypeError('Object.assign cannot be called with null or undefined');
  36412. }
  36413. return Object(val);
  36414. }
  36415. function shouldUseNative() {
  36416. try {
  36417. if (!Object.assign) {
  36418. return false;
  36419. }
  36420. // Detect buggy property enumeration order in older V8 versions.
  36421. // https://bugs.chromium.org/p/v8/issues/detail?id=4118
  36422. var test1 = new String('abc'); // eslint-disable-line
  36423. test1[5] = 'de';
  36424. if (Object.getOwnPropertyNames(test1)[0] === '5') {
  36425. return false;
  36426. }
  36427. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  36428. var test2 = {};
  36429. for (var i = 0; i < 10; i++) {
  36430. test2['_' + String.fromCharCode(i)] = i;
  36431. }
  36432. var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
  36433. return test2[n];
  36434. });
  36435. if (order2.join('') !== '0123456789') {
  36436. return false;
  36437. }
  36438. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  36439. var test3 = {};
  36440. 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
  36441. test3[letter] = letter;
  36442. });
  36443. if (Object.keys(Object.assign({}, test3)).join('') !==
  36444. 'abcdefghijklmnopqrst') {
  36445. return false;
  36446. }
  36447. return true;
  36448. } catch (e) {
  36449. // We don't expect any of the above to throw, but better to be safe.
  36450. return false;
  36451. }
  36452. }
  36453. module.exports = shouldUseNative() ? Object.assign : function (target, source) {
  36454. var from;
  36455. var to = toObject(target);
  36456. var symbols;
  36457. for (var s = 1; s < arguments.length; s++) {
  36458. from = Object(arguments[s]);
  36459. for (var key in from) {
  36460. if (hasOwnProperty.call(from, key)) {
  36461. to[key] = from[key];
  36462. }
  36463. }
  36464. if (Object.getOwnPropertySymbols) {
  36465. symbols = Object.getOwnPropertySymbols(from);
  36466. for (var i = 0; i < symbols.length; i++) {
  36467. if (propIsEnumerable.call(from, symbols[i])) {
  36468. to[symbols[i]] = from[symbols[i]];
  36469. }
  36470. }
  36471. }
  36472. }
  36473. return to;
  36474. };
  36475. },{}],3:[function(_dereq_,module,exports){
  36476. /*
  36477. * Copyright 2015 Google Inc. All Rights Reserved.
  36478. * Licensed under the Apache License, Version 2.0 (the "License");
  36479. * you may not use this file except in compliance with the License.
  36480. * You may obtain a copy of the License at
  36481. *
  36482. * http://www.apache.org/licenses/LICENSE-2.0
  36483. *
  36484. * Unless required by applicable law or agreed to in writing, software
  36485. * distributed under the License is distributed on an "AS IS" BASIS,
  36486. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  36487. * See the License for the specific language governing permissions and
  36488. * limitations under the License.
  36489. */
  36490. var Util = _dereq_('./util.js');
  36491. var WakeLock = _dereq_('./wakelock.js');
  36492. // Start at a higher number to reduce chance of conflict.
  36493. var nextDisplayId = 1000;
  36494. var hasShowDeprecationWarning = false;
  36495. var defaultLeftBounds = [0, 0, 0.5, 1];
  36496. var defaultRightBounds = [0.5, 0, 0.5, 1];
  36497. /**
  36498. * The base class for all VR frame data.
  36499. */
  36500. function VRFrameData() {
  36501. this.leftProjectionMatrix = new Float32Array(16);
  36502. this.leftViewMatrix = new Float32Array(16);
  36503. this.rightProjectionMatrix = new Float32Array(16);
  36504. this.rightViewMatrix = new Float32Array(16);
  36505. this.pose = null;
  36506. };
  36507. /**
  36508. * The base class for all VR displays.
  36509. */
  36510. function VRDisplay() {
  36511. this.isPolyfilled = true;
  36512. this.displayId = nextDisplayId++;
  36513. this.displayName = 'webvr-polyfill displayName';
  36514. this.depthNear = 0.01;
  36515. this.depthFar = 10000.0;
  36516. this.isConnected = true;
  36517. this.isPresenting = false;
  36518. this.capabilities = {
  36519. hasPosition: false,
  36520. hasOrientation: false,
  36521. hasExternalDisplay: false,
  36522. canPresent: false,
  36523. maxLayers: 1
  36524. };
  36525. this.stageParameters = null;
  36526. // "Private" members.
  36527. this.waitingForPresent_ = false;
  36528. this.layer_ = null;
  36529. this.fullscreenElement_ = null;
  36530. this.fullscreenWrapper_ = null;
  36531. this.fullscreenElementCachedStyle_ = null;
  36532. this.fullscreenEventTarget_ = null;
  36533. this.fullscreenChangeHandler_ = null;
  36534. this.fullscreenErrorHandler_ = null;
  36535. this.wakelock_ = new WakeLock();
  36536. }
  36537. VRDisplay.prototype.getFrameData = function(frameData) {
  36538. // TODO: Technically this should retain it's value for the duration of a frame
  36539. // but I doubt that's practical to do in javascript.
  36540. return Util.frameDataFromPose(frameData, this.getPose(), this);
  36541. };
  36542. VRDisplay.prototype.getPose = function() {
  36543. // TODO: Technically this should retain it's value for the duration of a frame
  36544. // but I doubt that's practical to do in javascript.
  36545. return this.getImmediatePose();
  36546. };
  36547. VRDisplay.prototype.requestAnimationFrame = function(callback) {
  36548. return window.requestAnimationFrame(callback);
  36549. };
  36550. VRDisplay.prototype.cancelAnimationFrame = function(id) {
  36551. return window.cancelAnimationFrame(id);
  36552. };
  36553. VRDisplay.prototype.wrapForFullscreen = function(element) {
  36554. // Don't wrap in iOS.
  36555. if (Util.isIOS()) {
  36556. return element;
  36557. }
  36558. if (!this.fullscreenWrapper_) {
  36559. this.fullscreenWrapper_ = document.createElement('div');
  36560. var cssProperties = [
  36561. 'height: ' + Math.min(screen.height, screen.width) + 'px !important',
  36562. 'top: 0 !important',
  36563. 'left: 0 !important',
  36564. 'right: 0 !important',
  36565. 'border: 0',
  36566. 'margin: 0',
  36567. 'padding: 0',
  36568. 'z-index: 999999 !important',
  36569. 'position: fixed',
  36570. ];
  36571. this.fullscreenWrapper_.setAttribute('style', cssProperties.join('; ') + ';');
  36572. this.fullscreenWrapper_.classList.add('webvr-polyfill-fullscreen-wrapper');
  36573. }
  36574. if (this.fullscreenElement_ == element) {
  36575. return this.fullscreenWrapper_;
  36576. }
  36577. // Remove any previously applied wrappers
  36578. this.removeFullscreenWrapper();
  36579. this.fullscreenElement_ = element;
  36580. var parent = this.fullscreenElement_.parentElement;
  36581. parent.insertBefore(this.fullscreenWrapper_, this.fullscreenElement_);
  36582. parent.removeChild(this.fullscreenElement_);
  36583. this.fullscreenWrapper_.insertBefore(this.fullscreenElement_, this.fullscreenWrapper_.firstChild);
  36584. this.fullscreenElementCachedStyle_ = this.fullscreenElement_.getAttribute('style');
  36585. var self = this;
  36586. function applyFullscreenElementStyle() {
  36587. if (!self.fullscreenElement_) {
  36588. return;
  36589. }
  36590. var cssProperties = [
  36591. 'position: absolute',
  36592. 'top: 0',
  36593. 'left: 0',
  36594. 'width: ' + Math.max(screen.width, screen.height) + 'px',
  36595. 'height: ' + Math.min(screen.height, screen.width) + 'px',
  36596. 'border: 0',
  36597. 'margin: 0',
  36598. 'padding: 0',
  36599. ];
  36600. self.fullscreenElement_.setAttribute('style', cssProperties.join('; ') + ';');
  36601. }
  36602. applyFullscreenElementStyle();
  36603. return this.fullscreenWrapper_;
  36604. };
  36605. VRDisplay.prototype.removeFullscreenWrapper = function() {
  36606. if (!this.fullscreenElement_) {
  36607. return;
  36608. }
  36609. var element = this.fullscreenElement_;
  36610. if (this.fullscreenElementCachedStyle_) {
  36611. element.setAttribute('style', this.fullscreenElementCachedStyle_);
  36612. } else {
  36613. element.removeAttribute('style');
  36614. }
  36615. this.fullscreenElement_ = null;
  36616. this.fullscreenElementCachedStyle_ = null;
  36617. var parent = this.fullscreenWrapper_.parentElement;
  36618. this.fullscreenWrapper_.removeChild(element);
  36619. parent.insertBefore(element, this.fullscreenWrapper_);
  36620. parent.removeChild(this.fullscreenWrapper_);
  36621. return element;
  36622. };
  36623. VRDisplay.prototype.requestPresent = function(layers) {
  36624. var wasPresenting = this.isPresenting;
  36625. var self = this;
  36626. if (!(layers instanceof Array)) {
  36627. if (!hasShowDeprecationWarning) {
  36628. console.warn("Using a deprecated form of requestPresent. Should pass in an array of VRLayers.");
  36629. hasShowDeprecationWarning = true;
  36630. }
  36631. layers = [layers];
  36632. }
  36633. return new Promise(function(resolve, reject) {
  36634. if (!self.capabilities.canPresent) {
  36635. reject(new Error('VRDisplay is not capable of presenting.'));
  36636. return;
  36637. }
  36638. if (layers.length == 0 || layers.length > self.capabilities.maxLayers) {
  36639. reject(new Error('Invalid number of layers.'));
  36640. return;
  36641. }
  36642. var incomingLayer = layers[0];
  36643. if (!incomingLayer.source) {
  36644. /*
  36645. todo: figure out the correct behavior if the source is not provided.
  36646. see https://github.com/w3c/webvr/issues/58
  36647. */
  36648. resolve();
  36649. return;
  36650. }
  36651. var leftBounds = incomingLayer.leftBounds || defaultLeftBounds;
  36652. var rightBounds = incomingLayer.rightBounds || defaultRightBounds;
  36653. if (wasPresenting) {
  36654. // Already presenting, just changing configuration
  36655. var layer = self.layer_;
  36656. if (layer.source !== incomingLayer.source) {
  36657. layer.source = incomingLayer.source;
  36658. }
  36659. for (var i = 0; i < 4; i++) {
  36660. if (layer.leftBounds[i] !== leftBounds[i]) {
  36661. layer.leftBounds[i] = leftBounds[i];
  36662. }
  36663. if (layer.rightBounds[i] !== rightBounds[i]) {
  36664. layer.rightBounds[i] = rightBounds[i];
  36665. }
  36666. }
  36667. resolve();
  36668. return;
  36669. }
  36670. // Was not already presenting.
  36671. self.layer_ = {
  36672. predistorted: incomingLayer.predistorted,
  36673. source: incomingLayer.source,
  36674. leftBounds: leftBounds.slice(0),
  36675. rightBounds: rightBounds.slice(0)
  36676. };
  36677. self.waitingForPresent_ = false;
  36678. if (self.layer_ && self.layer_.source) {
  36679. var fullscreenElement = self.wrapForFullscreen(self.layer_.source);
  36680. function onFullscreenChange() {
  36681. var actualFullscreenElement = Util.getFullscreenElement();
  36682. self.isPresenting = (fullscreenElement === actualFullscreenElement);
  36683. if (self.isPresenting) {
  36684. if (screen.orientation && screen.orientation.lock) {
  36685. screen.orientation.lock('landscape-primary').catch(function(error){
  36686. console.error('screen.orientation.lock() failed due to', error.message)
  36687. });
  36688. }
  36689. self.waitingForPresent_ = false;
  36690. self.beginPresent_();
  36691. resolve();
  36692. } else {
  36693. if (screen.orientation && screen.orientation.unlock) {
  36694. screen.orientation.unlock();
  36695. }
  36696. self.removeFullscreenWrapper();
  36697. self.wakelock_.release();
  36698. self.endPresent_();
  36699. self.removeFullscreenListeners_();
  36700. }
  36701. self.fireVRDisplayPresentChange_();
  36702. }
  36703. function onFullscreenError() {
  36704. if (!self.waitingForPresent_) {
  36705. return;
  36706. }
  36707. self.removeFullscreenWrapper();
  36708. self.removeFullscreenListeners_();
  36709. self.wakelock_.release();
  36710. self.waitingForPresent_ = false;
  36711. self.isPresenting = false;
  36712. reject(new Error('Unable to present.'));
  36713. }
  36714. self.addFullscreenListeners_(fullscreenElement,
  36715. onFullscreenChange, onFullscreenError);
  36716. if (Util.requestFullscreen(fullscreenElement)) {
  36717. self.wakelock_.request();
  36718. self.waitingForPresent_ = true;
  36719. } else if (Util.isIOS() || Util.isWebViewAndroid()) {
  36720. // *sigh* Just fake it.
  36721. self.wakelock_.request();
  36722. self.isPresenting = true;
  36723. self.beginPresent_();
  36724. self.fireVRDisplayPresentChange_();
  36725. resolve();
  36726. }
  36727. }
  36728. if (!self.waitingForPresent_ && !Util.isIOS()) {
  36729. Util.exitFullscreen();
  36730. reject(new Error('Unable to present.'));
  36731. }
  36732. });
  36733. };
  36734. VRDisplay.prototype.exitPresent = function() {
  36735. var wasPresenting = this.isPresenting;
  36736. var self = this;
  36737. this.isPresenting = false;
  36738. this.layer_ = null;
  36739. this.wakelock_.release();
  36740. return new Promise(function(resolve, reject) {
  36741. if (wasPresenting) {
  36742. if (!Util.exitFullscreen() && Util.isIOS()) {
  36743. self.endPresent_();
  36744. self.fireVRDisplayPresentChange_();
  36745. }
  36746. if(Util.isWebViewAndroid()) {
  36747. self.removeFullscreenWrapper();
  36748. self.removeFullscreenListeners_();
  36749. self.endPresent_();
  36750. self.fireVRDisplayPresentChange_();
  36751. }
  36752. resolve();
  36753. } else {
  36754. reject(new Error('Was not presenting to VRDisplay.'));
  36755. }
  36756. });
  36757. };
  36758. VRDisplay.prototype.getLayers = function() {
  36759. if (this.layer_) {
  36760. return [this.layer_];
  36761. }
  36762. return [];
  36763. };
  36764. VRDisplay.prototype.fireVRDisplayPresentChange_ = function() {
  36765. var event = new CustomEvent('vrdisplaypresentchange', {detail: {display: this}});
  36766. window.dispatchEvent(event);
  36767. };
  36768. VRDisplay.prototype.addFullscreenListeners_ = function(element, changeHandler, errorHandler) {
  36769. this.removeFullscreenListeners_();
  36770. this.fullscreenEventTarget_ = element;
  36771. this.fullscreenChangeHandler_ = changeHandler;
  36772. this.fullscreenErrorHandler_ = errorHandler;
  36773. if (changeHandler) {
  36774. if (document.fullscreenEnabled) {
  36775. element.addEventListener('fullscreenchange', changeHandler, false);
  36776. } else if (document.webkitFullscreenEnabled) {
  36777. element.addEventListener('webkitfullscreenchange', changeHandler, false);
  36778. } else if (document.mozFullScreenEnabled) {
  36779. document.addEventListener('mozfullscreenchange', changeHandler, false);
  36780. } else if (document.msFullscreenEnabled) {
  36781. element.addEventListener('msfullscreenchange', changeHandler, false);
  36782. }
  36783. }
  36784. if (errorHandler) {
  36785. if (document.fullscreenEnabled) {
  36786. element.addEventListener('fullscreenerror', errorHandler, false);
  36787. } else if (document.webkitFullscreenEnabled) {
  36788. element.addEventListener('webkitfullscreenerror', errorHandler, false);
  36789. } else if (document.mozFullScreenEnabled) {
  36790. document.addEventListener('mozfullscreenerror', errorHandler, false);
  36791. } else if (document.msFullscreenEnabled) {
  36792. element.addEventListener('msfullscreenerror', errorHandler, false);
  36793. }
  36794. }
  36795. };
  36796. VRDisplay.prototype.removeFullscreenListeners_ = function() {
  36797. if (!this.fullscreenEventTarget_)
  36798. return;
  36799. var element = this.fullscreenEventTarget_;
  36800. if (this.fullscreenChangeHandler_) {
  36801. var changeHandler = this.fullscreenChangeHandler_;
  36802. element.removeEventListener('fullscreenchange', changeHandler, false);
  36803. element.removeEventListener('webkitfullscreenchange', changeHandler, false);
  36804. document.removeEventListener('mozfullscreenchange', changeHandler, false);
  36805. element.removeEventListener('msfullscreenchange', changeHandler, false);
  36806. }
  36807. if (this.fullscreenErrorHandler_) {
  36808. var errorHandler = this.fullscreenErrorHandler_;
  36809. element.removeEventListener('fullscreenerror', errorHandler, false);
  36810. element.removeEventListener('webkitfullscreenerror', errorHandler, false);
  36811. document.removeEventListener('mozfullscreenerror', errorHandler, false);
  36812. element.removeEventListener('msfullscreenerror', errorHandler, false);
  36813. }
  36814. this.fullscreenEventTarget_ = null;
  36815. this.fullscreenChangeHandler_ = null;
  36816. this.fullscreenErrorHandler_ = null;
  36817. };
  36818. VRDisplay.prototype.beginPresent_ = function() {
  36819. // Override to add custom behavior when presentation begins.
  36820. };
  36821. VRDisplay.prototype.endPresent_ = function() {
  36822. // Override to add custom behavior when presentation ends.
  36823. };
  36824. VRDisplay.prototype.submitFrame = function(pose) {
  36825. // Override to add custom behavior for frame submission.
  36826. };
  36827. VRDisplay.prototype.getEyeParameters = function(whichEye) {
  36828. // Override to return accurate eye parameters if canPresent is true.
  36829. return null;
  36830. };
  36831. /*
  36832. * Deprecated classes
  36833. */
  36834. /**
  36835. * The base class for all VR devices. (Deprecated)
  36836. */
  36837. function VRDevice() {
  36838. this.isPolyfilled = true;
  36839. this.hardwareUnitId = 'webvr-polyfill hardwareUnitId';
  36840. this.deviceId = 'webvr-polyfill deviceId';
  36841. this.deviceName = 'webvr-polyfill deviceName';
  36842. }
  36843. /**
  36844. * The base class for all VR HMD devices. (Deprecated)
  36845. */
  36846. function HMDVRDevice() {
  36847. }
  36848. HMDVRDevice.prototype = new VRDevice();
  36849. /**
  36850. * The base class for all VR position sensor devices. (Deprecated)
  36851. */
  36852. function PositionSensorVRDevice() {
  36853. }
  36854. PositionSensorVRDevice.prototype = new VRDevice();
  36855. module.exports.VRFrameData = VRFrameData;
  36856. module.exports.VRDisplay = VRDisplay;
  36857. module.exports.VRDevice = VRDevice;
  36858. module.exports.HMDVRDevice = HMDVRDevice;
  36859. module.exports.PositionSensorVRDevice = PositionSensorVRDevice;
  36860. },{"./util.js":23,"./wakelock.js":25}],4:[function(_dereq_,module,exports){
  36861. /*
  36862. * Copyright 2016 Google Inc. All Rights Reserved.
  36863. * Licensed under the Apache License, Version 2.0 (the "License");
  36864. * you may not use this file except in compliance with the License.
  36865. * You may obtain a copy of the License at
  36866. *
  36867. * http://www.apache.org/licenses/LICENSE-2.0
  36868. *
  36869. * Unless required by applicable law or agreed to in writing, software
  36870. * distributed under the License is distributed on an "AS IS" BASIS,
  36871. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  36872. * See the License for the specific language governing permissions and
  36873. * limitations under the License.
  36874. */
  36875. var CardboardUI = _dereq_('./cardboard-ui.js');
  36876. var Util = _dereq_('./util.js');
  36877. var WGLUPreserveGLState = _dereq_('./deps/wglu-preserve-state.js');
  36878. var distortionVS = [
  36879. 'attribute vec2 position;',
  36880. 'attribute vec3 texCoord;',
  36881. 'varying vec2 vTexCoord;',
  36882. 'uniform vec4 viewportOffsetScale[2];',
  36883. 'void main() {',
  36884. ' vec4 viewport = viewportOffsetScale[int(texCoord.z)];',
  36885. ' vTexCoord = (texCoord.xy * viewport.zw) + viewport.xy;',
  36886. ' gl_Position = vec4( position, 1.0, 1.0 );',
  36887. '}',
  36888. ].join('\n');
  36889. var distortionFS = [
  36890. 'precision mediump float;',
  36891. 'uniform sampler2D diffuse;',
  36892. 'varying vec2 vTexCoord;',
  36893. 'void main() {',
  36894. ' gl_FragColor = texture2D(diffuse, vTexCoord);',
  36895. '}',
  36896. ].join('\n');
  36897. /**
  36898. * A mesh-based distorter.
  36899. */
  36900. function CardboardDistorter(gl) {
  36901. this.gl = gl;
  36902. this.ctxAttribs = gl.getContextAttributes();
  36903. this.meshWidth = 20;
  36904. this.meshHeight = 20;
  36905. this.bufferScale = WebVRConfig.BUFFER_SCALE;
  36906. this.bufferWidth = gl.drawingBufferWidth;
  36907. this.bufferHeight = gl.drawingBufferHeight;
  36908. // Patching support
  36909. this.realBindFramebuffer = gl.bindFramebuffer;
  36910. this.realEnable = gl.enable;
  36911. this.realDisable = gl.disable;
  36912. this.realColorMask = gl.colorMask;
  36913. this.realClearColor = gl.clearColor;
  36914. this.realViewport = gl.viewport;
  36915. if (!Util.isIOS()) {
  36916. this.realCanvasWidth = Object.getOwnPropertyDescriptor(gl.canvas.__proto__, 'width');
  36917. this.realCanvasHeight = Object.getOwnPropertyDescriptor(gl.canvas.__proto__, 'height');
  36918. }
  36919. this.isPatched = false;
  36920. // State tracking
  36921. this.lastBoundFramebuffer = null;
  36922. this.cullFace = false;
  36923. this.depthTest = false;
  36924. this.blend = false;
  36925. this.scissorTest = false;
  36926. this.stencilTest = false;
  36927. this.viewport = [0, 0, 0, 0];
  36928. this.colorMask = [true, true, true, true];
  36929. this.clearColor = [0, 0, 0, 0];
  36930. this.attribs = {
  36931. position: 0,
  36932. texCoord: 1
  36933. };
  36934. this.program = Util.linkProgram(gl, distortionVS, distortionFS, this.attribs);
  36935. this.uniforms = Util.getProgramUniforms(gl, this.program);
  36936. this.viewportOffsetScale = new Float32Array(8);
  36937. this.setTextureBounds();
  36938. this.vertexBuffer = gl.createBuffer();
  36939. this.indexBuffer = gl.createBuffer();
  36940. this.indexCount = 0;
  36941. this.renderTarget = gl.createTexture();
  36942. this.framebuffer = gl.createFramebuffer();
  36943. this.depthStencilBuffer = null;
  36944. this.depthBuffer = null;
  36945. this.stencilBuffer = null;
  36946. if (this.ctxAttribs.depth && this.ctxAttribs.stencil) {
  36947. this.depthStencilBuffer = gl.createRenderbuffer();
  36948. } else if (this.ctxAttribs.depth) {
  36949. this.depthBuffer = gl.createRenderbuffer();
  36950. } else if (this.ctxAttribs.stencil) {
  36951. this.stencilBuffer = gl.createRenderbuffer();
  36952. }
  36953. this.patch();
  36954. this.onResize();
  36955. if (!WebVRConfig.CARDBOARD_UI_DISABLED) {
  36956. this.cardboardUI = new CardboardUI(gl);
  36957. }
  36958. };
  36959. /**
  36960. * Tears down all the resources created by the distorter and removes any
  36961. * patches.
  36962. */
  36963. CardboardDistorter.prototype.destroy = function() {
  36964. var gl = this.gl;
  36965. this.unpatch();
  36966. gl.deleteProgram(this.program);
  36967. gl.deleteBuffer(this.vertexBuffer);
  36968. gl.deleteBuffer(this.indexBuffer);
  36969. gl.deleteTexture(this.renderTarget);
  36970. gl.deleteFramebuffer(this.framebuffer);
  36971. if (this.depthStencilBuffer) {
  36972. gl.deleteRenderbuffer(this.depthStencilBuffer);
  36973. }
  36974. if (this.depthBuffer) {
  36975. gl.deleteRenderbuffer(this.depthBuffer);
  36976. }
  36977. if (this.stencilBuffer) {
  36978. gl.deleteRenderbuffer(this.stencilBuffer);
  36979. }
  36980. if (this.cardboardUI) {
  36981. this.cardboardUI.destroy();
  36982. }
  36983. };
  36984. /**
  36985. * Resizes the backbuffer to match the canvas width and height.
  36986. */
  36987. CardboardDistorter.prototype.onResize = function() {
  36988. var gl = this.gl;
  36989. var self = this;
  36990. var glState = [
  36991. gl.RENDERBUFFER_BINDING,
  36992. gl.TEXTURE_BINDING_2D, gl.TEXTURE0
  36993. ];
  36994. WGLUPreserveGLState(gl, glState, function(gl) {
  36995. // Bind real backbuffer and clear it once. We don't need to clear it again
  36996. // after that because we're overwriting the same area every frame.
  36997. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, null);
  36998. // Put things in a good state
  36999. if (self.scissorTest) { self.realDisable.call(gl, gl.SCISSOR_TEST); }
  37000. self.realColorMask.call(gl, true, true, true, true);
  37001. self.realViewport.call(gl, 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  37002. self.realClearColor.call(gl, 0, 0, 0, 1);
  37003. gl.clear(gl.COLOR_BUFFER_BIT);
  37004. // Now bind and resize the fake backbuffer
  37005. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.framebuffer);
  37006. gl.bindTexture(gl.TEXTURE_2D, self.renderTarget);
  37007. gl.texImage2D(gl.TEXTURE_2D, 0, self.ctxAttribs.alpha ? gl.RGBA : gl.RGB,
  37008. self.bufferWidth, self.bufferHeight, 0,
  37009. self.ctxAttribs.alpha ? gl.RGBA : gl.RGB, gl.UNSIGNED_BYTE, null);
  37010. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  37011. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  37012. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  37013. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  37014. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, self.renderTarget, 0);
  37015. if (self.ctxAttribs.depth && self.ctxAttribs.stencil) {
  37016. gl.bindRenderbuffer(gl.RENDERBUFFER, self.depthStencilBuffer);
  37017. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL,
  37018. self.bufferWidth, self.bufferHeight);
  37019. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT,
  37020. gl.RENDERBUFFER, self.depthStencilBuffer);
  37021. } else if (self.ctxAttribs.depth) {
  37022. gl.bindRenderbuffer(gl.RENDERBUFFER, self.depthBuffer);
  37023. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16,
  37024. self.bufferWidth, self.bufferHeight);
  37025. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT,
  37026. gl.RENDERBUFFER, self.depthBuffer);
  37027. } else if (self.ctxAttribs.stencil) {
  37028. gl.bindRenderbuffer(gl.RENDERBUFFER, self.stencilBuffer);
  37029. gl.renderbufferStorage(gl.RENDERBUFFER, gl.STENCIL_INDEX8,
  37030. self.bufferWidth, self.bufferHeight);
  37031. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT,
  37032. gl.RENDERBUFFER, self.stencilBuffer);
  37033. }
  37034. if (!gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE) {
  37035. console.error('Framebuffer incomplete!');
  37036. }
  37037. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.lastBoundFramebuffer);
  37038. if (self.scissorTest) { self.realEnable.call(gl, gl.SCISSOR_TEST); }
  37039. self.realColorMask.apply(gl, self.colorMask);
  37040. self.realViewport.apply(gl, self.viewport);
  37041. self.realClearColor.apply(gl, self.clearColor);
  37042. });
  37043. if (this.cardboardUI) {
  37044. this.cardboardUI.onResize();
  37045. }
  37046. };
  37047. CardboardDistorter.prototype.patch = function() {
  37048. if (this.isPatched) {
  37049. return;
  37050. }
  37051. var self = this;
  37052. var canvas = this.gl.canvas;
  37053. var gl = this.gl;
  37054. if (!Util.isIOS()) {
  37055. canvas.width = Util.getScreenWidth() * this.bufferScale;
  37056. canvas.height = Util.getScreenHeight() * this.bufferScale;
  37057. Object.defineProperty(canvas, 'width', {
  37058. configurable: true,
  37059. enumerable: true,
  37060. get: function() {
  37061. return self.bufferWidth;
  37062. },
  37063. set: function(value) {
  37064. self.bufferWidth = value;
  37065. self.realCanvasWidth.set.call(canvas, value);
  37066. self.onResize();
  37067. }
  37068. });
  37069. Object.defineProperty(canvas, 'height', {
  37070. configurable: true,
  37071. enumerable: true,
  37072. get: function() {
  37073. return self.bufferHeight;
  37074. },
  37075. set: function(value) {
  37076. self.bufferHeight = value;
  37077. self.realCanvasHeight.set.call(canvas, value);
  37078. self.onResize();
  37079. }
  37080. });
  37081. }
  37082. this.lastBoundFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);
  37083. if (this.lastBoundFramebuffer == null) {
  37084. this.lastBoundFramebuffer = this.framebuffer;
  37085. this.gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer);
  37086. }
  37087. this.gl.bindFramebuffer = function(target, framebuffer) {
  37088. self.lastBoundFramebuffer = framebuffer ? framebuffer : self.framebuffer;
  37089. // Silently make calls to bind the default framebuffer bind ours instead.
  37090. self.realBindFramebuffer.call(gl, target, self.lastBoundFramebuffer);
  37091. };
  37092. this.cullFace = gl.getParameter(gl.CULL_FACE);
  37093. this.depthTest = gl.getParameter(gl.DEPTH_TEST);
  37094. this.blend = gl.getParameter(gl.BLEND);
  37095. this.scissorTest = gl.getParameter(gl.SCISSOR_TEST);
  37096. this.stencilTest = gl.getParameter(gl.STENCIL_TEST);
  37097. gl.enable = function(pname) {
  37098. switch (pname) {
  37099. case gl.CULL_FACE: self.cullFace = true; break;
  37100. case gl.DEPTH_TEST: self.depthTest = true; break;
  37101. case gl.BLEND: self.blend = true; break;
  37102. case gl.SCISSOR_TEST: self.scissorTest = true; break;
  37103. case gl.STENCIL_TEST: self.stencilTest = true; break;
  37104. }
  37105. self.realEnable.call(gl, pname);
  37106. };
  37107. gl.disable = function(pname) {
  37108. switch (pname) {
  37109. case gl.CULL_FACE: self.cullFace = false; break;
  37110. case gl.DEPTH_TEST: self.depthTest = false; break;
  37111. case gl.BLEND: self.blend = false; break;
  37112. case gl.SCISSOR_TEST: self.scissorTest = false; break;
  37113. case gl.STENCIL_TEST: self.stencilTest = false; break;
  37114. }
  37115. self.realDisable.call(gl, pname);
  37116. };
  37117. this.colorMask = gl.getParameter(gl.COLOR_WRITEMASK);
  37118. gl.colorMask = function(r, g, b, a) {
  37119. self.colorMask[0] = r;
  37120. self.colorMask[1] = g;
  37121. self.colorMask[2] = b;
  37122. self.colorMask[3] = a;
  37123. self.realColorMask.call(gl, r, g, b, a);
  37124. };
  37125. this.clearColor = gl.getParameter(gl.COLOR_CLEAR_VALUE);
  37126. gl.clearColor = function(r, g, b, a) {
  37127. self.clearColor[0] = r;
  37128. self.clearColor[1] = g;
  37129. self.clearColor[2] = b;
  37130. self.clearColor[3] = a;
  37131. self.realClearColor.call(gl, r, g, b, a);
  37132. };
  37133. this.viewport = gl.getParameter(gl.VIEWPORT);
  37134. gl.viewport = function(x, y, w, h) {
  37135. self.viewport[0] = x;
  37136. self.viewport[1] = y;
  37137. self.viewport[2] = w;
  37138. self.viewport[3] = h;
  37139. self.realViewport.call(gl, x, y, w, h);
  37140. };
  37141. this.isPatched = true;
  37142. Util.safariCssSizeWorkaround(canvas);
  37143. };
  37144. CardboardDistorter.prototype.unpatch = function() {
  37145. if (!this.isPatched) {
  37146. return;
  37147. }
  37148. var gl = this.gl;
  37149. var canvas = this.gl.canvas;
  37150. if (!Util.isIOS()) {
  37151. Object.defineProperty(canvas, 'width', this.realCanvasWidth);
  37152. Object.defineProperty(canvas, 'height', this.realCanvasHeight);
  37153. }
  37154. canvas.width = this.bufferWidth;
  37155. canvas.height = this.bufferHeight;
  37156. gl.bindFramebuffer = this.realBindFramebuffer;
  37157. gl.enable = this.realEnable;
  37158. gl.disable = this.realDisable;
  37159. gl.colorMask = this.realColorMask;
  37160. gl.clearColor = this.realClearColor;
  37161. gl.viewport = this.realViewport;
  37162. // Check to see if our fake backbuffer is bound and bind the real backbuffer
  37163. // if that's the case.
  37164. if (this.lastBoundFramebuffer == this.framebuffer) {
  37165. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  37166. }
  37167. this.isPatched = false;
  37168. setTimeout(function() {
  37169. Util.safariCssSizeWorkaround(canvas);
  37170. }, 1);
  37171. };
  37172. CardboardDistorter.prototype.setTextureBounds = function(leftBounds, rightBounds) {
  37173. if (!leftBounds) {
  37174. leftBounds = [0, 0, 0.5, 1];
  37175. }
  37176. if (!rightBounds) {
  37177. rightBounds = [0.5, 0, 0.5, 1];
  37178. }
  37179. // Left eye
  37180. this.viewportOffsetScale[0] = leftBounds[0]; // X
  37181. this.viewportOffsetScale[1] = leftBounds[1]; // Y
  37182. this.viewportOffsetScale[2] = leftBounds[2]; // Width
  37183. this.viewportOffsetScale[3] = leftBounds[3]; // Height
  37184. // Right eye
  37185. this.viewportOffsetScale[4] = rightBounds[0]; // X
  37186. this.viewportOffsetScale[5] = rightBounds[1]; // Y
  37187. this.viewportOffsetScale[6] = rightBounds[2]; // Width
  37188. this.viewportOffsetScale[7] = rightBounds[3]; // Height
  37189. };
  37190. /**
  37191. * Performs distortion pass on the injected backbuffer, rendering it to the real
  37192. * backbuffer.
  37193. */
  37194. CardboardDistorter.prototype.submitFrame = function() {
  37195. var gl = this.gl;
  37196. var self = this;
  37197. var glState = [];
  37198. if (!WebVRConfig.DIRTY_SUBMIT_FRAME_BINDINGS) {
  37199. glState.push(
  37200. gl.CURRENT_PROGRAM,
  37201. gl.ARRAY_BUFFER_BINDING,
  37202. gl.ELEMENT_ARRAY_BUFFER_BINDING,
  37203. gl.TEXTURE_BINDING_2D, gl.TEXTURE0
  37204. );
  37205. }
  37206. WGLUPreserveGLState(gl, glState, function(gl) {
  37207. // Bind the real default framebuffer
  37208. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, null);
  37209. // Make sure the GL state is in a good place
  37210. if (self.cullFace) { self.realDisable.call(gl, gl.CULL_FACE); }
  37211. if (self.depthTest) { self.realDisable.call(gl, gl.DEPTH_TEST); }
  37212. if (self.blend) { self.realDisable.call(gl, gl.BLEND); }
  37213. if (self.scissorTest) { self.realDisable.call(gl, gl.SCISSOR_TEST); }
  37214. if (self.stencilTest) { self.realDisable.call(gl, gl.STENCIL_TEST); }
  37215. self.realColorMask.call(gl, true, true, true, true);
  37216. self.realViewport.call(gl, 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  37217. // If the backbuffer has an alpha channel clear every frame so the page
  37218. // doesn't show through.
  37219. if (self.ctxAttribs.alpha || Util.isIOS()) {
  37220. self.realClearColor.call(gl, 0, 0, 0, 1);
  37221. gl.clear(gl.COLOR_BUFFER_BIT);
  37222. }
  37223. // Bind distortion program and mesh
  37224. gl.useProgram(self.program);
  37225. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, self.indexBuffer);
  37226. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  37227. gl.enableVertexAttribArray(self.attribs.position);
  37228. gl.enableVertexAttribArray(self.attribs.texCoord);
  37229. gl.vertexAttribPointer(self.attribs.position, 2, gl.FLOAT, false, 20, 0);
  37230. gl.vertexAttribPointer(self.attribs.texCoord, 3, gl.FLOAT, false, 20, 8);
  37231. gl.activeTexture(gl.TEXTURE0);
  37232. gl.uniform1i(self.uniforms.diffuse, 0);
  37233. gl.bindTexture(gl.TEXTURE_2D, self.renderTarget);
  37234. gl.uniform4fv(self.uniforms.viewportOffsetScale, self.viewportOffsetScale);
  37235. // Draws both eyes
  37236. gl.drawElements(gl.TRIANGLES, self.indexCount, gl.UNSIGNED_SHORT, 0);
  37237. if (self.cardboardUI) {
  37238. self.cardboardUI.renderNoState();
  37239. }
  37240. // Bind the fake default framebuffer again
  37241. self.realBindFramebuffer.call(self.gl, gl.FRAMEBUFFER, self.framebuffer);
  37242. // If preserveDrawingBuffer == false clear the framebuffer
  37243. if (!self.ctxAttribs.preserveDrawingBuffer) {
  37244. self.realClearColor.call(gl, 0, 0, 0, 0);
  37245. gl.clear(gl.COLOR_BUFFER_BIT);
  37246. }
  37247. if (!WebVRConfig.DIRTY_SUBMIT_FRAME_BINDINGS) {
  37248. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.lastBoundFramebuffer);
  37249. }
  37250. // Restore state
  37251. if (self.cullFace) { self.realEnable.call(gl, gl.CULL_FACE); }
  37252. if (self.depthTest) { self.realEnable.call(gl, gl.DEPTH_TEST); }
  37253. if (self.blend) { self.realEnable.call(gl, gl.BLEND); }
  37254. if (self.scissorTest) { self.realEnable.call(gl, gl.SCISSOR_TEST); }
  37255. if (self.stencilTest) { self.realEnable.call(gl, gl.STENCIL_TEST); }
  37256. self.realColorMask.apply(gl, self.colorMask);
  37257. self.realViewport.apply(gl, self.viewport);
  37258. if (self.ctxAttribs.alpha || !self.ctxAttribs.preserveDrawingBuffer) {
  37259. self.realClearColor.apply(gl, self.clearColor);
  37260. }
  37261. });
  37262. // Workaround for the fact that Safari doesn't allow us to patch the canvas
  37263. // width and height correctly. After each submit frame check to see what the
  37264. // real backbuffer size has been set to and resize the fake backbuffer size
  37265. // to match.
  37266. if (Util.isIOS()) {
  37267. var canvas = gl.canvas;
  37268. if (canvas.width != self.bufferWidth || canvas.height != self.bufferHeight) {
  37269. self.bufferWidth = canvas.width;
  37270. self.bufferHeight = canvas.height;
  37271. self.onResize();
  37272. }
  37273. }
  37274. };
  37275. /**
  37276. * Call when the deviceInfo has changed. At this point we need
  37277. * to re-calculate the distortion mesh.
  37278. */
  37279. CardboardDistorter.prototype.updateDeviceInfo = function(deviceInfo) {
  37280. var gl = this.gl;
  37281. var self = this;
  37282. var glState = [gl.ARRAY_BUFFER_BINDING, gl.ELEMENT_ARRAY_BUFFER_BINDING];
  37283. WGLUPreserveGLState(gl, glState, function(gl) {
  37284. var vertices = self.computeMeshVertices_(self.meshWidth, self.meshHeight, deviceInfo);
  37285. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  37286. gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
  37287. // Indices don't change based on device parameters, so only compute once.
  37288. if (!self.indexCount) {
  37289. var indices = self.computeMeshIndices_(self.meshWidth, self.meshHeight);
  37290. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, self.indexBuffer);
  37291. gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);
  37292. self.indexCount = indices.length;
  37293. }
  37294. });
  37295. };
  37296. /**
  37297. * Build the distortion mesh vertices.
  37298. * Based on code from the Unity cardboard plugin.
  37299. */
  37300. CardboardDistorter.prototype.computeMeshVertices_ = function(width, height, deviceInfo) {
  37301. var vertices = new Float32Array(2 * width * height * 5);
  37302. var lensFrustum = deviceInfo.getLeftEyeVisibleTanAngles();
  37303. var noLensFrustum = deviceInfo.getLeftEyeNoLensTanAngles();
  37304. var viewport = deviceInfo.getLeftEyeVisibleScreenRect(noLensFrustum);
  37305. var vidx = 0;
  37306. var iidx = 0;
  37307. for (var e = 0; e < 2; e++) {
  37308. for (var j = 0; j < height; j++) {
  37309. for (var i = 0; i < width; i++, vidx++) {
  37310. var u = i / (width - 1);
  37311. var v = j / (height - 1);
  37312. // Grid points regularly spaced in StreoScreen, and barrel distorted in
  37313. // the mesh.
  37314. var s = u;
  37315. var t = v;
  37316. var x = Util.lerp(lensFrustum[0], lensFrustum[2], u);
  37317. var y = Util.lerp(lensFrustum[3], lensFrustum[1], v);
  37318. var d = Math.sqrt(x * x + y * y);
  37319. var r = deviceInfo.distortion.distortInverse(d);
  37320. var p = x * r / d;
  37321. var q = y * r / d;
  37322. u = (p - noLensFrustum[0]) / (noLensFrustum[2] - noLensFrustum[0]);
  37323. v = (q - noLensFrustum[3]) / (noLensFrustum[1] - noLensFrustum[3]);
  37324. // Convert u,v to mesh screen coordinates.
  37325. var aspect = deviceInfo.device.widthMeters / deviceInfo.device.heightMeters;
  37326. // FIXME: The original Unity plugin multiplied U by the aspect ratio
  37327. // and didn't multiply either value by 2, but that seems to get it
  37328. // really close to correct looking for me. I hate this kind of "Don't
  37329. // know why it works" code though, and wold love a more logical
  37330. // explanation of what needs to happen here.
  37331. u = (viewport.x + u * viewport.width - 0.5) * 2.0; //* aspect;
  37332. v = (viewport.y + v * viewport.height - 0.5) * 2.0;
  37333. vertices[(vidx * 5) + 0] = u; // position.x
  37334. vertices[(vidx * 5) + 1] = v; // position.y
  37335. vertices[(vidx * 5) + 2] = s; // texCoord.x
  37336. vertices[(vidx * 5) + 3] = t; // texCoord.y
  37337. vertices[(vidx * 5) + 4] = e; // texCoord.z (viewport index)
  37338. }
  37339. }
  37340. var w = lensFrustum[2] - lensFrustum[0];
  37341. lensFrustum[0] = -(w + lensFrustum[0]);
  37342. lensFrustum[2] = w - lensFrustum[2];
  37343. w = noLensFrustum[2] - noLensFrustum[0];
  37344. noLensFrustum[0] = -(w + noLensFrustum[0]);
  37345. noLensFrustum[2] = w - noLensFrustum[2];
  37346. viewport.x = 1 - (viewport.x + viewport.width);
  37347. }
  37348. return vertices;
  37349. }
  37350. /**
  37351. * Build the distortion mesh indices.
  37352. * Based on code from the Unity cardboard plugin.
  37353. */
  37354. CardboardDistorter.prototype.computeMeshIndices_ = function(width, height) {
  37355. var indices = new Uint16Array(2 * (width - 1) * (height - 1) * 6);
  37356. var halfwidth = width / 2;
  37357. var halfheight = height / 2;
  37358. var vidx = 0;
  37359. var iidx = 0;
  37360. for (var e = 0; e < 2; e++) {
  37361. for (var j = 0; j < height; j++) {
  37362. for (var i = 0; i < width; i++, vidx++) {
  37363. if (i == 0 || j == 0)
  37364. continue;
  37365. // Build a quad. Lower right and upper left quadrants have quads with
  37366. // the triangle diagonal flipped to get the vignette to interpolate
  37367. // correctly.
  37368. if ((i <= halfwidth) == (j <= halfheight)) {
  37369. // Quad diagonal lower left to upper right.
  37370. indices[iidx++] = vidx;
  37371. indices[iidx++] = vidx - width - 1;
  37372. indices[iidx++] = vidx - width;
  37373. indices[iidx++] = vidx - width - 1;
  37374. indices[iidx++] = vidx;
  37375. indices[iidx++] = vidx - 1;
  37376. } else {
  37377. // Quad diagonal upper left to lower right.
  37378. indices[iidx++] = vidx - 1;
  37379. indices[iidx++] = vidx - width;
  37380. indices[iidx++] = vidx;
  37381. indices[iidx++] = vidx - width;
  37382. indices[iidx++] = vidx - 1;
  37383. indices[iidx++] = vidx - width - 1;
  37384. }
  37385. }
  37386. }
  37387. }
  37388. return indices;
  37389. };
  37390. CardboardDistorter.prototype.getOwnPropertyDescriptor_ = function(proto, attrName) {
  37391. var descriptor = Object.getOwnPropertyDescriptor(proto, attrName);
  37392. // In some cases (ahem... Safari), the descriptor returns undefined get and
  37393. // set fields. In this case, we need to create a synthetic property
  37394. // descriptor. This works around some of the issues in
  37395. // https://github.com/borismus/webvr-polyfill/issues/46
  37396. if (descriptor.get === undefined || descriptor.set === undefined) {
  37397. descriptor.configurable = true;
  37398. descriptor.enumerable = true;
  37399. descriptor.get = function() {
  37400. return this.getAttribute(attrName);
  37401. };
  37402. descriptor.set = function(val) {
  37403. this.setAttribute(attrName, val);
  37404. };
  37405. }
  37406. return descriptor;
  37407. };
  37408. module.exports = CardboardDistorter;
  37409. },{"./cardboard-ui.js":5,"./deps/wglu-preserve-state.js":7,"./util.js":23}],5:[function(_dereq_,module,exports){
  37410. /*
  37411. * Copyright 2016 Google Inc. All Rights Reserved.
  37412. * Licensed under the Apache License, Version 2.0 (the "License");
  37413. * you may not use this file except in compliance with the License.
  37414. * You may obtain a copy of the License at
  37415. *
  37416. * http://www.apache.org/licenses/LICENSE-2.0
  37417. *
  37418. * Unless required by applicable law or agreed to in writing, software
  37419. * distributed under the License is distributed on an "AS IS" BASIS,
  37420. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  37421. * See the License for the specific language governing permissions and
  37422. * limitations under the License.
  37423. */
  37424. var Util = _dereq_('./util.js');
  37425. var WGLUPreserveGLState = _dereq_('./deps/wglu-preserve-state.js');
  37426. var uiVS = [
  37427. 'attribute vec2 position;',
  37428. 'uniform mat4 projectionMat;',
  37429. 'void main() {',
  37430. ' gl_Position = projectionMat * vec4( position, -1.0, 1.0 );',
  37431. '}',
  37432. ].join('\n');
  37433. var uiFS = [
  37434. 'precision mediump float;',
  37435. 'uniform vec4 color;',
  37436. 'void main() {',
  37437. ' gl_FragColor = color;',
  37438. '}',
  37439. ].join('\n');
  37440. var DEG2RAD = Math.PI/180.0;
  37441. // The gear has 6 identical sections, each spanning 60 degrees.
  37442. var kAnglePerGearSection = 60;
  37443. // Half-angle of the span of the outer rim.
  37444. var kOuterRimEndAngle = 12;
  37445. // Angle between the middle of the outer rim and the start of the inner rim.
  37446. var kInnerRimBeginAngle = 20;
  37447. // Distance from center to outer rim, normalized so that the entire model
  37448. // fits in a [-1, 1] x [-1, 1] square.
  37449. var kOuterRadius = 1;
  37450. // Distance from center to depressed rim, in model units.
  37451. var kMiddleRadius = 0.75;
  37452. // Radius of the inner hollow circle, in model units.
  37453. var kInnerRadius = 0.3125;
  37454. // Center line thickness in DP.
  37455. var kCenterLineThicknessDp = 4;
  37456. // Button width in DP.
  37457. var kButtonWidthDp = 28;
  37458. // Factor to scale the touch area that responds to the touch.
  37459. var kTouchSlopFactor = 1.5;
  37460. var Angles = [
  37461. 0, kOuterRimEndAngle, kInnerRimBeginAngle,
  37462. kAnglePerGearSection - kInnerRimBeginAngle,
  37463. kAnglePerGearSection - kOuterRimEndAngle
  37464. ];
  37465. /**
  37466. * Renders the alignment line and "options" gear. It is assumed that the canvas
  37467. * this is rendered into covers the entire screen (or close to it.)
  37468. */
  37469. function CardboardUI(gl) {
  37470. this.gl = gl;
  37471. this.attribs = {
  37472. position: 0
  37473. };
  37474. this.program = Util.linkProgram(gl, uiVS, uiFS, this.attribs);
  37475. this.uniforms = Util.getProgramUniforms(gl, this.program);
  37476. this.vertexBuffer = gl.createBuffer();
  37477. this.gearOffset = 0;
  37478. this.gearVertexCount = 0;
  37479. this.arrowOffset = 0;
  37480. this.arrowVertexCount = 0;
  37481. this.projMat = new Float32Array(16);
  37482. this.listener = null;
  37483. this.onResize();
  37484. };
  37485. /**
  37486. * Tears down all the resources created by the UI renderer.
  37487. */
  37488. CardboardUI.prototype.destroy = function() {
  37489. var gl = this.gl;
  37490. if (this.listener) {
  37491. gl.canvas.removeEventListener('click', this.listener, false);
  37492. }
  37493. gl.deleteProgram(this.program);
  37494. gl.deleteBuffer(this.vertexBuffer);
  37495. };
  37496. /**
  37497. * Adds a listener to clicks on the gear and back icons
  37498. */
  37499. CardboardUI.prototype.listen = function(optionsCallback, backCallback) {
  37500. var canvas = this.gl.canvas;
  37501. this.listener = function(event) {
  37502. var midline = canvas.clientWidth / 2;
  37503. var buttonSize = kButtonWidthDp * kTouchSlopFactor;
  37504. // Check to see if the user clicked on (or around) the gear icon
  37505. if (event.clientX > midline - buttonSize &&
  37506. event.clientX < midline + buttonSize &&
  37507. event.clientY > canvas.clientHeight - buttonSize) {
  37508. optionsCallback(event);
  37509. }
  37510. // Check to see if the user clicked on (or around) the back icon
  37511. else if (event.clientX < buttonSize && event.clientY < buttonSize) {
  37512. backCallback(event);
  37513. }
  37514. };
  37515. canvas.addEventListener('click', this.listener, false);
  37516. };
  37517. /**
  37518. * Builds the UI mesh.
  37519. */
  37520. CardboardUI.prototype.onResize = function() {
  37521. var gl = this.gl;
  37522. var self = this;
  37523. var glState = [
  37524. gl.ARRAY_BUFFER_BINDING
  37525. ];
  37526. WGLUPreserveGLState(gl, glState, function(gl) {
  37527. var vertices = [];
  37528. var midline = gl.drawingBufferWidth / 2;
  37529. // Assumes your canvas width and height is scaled proportionately.
  37530. // TODO(smus): The following causes buttons to become huge on iOS, but seems
  37531. // like the right thing to do. For now, added a hack. But really, investigate why.
  37532. var dps = (gl.drawingBufferWidth / (screen.width * window.devicePixelRatio));
  37533. if (!Util.isIOS()) {
  37534. dps *= window.devicePixelRatio;
  37535. }
  37536. var lineWidth = kCenterLineThicknessDp * dps / 2;
  37537. var buttonSize = kButtonWidthDp * kTouchSlopFactor * dps;
  37538. var buttonScale = kButtonWidthDp * dps / 2;
  37539. var buttonBorder = ((kButtonWidthDp * kTouchSlopFactor) - kButtonWidthDp) * dps;
  37540. // Build centerline
  37541. vertices.push(midline - lineWidth, buttonSize);
  37542. vertices.push(midline - lineWidth, gl.drawingBufferHeight);
  37543. vertices.push(midline + lineWidth, buttonSize);
  37544. vertices.push(midline + lineWidth, gl.drawingBufferHeight);
  37545. // Build gear
  37546. self.gearOffset = (vertices.length / 2);
  37547. function addGearSegment(theta, r) {
  37548. var angle = (90 - theta) * DEG2RAD;
  37549. var x = Math.cos(angle);
  37550. var y = Math.sin(angle);
  37551. vertices.push(kInnerRadius * x * buttonScale + midline, kInnerRadius * y * buttonScale + buttonScale);
  37552. vertices.push(r * x * buttonScale + midline, r * y * buttonScale + buttonScale);
  37553. }
  37554. for (var i = 0; i <= 6; i++) {
  37555. var segmentTheta = i * kAnglePerGearSection;
  37556. addGearSegment(segmentTheta, kOuterRadius);
  37557. addGearSegment(segmentTheta + kOuterRimEndAngle, kOuterRadius);
  37558. addGearSegment(segmentTheta + kInnerRimBeginAngle, kMiddleRadius);
  37559. addGearSegment(segmentTheta + (kAnglePerGearSection - kInnerRimBeginAngle), kMiddleRadius);
  37560. addGearSegment(segmentTheta + (kAnglePerGearSection - kOuterRimEndAngle), kOuterRadius);
  37561. }
  37562. self.gearVertexCount = (vertices.length / 2) - self.gearOffset;
  37563. // Build back arrow
  37564. self.arrowOffset = (vertices.length / 2);
  37565. function addArrowVertex(x, y) {
  37566. vertices.push(buttonBorder + x, gl.drawingBufferHeight - buttonBorder - y);
  37567. }
  37568. var angledLineWidth = lineWidth / Math.sin(45 * DEG2RAD);
  37569. addArrowVertex(0, buttonScale);
  37570. addArrowVertex(buttonScale, 0);
  37571. addArrowVertex(buttonScale + angledLineWidth, angledLineWidth);
  37572. addArrowVertex(angledLineWidth, buttonScale + angledLineWidth);
  37573. addArrowVertex(angledLineWidth, buttonScale - angledLineWidth);
  37574. addArrowVertex(0, buttonScale);
  37575. addArrowVertex(buttonScale, buttonScale * 2);
  37576. addArrowVertex(buttonScale + angledLineWidth, (buttonScale * 2) - angledLineWidth);
  37577. addArrowVertex(angledLineWidth, buttonScale - angledLineWidth);
  37578. addArrowVertex(0, buttonScale);
  37579. addArrowVertex(angledLineWidth, buttonScale - lineWidth);
  37580. addArrowVertex(kButtonWidthDp * dps, buttonScale - lineWidth);
  37581. addArrowVertex(angledLineWidth, buttonScale + lineWidth);
  37582. addArrowVertex(kButtonWidthDp * dps, buttonScale + lineWidth);
  37583. self.arrowVertexCount = (vertices.length / 2) - self.arrowOffset;
  37584. // Buffer data
  37585. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  37586. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
  37587. });
  37588. };
  37589. /**
  37590. * Performs distortion pass on the injected backbuffer, rendering it to the real
  37591. * backbuffer.
  37592. */
  37593. CardboardUI.prototype.render = function() {
  37594. var gl = this.gl;
  37595. var self = this;
  37596. var glState = [
  37597. gl.CULL_FACE,
  37598. gl.DEPTH_TEST,
  37599. gl.BLEND,
  37600. gl.SCISSOR_TEST,
  37601. gl.STENCIL_TEST,
  37602. gl.COLOR_WRITEMASK,
  37603. gl.VIEWPORT,
  37604. gl.CURRENT_PROGRAM,
  37605. gl.ARRAY_BUFFER_BINDING
  37606. ];
  37607. WGLUPreserveGLState(gl, glState, function(gl) {
  37608. // Make sure the GL state is in a good place
  37609. gl.disable(gl.CULL_FACE);
  37610. gl.disable(gl.DEPTH_TEST);
  37611. gl.disable(gl.BLEND);
  37612. gl.disable(gl.SCISSOR_TEST);
  37613. gl.disable(gl.STENCIL_TEST);
  37614. gl.colorMask(true, true, true, true);
  37615. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  37616. self.renderNoState();
  37617. });
  37618. };
  37619. CardboardUI.prototype.renderNoState = function() {
  37620. var gl = this.gl;
  37621. // Bind distortion program and mesh
  37622. gl.useProgram(this.program);
  37623. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  37624. gl.enableVertexAttribArray(this.attribs.position);
  37625. gl.vertexAttribPointer(this.attribs.position, 2, gl.FLOAT, false, 8, 0);
  37626. gl.uniform4f(this.uniforms.color, 1.0, 1.0, 1.0, 1.0);
  37627. Util.orthoMatrix(this.projMat, 0, gl.drawingBufferWidth, 0, gl.drawingBufferHeight, 0.1, 1024.0);
  37628. gl.uniformMatrix4fv(this.uniforms.projectionMat, false, this.projMat);
  37629. // Draws UI element
  37630. gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  37631. gl.drawArrays(gl.TRIANGLE_STRIP, this.gearOffset, this.gearVertexCount);
  37632. gl.drawArrays(gl.TRIANGLE_STRIP, this.arrowOffset, this.arrowVertexCount);
  37633. };
  37634. module.exports = CardboardUI;
  37635. },{"./deps/wglu-preserve-state.js":7,"./util.js":23}],6:[function(_dereq_,module,exports){
  37636. /*
  37637. * Copyright 2016 Google Inc. All Rights Reserved.
  37638. * Licensed under the Apache License, Version 2.0 (the "License");
  37639. * you may not use this file except in compliance with the License.
  37640. * You may obtain a copy of the License at
  37641. *
  37642. * http://www.apache.org/licenses/LICENSE-2.0
  37643. *
  37644. * Unless required by applicable law or agreed to in writing, software
  37645. * distributed under the License is distributed on an "AS IS" BASIS,
  37646. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  37647. * See the License for the specific language governing permissions and
  37648. * limitations under the License.
  37649. */
  37650. var CardboardDistorter = _dereq_('./cardboard-distorter.js');
  37651. var CardboardUI = _dereq_('./cardboard-ui.js');
  37652. var DeviceInfo = _dereq_('./device-info.js');
  37653. var Dpdb = _dereq_('./dpdb/dpdb.js');
  37654. var FusionPoseSensor = _dereq_('./sensor-fusion/fusion-pose-sensor.js');
  37655. var RotateInstructions = _dereq_('./rotate-instructions.js');
  37656. var ViewerSelector = _dereq_('./viewer-selector.js');
  37657. var VRDisplay = _dereq_('./base.js').VRDisplay;
  37658. var Util = _dereq_('./util.js');
  37659. var Eye = {
  37660. LEFT: 'left',
  37661. RIGHT: 'right'
  37662. };
  37663. /**
  37664. * VRDisplay based on mobile device parameters and DeviceMotion APIs.
  37665. */
  37666. function CardboardVRDisplay() {
  37667. this.displayName = 'Cardboard VRDisplay (webvr-polyfill)';
  37668. this.capabilities.hasOrientation = true;
  37669. this.capabilities.canPresent = true;
  37670. // "Private" members.
  37671. this.bufferScale_ = WebVRConfig.BUFFER_SCALE;
  37672. this.poseSensor_ = new FusionPoseSensor();
  37673. this.distorter_ = null;
  37674. this.cardboardUI_ = null;
  37675. this.dpdb_ = new Dpdb(true, this.onDeviceParamsUpdated_.bind(this));
  37676. this.deviceInfo_ = new DeviceInfo(this.dpdb_.getDeviceParams());
  37677. this.viewerSelector_ = new ViewerSelector();
  37678. this.viewerSelector_.on('change', this.onViewerChanged_.bind(this));
  37679. // Set the correct initial viewer.
  37680. this.deviceInfo_.setViewer(this.viewerSelector_.getCurrentViewer());
  37681. if (!WebVRConfig.ROTATE_INSTRUCTIONS_DISABLED) {
  37682. this.rotateInstructions_ = new RotateInstructions();
  37683. }
  37684. if (Util.isIOS()) {
  37685. // Listen for resize events to workaround this awful Safari bug.
  37686. window.addEventListener('resize', this.onResize_.bind(this));
  37687. }
  37688. }
  37689. CardboardVRDisplay.prototype = new VRDisplay();
  37690. CardboardVRDisplay.prototype.getImmediatePose = function() {
  37691. return {
  37692. position: this.poseSensor_.getPosition(),
  37693. orientation: this.poseSensor_.getOrientation(),
  37694. linearVelocity: null,
  37695. linearAcceleration: null,
  37696. angularVelocity: null,
  37697. angularAcceleration: null
  37698. };
  37699. };
  37700. CardboardVRDisplay.prototype.resetPose = function() {
  37701. this.poseSensor_.resetPose();
  37702. };
  37703. CardboardVRDisplay.prototype.getEyeParameters = function(whichEye) {
  37704. var offset = [this.deviceInfo_.viewer.interLensDistance * 0.5, 0.0, 0.0];
  37705. var fieldOfView;
  37706. // TODO: FoV can be a little expensive to compute. Cache when device params change.
  37707. if (whichEye == Eye.LEFT) {
  37708. offset[0] *= -1.0;
  37709. fieldOfView = this.deviceInfo_.getFieldOfViewLeftEye();
  37710. } else if (whichEye == Eye.RIGHT) {
  37711. fieldOfView = this.deviceInfo_.getFieldOfViewRightEye();
  37712. } else {
  37713. console.error('Invalid eye provided: %s', whichEye);
  37714. return null;
  37715. }
  37716. return {
  37717. fieldOfView: fieldOfView,
  37718. offset: offset,
  37719. // TODO: Should be able to provide better values than these.
  37720. renderWidth: this.deviceInfo_.device.width * 0.5 * this.bufferScale_,
  37721. renderHeight: this.deviceInfo_.device.height * this.bufferScale_,
  37722. };
  37723. };
  37724. CardboardVRDisplay.prototype.onDeviceParamsUpdated_ = function(newParams) {
  37725. if (Util.isDebug()) {
  37726. console.log('DPDB reported that device params were updated.');
  37727. }
  37728. this.deviceInfo_.updateDeviceParams(newParams);
  37729. if (this.distorter_) {
  37730. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  37731. }
  37732. };
  37733. CardboardVRDisplay.prototype.updateBounds_ = function () {
  37734. if (this.layer_ && this.distorter_ && (this.layer_.leftBounds || this.layer_.rightBounds)) {
  37735. this.distorter_.setTextureBounds(this.layer_.leftBounds, this.layer_.rightBounds);
  37736. }
  37737. };
  37738. CardboardVRDisplay.prototype.beginPresent_ = function() {
  37739. var gl = this.layer_.source.getContext('webgl');
  37740. if (!gl)
  37741. gl = this.layer_.source.getContext('experimental-webgl');
  37742. if (!gl)
  37743. gl = this.layer_.source.getContext('webgl2');
  37744. if (!gl)
  37745. return; // Can't do distortion without a WebGL context.
  37746. // Provides a way to opt out of distortion
  37747. if (this.layer_.predistorted) {
  37748. if (!WebVRConfig.CARDBOARD_UI_DISABLED) {
  37749. gl.canvas.width = Util.getScreenWidth() * this.bufferScale_;
  37750. gl.canvas.height = Util.getScreenHeight() * this.bufferScale_;
  37751. this.cardboardUI_ = new CardboardUI(gl);
  37752. }
  37753. } else {
  37754. // Create a new distorter for the target context
  37755. this.distorter_ = new CardboardDistorter(gl);
  37756. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  37757. this.cardboardUI_ = this.distorter_.cardboardUI;
  37758. }
  37759. if (this.cardboardUI_) {
  37760. this.cardboardUI_.listen(function(e) {
  37761. // Options clicked.
  37762. this.viewerSelector_.show(this.layer_.source.parentElement);
  37763. e.stopPropagation();
  37764. e.preventDefault();
  37765. }.bind(this), function(e) {
  37766. // Back clicked.
  37767. this.exitPresent();
  37768. e.stopPropagation();
  37769. e.preventDefault();
  37770. }.bind(this));
  37771. }
  37772. if (this.rotateInstructions_) {
  37773. if (Util.isLandscapeMode() && Util.isMobile()) {
  37774. // In landscape mode, temporarily show the "put into Cardboard"
  37775. // interstitial. Otherwise, do the default thing.
  37776. this.rotateInstructions_.showTemporarily(3000, this.layer_.source.parentElement);
  37777. } else {
  37778. this.rotateInstructions_.update();
  37779. }
  37780. }
  37781. // Listen for orientation change events in order to show interstitial.
  37782. this.orientationHandler = this.onOrientationChange_.bind(this);
  37783. window.addEventListener('orientationchange', this.orientationHandler);
  37784. // Listen for present display change events in order to update distorter dimensions
  37785. this.vrdisplaypresentchangeHandler = this.updateBounds_.bind(this);
  37786. window.addEventListener('vrdisplaypresentchange', this.vrdisplaypresentchangeHandler);
  37787. // Fire this event initially, to give geometry-distortion clients the chance
  37788. // to do something custom.
  37789. this.fireVRDisplayDeviceParamsChange_();
  37790. };
  37791. CardboardVRDisplay.prototype.endPresent_ = function() {
  37792. if (this.distorter_) {
  37793. this.distorter_.destroy();
  37794. this.distorter_ = null;
  37795. }
  37796. if (this.cardboardUI_) {
  37797. this.cardboardUI_.destroy();
  37798. this.cardboardUI_ = null;
  37799. }
  37800. if (this.rotateInstructions_) {
  37801. this.rotateInstructions_.hide();
  37802. }
  37803. this.viewerSelector_.hide();
  37804. window.removeEventListener('orientationchange', this.orientationHandler);
  37805. window.removeEventListener('vrdisplaypresentchange', this.vrdisplaypresentchangeHandler);
  37806. };
  37807. CardboardVRDisplay.prototype.submitFrame = function(pose) {
  37808. if (this.distorter_) {
  37809. this.distorter_.submitFrame();
  37810. } else if (this.cardboardUI_ && this.layer_) {
  37811. // Hack for predistorted: true.
  37812. var canvas = this.layer_.source.getContext('webgl').canvas;
  37813. if (canvas.width != this.lastWidth || canvas.height != this.lastHeight) {
  37814. this.cardboardUI_.onResize();
  37815. }
  37816. this.lastWidth = canvas.width;
  37817. this.lastHeight = canvas.height;
  37818. // Render the Cardboard UI.
  37819. this.cardboardUI_.render();
  37820. }
  37821. };
  37822. CardboardVRDisplay.prototype.onOrientationChange_ = function(e) {
  37823. // Hide the viewer selector.
  37824. this.viewerSelector_.hide();
  37825. // Update the rotate instructions.
  37826. if (this.rotateInstructions_) {
  37827. this.rotateInstructions_.update();
  37828. }
  37829. this.onResize_();
  37830. };
  37831. CardboardVRDisplay.prototype.onResize_ = function(e) {
  37832. if (this.layer_) {
  37833. var gl = this.layer_.source.getContext('webgl');
  37834. // Size the CSS canvas.
  37835. // Added padding on right and bottom because iPhone 5 will not
  37836. // hide the URL bar unless content is bigger than the screen.
  37837. // This will not be visible as long as the container element (e.g. body)
  37838. // is set to 'overflow: hidden'.
  37839. var cssProperties = [
  37840. 'position: absolute',
  37841. 'top: 0',
  37842. 'left: 0',
  37843. 'width: ' + Math.max(screen.width, screen.height) + 'px',
  37844. 'height: ' + Math.min(screen.height, screen.width) + 'px',
  37845. 'border: 0',
  37846. 'margin: 0',
  37847. 'padding: 0 10px 10px 0',
  37848. ];
  37849. gl.canvas.setAttribute('style', cssProperties.join('; ') + ';');
  37850. Util.safariCssSizeWorkaround(gl.canvas);
  37851. }
  37852. };
  37853. CardboardVRDisplay.prototype.onViewerChanged_ = function(viewer) {
  37854. this.deviceInfo_.setViewer(viewer);
  37855. if (this.distorter_) {
  37856. // Update the distortion appropriately.
  37857. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  37858. }
  37859. // Fire a new event containing viewer and device parameters for clients that
  37860. // want to implement their own geometry-based distortion.
  37861. this.fireVRDisplayDeviceParamsChange_();
  37862. };
  37863. CardboardVRDisplay.prototype.fireVRDisplayDeviceParamsChange_ = function() {
  37864. var event = new CustomEvent('vrdisplaydeviceparamschange', {
  37865. detail: {
  37866. vrdisplay: this,
  37867. deviceInfo: this.deviceInfo_,
  37868. }
  37869. });
  37870. window.dispatchEvent(event);
  37871. };
  37872. module.exports = CardboardVRDisplay;
  37873. },{"./base.js":3,"./cardboard-distorter.js":4,"./cardboard-ui.js":5,"./device-info.js":8,"./dpdb/dpdb.js":13,"./rotate-instructions.js":17,"./sensor-fusion/fusion-pose-sensor.js":19,"./util.js":23,"./viewer-selector.js":24}],7:[function(_dereq_,module,exports){
  37874. /*
  37875. Copyright (c) 2016, Brandon Jones.
  37876. Permission is hereby granted, free of charge, to any person obtaining a copy
  37877. of this software and associated documentation files (the "Software"), to deal
  37878. in the Software without restriction, including without limitation the rights
  37879. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  37880. copies of the Software, and to permit persons to whom the Software is
  37881. furnished to do so, subject to the following conditions:
  37882. The above copyright notice and this permission notice shall be included in
  37883. all copies or substantial portions of the Software.
  37884. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  37885. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  37886. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  37887. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  37888. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  37889. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  37890. THE SOFTWARE.
  37891. */
  37892. /*
  37893. Caches specified GL state, runs a callback, and restores the cached state when
  37894. done.
  37895. Example usage:
  37896. var savedState = [
  37897. gl.ARRAY_BUFFER_BINDING,
  37898. // TEXTURE_BINDING_2D or _CUBE_MAP must always be followed by the texure unit.
  37899. gl.TEXTURE_BINDING_2D, gl.TEXTURE0,
  37900. gl.CLEAR_COLOR,
  37901. ];
  37902. // After this call the array buffer, texture unit 0, active texture, and clear
  37903. // color will be restored. The viewport will remain changed, however, because
  37904. // gl.VIEWPORT was not included in the savedState list.
  37905. WGLUPreserveGLState(gl, savedState, function(gl) {
  37906. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  37907. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  37908. gl.bufferData(gl.ARRAY_BUFFER, ....);
  37909. gl.activeTexture(gl.TEXTURE0);
  37910. gl.bindTexture(gl.TEXTURE_2D, texture);
  37911. gl.texImage2D(gl.TEXTURE_2D, ...);
  37912. gl.clearColor(1, 0, 0, 1);
  37913. gl.clear(gl.COLOR_BUFFER_BIT);
  37914. });
  37915. Note that this is not intended to be fast. Managing state in your own code to
  37916. avoid redundant state setting and querying will always be faster. This function
  37917. is most useful for cases where you may not have full control over the WebGL
  37918. calls being made, such as tooling or effect injectors.
  37919. */
  37920. function WGLUPreserveGLState(gl, bindings, callback) {
  37921. if (!bindings) {
  37922. callback(gl);
  37923. return;
  37924. }
  37925. var boundValues = [];
  37926. var activeTexture = null;
  37927. for (var i = 0; i < bindings.length; ++i) {
  37928. var binding = bindings[i];
  37929. switch (binding) {
  37930. case gl.TEXTURE_BINDING_2D:
  37931. case gl.TEXTURE_BINDING_CUBE_MAP:
  37932. var textureUnit = bindings[++i];
  37933. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31) {
  37934. console.error("TEXTURE_BINDING_2D or TEXTURE_BINDING_CUBE_MAP must be followed by a valid texture unit");
  37935. boundValues.push(null, null);
  37936. break;
  37937. }
  37938. if (!activeTexture) {
  37939. activeTexture = gl.getParameter(gl.ACTIVE_TEXTURE);
  37940. }
  37941. gl.activeTexture(textureUnit);
  37942. boundValues.push(gl.getParameter(binding), null);
  37943. break;
  37944. case gl.ACTIVE_TEXTURE:
  37945. activeTexture = gl.getParameter(gl.ACTIVE_TEXTURE);
  37946. boundValues.push(null);
  37947. break;
  37948. default:
  37949. boundValues.push(gl.getParameter(binding));
  37950. break;
  37951. }
  37952. }
  37953. callback(gl);
  37954. for (var i = 0; i < bindings.length; ++i) {
  37955. var binding = bindings[i];
  37956. var boundValue = boundValues[i];
  37957. switch (binding) {
  37958. case gl.ACTIVE_TEXTURE:
  37959. break; // Ignore this binding, since we special-case it to happen last.
  37960. case gl.ARRAY_BUFFER_BINDING:
  37961. gl.bindBuffer(gl.ARRAY_BUFFER, boundValue);
  37962. break;
  37963. case gl.COLOR_CLEAR_VALUE:
  37964. gl.clearColor(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  37965. break;
  37966. case gl.COLOR_WRITEMASK:
  37967. gl.colorMask(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  37968. break;
  37969. case gl.CURRENT_PROGRAM:
  37970. gl.useProgram(boundValue);
  37971. break;
  37972. case gl.ELEMENT_ARRAY_BUFFER_BINDING:
  37973. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, boundValue);
  37974. break;
  37975. case gl.FRAMEBUFFER_BINDING:
  37976. gl.bindFramebuffer(gl.FRAMEBUFFER, boundValue);
  37977. break;
  37978. case gl.RENDERBUFFER_BINDING:
  37979. gl.bindRenderbuffer(gl.RENDERBUFFER, boundValue);
  37980. break;
  37981. case gl.TEXTURE_BINDING_2D:
  37982. var textureUnit = bindings[++i];
  37983. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31)
  37984. break;
  37985. gl.activeTexture(textureUnit);
  37986. gl.bindTexture(gl.TEXTURE_2D, boundValue);
  37987. break;
  37988. case gl.TEXTURE_BINDING_CUBE_MAP:
  37989. var textureUnit = bindings[++i];
  37990. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31)
  37991. break;
  37992. gl.activeTexture(textureUnit);
  37993. gl.bindTexture(gl.TEXTURE_CUBE_MAP, boundValue);
  37994. break;
  37995. case gl.VIEWPORT:
  37996. gl.viewport(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  37997. break;
  37998. case gl.BLEND:
  37999. case gl.CULL_FACE:
  38000. case gl.DEPTH_TEST:
  38001. case gl.SCISSOR_TEST:
  38002. case gl.STENCIL_TEST:
  38003. if (boundValue) {
  38004. gl.enable(binding);
  38005. } else {
  38006. gl.disable(binding);
  38007. }
  38008. break;
  38009. default:
  38010. console.log("No GL restore behavior for 0x" + binding.toString(16));
  38011. break;
  38012. }
  38013. if (activeTexture) {
  38014. gl.activeTexture(activeTexture);
  38015. }
  38016. }
  38017. }
  38018. module.exports = WGLUPreserveGLState;
  38019. },{}],8:[function(_dereq_,module,exports){
  38020. /*
  38021. * Copyright 2015 Google Inc. All Rights Reserved.
  38022. * Licensed under the Apache License, Version 2.0 (the "License");
  38023. * you may not use this file except in compliance with the License.
  38024. * You may obtain a copy of the License at
  38025. *
  38026. * http://www.apache.org/licenses/LICENSE-2.0
  38027. *
  38028. * Unless required by applicable law or agreed to in writing, software
  38029. * distributed under the License is distributed on an "AS IS" BASIS,
  38030. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  38031. * See the License for the specific language governing permissions and
  38032. * limitations under the License.
  38033. */
  38034. var Distortion = _dereq_('./distortion/distortion.js');
  38035. var MathUtil = _dereq_('./math-util.js');
  38036. var Util = _dereq_('./util.js');
  38037. function Device(params) {
  38038. this.width = params.width || Util.getScreenWidth();
  38039. this.height = params.height || Util.getScreenHeight();
  38040. this.widthMeters = params.widthMeters;
  38041. this.heightMeters = params.heightMeters;
  38042. this.bevelMeters = params.bevelMeters;
  38043. }
  38044. // Fallback Android device (based on Nexus 5 measurements) for use when
  38045. // we can't recognize an Android device.
  38046. var DEFAULT_ANDROID = new Device({
  38047. widthMeters: 0.110,
  38048. heightMeters: 0.062,
  38049. bevelMeters: 0.004
  38050. });
  38051. // Fallback iOS device (based on iPhone6) for use when
  38052. // we can't recognize an Android device.
  38053. var DEFAULT_IOS = new Device({
  38054. widthMeters: 0.1038,
  38055. heightMeters: 0.0584,
  38056. bevelMeters: 0.004
  38057. });
  38058. var Viewers = {
  38059. CardboardV1: new CardboardViewer({
  38060. id: 'CardboardV1',
  38061. label: 'Cardboard I/O 2014',
  38062. fov: 40,
  38063. interLensDistance: 0.060,
  38064. baselineLensDistance: 0.035,
  38065. screenLensDistance: 0.042,
  38066. distortionCoefficients: [0.441, 0.156],
  38067. inverseCoefficients: [-0.4410035, 0.42756155, -0.4804439, 0.5460139,
  38068. -0.58821183, 0.5733938, -0.48303202, 0.33299083, -0.17573841,
  38069. 0.0651772, -0.01488963, 0.001559834]
  38070. }),
  38071. CardboardV2: new CardboardViewer({
  38072. id: 'CardboardV2',
  38073. label: 'Cardboard I/O 2015',
  38074. fov: 60,
  38075. interLensDistance: 0.064,
  38076. baselineLensDistance: 0.035,
  38077. screenLensDistance: 0.039,
  38078. distortionCoefficients: [0.34, 0.55],
  38079. inverseCoefficients: [-0.33836704, -0.18162185, 0.862655, -1.2462051,
  38080. 1.0560602, -0.58208317, 0.21609078, -0.05444823, 0.009177956,
  38081. -9.904169E-4, 6.183535E-5, -1.6981803E-6]
  38082. })
  38083. };
  38084. var DEFAULT_LEFT_CENTER = {x: 0.5, y: 0.5};
  38085. var DEFAULT_RIGHT_CENTER = {x: 0.5, y: 0.5};
  38086. /**
  38087. * Manages information about the device and the viewer.
  38088. *
  38089. * deviceParams indicates the parameters of the device to use (generally
  38090. * obtained from dpdb.getDeviceParams()). Can be null to mean no device
  38091. * params were found.
  38092. */
  38093. function DeviceInfo(deviceParams) {
  38094. this.viewer = Viewers.CardboardV2;
  38095. this.updateDeviceParams(deviceParams);
  38096. this.distortion = new Distortion(this.viewer.distortionCoefficients);
  38097. }
  38098. DeviceInfo.prototype.updateDeviceParams = function(deviceParams) {
  38099. this.device = this.determineDevice_(deviceParams) || this.device;
  38100. };
  38101. DeviceInfo.prototype.getDevice = function() {
  38102. return this.device;
  38103. };
  38104. DeviceInfo.prototype.setViewer = function(viewer) {
  38105. this.viewer = viewer;
  38106. this.distortion = new Distortion(this.viewer.distortionCoefficients);
  38107. };
  38108. DeviceInfo.prototype.determineDevice_ = function(deviceParams) {
  38109. if (!deviceParams) {
  38110. // No parameters, so use a default.
  38111. if (Util.isIOS()) {
  38112. console.warn('Using fallback iOS device measurements.');
  38113. return DEFAULT_IOS;
  38114. } else {
  38115. console.warn('Using fallback Android device measurements.');
  38116. return DEFAULT_ANDROID;
  38117. }
  38118. }
  38119. // Compute device screen dimensions based on deviceParams.
  38120. var METERS_PER_INCH = 0.0254;
  38121. var metersPerPixelX = METERS_PER_INCH / deviceParams.xdpi;
  38122. var metersPerPixelY = METERS_PER_INCH / deviceParams.ydpi;
  38123. var width = Util.getScreenWidth();
  38124. var height = Util.getScreenHeight();
  38125. return new Device({
  38126. widthMeters: metersPerPixelX * width,
  38127. heightMeters: metersPerPixelY * height,
  38128. bevelMeters: deviceParams.bevelMm * 0.001,
  38129. });
  38130. };
  38131. /**
  38132. * Calculates field of view for the left eye.
  38133. */
  38134. DeviceInfo.prototype.getDistortedFieldOfViewLeftEye = function() {
  38135. var viewer = this.viewer;
  38136. var device = this.device;
  38137. var distortion = this.distortion;
  38138. // Device.height and device.width for device in portrait mode, so transpose.
  38139. var eyeToScreenDistance = viewer.screenLensDistance;
  38140. var outerDist = (device.widthMeters - viewer.interLensDistance) / 2;
  38141. var innerDist = viewer.interLensDistance / 2;
  38142. var bottomDist = viewer.baselineLensDistance - device.bevelMeters;
  38143. var topDist = device.heightMeters - bottomDist;
  38144. var outerAngle = MathUtil.radToDeg * Math.atan(
  38145. distortion.distort(outerDist / eyeToScreenDistance));
  38146. var innerAngle = MathUtil.radToDeg * Math.atan(
  38147. distortion.distort(innerDist / eyeToScreenDistance));
  38148. var bottomAngle = MathUtil.radToDeg * Math.atan(
  38149. distortion.distort(bottomDist / eyeToScreenDistance));
  38150. var topAngle = MathUtil.radToDeg * Math.atan(
  38151. distortion.distort(topDist / eyeToScreenDistance));
  38152. return {
  38153. leftDegrees: Math.min(outerAngle, viewer.fov),
  38154. rightDegrees: Math.min(innerAngle, viewer.fov),
  38155. downDegrees: Math.min(bottomAngle, viewer.fov),
  38156. upDegrees: Math.min(topAngle, viewer.fov)
  38157. };
  38158. };
  38159. /**
  38160. * Calculates the tan-angles from the maximum FOV for the left eye for the
  38161. * current device and screen parameters.
  38162. */
  38163. DeviceInfo.prototype.getLeftEyeVisibleTanAngles = function() {
  38164. var viewer = this.viewer;
  38165. var device = this.device;
  38166. var distortion = this.distortion;
  38167. // Tan-angles from the max FOV.
  38168. var fovLeft = Math.tan(-MathUtil.degToRad * viewer.fov);
  38169. var fovTop = Math.tan(MathUtil.degToRad * viewer.fov);
  38170. var fovRight = Math.tan(MathUtil.degToRad * viewer.fov);
  38171. var fovBottom = Math.tan(-MathUtil.degToRad * viewer.fov);
  38172. // Viewport size.
  38173. var halfWidth = device.widthMeters / 4;
  38174. var halfHeight = device.heightMeters / 2;
  38175. // Viewport center, measured from left lens position.
  38176. var verticalLensOffset = (viewer.baselineLensDistance - device.bevelMeters - halfHeight);
  38177. var centerX = viewer.interLensDistance / 2 - halfWidth;
  38178. var centerY = -verticalLensOffset;
  38179. var centerZ = viewer.screenLensDistance;
  38180. // Tan-angles of the viewport edges, as seen through the lens.
  38181. var screenLeft = distortion.distort((centerX - halfWidth) / centerZ);
  38182. var screenTop = distortion.distort((centerY + halfHeight) / centerZ);
  38183. var screenRight = distortion.distort((centerX + halfWidth) / centerZ);
  38184. var screenBottom = distortion.distort((centerY - halfHeight) / centerZ);
  38185. // Compare the two sets of tan-angles and take the value closer to zero on each side.
  38186. var result = new Float32Array(4);
  38187. result[0] = Math.max(fovLeft, screenLeft);
  38188. result[1] = Math.min(fovTop, screenTop);
  38189. result[2] = Math.min(fovRight, screenRight);
  38190. result[3] = Math.max(fovBottom, screenBottom);
  38191. return result;
  38192. };
  38193. /**
  38194. * Calculates the tan-angles from the maximum FOV for the left eye for the
  38195. * current device and screen parameters, assuming no lenses.
  38196. */
  38197. DeviceInfo.prototype.getLeftEyeNoLensTanAngles = function() {
  38198. var viewer = this.viewer;
  38199. var device = this.device;
  38200. var distortion = this.distortion;
  38201. var result = new Float32Array(4);
  38202. // Tan-angles from the max FOV.
  38203. var fovLeft = distortion.distortInverse(Math.tan(-MathUtil.degToRad * viewer.fov));
  38204. var fovTop = distortion.distortInverse(Math.tan(MathUtil.degToRad * viewer.fov));
  38205. var fovRight = distortion.distortInverse(Math.tan(MathUtil.degToRad * viewer.fov));
  38206. var fovBottom = distortion.distortInverse(Math.tan(-MathUtil.degToRad * viewer.fov));
  38207. // Viewport size.
  38208. var halfWidth = device.widthMeters / 4;
  38209. var halfHeight = device.heightMeters / 2;
  38210. // Viewport center, measured from left lens position.
  38211. var verticalLensOffset = (viewer.baselineLensDistance - device.bevelMeters - halfHeight);
  38212. var centerX = viewer.interLensDistance / 2 - halfWidth;
  38213. var centerY = -verticalLensOffset;
  38214. var centerZ = viewer.screenLensDistance;
  38215. // Tan-angles of the viewport edges, as seen through the lens.
  38216. var screenLeft = (centerX - halfWidth) / centerZ;
  38217. var screenTop = (centerY + halfHeight) / centerZ;
  38218. var screenRight = (centerX + halfWidth) / centerZ;
  38219. var screenBottom = (centerY - halfHeight) / centerZ;
  38220. // Compare the two sets of tan-angles and take the value closer to zero on each side.
  38221. result[0] = Math.max(fovLeft, screenLeft);
  38222. result[1] = Math.min(fovTop, screenTop);
  38223. result[2] = Math.min(fovRight, screenRight);
  38224. result[3] = Math.max(fovBottom, screenBottom);
  38225. return result;
  38226. };
  38227. /**
  38228. * Calculates the screen rectangle visible from the left eye for the
  38229. * current device and screen parameters.
  38230. */
  38231. DeviceInfo.prototype.getLeftEyeVisibleScreenRect = function(undistortedFrustum) {
  38232. var viewer = this.viewer;
  38233. var device = this.device;
  38234. var dist = viewer.screenLensDistance;
  38235. var eyeX = (device.widthMeters - viewer.interLensDistance) / 2;
  38236. var eyeY = viewer.baselineLensDistance - device.bevelMeters;
  38237. var left = (undistortedFrustum[0] * dist + eyeX) / device.widthMeters;
  38238. var top = (undistortedFrustum[1] * dist + eyeY) / device.heightMeters;
  38239. var right = (undistortedFrustum[2] * dist + eyeX) / device.widthMeters;
  38240. var bottom = (undistortedFrustum[3] * dist + eyeY) / device.heightMeters;
  38241. return {
  38242. x: left,
  38243. y: bottom,
  38244. width: right - left,
  38245. height: top - bottom
  38246. };
  38247. };
  38248. DeviceInfo.prototype.getFieldOfViewLeftEye = function(opt_isUndistorted) {
  38249. return opt_isUndistorted ? this.getUndistortedFieldOfViewLeftEye() :
  38250. this.getDistortedFieldOfViewLeftEye();
  38251. };
  38252. DeviceInfo.prototype.getFieldOfViewRightEye = function(opt_isUndistorted) {
  38253. var fov = this.getFieldOfViewLeftEye(opt_isUndistorted);
  38254. return {
  38255. leftDegrees: fov.rightDegrees,
  38256. rightDegrees: fov.leftDegrees,
  38257. upDegrees: fov.upDegrees,
  38258. downDegrees: fov.downDegrees
  38259. };
  38260. };
  38261. /**
  38262. * Calculates undistorted field of view for the left eye.
  38263. */
  38264. DeviceInfo.prototype.getUndistortedFieldOfViewLeftEye = function() {
  38265. var p = this.getUndistortedParams_();
  38266. return {
  38267. leftDegrees: MathUtil.radToDeg * Math.atan(p.outerDist),
  38268. rightDegrees: MathUtil.radToDeg * Math.atan(p.innerDist),
  38269. downDegrees: MathUtil.radToDeg * Math.atan(p.bottomDist),
  38270. upDegrees: MathUtil.radToDeg * Math.atan(p.topDist)
  38271. };
  38272. };
  38273. DeviceInfo.prototype.getUndistortedViewportLeftEye = function() {
  38274. var p = this.getUndistortedParams_();
  38275. var viewer = this.viewer;
  38276. var device = this.device;
  38277. // Distances stored in local variables are in tan-angle units unless otherwise
  38278. // noted.
  38279. var eyeToScreenDistance = viewer.screenLensDistance;
  38280. var screenWidth = device.widthMeters / eyeToScreenDistance;
  38281. var screenHeight = device.heightMeters / eyeToScreenDistance;
  38282. var xPxPerTanAngle = device.width / screenWidth;
  38283. var yPxPerTanAngle = device.height / screenHeight;
  38284. var x = Math.round((p.eyePosX - p.outerDist) * xPxPerTanAngle);
  38285. var y = Math.round((p.eyePosY - p.bottomDist) * yPxPerTanAngle);
  38286. return {
  38287. x: x,
  38288. y: y,
  38289. width: Math.round((p.eyePosX + p.innerDist) * xPxPerTanAngle) - x,
  38290. height: Math.round((p.eyePosY + p.topDist) * yPxPerTanAngle) - y
  38291. };
  38292. };
  38293. DeviceInfo.prototype.getUndistortedParams_ = function() {
  38294. var viewer = this.viewer;
  38295. var device = this.device;
  38296. var distortion = this.distortion;
  38297. // Most of these variables in tan-angle units.
  38298. var eyeToScreenDistance = viewer.screenLensDistance;
  38299. var halfLensDistance = viewer.interLensDistance / 2 / eyeToScreenDistance;
  38300. var screenWidth = device.widthMeters / eyeToScreenDistance;
  38301. var screenHeight = device.heightMeters / eyeToScreenDistance;
  38302. var eyePosX = screenWidth / 2 - halfLensDistance;
  38303. var eyePosY = (viewer.baselineLensDistance - device.bevelMeters) / eyeToScreenDistance;
  38304. var maxFov = viewer.fov;
  38305. var viewerMax = distortion.distortInverse(Math.tan(MathUtil.degToRad * maxFov));
  38306. var outerDist = Math.min(eyePosX, viewerMax);
  38307. var innerDist = Math.min(halfLensDistance, viewerMax);
  38308. var bottomDist = Math.min(eyePosY, viewerMax);
  38309. var topDist = Math.min(screenHeight - eyePosY, viewerMax);
  38310. return {
  38311. outerDist: outerDist,
  38312. innerDist: innerDist,
  38313. topDist: topDist,
  38314. bottomDist: bottomDist,
  38315. eyePosX: eyePosX,
  38316. eyePosY: eyePosY
  38317. };
  38318. };
  38319. function CardboardViewer(params) {
  38320. // A machine readable ID.
  38321. this.id = params.id;
  38322. // A human readable label.
  38323. this.label = params.label;
  38324. // Field of view in degrees (per side).
  38325. this.fov = params.fov;
  38326. // Distance between lens centers in meters.
  38327. this.interLensDistance = params.interLensDistance;
  38328. // Distance between viewer baseline and lens center in meters.
  38329. this.baselineLensDistance = params.baselineLensDistance;
  38330. // Screen-to-lens distance in meters.
  38331. this.screenLensDistance = params.screenLensDistance;
  38332. // Distortion coefficients.
  38333. this.distortionCoefficients = params.distortionCoefficients;
  38334. // Inverse distortion coefficients.
  38335. // TODO: Calculate these from distortionCoefficients in the future.
  38336. this.inverseCoefficients = params.inverseCoefficients;
  38337. }
  38338. // Export viewer information.
  38339. DeviceInfo.Viewers = Viewers;
  38340. module.exports = DeviceInfo;
  38341. },{"./distortion/distortion.js":10,"./math-util.js":15,"./util.js":23}],9:[function(_dereq_,module,exports){
  38342. /*
  38343. * Copyright 2016 Google Inc. All Rights Reserved.
  38344. * Licensed under the Apache License, Version 2.0 (the "License");
  38345. * you may not use this file except in compliance with the License.
  38346. * You may obtain a copy of the License at
  38347. *
  38348. * http://www.apache.org/licenses/LICENSE-2.0
  38349. *
  38350. * Unless required by applicable law or agreed to in writing, software
  38351. * distributed under the License is distributed on an "AS IS" BASIS,
  38352. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  38353. * See the License for the specific language governing permissions and
  38354. * limitations under the License.
  38355. */
  38356. var VRDisplay = _dereq_('./base.js').VRDisplay;
  38357. var HMDVRDevice = _dereq_('./base.js').HMDVRDevice;
  38358. var PositionSensorVRDevice = _dereq_('./base.js').PositionSensorVRDevice;
  38359. /**
  38360. * Wraps a VRDisplay and exposes it as a HMDVRDevice
  38361. */
  38362. function VRDisplayHMDDevice(display) {
  38363. this.display = display;
  38364. this.hardwareUnitId = display.displayId;
  38365. this.deviceId = 'webvr-polyfill:HMD:' + display.displayId;
  38366. this.deviceName = display.displayName + ' (HMD)';
  38367. }
  38368. VRDisplayHMDDevice.prototype = new HMDVRDevice();
  38369. VRDisplayHMDDevice.prototype.getEyeParameters = function(whichEye) {
  38370. var eyeParameters = this.display.getEyeParameters(whichEye);
  38371. return {
  38372. currentFieldOfView: eyeParameters.fieldOfView,
  38373. maximumFieldOfView: eyeParameters.fieldOfView,
  38374. minimumFieldOfView: eyeParameters.fieldOfView,
  38375. recommendedFieldOfView: eyeParameters.fieldOfView,
  38376. eyeTranslation: { x: eyeParameters.offset[0], y: eyeParameters.offset[1], z: eyeParameters.offset[2] },
  38377. renderRect: {
  38378. x: (whichEye == 'right') ? eyeParameters.renderWidth : 0,
  38379. y: 0,
  38380. width: eyeParameters.renderWidth,
  38381. height: eyeParameters.renderHeight
  38382. }
  38383. };
  38384. };
  38385. VRDisplayHMDDevice.prototype.setFieldOfView =
  38386. function(opt_fovLeft, opt_fovRight, opt_zNear, opt_zFar) {
  38387. // Not supported. getEyeParameters reports that the min, max, and recommended
  38388. // FoV is all the same, so no adjustment can be made.
  38389. };
  38390. // TODO: Need to hook requestFullscreen to see if a wrapped VRDisplay was passed
  38391. // in as an option. If so we should prevent the default fullscreen behavior and
  38392. // call VRDisplay.requestPresent instead.
  38393. /**
  38394. * Wraps a VRDisplay and exposes it as a PositionSensorVRDevice
  38395. */
  38396. function VRDisplayPositionSensorDevice(display) {
  38397. this.display = display;
  38398. this.hardwareUnitId = display.displayId;
  38399. this.deviceId = 'webvr-polyfill:PositionSensor: ' + display.displayId;
  38400. this.deviceName = display.displayName + ' (PositionSensor)';
  38401. }
  38402. VRDisplayPositionSensorDevice.prototype = new PositionSensorVRDevice();
  38403. VRDisplayPositionSensorDevice.prototype.getState = function() {
  38404. var pose = this.display.getPose();
  38405. return {
  38406. position: pose.position ? { x: pose.position[0], y: pose.position[1], z: pose.position[2] } : null,
  38407. orientation: pose.orientation ? { x: pose.orientation[0], y: pose.orientation[1], z: pose.orientation[2], w: pose.orientation[3] } : null,
  38408. linearVelocity: null,
  38409. linearAcceleration: null,
  38410. angularVelocity: null,
  38411. angularAcceleration: null
  38412. };
  38413. };
  38414. VRDisplayPositionSensorDevice.prototype.resetState = function() {
  38415. return this.positionDevice.resetPose();
  38416. };
  38417. module.exports.VRDisplayHMDDevice = VRDisplayHMDDevice;
  38418. module.exports.VRDisplayPositionSensorDevice = VRDisplayPositionSensorDevice;
  38419. },{"./base.js":3}],10:[function(_dereq_,module,exports){
  38420. /**
  38421. * TODO(smus): Implement coefficient inversion.
  38422. */
  38423. function Distortion(coefficients) {
  38424. this.coefficients = coefficients;
  38425. }
  38426. /**
  38427. * Calculates the inverse distortion for a radius.
  38428. * </p><p>
  38429. * Allows to compute the original undistorted radius from a distorted one.
  38430. * See also getApproximateInverseDistortion() for a faster but potentially
  38431. * less accurate method.
  38432. *
  38433. * @param {Number} radius Distorted radius from the lens center in tan-angle units.
  38434. * @return {Number} The undistorted radius in tan-angle units.
  38435. */
  38436. Distortion.prototype.distortInverse = function(radius) {
  38437. // Secant method.
  38438. var r0 = 0;
  38439. var r1 = 1;
  38440. var dr0 = radius - this.distort(r0);
  38441. while (Math.abs(r1 - r0) > 0.0001 /** 0.1mm */) {
  38442. var dr1 = radius - this.distort(r1);
  38443. var r2 = r1 - dr1 * ((r1 - r0) / (dr1 - dr0));
  38444. r0 = r1;
  38445. r1 = r2;
  38446. dr0 = dr1;
  38447. }
  38448. return r1;
  38449. };
  38450. /**
  38451. * Distorts a radius by its distortion factor from the center of the lenses.
  38452. *
  38453. * @param {Number} radius Radius from the lens center in tan-angle units.
  38454. * @return {Number} The distorted radius in tan-angle units.
  38455. */
  38456. Distortion.prototype.distort = function(radius) {
  38457. var r2 = radius * radius;
  38458. var ret = 0;
  38459. for (var i = 0; i < this.coefficients.length; i++) {
  38460. ret = r2 * (ret + this.coefficients[i]);
  38461. }
  38462. return (ret + 1) * radius;
  38463. };
  38464. // Functions below roughly ported from
  38465. // https://github.com/googlesamples/cardboard-unity/blob/master/Cardboard/Scripts/CardboardProfile.cs#L412
  38466. // Solves a small linear equation via destructive gaussian
  38467. // elimination and back substitution. This isn't generic numeric
  38468. // code, it's just a quick hack to work with the generally
  38469. // well-behaved symmetric matrices for least-squares fitting.
  38470. // Not intended for reuse.
  38471. //
  38472. // @param a Input positive definite symmetrical matrix. Destroyed
  38473. // during calculation.
  38474. // @param y Input right-hand-side values. Destroyed during calculation.
  38475. // @return Resulting x value vector.
  38476. //
  38477. Distortion.prototype.solveLinear_ = function(a, y) {
  38478. var n = a.length;
  38479. // Gaussian elimination (no row exchange) to triangular matrix.
  38480. // The input matrix is a A^T A product which should be a positive
  38481. // definite symmetrical matrix, and if I remember my linear
  38482. // algebra right this implies that the pivots will be nonzero and
  38483. // calculations sufficiently accurate without needing row
  38484. // exchange.
  38485. for (var j = 0; j < n - 1; ++j) {
  38486. for (var k = j + 1; k < n; ++k) {
  38487. var p = a[j][k] / a[j][j];
  38488. for (var i = j + 1; i < n; ++i) {
  38489. a[i][k] -= p * a[i][j];
  38490. }
  38491. y[k] -= p * y[j];
  38492. }
  38493. }
  38494. // From this point on, only the matrix elements a[j][i] with i>=j are
  38495. // valid. The elimination doesn't fill in eliminated 0 values.
  38496. var x = new Array(n);
  38497. // Back substitution.
  38498. for (var j = n - 1; j >= 0; --j) {
  38499. var v = y[j];
  38500. for (var i = j + 1; i < n; ++i) {
  38501. v -= a[i][j] * x[i];
  38502. }
  38503. x[j] = v / a[j][j];
  38504. }
  38505. return x;
  38506. };
  38507. // Solves a least-squares matrix equation. Given the equation A * x = y, calculate the
  38508. // least-square fit x = inverse(A * transpose(A)) * transpose(A) * y. The way this works
  38509. // is that, while A is typically not a square matrix (and hence not invertible), A * transpose(A)
  38510. // is always square. That is:
  38511. // A * x = y
  38512. // transpose(A) * (A * x) = transpose(A) * y <- multiply both sides by transpose(A)
  38513. // (transpose(A) * A) * x = transpose(A) * y <- associativity
  38514. // x = inverse(transpose(A) * A) * transpose(A) * y <- solve for x
  38515. // Matrix A's row count (first index) must match y's value count. A's column count (second index)
  38516. // determines the length of the result vector x.
  38517. Distortion.prototype.solveLeastSquares_ = function(matA, vecY) {
  38518. var i, j, k, sum;
  38519. var numSamples = matA.length;
  38520. var numCoefficients = matA[0].length;
  38521. if (numSamples != vecY.Length) {
  38522. throw new Error("Matrix / vector dimension mismatch");
  38523. }
  38524. // Calculate transpose(A) * A
  38525. var matATA = new Array(numCoefficients);
  38526. for (k = 0; k < numCoefficients; ++k) {
  38527. matATA[k] = new Array(numCoefficients);
  38528. for (j = 0; j < numCoefficients; ++j) {
  38529. sum = 0;
  38530. for (i = 0; i < numSamples; ++i) {
  38531. sum += matA[j][i] * matA[k][i];
  38532. }
  38533. matATA[k][j] = sum;
  38534. }
  38535. }
  38536. // Calculate transpose(A) * y
  38537. var vecATY = new Array(numCoefficients);
  38538. for (j = 0; j < numCoefficients; ++j) {
  38539. sum = 0;
  38540. for (i = 0; i < numSamples; ++i) {
  38541. sum += matA[j][i] * vecY[i];
  38542. }
  38543. vecATY[j] = sum;
  38544. }
  38545. // Now solve (A * transpose(A)) * x = transpose(A) * y.
  38546. return this.solveLinear_(matATA, vecATY);
  38547. };
  38548. /// Calculates an approximate inverse to the given radial distortion parameters.
  38549. Distortion.prototype.approximateInverse = function(maxRadius, numSamples) {
  38550. maxRadius = maxRadius || 1;
  38551. numSamples = numSamples || 100;
  38552. var numCoefficients = 6;
  38553. var i, j;
  38554. // R + K1*R^3 + K2*R^5 = r, with R = rp = distort(r)
  38555. // Repeating for numSamples:
  38556. // [ R0^3, R0^5 ] * [ K1 ] = [ r0 - R0 ]
  38557. // [ R1^3, R1^5 ] [ K2 ] [ r1 - R1 ]
  38558. // [ R2^3, R2^5 ] [ r2 - R2 ]
  38559. // [ etc... ] [ etc... ]
  38560. // That is:
  38561. // matA * [K1, K2] = y
  38562. // Solve:
  38563. // [K1, K2] = inverse(transpose(matA) * matA) * transpose(matA) * y
  38564. var matA = new Array(numCoefficients);
  38565. for (j = 0; j < numCoefficients; ++j) {
  38566. matA[j] = new Array(numSamples);
  38567. }
  38568. var vecY = new Array(numSamples);
  38569. for (i = 0; i < numSamples; ++i) {
  38570. var r = maxRadius * (i + 1) / numSamples;
  38571. var rp = this.distort(r);
  38572. var v = rp;
  38573. for (j = 0; j < numCoefficients; ++j) {
  38574. v *= rp * rp;
  38575. matA[j][i] = v;
  38576. }
  38577. vecY[i] = r - rp;
  38578. }
  38579. var inverseCoefficients = this.solveLeastSquares_(matA, vecY);
  38580. return new Distortion(inverseCoefficients);
  38581. };
  38582. module.exports = Distortion;
  38583. },{}],11:[function(_dereq_,module,exports){
  38584. /*
  38585. * Copyright 2015 Google Inc. All Rights Reserved.
  38586. * Licensed under the Apache License, Version 2.0 (the "License");
  38587. * you may not use this file except in compliance with the License.
  38588. * You may obtain a copy of the License at
  38589. *
  38590. * http://www.apache.org/licenses/LICENSE-2.0
  38591. *
  38592. * Unless required by applicable law or agreed to in writing, software
  38593. * distributed under the License is distributed on an "AS IS" BASIS,
  38594. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  38595. * See the License for the specific language governing permissions and
  38596. * limitations under the License.
  38597. */
  38598. /**
  38599. * DPDB cache.
  38600. */
  38601. var DPDB_CACHE = {
  38602. "format": 1,
  38603. "last_updated": "2016-01-20T00:18:35Z",
  38604. "devices": [
  38605. {
  38606. "type": "android",
  38607. "rules": [
  38608. { "mdmh": "asus/*/Nexus 7/*" },
  38609. { "ua": "Nexus 7" }
  38610. ],
  38611. "dpi": [ 320.8, 323.0 ],
  38612. "bw": 3,
  38613. "ac": 500
  38614. },
  38615. {
  38616. "type": "android",
  38617. "rules": [
  38618. { "mdmh": "asus/*/ASUS_Z00AD/*" },
  38619. { "ua": "ASUS_Z00AD" }
  38620. ],
  38621. "dpi": [ 403.0, 404.6 ],
  38622. "bw": 3,
  38623. "ac": 1000
  38624. },
  38625. {
  38626. "type": "android",
  38627. "rules": [
  38628. { "mdmh": "Google//Pixel XL/" },
  38629. { "ua": "Pixel XL" }
  38630. ],
  38631. "dpi": [537.9, 533],
  38632. "bw": 3,
  38633. "ac": 1000
  38634. },
  38635. {
  38636. "type": "android",
  38637. "rules": [
  38638. { "mdmh": "HTC/*/HTC6435LVW/*" },
  38639. { "ua": "HTC6435LVW" }
  38640. ],
  38641. "dpi": [ 449.7, 443.3 ],
  38642. "bw": 3,
  38643. "ac": 1000
  38644. },
  38645. {
  38646. "type": "android",
  38647. "rules": [
  38648. { "mdmh": "HTC/*/HTC One XL/*" },
  38649. { "ua": "HTC One XL" }
  38650. ],
  38651. "dpi": [ 315.3, 314.6 ],
  38652. "bw": 3,
  38653. "ac": 1000
  38654. },
  38655. {
  38656. "type": "android",
  38657. "rules": [
  38658. { "mdmh": "htc/*/Nexus 9/*" },
  38659. { "ua": "Nexus 9" }
  38660. ],
  38661. "dpi": 289.0,
  38662. "bw": 3,
  38663. "ac": 500
  38664. },
  38665. {
  38666. "type": "android",
  38667. "rules": [
  38668. { "mdmh": "HTC/*/HTC One M9/*" },
  38669. { "ua": "HTC One M9" }
  38670. ],
  38671. "dpi": [ 442.5, 443.3 ],
  38672. "bw": 3,
  38673. "ac": 500
  38674. },
  38675. {
  38676. "type": "android",
  38677. "rules": [
  38678. { "mdmh": "HTC/*/HTC One_M8/*" },
  38679. { "ua": "HTC One_M8" }
  38680. ],
  38681. "dpi": [ 449.7, 447.4 ],
  38682. "bw": 3,
  38683. "ac": 500
  38684. },
  38685. {
  38686. "type": "android",
  38687. "rules": [
  38688. { "mdmh": "HTC/*/HTC One/*" },
  38689. { "ua": "HTC One" }
  38690. ],
  38691. "dpi": 472.8,
  38692. "bw": 3,
  38693. "ac": 1000
  38694. },
  38695. {
  38696. "type": "android",
  38697. "rules": [
  38698. { "mdmh": "Huawei/*/Nexus 6P/*" },
  38699. { "ua": "Nexus 6P" }
  38700. ],
  38701. "dpi": [ 515.1, 518.0 ],
  38702. "bw": 3,
  38703. "ac": 1000
  38704. },
  38705. {
  38706. "type": "android",
  38707. "rules": [
  38708. { "mdmh": "LGE/*/Nexus 5X/*" },
  38709. { "ua": "Nexus 5X" }
  38710. ],
  38711. "dpi": [ 422.0, 419.9 ],
  38712. "bw": 3,
  38713. "ac": 1000
  38714. },
  38715. {
  38716. "type": "android",
  38717. "rules": [
  38718. { "mdmh": "LGE/*/LGMS345/*" },
  38719. { "ua": "LGMS345" }
  38720. ],
  38721. "dpi": [ 221.7, 219.1 ],
  38722. "bw": 3,
  38723. "ac": 500
  38724. },
  38725. {
  38726. "type": "android",
  38727. "rules": [
  38728. { "mdmh": "LGE/*/LG-D800/*" },
  38729. { "ua": "LG-D800" }
  38730. ],
  38731. "dpi": [ 422.0, 424.1 ],
  38732. "bw": 3,
  38733. "ac": 500
  38734. },
  38735. {
  38736. "type": "android",
  38737. "rules": [
  38738. { "mdmh": "LGE/*/LG-D850/*" },
  38739. { "ua": "LG-D850" }
  38740. ],
  38741. "dpi": [ 537.9, 541.9 ],
  38742. "bw": 3,
  38743. "ac": 500
  38744. },
  38745. {
  38746. "type": "android",
  38747. "rules": [
  38748. { "mdmh": "LGE/*/VS985 4G/*" },
  38749. { "ua": "VS985 4G" }
  38750. ],
  38751. "dpi": [ 537.9, 535.6 ],
  38752. "bw": 3,
  38753. "ac": 1000
  38754. },
  38755. {
  38756. "type": "android",
  38757. "rules": [
  38758. { "mdmh": "LGE/*/Nexus 5/*" },
  38759. { "ua": "Nexus 5 " }
  38760. ],
  38761. "dpi": [ 442.4, 444.8 ],
  38762. "bw": 3,
  38763. "ac": 1000
  38764. },
  38765. {
  38766. "type": "android",
  38767. "rules": [
  38768. { "mdmh": "LGE/*/Nexus 4/*" },
  38769. { "ua": "Nexus 4" }
  38770. ],
  38771. "dpi": [ 319.8, 318.4 ],
  38772. "bw": 3,
  38773. "ac": 1000
  38774. },
  38775. {
  38776. "type": "android",
  38777. "rules": [
  38778. { "mdmh": "LGE/*/LG-P769/*" },
  38779. { "ua": "LG-P769" }
  38780. ],
  38781. "dpi": [ 240.6, 247.5 ],
  38782. "bw": 3,
  38783. "ac": 1000
  38784. },
  38785. {
  38786. "type": "android",
  38787. "rules": [
  38788. { "mdmh": "LGE/*/LGMS323/*" },
  38789. { "ua": "LGMS323" }
  38790. ],
  38791. "dpi": [ 206.6, 204.6 ],
  38792. "bw": 3,
  38793. "ac": 1000
  38794. },
  38795. {
  38796. "type": "android",
  38797. "rules": [
  38798. { "mdmh": "LGE/*/LGLS996/*" },
  38799. { "ua": "LGLS996" }
  38800. ],
  38801. "dpi": [ 403.4, 401.5 ],
  38802. "bw": 3,
  38803. "ac": 1000
  38804. },
  38805. {
  38806. "type": "android",
  38807. "rules": [
  38808. { "mdmh": "Micromax/*/4560MMX/*" },
  38809. { "ua": "4560MMX" }
  38810. ],
  38811. "dpi": [ 240.0, 219.4 ],
  38812. "bw": 3,
  38813. "ac": 1000
  38814. },
  38815. {
  38816. "type": "android",
  38817. "rules": [
  38818. { "mdmh": "Micromax/*/A250/*" },
  38819. { "ua": "Micromax A250" }
  38820. ],
  38821. "dpi": [ 480.0, 446.4 ],
  38822. "bw": 3,
  38823. "ac": 1000
  38824. },
  38825. {
  38826. "type": "android",
  38827. "rules": [
  38828. { "mdmh": "Micromax/*/Micromax AQ4501/*" },
  38829. { "ua": "Micromax AQ4501" }
  38830. ],
  38831. "dpi": 240.0,
  38832. "bw": 3,
  38833. "ac": 500
  38834. },
  38835. {
  38836. "type": "android",
  38837. "rules": [
  38838. { "mdmh": "motorola/*/DROID RAZR/*" },
  38839. { "ua": "DROID RAZR" }
  38840. ],
  38841. "dpi": [ 368.1, 256.7 ],
  38842. "bw": 3,
  38843. "ac": 1000
  38844. },
  38845. {
  38846. "type": "android",
  38847. "rules": [
  38848. { "mdmh": "motorola/*/XT830C/*" },
  38849. { "ua": "XT830C" }
  38850. ],
  38851. "dpi": [ 254.0, 255.9 ],
  38852. "bw": 3,
  38853. "ac": 1000
  38854. },
  38855. {
  38856. "type": "android",
  38857. "rules": [
  38858. { "mdmh": "motorola/*/XT1021/*" },
  38859. { "ua": "XT1021" }
  38860. ],
  38861. "dpi": [ 254.0, 256.7 ],
  38862. "bw": 3,
  38863. "ac": 500
  38864. },
  38865. {
  38866. "type": "android",
  38867. "rules": [
  38868. { "mdmh": "motorola/*/XT1023/*" },
  38869. { "ua": "XT1023" }
  38870. ],
  38871. "dpi": [ 254.0, 256.7 ],
  38872. "bw": 3,
  38873. "ac": 500
  38874. },
  38875. {
  38876. "type": "android",
  38877. "rules": [
  38878. { "mdmh": "motorola/*/XT1028/*" },
  38879. { "ua": "XT1028" }
  38880. ],
  38881. "dpi": [ 326.6, 327.6 ],
  38882. "bw": 3,
  38883. "ac": 1000
  38884. },
  38885. {
  38886. "type": "android",
  38887. "rules": [
  38888. { "mdmh": "motorola/*/XT1034/*" },
  38889. { "ua": "XT1034" }
  38890. ],
  38891. "dpi": [ 326.6, 328.4 ],
  38892. "bw": 3,
  38893. "ac": 500
  38894. },
  38895. {
  38896. "type": "android",
  38897. "rules": [
  38898. { "mdmh": "motorola/*/XT1053/*" },
  38899. { "ua": "XT1053" }
  38900. ],
  38901. "dpi": [ 315.3, 316.1 ],
  38902. "bw": 3,
  38903. "ac": 1000
  38904. },
  38905. {
  38906. "type": "android",
  38907. "rules": [
  38908. { "mdmh": "motorola/*/XT1562/*" },
  38909. { "ua": "XT1562" }
  38910. ],
  38911. "dpi": [ 403.4, 402.7 ],
  38912. "bw": 3,
  38913. "ac": 1000
  38914. },
  38915. {
  38916. "type": "android",
  38917. "rules": [
  38918. { "mdmh": "motorola/*/Nexus 6/*" },
  38919. { "ua": "Nexus 6 " }
  38920. ],
  38921. "dpi": [ 494.3, 489.7 ],
  38922. "bw": 3,
  38923. "ac": 1000
  38924. },
  38925. {
  38926. "type": "android",
  38927. "rules": [
  38928. { "mdmh": "motorola/*/XT1063/*" },
  38929. { "ua": "XT1063" }
  38930. ],
  38931. "dpi": [ 295.0, 296.6 ],
  38932. "bw": 3,
  38933. "ac": 1000
  38934. },
  38935. {
  38936. "type": "android",
  38937. "rules": [
  38938. { "mdmh": "motorola/*/XT1064/*" },
  38939. { "ua": "XT1064" }
  38940. ],
  38941. "dpi": [ 295.0, 295.6 ],
  38942. "bw": 3,
  38943. "ac": 500
  38944. },
  38945. {
  38946. "type": "android",
  38947. "rules": [
  38948. { "mdmh": "motorola/*/XT1092/*" },
  38949. { "ua": "XT1092" }
  38950. ],
  38951. "dpi": [ 422.0, 424.1 ],
  38952. "bw": 3,
  38953. "ac": 500
  38954. },
  38955. {
  38956. "type": "android",
  38957. "rules": [
  38958. { "mdmh": "motorola/*/XT1095/*" },
  38959. { "ua": "XT1095" }
  38960. ],
  38961. "dpi": [ 422.0, 423.4 ],
  38962. "bw": 3,
  38963. "ac": 1000
  38964. },
  38965. {
  38966. "type": "android",
  38967. "rules": [
  38968. { "mdmh": "motorola/*/G4/*" },
  38969. { "ua": "Moto G (4)" }
  38970. ],
  38971. "dpi": 401.0,
  38972. "bw": 4,
  38973. "ac": 1000
  38974. },
  38975. {
  38976. "type": "android",
  38977. "rules": [
  38978. { "mdmh": "OnePlus/*/A0001/*" },
  38979. { "ua": "A0001" }
  38980. ],
  38981. "dpi": [ 403.4, 401.0 ],
  38982. "bw": 3,
  38983. "ac": 1000
  38984. },
  38985. {
  38986. "type": "android",
  38987. "rules": [
  38988. { "mdmh": "OnePlus/*/ONE E1005/*" },
  38989. { "ua": "ONE E1005" }
  38990. ],
  38991. "dpi": [ 442.4, 441.4 ],
  38992. "bw": 3,
  38993. "ac": 1000
  38994. },
  38995. {
  38996. "type": "android",
  38997. "rules": [
  38998. { "mdmh": "OnePlus/*/ONE A2005/*" },
  38999. { "ua": "ONE A2005" }
  39000. ],
  39001. "dpi": [ 391.9, 405.4 ],
  39002. "bw": 3,
  39003. "ac": 1000
  39004. },
  39005. {
  39006. "type": "android",
  39007. "rules": [
  39008. { "mdmh": "OPPO/*/X909/*" },
  39009. { "ua": "X909" }
  39010. ],
  39011. "dpi": [ 442.4, 444.1 ],
  39012. "bw": 3,
  39013. "ac": 1000
  39014. },
  39015. {
  39016. "type": "android",
  39017. "rules": [
  39018. { "mdmh": "samsung/*/GT-I9082/*" },
  39019. { "ua": "GT-I9082" }
  39020. ],
  39021. "dpi": [ 184.7, 185.4 ],
  39022. "bw": 3,
  39023. "ac": 1000
  39024. },
  39025. {
  39026. "type": "android",
  39027. "rules": [
  39028. { "mdmh": "samsung/*/SM-G360P/*" },
  39029. { "ua": "SM-G360P" }
  39030. ],
  39031. "dpi": [ 196.7, 205.4 ],
  39032. "bw": 3,
  39033. "ac": 1000
  39034. },
  39035. {
  39036. "type": "android",
  39037. "rules": [
  39038. { "mdmh": "samsung/*/Nexus S/*" },
  39039. { "ua": "Nexus S" }
  39040. ],
  39041. "dpi": [ 234.5, 229.8 ],
  39042. "bw": 3,
  39043. "ac": 1000
  39044. },
  39045. {
  39046. "type": "android",
  39047. "rules": [
  39048. { "mdmh": "samsung/*/GT-I9300/*" },
  39049. { "ua": "GT-I9300" }
  39050. ],
  39051. "dpi": [ 304.8, 303.9 ],
  39052. "bw": 5,
  39053. "ac": 500
  39054. },
  39055. {
  39056. "type": "android",
  39057. "rules": [
  39058. { "mdmh": "samsung/*/SM-T230NU/*" },
  39059. { "ua": "SM-T230NU" }
  39060. ],
  39061. "dpi": 216.0,
  39062. "bw": 3,
  39063. "ac": 500
  39064. },
  39065. {
  39066. "type": "android",
  39067. "rules": [
  39068. { "mdmh": "samsung/*/SGH-T399/*" },
  39069. { "ua": "SGH-T399" }
  39070. ],
  39071. "dpi": [ 217.7, 231.4 ],
  39072. "bw": 3,
  39073. "ac": 1000
  39074. },
  39075. {
  39076. "type": "android",
  39077. "rules": [
  39078. { "mdmh": "samsung/*/SM-N9005/*" },
  39079. { "ua": "SM-N9005" }
  39080. ],
  39081. "dpi": [ 386.4, 387.0 ],
  39082. "bw": 3,
  39083. "ac": 500
  39084. },
  39085. {
  39086. "type": "android",
  39087. "rules": [
  39088. { "mdmh": "samsung/*/SAMSUNG-SM-N900A/*" },
  39089. { "ua": "SAMSUNG-SM-N900A" }
  39090. ],
  39091. "dpi": [ 386.4, 387.7 ],
  39092. "bw": 3,
  39093. "ac": 1000
  39094. },
  39095. {
  39096. "type": "android",
  39097. "rules": [
  39098. { "mdmh": "samsung/*/GT-I9500/*" },
  39099. { "ua": "GT-I9500" }
  39100. ],
  39101. "dpi": [ 442.5, 443.3 ],
  39102. "bw": 3,
  39103. "ac": 500
  39104. },
  39105. {
  39106. "type": "android",
  39107. "rules": [
  39108. { "mdmh": "samsung/*/GT-I9505/*" },
  39109. { "ua": "GT-I9505" }
  39110. ],
  39111. "dpi": 439.4,
  39112. "bw": 4,
  39113. "ac": 1000
  39114. },
  39115. {
  39116. "type": "android",
  39117. "rules": [
  39118. { "mdmh": "samsung/*/SM-G900F/*" },
  39119. { "ua": "SM-G900F" }
  39120. ],
  39121. "dpi": [ 415.6, 431.6 ],
  39122. "bw": 5,
  39123. "ac": 1000
  39124. },
  39125. {
  39126. "type": "android",
  39127. "rules": [
  39128. { "mdmh": "samsung/*/SM-G900M/*" },
  39129. { "ua": "SM-G900M" }
  39130. ],
  39131. "dpi": [ 415.6, 431.6 ],
  39132. "bw": 5,
  39133. "ac": 1000
  39134. },
  39135. {
  39136. "type": "android",
  39137. "rules": [
  39138. { "mdmh": "samsung/*/SM-G800F/*" },
  39139. { "ua": "SM-G800F" }
  39140. ],
  39141. "dpi": 326.8,
  39142. "bw": 3,
  39143. "ac": 1000
  39144. },
  39145. {
  39146. "type": "android",
  39147. "rules": [
  39148. { "mdmh": "samsung/*/SM-G906S/*" },
  39149. { "ua": "SM-G906S" }
  39150. ],
  39151. "dpi": [ 562.7, 572.4 ],
  39152. "bw": 3,
  39153. "ac": 1000
  39154. },
  39155. {
  39156. "type": "android",
  39157. "rules": [
  39158. { "mdmh": "samsung/*/GT-I9300/*" },
  39159. { "ua": "GT-I9300" }
  39160. ],
  39161. "dpi": [ 306.7, 304.8 ],
  39162. "bw": 5,
  39163. "ac": 1000
  39164. },
  39165. {
  39166. "type": "android",
  39167. "rules": [
  39168. { "mdmh": "samsung/*/SM-T535/*" },
  39169. { "ua": "SM-T535" }
  39170. ],
  39171. "dpi": [ 142.6, 136.4 ],
  39172. "bw": 3,
  39173. "ac": 500
  39174. },
  39175. {
  39176. "type": "android",
  39177. "rules": [
  39178. { "mdmh": "samsung/*/SM-N920C/*" },
  39179. { "ua": "SM-N920C" }
  39180. ],
  39181. "dpi": [ 515.1, 518.4 ],
  39182. "bw": 3,
  39183. "ac": 1000
  39184. },
  39185. {
  39186. "type": "android",
  39187. "rules": [
  39188. { "mdmh": "samsung/*/GT-I9300I/*" },
  39189. { "ua": "GT-I9300I" }
  39190. ],
  39191. "dpi": [ 304.8, 305.8 ],
  39192. "bw": 3,
  39193. "ac": 1000
  39194. },
  39195. {
  39196. "type": "android",
  39197. "rules": [
  39198. { "mdmh": "samsung/*/GT-I9195/*" },
  39199. { "ua": "GT-I9195" }
  39200. ],
  39201. "dpi": [ 249.4, 256.7 ],
  39202. "bw": 3,
  39203. "ac": 500
  39204. },
  39205. {
  39206. "type": "android",
  39207. "rules": [
  39208. { "mdmh": "samsung/*/SPH-L520/*" },
  39209. { "ua": "SPH-L520" }
  39210. ],
  39211. "dpi": [ 249.4, 255.9 ],
  39212. "bw": 3,
  39213. "ac": 1000
  39214. },
  39215. {
  39216. "type": "android",
  39217. "rules": [
  39218. { "mdmh": "samsung/*/SAMSUNG-SGH-I717/*" },
  39219. { "ua": "SAMSUNG-SGH-I717" }
  39220. ],
  39221. "dpi": 285.8,
  39222. "bw": 3,
  39223. "ac": 1000
  39224. },
  39225. {
  39226. "type": "android",
  39227. "rules": [
  39228. { "mdmh": "samsung/*/SPH-D710/*" },
  39229. { "ua": "SPH-D710" }
  39230. ],
  39231. "dpi": [ 217.7, 204.2 ],
  39232. "bw": 3,
  39233. "ac": 1000
  39234. },
  39235. {
  39236. "type": "android",
  39237. "rules": [
  39238. { "mdmh": "samsung/*/GT-N7100/*" },
  39239. { "ua": "GT-N7100" }
  39240. ],
  39241. "dpi": 265.1,
  39242. "bw": 3,
  39243. "ac": 1000
  39244. },
  39245. {
  39246. "type": "android",
  39247. "rules": [
  39248. { "mdmh": "samsung/*/SCH-I605/*" },
  39249. { "ua": "SCH-I605" }
  39250. ],
  39251. "dpi": 265.1,
  39252. "bw": 3,
  39253. "ac": 1000
  39254. },
  39255. {
  39256. "type": "android",
  39257. "rules": [
  39258. { "mdmh": "samsung/*/Galaxy Nexus/*" },
  39259. { "ua": "Galaxy Nexus" }
  39260. ],
  39261. "dpi": [ 315.3, 314.2 ],
  39262. "bw": 3,
  39263. "ac": 1000
  39264. },
  39265. {
  39266. "type": "android",
  39267. "rules": [
  39268. { "mdmh": "samsung/*/SM-N910H/*" },
  39269. { "ua": "SM-N910H" }
  39270. ],
  39271. "dpi": [ 515.1, 518.0 ],
  39272. "bw": 3,
  39273. "ac": 1000
  39274. },
  39275. {
  39276. "type": "android",
  39277. "rules": [
  39278. { "mdmh": "samsung/*/SM-N910C/*" },
  39279. { "ua": "SM-N910C" }
  39280. ],
  39281. "dpi": [ 515.2, 520.2 ],
  39282. "bw": 3,
  39283. "ac": 500
  39284. },
  39285. {
  39286. "type": "android",
  39287. "rules": [
  39288. { "mdmh": "samsung/*/SM-G130M/*" },
  39289. { "ua": "SM-G130M" }
  39290. ],
  39291. "dpi": [ 165.9, 164.8 ],
  39292. "bw": 3,
  39293. "ac": 500
  39294. },
  39295. {
  39296. "type": "android",
  39297. "rules": [
  39298. { "mdmh": "samsung/*/SM-G928I/*" },
  39299. { "ua": "SM-G928I" }
  39300. ],
  39301. "dpi": [ 515.1, 518.4 ],
  39302. "bw": 3,
  39303. "ac": 1000
  39304. },
  39305. {
  39306. "type": "android",
  39307. "rules": [
  39308. { "mdmh": "samsung/*/SM-G920F/*" },
  39309. { "ua": "SM-G920F" }
  39310. ],
  39311. "dpi": 580.6,
  39312. "bw": 3,
  39313. "ac": 500
  39314. },
  39315. {
  39316. "type": "android",
  39317. "rules": [
  39318. { "mdmh": "samsung/*/SM-G920P/*" },
  39319. { "ua": "SM-G920P" }
  39320. ],
  39321. "dpi": [ 522.5, 577.0 ],
  39322. "bw": 3,
  39323. "ac": 1000
  39324. },
  39325. {
  39326. "type": "android",
  39327. "rules": [
  39328. { "mdmh": "samsung/*/SM-G925F/*" },
  39329. { "ua": "SM-G925F" }
  39330. ],
  39331. "dpi": 580.6,
  39332. "bw": 3,
  39333. "ac": 500
  39334. },
  39335. {
  39336. "type": "android",
  39337. "rules": [
  39338. { "mdmh": "samsung/*/SM-G925V/*" },
  39339. { "ua": "SM-G925V" }
  39340. ],
  39341. "dpi": [ 522.5, 576.6 ],
  39342. "bw": 3,
  39343. "ac": 1000
  39344. },
  39345. {
  39346. "type": "android",
  39347. "rules": [
  39348. { "mdmh": "samsung/*/SM-G935F/*" },
  39349. { "ua": "SM-G935F" }
  39350. ],
  39351. "dpi": 534,
  39352. "bw": 3,
  39353. "ac": 500
  39354. },
  39355. {
  39356. "type": "android",
  39357. "rules": [
  39358. { "mdmh": "Sony/*/C6903/*" },
  39359. { "ua": "C6903" }
  39360. ],
  39361. "dpi": [ 442.5, 443.3 ],
  39362. "bw": 3,
  39363. "ac": 500
  39364. },
  39365. {
  39366. "type": "android",
  39367. "rules": [
  39368. { "mdmh": "Sony/*/D6653/*" },
  39369. { "ua": "D6653" }
  39370. ],
  39371. "dpi": [ 428.6, 427.6 ],
  39372. "bw": 3,
  39373. "ac": 1000
  39374. },
  39375. {
  39376. "type": "android",
  39377. "rules": [
  39378. { "mdmh": "Sony/*/E6653/*" },
  39379. { "ua": "E6653" }
  39380. ],
  39381. "dpi": [ 428.6, 425.7 ],
  39382. "bw": 3,
  39383. "ac": 1000
  39384. },
  39385. {
  39386. "type": "android",
  39387. "rules": [
  39388. { "mdmh": "Sony/*/E6853/*" },
  39389. { "ua": "E6853" }
  39390. ],
  39391. "dpi": [ 403.4, 401.9 ],
  39392. "bw": 3,
  39393. "ac": 1000
  39394. },
  39395. {
  39396. "type": "android",
  39397. "rules": [
  39398. { "mdmh": "Sony/*/SGP321/*" },
  39399. { "ua": "SGP321" }
  39400. ],
  39401. "dpi": [ 224.7, 224.1 ],
  39402. "bw": 3,
  39403. "ac": 500
  39404. },
  39405. {
  39406. "type": "android",
  39407. "rules": [
  39408. { "mdmh": "TCT/*/ALCATEL ONE TOUCH Fierce/*" },
  39409. { "ua": "ALCATEL ONE TOUCH Fierce" }
  39410. ],
  39411. "dpi": [ 240.0, 247.5 ],
  39412. "bw": 3,
  39413. "ac": 1000
  39414. },
  39415. {
  39416. "type": "android",
  39417. "rules": [
  39418. { "mdmh": "THL/*/thl 5000/*" },
  39419. { "ua": "thl 5000" }
  39420. ],
  39421. "dpi": [ 480.0, 443.3 ],
  39422. "bw": 3,
  39423. "ac": 1000
  39424. },
  39425. {
  39426. "type": "android",
  39427. "rules": [
  39428. { "mdmh": "ZTE/*/ZTE Blade L2/*" },
  39429. { "ua": "ZTE Blade L2" }
  39430. ],
  39431. "dpi": 240.0,
  39432. "bw": 3,
  39433. "ac": 500
  39434. },
  39435. {
  39436. "type": "ios",
  39437. "rules": [ { "res": [ 640, 960 ] } ],
  39438. "dpi": [ 325.1, 328.4 ],
  39439. "bw": 4,
  39440. "ac": 1000
  39441. },
  39442. {
  39443. "type": "ios",
  39444. "rules": [ { "res": [ 640, 1136 ] } ],
  39445. "dpi": [ 317.1, 320.2 ],
  39446. "bw": 3,
  39447. "ac": 1000
  39448. },
  39449. {
  39450. "type": "ios",
  39451. "rules": [ { "res": [ 750, 1334 ] } ],
  39452. "dpi": 326.4,
  39453. "bw": 4,
  39454. "ac": 1000
  39455. },
  39456. {
  39457. "type": "ios",
  39458. "rules": [ { "res": [ 1242, 2208 ] } ],
  39459. "dpi": [ 453.6, 458.4 ],
  39460. "bw": 4,
  39461. "ac": 1000
  39462. },
  39463. {
  39464. "type": "ios",
  39465. "rules": [ { "res": [ 1125, 2001 ] } ],
  39466. "dpi": [ 410.9, 415.4 ],
  39467. "bw": 4,
  39468. "ac": 1000
  39469. }
  39470. ]};
  39471. module.exports = DPDB_CACHE;
  39472. },{}],12:[function(_dereq_,module,exports){
  39473. module.exports={
  39474. "format":1,
  39475. "last_updated":"2017-01-12T08:41:55Z",
  39476. "devices":[
  39477. {
  39478. "type":"android",
  39479. "rules":[
  39480. {
  39481. "mdmh":"asus/*/Nexus 7/*"
  39482. },
  39483. {
  39484. "ua":"Nexus 7"
  39485. }
  39486. ],
  39487. "dpi":[
  39488. 320.8,
  39489. 323
  39490. ],
  39491. "bw":3,
  39492. "ac":500
  39493. },
  39494. {
  39495. "type":"android",
  39496. "rules":[
  39497. {
  39498. "mdmh":"asus/*/ASUS_Z00AD/*"
  39499. },
  39500. {
  39501. "ua":"ASUS_Z00AD"
  39502. }
  39503. ],
  39504. "dpi":[
  39505. 403,
  39506. 404.6
  39507. ],
  39508. "bw":3,
  39509. "ac":1000
  39510. },
  39511. {
  39512. "type": "android",
  39513. "rules": [
  39514. {
  39515. "mdmh": "Google//Pixel XL/"
  39516. },
  39517. {
  39518. "ua": "Pixel XL"
  39519. }
  39520. ],
  39521. "dpi": [
  39522. 537.9,
  39523. 533
  39524. ],
  39525. "bw": 3,
  39526. "ac": 1000
  39527. },
  39528. {
  39529. "type":"android",
  39530. "rules":[
  39531. {
  39532. "mdmh":"HTC/*/HTC6435LVW/*"
  39533. },
  39534. {
  39535. "ua":"HTC6435LVW"
  39536. }
  39537. ],
  39538. "dpi":[
  39539. 449.7,
  39540. 443.3
  39541. ],
  39542. "bw":3,
  39543. "ac":1000
  39544. },
  39545. {
  39546. "type":"android",
  39547. "rules":[
  39548. {
  39549. "mdmh":"HTC/*/HTC One XL/*"
  39550. },
  39551. {
  39552. "ua":"HTC One XL"
  39553. }
  39554. ],
  39555. "dpi":[
  39556. 315.3,
  39557. 314.6
  39558. ],
  39559. "bw":3,
  39560. "ac":1000
  39561. },
  39562. {
  39563. "type":"android",
  39564. "rules":[
  39565. {
  39566. "mdmh":"htc/*/Nexus 9/*"
  39567. },
  39568. {
  39569. "ua":"Nexus 9"
  39570. }
  39571. ],
  39572. "dpi":289,
  39573. "bw":3,
  39574. "ac":500
  39575. },
  39576. {
  39577. "type":"android",
  39578. "rules":[
  39579. {
  39580. "mdmh":"HTC/*/HTC One M9/*"
  39581. },
  39582. {
  39583. "ua":"HTC One M9"
  39584. }
  39585. ],
  39586. "dpi":[
  39587. 442.5,
  39588. 443.3
  39589. ],
  39590. "bw":3,
  39591. "ac":500
  39592. },
  39593. {
  39594. "type":"android",
  39595. "rules":[
  39596. {
  39597. "mdmh":"HTC/*/HTC One_M8/*"
  39598. },
  39599. {
  39600. "ua":"HTC One_M8"
  39601. }
  39602. ],
  39603. "dpi":[
  39604. 449.7,
  39605. 447.4
  39606. ],
  39607. "bw":3,
  39608. "ac":500
  39609. },
  39610. {
  39611. "type":"android",
  39612. "rules":[
  39613. {
  39614. "mdmh":"HTC/*/HTC One/*"
  39615. },
  39616. {
  39617. "ua":"HTC One"
  39618. }
  39619. ],
  39620. "dpi":472.8,
  39621. "bw":3,
  39622. "ac":1000
  39623. },
  39624. {
  39625. "type":"android",
  39626. "rules":[
  39627. {
  39628. "mdmh":"Huawei/*/Nexus 6P/*"
  39629. },
  39630. {
  39631. "ua":"Nexus 6P"
  39632. }
  39633. ],
  39634. "dpi":[
  39635. 515.1,
  39636. 518
  39637. ],
  39638. "bw":3,
  39639. "ac":1000
  39640. },
  39641. {
  39642. "type":"android",
  39643. "rules":[
  39644. {
  39645. "mdmh":"LGE/*/Nexus 5X/*"
  39646. },
  39647. {
  39648. "ua":"Nexus 5X"
  39649. }
  39650. ],
  39651. "dpi":[
  39652. 422,
  39653. 419.9
  39654. ],
  39655. "bw":3,
  39656. "ac":1000
  39657. },
  39658. {
  39659. "type":"android",
  39660. "rules":[
  39661. {
  39662. "mdmh":"LGE/*/LGMS345/*"
  39663. },
  39664. {
  39665. "ua":"LGMS345"
  39666. }
  39667. ],
  39668. "dpi":[
  39669. 221.7,
  39670. 219.1
  39671. ],
  39672. "bw":3,
  39673. "ac":500
  39674. },
  39675. {
  39676. "type":"android",
  39677. "rules":[
  39678. {
  39679. "mdmh":"LGE/*/LG-D800/*"
  39680. },
  39681. {
  39682. "ua":"LG-D800"
  39683. }
  39684. ],
  39685. "dpi":[
  39686. 422,
  39687. 424.1
  39688. ],
  39689. "bw":3,
  39690. "ac":500
  39691. },
  39692. {
  39693. "type":"android",
  39694. "rules":[
  39695. {
  39696. "mdmh":"LGE/*/LG-D850/*"
  39697. },
  39698. {
  39699. "ua":"LG-D850"
  39700. }
  39701. ],
  39702. "dpi":[
  39703. 537.9,
  39704. 541.9
  39705. ],
  39706. "bw":3,
  39707. "ac":500
  39708. },
  39709. {
  39710. "type":"android",
  39711. "rules":[
  39712. {
  39713. "mdmh":"LGE/*/VS985 4G/*"
  39714. },
  39715. {
  39716. "ua":"VS985 4G"
  39717. }
  39718. ],
  39719. "dpi":[
  39720. 537.9,
  39721. 535.6
  39722. ],
  39723. "bw":3,
  39724. "ac":1000
  39725. },
  39726. {
  39727. "type":"android",
  39728. "rules":[
  39729. {
  39730. "mdmh":"LGE/*/Nexus 5/*"
  39731. },
  39732. {
  39733. "ua":"Nexus 5 B"
  39734. }
  39735. ],
  39736. "dpi":[
  39737. 442.4,
  39738. 444.8
  39739. ],
  39740. "bw":3,
  39741. "ac":1000
  39742. },
  39743. {
  39744. "type":"android",
  39745. "rules":[
  39746. {
  39747. "mdmh":"LGE/*/Nexus 4/*"
  39748. },
  39749. {
  39750. "ua":"Nexus 4"
  39751. }
  39752. ],
  39753. "dpi":[
  39754. 319.8,
  39755. 318.4
  39756. ],
  39757. "bw":3,
  39758. "ac":1000
  39759. },
  39760. {
  39761. "type":"android",
  39762. "rules":[
  39763. {
  39764. "mdmh":"LGE/*/LG-P769/*"
  39765. },
  39766. {
  39767. "ua":"LG-P769"
  39768. }
  39769. ],
  39770. "dpi":[
  39771. 240.6,
  39772. 247.5
  39773. ],
  39774. "bw":3,
  39775. "ac":1000
  39776. },
  39777. {
  39778. "type":"android",
  39779. "rules":[
  39780. {
  39781. "mdmh":"LGE/*/LGMS323/*"
  39782. },
  39783. {
  39784. "ua":"LGMS323"
  39785. }
  39786. ],
  39787. "dpi":[
  39788. 206.6,
  39789. 204.6
  39790. ],
  39791. "bw":3,
  39792. "ac":1000
  39793. },
  39794. {
  39795. "type":"android",
  39796. "rules":[
  39797. {
  39798. "mdmh":"LGE/*/LGLS996/*"
  39799. },
  39800. {
  39801. "ua":"LGLS996"
  39802. }
  39803. ],
  39804. "dpi":[
  39805. 403.4,
  39806. 401.5
  39807. ],
  39808. "bw":3,
  39809. "ac":1000
  39810. },
  39811. {
  39812. "type":"android",
  39813. "rules":[
  39814. {
  39815. "mdmh":"Micromax/*/4560MMX/*"
  39816. },
  39817. {
  39818. "ua":"4560MMX"
  39819. }
  39820. ],
  39821. "dpi":[
  39822. 240,
  39823. 219.4
  39824. ],
  39825. "bw":3,
  39826. "ac":1000
  39827. },
  39828. {
  39829. "type":"android",
  39830. "rules":[
  39831. {
  39832. "mdmh":"Micromax/*/A250/*"
  39833. },
  39834. {
  39835. "ua":"Micromax A250"
  39836. }
  39837. ],
  39838. "dpi":[
  39839. 480,
  39840. 446.4
  39841. ],
  39842. "bw":3,
  39843. "ac":1000
  39844. },
  39845. {
  39846. "type":"android",
  39847. "rules":[
  39848. {
  39849. "mdmh":"Micromax/*/Micromax AQ4501/*"
  39850. },
  39851. {
  39852. "ua":"Micromax AQ4501"
  39853. }
  39854. ],
  39855. "dpi":240,
  39856. "bw":3,
  39857. "ac":500
  39858. },
  39859. {
  39860. "type":"android",
  39861. "rules":[
  39862. {
  39863. "mdmh":"motorola/*/DROID RAZR/*"
  39864. },
  39865. {
  39866. "ua":"DROID RAZR"
  39867. }
  39868. ],
  39869. "dpi":[
  39870. 368.1,
  39871. 256.7
  39872. ],
  39873. "bw":3,
  39874. "ac":1000
  39875. },
  39876. {
  39877. "type":"android",
  39878. "rules":[
  39879. {
  39880. "mdmh":"motorola/*/XT830C/*"
  39881. },
  39882. {
  39883. "ua":"XT830C"
  39884. }
  39885. ],
  39886. "dpi":[
  39887. 254,
  39888. 255.9
  39889. ],
  39890. "bw":3,
  39891. "ac":1000
  39892. },
  39893. {
  39894. "type":"android",
  39895. "rules":[
  39896. {
  39897. "mdmh":"motorola/*/XT1021/*"
  39898. },
  39899. {
  39900. "ua":"XT1021"
  39901. }
  39902. ],
  39903. "dpi":[
  39904. 254,
  39905. 256.7
  39906. ],
  39907. "bw":3,
  39908. "ac":500
  39909. },
  39910. {
  39911. "type":"android",
  39912. "rules":[
  39913. {
  39914. "mdmh":"motorola/*/XT1023/*"
  39915. },
  39916. {
  39917. "ua":"XT1023"
  39918. }
  39919. ],
  39920. "dpi":[
  39921. 254,
  39922. 256.7
  39923. ],
  39924. "bw":3,
  39925. "ac":500
  39926. },
  39927. {
  39928. "type":"android",
  39929. "rules":[
  39930. {
  39931. "mdmh":"motorola/*/XT1028/*"
  39932. },
  39933. {
  39934. "ua":"XT1028"
  39935. }
  39936. ],
  39937. "dpi":[
  39938. 326.6,
  39939. 327.6
  39940. ],
  39941. "bw":3,
  39942. "ac":1000
  39943. },
  39944. {
  39945. "type":"android",
  39946. "rules":[
  39947. {
  39948. "mdmh":"motorola/*/XT1034/*"
  39949. },
  39950. {
  39951. "ua":"XT1034"
  39952. }
  39953. ],
  39954. "dpi":[
  39955. 326.6,
  39956. 328.4
  39957. ],
  39958. "bw":3,
  39959. "ac":500
  39960. },
  39961. {
  39962. "type":"android",
  39963. "rules":[
  39964. {
  39965. "mdmh":"motorola/*/XT1053/*"
  39966. },
  39967. {
  39968. "ua":"XT1053"
  39969. }
  39970. ],
  39971. "dpi":[
  39972. 315.3,
  39973. 316.1
  39974. ],
  39975. "bw":3,
  39976. "ac":1000
  39977. },
  39978. {
  39979. "type":"android",
  39980. "rules":[
  39981. {
  39982. "mdmh":"motorola/*/XT1562/*"
  39983. },
  39984. {
  39985. "ua":"XT1562"
  39986. }
  39987. ],
  39988. "dpi":[
  39989. 403.4,
  39990. 402.7
  39991. ],
  39992. "bw":3,
  39993. "ac":1000
  39994. },
  39995. {
  39996. "type":"android",
  39997. "rules":[
  39998. {
  39999. "mdmh":"motorola/*/Nexus 6/*"
  40000. },
  40001. {
  40002. "ua":"Nexus 6 B"
  40003. }
  40004. ],
  40005. "dpi":[
  40006. 494.3,
  40007. 489.7
  40008. ],
  40009. "bw":3,
  40010. "ac":1000
  40011. },
  40012. {
  40013. "type":"android",
  40014. "rules":[
  40015. {
  40016. "mdmh":"motorola/*/XT1063/*"
  40017. },
  40018. {
  40019. "ua":"XT1063"
  40020. }
  40021. ],
  40022. "dpi":[
  40023. 295,
  40024. 296.6
  40025. ],
  40026. "bw":3,
  40027. "ac":1000
  40028. },
  40029. {
  40030. "type":"android",
  40031. "rules":[
  40032. {
  40033. "mdmh":"motorola/*/XT1064/*"
  40034. },
  40035. {
  40036. "ua":"XT1064"
  40037. }
  40038. ],
  40039. "dpi":[
  40040. 295,
  40041. 295.6
  40042. ],
  40043. "bw":3,
  40044. "ac":500
  40045. },
  40046. {
  40047. "type":"android",
  40048. "rules":[
  40049. {
  40050. "mdmh":"motorola/*/XT1092/*"
  40051. },
  40052. {
  40053. "ua":"XT1092"
  40054. }
  40055. ],
  40056. "dpi":[
  40057. 422,
  40058. 424.1
  40059. ],
  40060. "bw":3,
  40061. "ac":500
  40062. },
  40063. {
  40064. "type":"android",
  40065. "rules":[
  40066. {
  40067. "mdmh":"motorola/*/XT1095/*"
  40068. },
  40069. {
  40070. "ua":"XT1095"
  40071. }
  40072. ],
  40073. "dpi":[
  40074. 422,
  40075. 423.4
  40076. ],
  40077. "bw":3,
  40078. "ac":1000
  40079. },
  40080. {
  40081. "type": "android",
  40082. "rules": [
  40083. {
  40084. "mdmh": "motorola/*/G4/*"
  40085. },
  40086. {
  40087. "ua": "Moto G (4)"
  40088. }
  40089. ],
  40090. "dpi": 401.0,
  40091. "bw": 4,
  40092. "ac": 1000
  40093. },
  40094. {
  40095. "type":"android",
  40096. "rules":[
  40097. {
  40098. "mdmh":"OnePlus/*/A0001/*"
  40099. },
  40100. {
  40101. "ua":"A0001"
  40102. }
  40103. ],
  40104. "dpi":[
  40105. 403.4,
  40106. 401
  40107. ],
  40108. "bw":3,
  40109. "ac":1000
  40110. },
  40111. {
  40112. "type":"android",
  40113. "rules":[
  40114. {
  40115. "mdmh":"OnePlus/*/ONE E1005/*"
  40116. },
  40117. {
  40118. "ua":"ONE E1005"
  40119. }
  40120. ],
  40121. "dpi":[
  40122. 442.4,
  40123. 441.4
  40124. ],
  40125. "bw":3,
  40126. "ac":1000
  40127. },
  40128. {
  40129. "type":"android",
  40130. "rules":[
  40131. {
  40132. "mdmh":"OnePlus/*/ONE A2005/*"
  40133. },
  40134. {
  40135. "ua":"ONE A2005"
  40136. }
  40137. ],
  40138. "dpi":[
  40139. 391.9,
  40140. 405.4
  40141. ],
  40142. "bw":3,
  40143. "ac":1000
  40144. },
  40145. {
  40146. "type":"android",
  40147. "rules":[
  40148. {
  40149. "mdmh":"OPPO/*/X909/*"
  40150. },
  40151. {
  40152. "ua":"X909"
  40153. }
  40154. ],
  40155. "dpi":[
  40156. 442.4,
  40157. 444.1
  40158. ],
  40159. "bw":3,
  40160. "ac":1000
  40161. },
  40162. {
  40163. "type":"android",
  40164. "rules":[
  40165. {
  40166. "mdmh":"samsung/*/GT-I9082/*"
  40167. },
  40168. {
  40169. "ua":"GT-I9082"
  40170. }
  40171. ],
  40172. "dpi":[
  40173. 184.7,
  40174. 185.4
  40175. ],
  40176. "bw":3,
  40177. "ac":1000
  40178. },
  40179. {
  40180. "type":"android",
  40181. "rules":[
  40182. {
  40183. "mdmh":"samsung/*/SM-G360P/*"
  40184. },
  40185. {
  40186. "ua":"SM-G360P"
  40187. }
  40188. ],
  40189. "dpi":[
  40190. 196.7,
  40191. 205.4
  40192. ],
  40193. "bw":3,
  40194. "ac":1000
  40195. },
  40196. {
  40197. "type":"android",
  40198. "rules":[
  40199. {
  40200. "mdmh":"samsung/*/Nexus S/*"
  40201. },
  40202. {
  40203. "ua":"Nexus S"
  40204. }
  40205. ],
  40206. "dpi":[
  40207. 234.5,
  40208. 229.8
  40209. ],
  40210. "bw":3,
  40211. "ac":1000
  40212. },
  40213. {
  40214. "type":"android",
  40215. "rules":[
  40216. {
  40217. "mdmh":"samsung/*/GT-I9300/*"
  40218. },
  40219. {
  40220. "ua":"GT-I9300"
  40221. }
  40222. ],
  40223. "dpi":[
  40224. 304.8,
  40225. 303.9
  40226. ],
  40227. "bw":5,
  40228. "ac":500
  40229. },
  40230. {
  40231. "type":"android",
  40232. "rules":[
  40233. {
  40234. "mdmh":"samsung/*/SM-T230NU/*"
  40235. },
  40236. {
  40237. "ua":"SM-T230NU"
  40238. }
  40239. ],
  40240. "dpi":216,
  40241. "bw":3,
  40242. "ac":500
  40243. },
  40244. {
  40245. "type":"android",
  40246. "rules":[
  40247. {
  40248. "mdmh":"samsung/*/SGH-T399/*"
  40249. },
  40250. {
  40251. "ua":"SGH-T399"
  40252. }
  40253. ],
  40254. "dpi":[
  40255. 217.7,
  40256. 231.4
  40257. ],
  40258. "bw":3,
  40259. "ac":1000
  40260. },
  40261. {
  40262. "type":"android",
  40263. "rules":[
  40264. {
  40265. "mdmh":"samsung/*/SM-N9005/*"
  40266. },
  40267. {
  40268. "ua":"SM-N9005"
  40269. }
  40270. ],
  40271. "dpi":[
  40272. 386.4,
  40273. 387
  40274. ],
  40275. "bw":3,
  40276. "ac":500
  40277. },
  40278. {
  40279. "type":"android",
  40280. "rules":[
  40281. {
  40282. "mdmh":"samsung/*/SAMSUNG-SM-N900A/*"
  40283. },
  40284. {
  40285. "ua":"SAMSUNG-SM-N900A"
  40286. }
  40287. ],
  40288. "dpi":[
  40289. 386.4,
  40290. 387.7
  40291. ],
  40292. "bw":3,
  40293. "ac":1000
  40294. },
  40295. {
  40296. "type":"android",
  40297. "rules":[
  40298. {
  40299. "mdmh":"samsung/*/GT-I9500/*"
  40300. },
  40301. {
  40302. "ua":"GT-I9500"
  40303. }
  40304. ],
  40305. "dpi":[
  40306. 442.5,
  40307. 443.3
  40308. ],
  40309. "bw":3,
  40310. "ac":500
  40311. },
  40312. {
  40313. "type":"android",
  40314. "rules":[
  40315. {
  40316. "mdmh":"samsung/*/GT-I9505/*"
  40317. },
  40318. {
  40319. "ua":"GT-I9505"
  40320. }
  40321. ],
  40322. "dpi":439.4,
  40323. "bw":4,
  40324. "ac":1000
  40325. },
  40326. {
  40327. "type":"android",
  40328. "rules":[
  40329. {
  40330. "mdmh":"samsung/*/SM-G900F/*"
  40331. },
  40332. {
  40333. "ua":"SM-G900F"
  40334. }
  40335. ],
  40336. "dpi":[
  40337. 415.6,
  40338. 431.6
  40339. ],
  40340. "bw":5,
  40341. "ac":1000
  40342. },
  40343. {
  40344. "type":"android",
  40345. "rules":[
  40346. {
  40347. "mdmh":"samsung/*/SM-G900M/*"
  40348. },
  40349. {
  40350. "ua":"SM-G900M"
  40351. }
  40352. ],
  40353. "dpi":[
  40354. 415.6,
  40355. 431.6
  40356. ],
  40357. "bw":5,
  40358. "ac":1000
  40359. },
  40360. {
  40361. "type":"android",
  40362. "rules":[
  40363. {
  40364. "mdmh":"samsung/*/SM-G800F/*"
  40365. },
  40366. {
  40367. "ua":"SM-G800F"
  40368. }
  40369. ],
  40370. "dpi":326.8,
  40371. "bw":3,
  40372. "ac":1000
  40373. },
  40374. {
  40375. "type":"android",
  40376. "rules":[
  40377. {
  40378. "mdmh":"samsung/*/SM-G906S/*"
  40379. },
  40380. {
  40381. "ua":"SM-G906S"
  40382. }
  40383. ],
  40384. "dpi":[
  40385. 562.7,
  40386. 572.4
  40387. ],
  40388. "bw":3,
  40389. "ac":1000
  40390. },
  40391. {
  40392. "type":"android",
  40393. "rules":[
  40394. {
  40395. "mdmh":"samsung/*/GT-I9300/*"
  40396. },
  40397. {
  40398. "ua":"GT-I9300"
  40399. }
  40400. ],
  40401. "dpi":[
  40402. 306.7,
  40403. 304.8
  40404. ],
  40405. "bw":5,
  40406. "ac":1000
  40407. },
  40408. {
  40409. "type":"android",
  40410. "rules":[
  40411. {
  40412. "mdmh":"samsung/*/SM-T535/*"
  40413. },
  40414. {
  40415. "ua":"SM-T535"
  40416. }
  40417. ],
  40418. "dpi":[
  40419. 142.6,
  40420. 136.4
  40421. ],
  40422. "bw":3,
  40423. "ac":500
  40424. },
  40425. {
  40426. "type":"android",
  40427. "rules":[
  40428. {
  40429. "mdmh":"samsung/*/SM-N920C/*"
  40430. },
  40431. {
  40432. "ua":"SM-N920C"
  40433. }
  40434. ],
  40435. "dpi":[
  40436. 515.1,
  40437. 518.4
  40438. ],
  40439. "bw":3,
  40440. "ac":1000
  40441. },
  40442. {
  40443. "type": "android",
  40444. "rules": [
  40445. {
  40446. "mdmh": "samsung/*/SM-N920W8/*"
  40447. },
  40448. {
  40449. "ua": "SM-N920W8"
  40450. }
  40451. ],
  40452. "dpi": [
  40453. 515.1,
  40454. 518.4
  40455. ],
  40456. "bw": 3,
  40457. "ac": 1000
  40458. },
  40459. {
  40460. "type":"android",
  40461. "rules":[
  40462. {
  40463. "mdmh":"samsung/*/GT-I9300I/*"
  40464. },
  40465. {
  40466. "ua":"GT-I9300I"
  40467. }
  40468. ],
  40469. "dpi":[
  40470. 304.8,
  40471. 305.8
  40472. ],
  40473. "bw":3,
  40474. "ac":1000
  40475. },
  40476. {
  40477. "type":"android",
  40478. "rules":[
  40479. {
  40480. "mdmh":"samsung/*/GT-I9195/*"
  40481. },
  40482. {
  40483. "ua":"GT-I9195"
  40484. }
  40485. ],
  40486. "dpi":[
  40487. 249.4,
  40488. 256.7
  40489. ],
  40490. "bw":3,
  40491. "ac":500
  40492. },
  40493. {
  40494. "type":"android",
  40495. "rules":[
  40496. {
  40497. "mdmh":"samsung/*/SPH-L520/*"
  40498. },
  40499. {
  40500. "ua":"SPH-L520"
  40501. }
  40502. ],
  40503. "dpi":[
  40504. 249.4,
  40505. 255.9
  40506. ],
  40507. "bw":3,
  40508. "ac":1000
  40509. },
  40510. {
  40511. "type":"android",
  40512. "rules":[
  40513. {
  40514. "mdmh":"samsung/*/SAMSUNG-SGH-I717/*"
  40515. },
  40516. {
  40517. "ua":"SAMSUNG-SGH-I717"
  40518. }
  40519. ],
  40520. "dpi":285.8,
  40521. "bw":3,
  40522. "ac":1000
  40523. },
  40524. {
  40525. "type":"android",
  40526. "rules":[
  40527. {
  40528. "mdmh":"samsung/*/SPH-D710/*"
  40529. },
  40530. {
  40531. "ua":"SPH-D710"
  40532. }
  40533. ],
  40534. "dpi":[
  40535. 217.7,
  40536. 204.2
  40537. ],
  40538. "bw":3,
  40539. "ac":1000
  40540. },
  40541. {
  40542. "type":"android",
  40543. "rules":[
  40544. {
  40545. "mdmh":"samsung/*/GT-N7100/*"
  40546. },
  40547. {
  40548. "ua":"GT-N7100"
  40549. }
  40550. ],
  40551. "dpi":265.1,
  40552. "bw":3,
  40553. "ac":1000
  40554. },
  40555. {
  40556. "type":"android",
  40557. "rules":[
  40558. {
  40559. "mdmh":"samsung/*/SCH-I605/*"
  40560. },
  40561. {
  40562. "ua":"SCH-I605"
  40563. }
  40564. ],
  40565. "dpi":265.1,
  40566. "bw":3,
  40567. "ac":1000
  40568. },
  40569. {
  40570. "type":"android",
  40571. "rules":[
  40572. {
  40573. "mdmh":"samsung/*/Galaxy Nexus/*"
  40574. },
  40575. {
  40576. "ua":"Galaxy Nexus"
  40577. }
  40578. ],
  40579. "dpi":[
  40580. 315.3,
  40581. 314.2
  40582. ],
  40583. "bw":3,
  40584. "ac":1000
  40585. },
  40586. {
  40587. "type":"android",
  40588. "rules":[
  40589. {
  40590. "mdmh":"samsung/*/SM-N910H/*"
  40591. },
  40592. {
  40593. "ua":"SM-N910H"
  40594. }
  40595. ],
  40596. "dpi":[
  40597. 515.1,
  40598. 518
  40599. ],
  40600. "bw":3,
  40601. "ac":1000
  40602. },
  40603. {
  40604. "type":"android",
  40605. "rules":[
  40606. {
  40607. "mdmh":"samsung/*/SM-N910C/*"
  40608. },
  40609. {
  40610. "ua":"SM-N910C"
  40611. }
  40612. ],
  40613. "dpi":[
  40614. 515.2,
  40615. 520.2
  40616. ],
  40617. "bw":3,
  40618. "ac":500
  40619. },
  40620. {
  40621. "type":"android",
  40622. "rules":[
  40623. {
  40624. "mdmh":"samsung/*/SM-G130M/*"
  40625. },
  40626. {
  40627. "ua":"SM-G130M"
  40628. }
  40629. ],
  40630. "dpi":[
  40631. 165.9,
  40632. 164.8
  40633. ],
  40634. "bw":3,
  40635. "ac":500
  40636. },
  40637. {
  40638. "type":"android",
  40639. "rules":[
  40640. {
  40641. "mdmh":"samsung/*/SM-G928I/*"
  40642. },
  40643. {
  40644. "ua":"SM-G928I"
  40645. }
  40646. ],
  40647. "dpi":[
  40648. 515.1,
  40649. 518.4
  40650. ],
  40651. "bw":3,
  40652. "ac":1000
  40653. },
  40654. {
  40655. "type":"android",
  40656. "rules":[
  40657. {
  40658. "mdmh":"samsung/*/SM-G920F/*"
  40659. },
  40660. {
  40661. "ua":"SM-G920F"
  40662. }
  40663. ],
  40664. "dpi":580.6,
  40665. "bw":3,
  40666. "ac":500
  40667. },
  40668. {
  40669. "type":"android",
  40670. "rules":[
  40671. {
  40672. "mdmh":"samsung/*/SM-G920P/*"
  40673. },
  40674. {
  40675. "ua":"SM-G920P"
  40676. }
  40677. ],
  40678. "dpi":[
  40679. 522.5,
  40680. 577
  40681. ],
  40682. "bw":3,
  40683. "ac":1000
  40684. },
  40685. {
  40686. "type":"android",
  40687. "rules":[
  40688. {
  40689. "mdmh":"samsung/*/SM-G925F/*"
  40690. },
  40691. {
  40692. "ua":"SM-G925F"
  40693. }
  40694. ],
  40695. "dpi":580.6,
  40696. "bw":3,
  40697. "ac":500
  40698. },
  40699. {
  40700. "type":"android",
  40701. "rules":[
  40702. {
  40703. "mdmh":"samsung/*/SM-G925V/*"
  40704. },
  40705. {
  40706. "ua":"SM-G925V"
  40707. }
  40708. ],
  40709. "dpi":[
  40710. 522.5,
  40711. 576.6
  40712. ],
  40713. "bw":3,
  40714. "ac":1000
  40715. },
  40716. {
  40717. "type": "android",
  40718. "rules": [
  40719. {
  40720. "mdmh": "samsung/*/SM-G930F/*"
  40721. },
  40722. {
  40723. "ua": "SM-G930F"
  40724. }
  40725. ],
  40726. "dpi": 576.6,
  40727. "bw": 3,
  40728. "ac": 1000
  40729. },
  40730. {
  40731. "type":"android",
  40732. "rules":[
  40733. {
  40734. "mdmh":"samsung/*/SM-G935F/*"
  40735. },
  40736. {
  40737. "ua":"SM-G935F"
  40738. }
  40739. ],
  40740. "dpi":533,
  40741. "bw":3,
  40742. "ac":500
  40743. },
  40744. {
  40745. "type":"android",
  40746. "rules":[
  40747. {
  40748. "mdmh":"Sony/*/C6903/*"
  40749. },
  40750. {
  40751. "ua":"C6903"
  40752. }
  40753. ],
  40754. "dpi":[
  40755. 442.5,
  40756. 443.3
  40757. ],
  40758. "bw":3,
  40759. "ac":500
  40760. },
  40761. {
  40762. "type":"android",
  40763. "rules":[
  40764. {
  40765. "mdmh":"Sony/*/D6653/*"
  40766. },
  40767. {
  40768. "ua":"D6653"
  40769. }
  40770. ],
  40771. "dpi":[
  40772. 428.6,
  40773. 427.6
  40774. ],
  40775. "bw":3,
  40776. "ac":1000
  40777. },
  40778. {
  40779. "type":"android",
  40780. "rules":[
  40781. {
  40782. "mdmh":"Sony/*/E6653/*"
  40783. },
  40784. {
  40785. "ua":"E6653"
  40786. }
  40787. ],
  40788. "dpi":[
  40789. 428.6,
  40790. 425.7
  40791. ],
  40792. "bw":3,
  40793. "ac":1000
  40794. },
  40795. {
  40796. "type":"android",
  40797. "rules":[
  40798. {
  40799. "mdmh":"Sony/*/E6853/*"
  40800. },
  40801. {
  40802. "ua":"E6853"
  40803. }
  40804. ],
  40805. "dpi":[
  40806. 403.4,
  40807. 401.9
  40808. ],
  40809. "bw":3,
  40810. "ac":1000
  40811. },
  40812. {
  40813. "type":"android",
  40814. "rules":[
  40815. {
  40816. "mdmh":"Sony/*/SGP321/*"
  40817. },
  40818. {
  40819. "ua":"SGP321"
  40820. }
  40821. ],
  40822. "dpi":[
  40823. 224.7,
  40824. 224.1
  40825. ],
  40826. "bw":3,
  40827. "ac":500
  40828. },
  40829. {
  40830. "type":"android",
  40831. "rules":[
  40832. {
  40833. "mdmh":"TCT/*/ALCATEL ONE TOUCH Fierce/*"
  40834. },
  40835. {
  40836. "ua":"ALCATEL ONE TOUCH Fierce"
  40837. }
  40838. ],
  40839. "dpi":[
  40840. 240,
  40841. 247.5
  40842. ],
  40843. "bw":3,
  40844. "ac":1000
  40845. },
  40846. {
  40847. "type":"android",
  40848. "rules":[
  40849. {
  40850. "mdmh":"THL/*/thl 5000/*"
  40851. },
  40852. {
  40853. "ua":"thl 5000"
  40854. }
  40855. ],
  40856. "dpi":[
  40857. 480,
  40858. 443.3
  40859. ],
  40860. "bw":3,
  40861. "ac":1000
  40862. },
  40863. {
  40864. "type":"android",
  40865. "rules":[
  40866. {
  40867. "mdmh":"ZTE/*/ZTE Blade L2/*"
  40868. },
  40869. {
  40870. "ua":"ZTE Blade L2"
  40871. }
  40872. ],
  40873. "dpi":240,
  40874. "bw":3,
  40875. "ac":500
  40876. },
  40877. {
  40878. "type":"ios",
  40879. "rules":[
  40880. {
  40881. "res":[
  40882. 640,
  40883. 960
  40884. ]
  40885. }
  40886. ],
  40887. "dpi":[
  40888. 325.1,
  40889. 328.4
  40890. ],
  40891. "bw":4,
  40892. "ac":1000
  40893. },
  40894. {
  40895. "type":"ios",
  40896. "rules":[
  40897. {
  40898. "res":[
  40899. 640,
  40900. 1136
  40901. ]
  40902. }
  40903. ],
  40904. "dpi":[
  40905. 317.1,
  40906. 320.2
  40907. ],
  40908. "bw":3,
  40909. "ac":1000
  40910. },
  40911. {
  40912. "type":"ios",
  40913. "rules":[
  40914. {
  40915. "res":[
  40916. 750,
  40917. 1334
  40918. ]
  40919. }
  40920. ],
  40921. "dpi":326.4,
  40922. "bw":4,
  40923. "ac":1000
  40924. },
  40925. {
  40926. "type":"ios",
  40927. "rules":[
  40928. {
  40929. "res":[
  40930. 1242,
  40931. 2208
  40932. ]
  40933. }
  40934. ],
  40935. "dpi":[
  40936. 453.6,
  40937. 458.4
  40938. ],
  40939. "bw":4,
  40940. "ac":1000
  40941. },
  40942. {
  40943. "type":"ios",
  40944. "rules":[
  40945. {
  40946. "res":[
  40947. 1125,
  40948. 2001
  40949. ]
  40950. }
  40951. ],
  40952. "dpi":[
  40953. 410.9,
  40954. 415.4
  40955. ],
  40956. "bw":4,
  40957. "ac":1000
  40958. }
  40959. ]
  40960. }
  40961. },{}],13:[function(_dereq_,module,exports){
  40962. /*
  40963. * Copyright 2015 Google Inc. All Rights Reserved.
  40964. * Licensed under the Apache License, Version 2.0 (the "License");
  40965. * you may not use this file except in compliance with the License.
  40966. * You may obtain a copy of the License at
  40967. *
  40968. * http://www.apache.org/licenses/LICENSE-2.0
  40969. *
  40970. * Unless required by applicable law or agreed to in writing, software
  40971. * distributed under the License is distributed on an "AS IS" BASIS,
  40972. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40973. * See the License for the specific language governing permissions and
  40974. * limitations under the License.
  40975. */
  40976. // Offline cache of the DPDB, to be used until we load the online one (and
  40977. // as a fallback in case we can't load the online one).
  40978. var DPDB_CACHE = _dereq_('./dpdb-cache.js');
  40979. var Util = _dereq_('../util.js');
  40980. // Online DPDB URL.
  40981. var ONLINE_DPDB_URL = _dereq_('./dpdb.json');
  40982. /**
  40983. * Calculates device parameters based on the DPDB (Device Parameter Database).
  40984. * Initially, uses the cached DPDB values.
  40985. *
  40986. * If fetchOnline == true, then this object tries to fetch the online version
  40987. * of the DPDB and updates the device info if a better match is found.
  40988. * Calls the onDeviceParamsUpdated callback when there is an update to the
  40989. * device information.
  40990. */
  40991. function Dpdb(fetchOnline, onDeviceParamsUpdated) {
  40992. // Start with the offline DPDB cache while we are loading the real one.
  40993. this.dpdb = DPDB_CACHE;
  40994. // Calculate device params based on the offline version of the DPDB.
  40995. this.recalculateDeviceParams_();
  40996. // XHR to fetch online DPDB file, if requested.
  40997. if (fetchOnline) {
  40998. // Set the callback.
  40999. this.onDeviceParamsUpdated = onDeviceParamsUpdated;
  41000. var xhr = new XMLHttpRequest();
  41001. var obj = this;
  41002. xhr.open('GET', ONLINE_DPDB_URL, true);
  41003. xhr.addEventListener('load', function() {
  41004. obj.loading = false;
  41005. if (xhr.status >= 200 && xhr.status <= 299) {
  41006. // Success.
  41007. obj.dpdb = JSON.parse(xhr.response);
  41008. obj.recalculateDeviceParams_();
  41009. } else {
  41010. // Error loading the DPDB.
  41011. console.error('Error loading online DPDB!');
  41012. }
  41013. });
  41014. xhr.send();
  41015. }
  41016. }
  41017. // Returns the current device parameters.
  41018. Dpdb.prototype.getDeviceParams = function() {
  41019. return this.deviceParams;
  41020. };
  41021. // Recalculates this device's parameters based on the DPDB.
  41022. Dpdb.prototype.recalculateDeviceParams_ = function() {
  41023. var newDeviceParams = this.calcDeviceParams_();
  41024. if (newDeviceParams) {
  41025. this.deviceParams = newDeviceParams;
  41026. // Invoke callback, if it is set.
  41027. if (this.onDeviceParamsUpdated) {
  41028. this.onDeviceParamsUpdated(this.deviceParams);
  41029. }
  41030. } else {
  41031. console.error('Failed to recalculate device parameters.');
  41032. }
  41033. };
  41034. // Returns a DeviceParams object that represents the best guess as to this
  41035. // device's parameters. Can return null if the device does not match any
  41036. // known devices.
  41037. Dpdb.prototype.calcDeviceParams_ = function() {
  41038. var db = this.dpdb; // shorthand
  41039. if (!db) {
  41040. console.error('DPDB not available.');
  41041. return null;
  41042. }
  41043. if (db.format != 1) {
  41044. console.error('DPDB has unexpected format version.');
  41045. return null;
  41046. }
  41047. if (!db.devices || !db.devices.length) {
  41048. console.error('DPDB does not have a devices section.');
  41049. return null;
  41050. }
  41051. // Get the actual user agent and screen dimensions in pixels.
  41052. var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  41053. var width = Util.getScreenWidth();
  41054. var height = Util.getScreenHeight();
  41055. if (!db.devices) {
  41056. console.error('DPDB has no devices section.');
  41057. return null;
  41058. }
  41059. for (var i = 0; i < db.devices.length; i++) {
  41060. var device = db.devices[i];
  41061. if (!device.rules) {
  41062. console.warn('Device[' + i + '] has no rules section.');
  41063. continue;
  41064. }
  41065. if (device.type != 'ios' && device.type != 'android') {
  41066. console.warn('Device[' + i + '] has invalid type.');
  41067. continue;
  41068. }
  41069. // See if this device is of the appropriate type.
  41070. if (Util.isIOS() != (device.type == 'ios')) continue;
  41071. // See if this device matches any of the rules:
  41072. var matched = false;
  41073. for (var j = 0; j < device.rules.length; j++) {
  41074. var rule = device.rules[j];
  41075. if (this.matchRule_(rule, userAgent, width, height)) {
  41076. matched = true;
  41077. break;
  41078. }
  41079. }
  41080. if (!matched) continue;
  41081. // device.dpi might be an array of [ xdpi, ydpi] or just a scalar.
  41082. var xdpi = device.dpi[0] || device.dpi;
  41083. var ydpi = device.dpi[1] || device.dpi;
  41084. return new DeviceParams({ xdpi: xdpi, ydpi: ydpi, bevelMm: device.bw });
  41085. }
  41086. console.warn('No DPDB device match.');
  41087. return null;
  41088. };
  41089. Dpdb.prototype.matchRule_ = function(rule, ua, screenWidth, screenHeight) {
  41090. // We can only match 'ua' and 'res' rules, not other types like 'mdmh'
  41091. // (which are meant for native platforms).
  41092. if (!rule.ua && !rule.res) return false;
  41093. // If our user agent string doesn't contain the indicated user agent string,
  41094. // the match fails.
  41095. if (rule.ua && ua.indexOf(rule.ua) < 0) return false;
  41096. // If the rule specifies screen dimensions that don't correspond to ours,
  41097. // the match fails.
  41098. if (rule.res) {
  41099. if (!rule.res[0] || !rule.res[1]) return false;
  41100. var resX = rule.res[0];
  41101. var resY = rule.res[1];
  41102. // Compare min and max so as to make the order not matter, i.e., it should
  41103. // be true that 640x480 == 480x640.
  41104. if (Math.min(screenWidth, screenHeight) != Math.min(resX, resY) ||
  41105. (Math.max(screenWidth, screenHeight) != Math.max(resX, resY))) {
  41106. return false;
  41107. }
  41108. }
  41109. return true;
  41110. }
  41111. function DeviceParams(params) {
  41112. this.xdpi = params.xdpi;
  41113. this.ydpi = params.ydpi;
  41114. this.bevelMm = params.bevelMm;
  41115. }
  41116. module.exports = Dpdb;
  41117. },{"../util.js":23,"./dpdb-cache.js":11,"./dpdb.json":12}],14:[function(_dereq_,module,exports){
  41118. /*
  41119. * Copyright 2015 Google Inc. All Rights Reserved.
  41120. * Licensed under the Apache License, Version 2.0 (the "License");
  41121. * you may not use this file except in compliance with the License.
  41122. * You may obtain a copy of the License at
  41123. *
  41124. * http://www.apache.org/licenses/LICENSE-2.0
  41125. *
  41126. * Unless required by applicable law or agreed to in writing, software
  41127. * distributed under the License is distributed on an "AS IS" BASIS,
  41128. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41129. * See the License for the specific language governing permissions and
  41130. * limitations under the License.
  41131. */
  41132. var Util = _dereq_('./util.js');
  41133. var WebVRPolyfill = _dereq_('./webvr-polyfill.js').WebVRPolyfill;
  41134. // Initialize a WebVRConfig just in case.
  41135. window.WebVRConfig = Util.extend({
  41136. // Forces availability of VR mode, even for non-mobile devices.
  41137. FORCE_ENABLE_VR: false,
  41138. // Complementary filter coefficient. 0 for accelerometer, 1 for gyro.
  41139. K_FILTER: 0.98,
  41140. // How far into the future to predict during fast motion (in seconds).
  41141. PREDICTION_TIME_S: 0.040,
  41142. // Flag to enable touch panner. In case you have your own touch controls.
  41143. TOUCH_PANNER_DISABLED: true,
  41144. // Flag to disabled the UI in VR Mode.
  41145. CARDBOARD_UI_DISABLED: false, // Default: false
  41146. // Flag to disable the instructions to rotate your device.
  41147. ROTATE_INSTRUCTIONS_DISABLED: false, // Default: false.
  41148. // Enable yaw panning only, disabling roll and pitch. This can be useful
  41149. // for panoramas with nothing interesting above or below.
  41150. YAW_ONLY: false,
  41151. // To disable keyboard and mouse controls, if you want to use your own
  41152. // implementation.
  41153. MOUSE_KEYBOARD_CONTROLS_DISABLED: false,
  41154. // Prevent the polyfill from initializing immediately. Requires the app
  41155. // to call InitializeWebVRPolyfill() before it can be used.
  41156. DEFER_INITIALIZATION: false,
  41157. // Enable the deprecated version of the API (navigator.getVRDevices).
  41158. ENABLE_DEPRECATED_API: false,
  41159. // Scales the recommended buffer size reported by WebVR, which can improve
  41160. // performance.
  41161. // UPDATE(2016-05-03): Setting this to 0.5 by default since 1.0 does not
  41162. // perform well on many mobile devices.
  41163. BUFFER_SCALE: 0.5,
  41164. // Allow VRDisplay.submitFrame to change gl bindings, which is more
  41165. // efficient if the application code will re-bind its resources on the
  41166. // next frame anyway. This has been seen to cause rendering glitches with
  41167. // THREE.js.
  41168. // Dirty bindings include: gl.FRAMEBUFFER_BINDING, gl.CURRENT_PROGRAM,
  41169. // gl.ARRAY_BUFFER_BINDING, gl.ELEMENT_ARRAY_BUFFER_BINDING,
  41170. // and gl.TEXTURE_BINDING_2D for texture unit 0.
  41171. DIRTY_SUBMIT_FRAME_BINDINGS: false,
  41172. // When set to true, this will cause a polyfilled VRDisplay to always be
  41173. // appended to the list returned by navigator.getVRDisplays(), even if that
  41174. // list includes a native VRDisplay.
  41175. ALWAYS_APPEND_POLYFILL_DISPLAY: false
  41176. }, window.WebVRConfig);
  41177. if (!window.WebVRConfig.DEFER_INITIALIZATION) {
  41178. new WebVRPolyfill();
  41179. } else {
  41180. window.InitializeWebVRPolyfill = function() {
  41181. new WebVRPolyfill();
  41182. }
  41183. }
  41184. },{"./util.js":23,"./webvr-polyfill.js":26}],15:[function(_dereq_,module,exports){
  41185. /*
  41186. * Copyright 2016 Google Inc. All Rights Reserved.
  41187. * Licensed under the Apache License, Version 2.0 (the "License");
  41188. * you may not use this file except in compliance with the License.
  41189. * You may obtain a copy of the License at
  41190. *
  41191. * http://www.apache.org/licenses/LICENSE-2.0
  41192. *
  41193. * Unless required by applicable law or agreed to in writing, software
  41194. * distributed under the License is distributed on an "AS IS" BASIS,
  41195. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41196. * See the License for the specific language governing permissions and
  41197. * limitations under the License.
  41198. */
  41199. var MathUtil = window.MathUtil || {};
  41200. MathUtil.degToRad = Math.PI / 180;
  41201. MathUtil.radToDeg = 180 / Math.PI;
  41202. // Some minimal math functionality borrowed from THREE.Math and stripped down
  41203. // for the purposes of this library.
  41204. MathUtil.Vector2 = function ( x, y ) {
  41205. this.x = x || 0;
  41206. this.y = y || 0;
  41207. };
  41208. MathUtil.Vector2.prototype = {
  41209. constructor: MathUtil.Vector2,
  41210. set: function ( x, y ) {
  41211. this.x = x;
  41212. this.y = y;
  41213. return this;
  41214. },
  41215. copy: function ( v ) {
  41216. this.x = v.x;
  41217. this.y = v.y;
  41218. return this;
  41219. },
  41220. subVectors: function ( a, b ) {
  41221. this.x = a.x - b.x;
  41222. this.y = a.y - b.y;
  41223. return this;
  41224. },
  41225. };
  41226. MathUtil.Vector3 = function ( x, y, z ) {
  41227. this.x = x || 0;
  41228. this.y = y || 0;
  41229. this.z = z || 0;
  41230. };
  41231. MathUtil.Vector3.prototype = {
  41232. constructor: MathUtil.Vector3,
  41233. set: function ( x, y, z ) {
  41234. this.x = x;
  41235. this.y = y;
  41236. this.z = z;
  41237. return this;
  41238. },
  41239. copy: function ( v ) {
  41240. this.x = v.x;
  41241. this.y = v.y;
  41242. this.z = v.z;
  41243. return this;
  41244. },
  41245. length: function () {
  41246. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  41247. },
  41248. normalize: function () {
  41249. var scalar = this.length();
  41250. if ( scalar !== 0 ) {
  41251. var invScalar = 1 / scalar;
  41252. this.multiplyScalar(invScalar);
  41253. } else {
  41254. this.x = 0;
  41255. this.y = 0;
  41256. this.z = 0;
  41257. }
  41258. return this;
  41259. },
  41260. multiplyScalar: function ( scalar ) {
  41261. this.x *= scalar;
  41262. this.y *= scalar;
  41263. this.z *= scalar;
  41264. },
  41265. applyQuaternion: function ( q ) {
  41266. var x = this.x;
  41267. var y = this.y;
  41268. var z = this.z;
  41269. var qx = q.x;
  41270. var qy = q.y;
  41271. var qz = q.z;
  41272. var qw = q.w;
  41273. // calculate quat * vector
  41274. var ix = qw * x + qy * z - qz * y;
  41275. var iy = qw * y + qz * x - qx * z;
  41276. var iz = qw * z + qx * y - qy * x;
  41277. var iw = - qx * x - qy * y - qz * z;
  41278. // calculate result * inverse quat
  41279. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  41280. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  41281. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  41282. return this;
  41283. },
  41284. dot: function ( v ) {
  41285. return this.x * v.x + this.y * v.y + this.z * v.z;
  41286. },
  41287. crossVectors: function ( a, b ) {
  41288. var ax = a.x, ay = a.y, az = a.z;
  41289. var bx = b.x, by = b.y, bz = b.z;
  41290. this.x = ay * bz - az * by;
  41291. this.y = az * bx - ax * bz;
  41292. this.z = ax * by - ay * bx;
  41293. return this;
  41294. },
  41295. };
  41296. MathUtil.Quaternion = function ( x, y, z, w ) {
  41297. this.x = x || 0;
  41298. this.y = y || 0;
  41299. this.z = z || 0;
  41300. this.w = ( w !== undefined ) ? w : 1;
  41301. };
  41302. MathUtil.Quaternion.prototype = {
  41303. constructor: MathUtil.Quaternion,
  41304. set: function ( x, y, z, w ) {
  41305. this.x = x;
  41306. this.y = y;
  41307. this.z = z;
  41308. this.w = w;
  41309. return this;
  41310. },
  41311. copy: function ( quaternion ) {
  41312. this.x = quaternion.x;
  41313. this.y = quaternion.y;
  41314. this.z = quaternion.z;
  41315. this.w = quaternion.w;
  41316. return this;
  41317. },
  41318. setFromEulerXYZ: function( x, y, z ) {
  41319. var c1 = Math.cos( x / 2 );
  41320. var c2 = Math.cos( y / 2 );
  41321. var c3 = Math.cos( z / 2 );
  41322. var s1 = Math.sin( x / 2 );
  41323. var s2 = Math.sin( y / 2 );
  41324. var s3 = Math.sin( z / 2 );
  41325. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  41326. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  41327. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  41328. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  41329. return this;
  41330. },
  41331. setFromEulerYXZ: function( x, y, z ) {
  41332. var c1 = Math.cos( x / 2 );
  41333. var c2 = Math.cos( y / 2 );
  41334. var c3 = Math.cos( z / 2 );
  41335. var s1 = Math.sin( x / 2 );
  41336. var s2 = Math.sin( y / 2 );
  41337. var s3 = Math.sin( z / 2 );
  41338. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  41339. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  41340. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  41341. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  41342. return this;
  41343. },
  41344. setFromAxisAngle: function ( axis, angle ) {
  41345. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  41346. // assumes axis is normalized
  41347. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  41348. this.x = axis.x * s;
  41349. this.y = axis.y * s;
  41350. this.z = axis.z * s;
  41351. this.w = Math.cos( halfAngle );
  41352. return this;
  41353. },
  41354. multiply: function ( q ) {
  41355. return this.multiplyQuaternions( this, q );
  41356. },
  41357. multiplyQuaternions: function ( a, b ) {
  41358. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  41359. var qax = a.x, qay = a.y, qaz = a.z, qaw = a.w;
  41360. var qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  41361. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  41362. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  41363. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  41364. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  41365. return this;
  41366. },
  41367. inverse: function () {
  41368. this.x *= -1;
  41369. this.y *= -1;
  41370. this.z *= -1;
  41371. this.normalize();
  41372. return this;
  41373. },
  41374. normalize: function () {
  41375. var l = Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  41376. if ( l === 0 ) {
  41377. this.x = 0;
  41378. this.y = 0;
  41379. this.z = 0;
  41380. this.w = 1;
  41381. } else {
  41382. l = 1 / l;
  41383. this.x = this.x * l;
  41384. this.y = this.y * l;
  41385. this.z = this.z * l;
  41386. this.w = this.w * l;
  41387. }
  41388. return this;
  41389. },
  41390. slerp: function ( qb, t ) {
  41391. if ( t === 0 ) return this;
  41392. if ( t === 1 ) return this.copy( qb );
  41393. var x = this.x, y = this.y, z = this.z, w = this.w;
  41394. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  41395. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  41396. if ( cosHalfTheta < 0 ) {
  41397. this.w = - qb.w;
  41398. this.x = - qb.x;
  41399. this.y = - qb.y;
  41400. this.z = - qb.z;
  41401. cosHalfTheta = - cosHalfTheta;
  41402. } else {
  41403. this.copy( qb );
  41404. }
  41405. if ( cosHalfTheta >= 1.0 ) {
  41406. this.w = w;
  41407. this.x = x;
  41408. this.y = y;
  41409. this.z = z;
  41410. return this;
  41411. }
  41412. var halfTheta = Math.acos( cosHalfTheta );
  41413. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  41414. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  41415. this.w = 0.5 * ( w + this.w );
  41416. this.x = 0.5 * ( x + this.x );
  41417. this.y = 0.5 * ( y + this.y );
  41418. this.z = 0.5 * ( z + this.z );
  41419. return this;
  41420. }
  41421. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  41422. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  41423. this.w = ( w * ratioA + this.w * ratioB );
  41424. this.x = ( x * ratioA + this.x * ratioB );
  41425. this.y = ( y * ratioA + this.y * ratioB );
  41426. this.z = ( z * ratioA + this.z * ratioB );
  41427. return this;
  41428. },
  41429. setFromUnitVectors: function () {
  41430. // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final
  41431. // assumes direction vectors vFrom and vTo are normalized
  41432. var v1, r;
  41433. var EPS = 0.000001;
  41434. return function ( vFrom, vTo ) {
  41435. if ( v1 === undefined ) v1 = new MathUtil.Vector3();
  41436. r = vFrom.dot( vTo ) + 1;
  41437. if ( r < EPS ) {
  41438. r = 0;
  41439. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  41440. v1.set( - vFrom.y, vFrom.x, 0 );
  41441. } else {
  41442. v1.set( 0, - vFrom.z, vFrom.y );
  41443. }
  41444. } else {
  41445. v1.crossVectors( vFrom, vTo );
  41446. }
  41447. this.x = v1.x;
  41448. this.y = v1.y;
  41449. this.z = v1.z;
  41450. this.w = r;
  41451. this.normalize();
  41452. return this;
  41453. }
  41454. }(),
  41455. };
  41456. module.exports = MathUtil;
  41457. },{}],16:[function(_dereq_,module,exports){
  41458. /*
  41459. * Copyright 2016 Google Inc. All Rights Reserved.
  41460. * Licensed under the Apache License, Version 2.0 (the "License");
  41461. * you may not use this file except in compliance with the License.
  41462. * You may obtain a copy of the License at
  41463. *
  41464. * http://www.apache.org/licenses/LICENSE-2.0
  41465. *
  41466. * Unless required by applicable law or agreed to in writing, software
  41467. * distributed under the License is distributed on an "AS IS" BASIS,
  41468. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41469. * See the License for the specific language governing permissions and
  41470. * limitations under the License.
  41471. */
  41472. var VRDisplay = _dereq_('./base.js').VRDisplay;
  41473. var MathUtil = _dereq_('./math-util.js');
  41474. var Util = _dereq_('./util.js');
  41475. // How much to rotate per key stroke.
  41476. var KEY_SPEED = 0.15;
  41477. var KEY_ANIMATION_DURATION = 80;
  41478. // How much to rotate for mouse events.
  41479. var MOUSE_SPEED_X = 0.5;
  41480. var MOUSE_SPEED_Y = 0.3;
  41481. /**
  41482. * VRDisplay based on mouse and keyboard input. Designed for desktops/laptops
  41483. * where orientation events aren't supported. Cannot present.
  41484. */
  41485. function MouseKeyboardVRDisplay() {
  41486. this.displayName = 'Mouse and Keyboard VRDisplay (webvr-polyfill)';
  41487. this.capabilities.hasOrientation = true;
  41488. // Attach to mouse and keyboard events.
  41489. window.addEventListener('keydown', this.onKeyDown_.bind(this));
  41490. window.addEventListener('mousemove', this.onMouseMove_.bind(this));
  41491. window.addEventListener('mousedown', this.onMouseDown_.bind(this));
  41492. window.addEventListener('mouseup', this.onMouseUp_.bind(this));
  41493. // "Private" members.
  41494. this.phi_ = 0;
  41495. this.theta_ = 0;
  41496. // Variables for keyboard-based rotation animation.
  41497. this.targetAngle_ = null;
  41498. this.angleAnimation_ = null;
  41499. // State variables for calculations.
  41500. this.orientation_ = new MathUtil.Quaternion();
  41501. // Variables for mouse-based rotation.
  41502. this.rotateStart_ = new MathUtil.Vector2();
  41503. this.rotateEnd_ = new MathUtil.Vector2();
  41504. this.rotateDelta_ = new MathUtil.Vector2();
  41505. this.isDragging_ = false;
  41506. this.orientationOut_ = new Float32Array(4);
  41507. }
  41508. MouseKeyboardVRDisplay.prototype = new VRDisplay();
  41509. MouseKeyboardVRDisplay.prototype.getImmediatePose = function() {
  41510. this.orientation_.setFromEulerYXZ(this.phi_, this.theta_, 0);
  41511. this.orientationOut_[0] = this.orientation_.x;
  41512. this.orientationOut_[1] = this.orientation_.y;
  41513. this.orientationOut_[2] = this.orientation_.z;
  41514. this.orientationOut_[3] = this.orientation_.w;
  41515. return {
  41516. position: null,
  41517. orientation: this.orientationOut_,
  41518. linearVelocity: null,
  41519. linearAcceleration: null,
  41520. angularVelocity: null,
  41521. angularAcceleration: null
  41522. };
  41523. };
  41524. MouseKeyboardVRDisplay.prototype.onKeyDown_ = function(e) {
  41525. // Track WASD and arrow keys.
  41526. if (e.keyCode == 38) { // Up key.
  41527. this.animatePhi_(this.phi_ + KEY_SPEED);
  41528. } else if (e.keyCode == 39) { // Right key.
  41529. this.animateTheta_(this.theta_ - KEY_SPEED);
  41530. } else if (e.keyCode == 40) { // Down key.
  41531. this.animatePhi_(this.phi_ - KEY_SPEED);
  41532. } else if (e.keyCode == 37) { // Left key.
  41533. this.animateTheta_(this.theta_ + KEY_SPEED);
  41534. }
  41535. };
  41536. MouseKeyboardVRDisplay.prototype.animateTheta_ = function(targetAngle) {
  41537. this.animateKeyTransitions_('theta_', targetAngle);
  41538. };
  41539. MouseKeyboardVRDisplay.prototype.animatePhi_ = function(targetAngle) {
  41540. // Prevent looking too far up or down.
  41541. targetAngle = Util.clamp(targetAngle, -Math.PI/2, Math.PI/2);
  41542. this.animateKeyTransitions_('phi_', targetAngle);
  41543. };
  41544. /**
  41545. * Start an animation to transition an angle from one value to another.
  41546. */
  41547. MouseKeyboardVRDisplay.prototype.animateKeyTransitions_ = function(angleName, targetAngle) {
  41548. // If an animation is currently running, cancel it.
  41549. if (this.angleAnimation_) {
  41550. cancelAnimationFrame(this.angleAnimation_);
  41551. }
  41552. var startAngle = this[angleName];
  41553. var startTime = new Date();
  41554. // Set up an interval timer to perform the animation.
  41555. this.angleAnimation_ = requestAnimationFrame(function animate() {
  41556. // Once we're finished the animation, we're done.
  41557. var elapsed = new Date() - startTime;
  41558. if (elapsed >= KEY_ANIMATION_DURATION) {
  41559. this[angleName] = targetAngle;
  41560. cancelAnimationFrame(this.angleAnimation_);
  41561. return;
  41562. }
  41563. // loop with requestAnimationFrame
  41564. this.angleAnimation_ = requestAnimationFrame(animate.bind(this))
  41565. // Linearly interpolate the angle some amount.
  41566. var percent = elapsed / KEY_ANIMATION_DURATION;
  41567. this[angleName] = startAngle + (targetAngle - startAngle) * percent;
  41568. }.bind(this));
  41569. };
  41570. MouseKeyboardVRDisplay.prototype.onMouseDown_ = function(e) {
  41571. this.rotateStart_.set(e.clientX, e.clientY);
  41572. this.isDragging_ = true;
  41573. };
  41574. // Very similar to https://gist.github.com/mrflix/8351020
  41575. MouseKeyboardVRDisplay.prototype.onMouseMove_ = function(e) {
  41576. if (!this.isDragging_ && !this.isPointerLocked_()) {
  41577. return;
  41578. }
  41579. // Support pointer lock API.
  41580. if (this.isPointerLocked_()) {
  41581. var movementX = e.movementX || e.mozMovementX || 0;
  41582. var movementY = e.movementY || e.mozMovementY || 0;
  41583. this.rotateEnd_.set(this.rotateStart_.x - movementX, this.rotateStart_.y - movementY);
  41584. } else {
  41585. this.rotateEnd_.set(e.clientX, e.clientY);
  41586. }
  41587. // Calculate how much we moved in mouse space.
  41588. this.rotateDelta_.subVectors(this.rotateEnd_, this.rotateStart_);
  41589. this.rotateStart_.copy(this.rotateEnd_);
  41590. // Keep track of the cumulative euler angles.
  41591. this.phi_ += 2 * Math.PI * this.rotateDelta_.y / screen.height * MOUSE_SPEED_Y;
  41592. this.theta_ += 2 * Math.PI * this.rotateDelta_.x / screen.width * MOUSE_SPEED_X;
  41593. // Prevent looking too far up or down.
  41594. this.phi_ = Util.clamp(this.phi_, -Math.PI/2, Math.PI/2);
  41595. };
  41596. MouseKeyboardVRDisplay.prototype.onMouseUp_ = function(e) {
  41597. this.isDragging_ = false;
  41598. };
  41599. MouseKeyboardVRDisplay.prototype.isPointerLocked_ = function() {
  41600. var el = document.pointerLockElement || document.mozPointerLockElement ||
  41601. document.webkitPointerLockElement;
  41602. return el !== undefined;
  41603. };
  41604. MouseKeyboardVRDisplay.prototype.resetPose = function() {
  41605. this.phi_ = 0;
  41606. this.theta_ = 0;
  41607. };
  41608. module.exports = MouseKeyboardVRDisplay;
  41609. },{"./base.js":3,"./math-util.js":15,"./util.js":23}],17:[function(_dereq_,module,exports){
  41610. /*
  41611. * Copyright 2015 Google Inc. All Rights Reserved.
  41612. * Licensed under the Apache License, Version 2.0 (the "License");
  41613. * you may not use this file except in compliance with the License.
  41614. * You may obtain a copy of the License at
  41615. *
  41616. * http://www.apache.org/licenses/LICENSE-2.0
  41617. *
  41618. * Unless required by applicable law or agreed to in writing, software
  41619. * distributed under the License is distributed on an "AS IS" BASIS,
  41620. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41621. * See the License for the specific language governing permissions and
  41622. * limitations under the License.
  41623. */
  41624. var Util = _dereq_('./util.js');
  41625. function RotateInstructions() {
  41626. this.loadIcon_();
  41627. var overlay = document.createElement('div');
  41628. var s = overlay.style;
  41629. s.position = 'fixed';
  41630. s.top = 0;
  41631. s.right = 0;
  41632. s.bottom = 0;
  41633. s.left = 0;
  41634. s.backgroundColor = 'gray';
  41635. s.fontFamily = 'sans-serif';
  41636. // Force this to be above the fullscreen canvas, which is at zIndex: 999999.
  41637. s.zIndex = 1000000;
  41638. var img = document.createElement('img');
  41639. img.src = this.icon;
  41640. var s = img.style;
  41641. s.marginLeft = '25%';
  41642. s.marginTop = '25%';
  41643. s.width = '50%';
  41644. overlay.appendChild(img);
  41645. var text = document.createElement('div');
  41646. var s = text.style;
  41647. s.textAlign = 'center';
  41648. s.fontSize = '16px';
  41649. s.lineHeight = '24px';
  41650. s.margin = '24px 25%';
  41651. s.width = '50%';
  41652. text.innerHTML = 'Place your phone into your Cardboard viewer.';
  41653. overlay.appendChild(text);
  41654. var snackbar = document.createElement('div');
  41655. var s = snackbar.style;
  41656. s.backgroundColor = '#CFD8DC';
  41657. s.position = 'fixed';
  41658. s.bottom = 0;
  41659. s.width = '100%';
  41660. s.height = '48px';
  41661. s.padding = '14px 24px';
  41662. s.boxSizing = 'border-box';
  41663. s.color = '#656A6B';
  41664. overlay.appendChild(snackbar);
  41665. var snackbarText = document.createElement('div');
  41666. snackbarText.style.float = 'left';
  41667. snackbarText.innerHTML = 'No Cardboard viewer?';
  41668. var snackbarButton = document.createElement('a');
  41669. snackbarButton.href = 'https://www.google.com/get/cardboard/get-cardboard/';
  41670. snackbarButton.innerHTML = 'get one';
  41671. snackbarButton.target = '_blank';
  41672. var s = snackbarButton.style;
  41673. s.float = 'right';
  41674. s.fontWeight = 600;
  41675. s.textTransform = 'uppercase';
  41676. s.borderLeft = '1px solid gray';
  41677. s.paddingLeft = '24px';
  41678. s.textDecoration = 'none';
  41679. s.color = '#656A6B';
  41680. snackbar.appendChild(snackbarText);
  41681. snackbar.appendChild(snackbarButton);
  41682. this.overlay = overlay;
  41683. this.text = text;
  41684. this.hide();
  41685. }
  41686. RotateInstructions.prototype.show = function(parent) {
  41687. if (!parent && !this.overlay.parentElement) {
  41688. document.body.appendChild(this.overlay);
  41689. } else if (parent) {
  41690. if (this.overlay.parentElement && this.overlay.parentElement != parent)
  41691. this.overlay.parentElement.removeChild(this.overlay);
  41692. parent.appendChild(this.overlay);
  41693. }
  41694. this.overlay.style.display = 'block';
  41695. var img = this.overlay.querySelector('img');
  41696. var s = img.style;
  41697. if (Util.isLandscapeMode()) {
  41698. s.width = '20%';
  41699. s.marginLeft = '40%';
  41700. s.marginTop = '3%';
  41701. } else {
  41702. s.width = '50%';
  41703. s.marginLeft = '25%';
  41704. s.marginTop = '25%';
  41705. }
  41706. };
  41707. RotateInstructions.prototype.hide = function() {
  41708. this.overlay.style.display = 'none';
  41709. };
  41710. RotateInstructions.prototype.showTemporarily = function(ms, parent) {
  41711. this.show(parent);
  41712. this.timer = setTimeout(this.hide.bind(this), ms);
  41713. };
  41714. RotateInstructions.prototype.disableShowTemporarily = function() {
  41715. clearTimeout(this.timer);
  41716. };
  41717. RotateInstructions.prototype.update = function() {
  41718. this.disableShowTemporarily();
  41719. // In portrait VR mode, tell the user to rotate to landscape. Otherwise, hide
  41720. // the instructions.
  41721. if (!Util.isLandscapeMode() && Util.isMobile()) {
  41722. this.show();
  41723. } else {
  41724. this.hide();
  41725. }
  41726. };
  41727. RotateInstructions.prototype.loadIcon_ = function() {
  41728. // Encoded asset_src/rotate-instructions.svg
  41729. 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+');
  41730. };
  41731. module.exports = RotateInstructions;
  41732. },{"./util.js":23}],18:[function(_dereq_,module,exports){
  41733. /*
  41734. * Copyright 2015 Google Inc. All Rights Reserved.
  41735. * Licensed under the Apache License, Version 2.0 (the "License");
  41736. * you may not use this file except in compliance with the License.
  41737. * You may obtain a copy of the License at
  41738. *
  41739. * http://www.apache.org/licenses/LICENSE-2.0
  41740. *
  41741. * Unless required by applicable law or agreed to in writing, software
  41742. * distributed under the License is distributed on an "AS IS" BASIS,
  41743. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41744. * See the License for the specific language governing permissions and
  41745. * limitations under the License.
  41746. */
  41747. var SensorSample = _dereq_('./sensor-sample.js');
  41748. var MathUtil = _dereq_('../math-util.js');
  41749. var Util = _dereq_('../util.js');
  41750. /**
  41751. * An implementation of a simple complementary filter, which fuses gyroscope and
  41752. * accelerometer data from the 'devicemotion' event.
  41753. *
  41754. * Accelerometer data is very noisy, but stable over the long term.
  41755. * Gyroscope data is smooth, but tends to drift over the long term.
  41756. *
  41757. * This fusion is relatively simple:
  41758. * 1. Get orientation estimates from accelerometer by applying a low-pass filter
  41759. * on that data.
  41760. * 2. Get orientation estimates from gyroscope by integrating over time.
  41761. * 3. Combine the two estimates, weighing (1) in the long term, but (2) for the
  41762. * short term.
  41763. */
  41764. function ComplementaryFilter(kFilter) {
  41765. this.kFilter = kFilter;
  41766. // Raw sensor measurements.
  41767. this.currentAccelMeasurement = new SensorSample();
  41768. this.currentGyroMeasurement = new SensorSample();
  41769. this.previousGyroMeasurement = new SensorSample();
  41770. // Set default look direction to be in the correct direction.
  41771. if (Util.isIOS()) {
  41772. this.filterQ = new MathUtil.Quaternion(-1, 0, 0, 1);
  41773. } else {
  41774. this.filterQ = new MathUtil.Quaternion(1, 0, 0, 1);
  41775. }
  41776. this.previousFilterQ = new MathUtil.Quaternion();
  41777. this.previousFilterQ.copy(this.filterQ);
  41778. // Orientation based on the accelerometer.
  41779. this.accelQ = new MathUtil.Quaternion();
  41780. // Whether or not the orientation has been initialized.
  41781. this.isOrientationInitialized = false;
  41782. // Running estimate of gravity based on the current orientation.
  41783. this.estimatedGravity = new MathUtil.Vector3();
  41784. // Measured gravity based on accelerometer.
  41785. this.measuredGravity = new MathUtil.Vector3();
  41786. // Debug only quaternion of gyro-based orientation.
  41787. this.gyroIntegralQ = new MathUtil.Quaternion();
  41788. }
  41789. ComplementaryFilter.prototype.addAccelMeasurement = function(vector, timestampS) {
  41790. this.currentAccelMeasurement.set(vector, timestampS);
  41791. };
  41792. ComplementaryFilter.prototype.addGyroMeasurement = function(vector, timestampS) {
  41793. this.currentGyroMeasurement.set(vector, timestampS);
  41794. var deltaT = timestampS - this.previousGyroMeasurement.timestampS;
  41795. if (Util.isTimestampDeltaValid(deltaT)) {
  41796. this.run_();
  41797. }
  41798. this.previousGyroMeasurement.copy(this.currentGyroMeasurement);
  41799. };
  41800. ComplementaryFilter.prototype.run_ = function() {
  41801. if (!this.isOrientationInitialized) {
  41802. this.accelQ = this.accelToQuaternion_(this.currentAccelMeasurement.sample);
  41803. this.previousFilterQ.copy(this.accelQ);
  41804. this.isOrientationInitialized = true;
  41805. return;
  41806. }
  41807. var deltaT = this.currentGyroMeasurement.timestampS -
  41808. this.previousGyroMeasurement.timestampS;
  41809. // Convert gyro rotation vector to a quaternion delta.
  41810. var gyroDeltaQ = this.gyroToQuaternionDelta_(this.currentGyroMeasurement.sample, deltaT);
  41811. this.gyroIntegralQ.multiply(gyroDeltaQ);
  41812. // filter_1 = K * (filter_0 + gyro * dT) + (1 - K) * accel.
  41813. this.filterQ.copy(this.previousFilterQ);
  41814. this.filterQ.multiply(gyroDeltaQ);
  41815. // Calculate the delta between the current estimated gravity and the real
  41816. // gravity vector from accelerometer.
  41817. var invFilterQ = new MathUtil.Quaternion();
  41818. invFilterQ.copy(this.filterQ);
  41819. invFilterQ.inverse();
  41820. this.estimatedGravity.set(0, 0, -1);
  41821. this.estimatedGravity.applyQuaternion(invFilterQ);
  41822. this.estimatedGravity.normalize();
  41823. this.measuredGravity.copy(this.currentAccelMeasurement.sample);
  41824. this.measuredGravity.normalize();
  41825. // Compare estimated gravity with measured gravity, get the delta quaternion
  41826. // between the two.
  41827. var deltaQ = new MathUtil.Quaternion();
  41828. deltaQ.setFromUnitVectors(this.estimatedGravity, this.measuredGravity);
  41829. deltaQ.inverse();
  41830. if (Util.isDebug()) {
  41831. console.log('Delta: %d deg, G_est: (%s, %s, %s), G_meas: (%s, %s, %s)',
  41832. MathUtil.radToDeg * Util.getQuaternionAngle(deltaQ),
  41833. (this.estimatedGravity.x).toFixed(1),
  41834. (this.estimatedGravity.y).toFixed(1),
  41835. (this.estimatedGravity.z).toFixed(1),
  41836. (this.measuredGravity.x).toFixed(1),
  41837. (this.measuredGravity.y).toFixed(1),
  41838. (this.measuredGravity.z).toFixed(1));
  41839. }
  41840. // Calculate the SLERP target: current orientation plus the measured-estimated
  41841. // quaternion delta.
  41842. var targetQ = new MathUtil.Quaternion();
  41843. targetQ.copy(this.filterQ);
  41844. targetQ.multiply(deltaQ);
  41845. // SLERP factor: 0 is pure gyro, 1 is pure accel.
  41846. this.filterQ.slerp(targetQ, 1 - this.kFilter);
  41847. this.previousFilterQ.copy(this.filterQ);
  41848. };
  41849. ComplementaryFilter.prototype.getOrientation = function() {
  41850. return this.filterQ;
  41851. };
  41852. ComplementaryFilter.prototype.accelToQuaternion_ = function(accel) {
  41853. var normAccel = new MathUtil.Vector3();
  41854. normAccel.copy(accel);
  41855. normAccel.normalize();
  41856. var quat = new MathUtil.Quaternion();
  41857. quat.setFromUnitVectors(new MathUtil.Vector3(0, 0, -1), normAccel);
  41858. quat.inverse();
  41859. return quat;
  41860. };
  41861. ComplementaryFilter.prototype.gyroToQuaternionDelta_ = function(gyro, dt) {
  41862. // Extract axis and angle from the gyroscope data.
  41863. var quat = new MathUtil.Quaternion();
  41864. var axis = new MathUtil.Vector3();
  41865. axis.copy(gyro);
  41866. axis.normalize();
  41867. quat.setFromAxisAngle(axis, gyro.length() * dt);
  41868. return quat;
  41869. };
  41870. module.exports = ComplementaryFilter;
  41871. },{"../math-util.js":15,"../util.js":23,"./sensor-sample.js":21}],19:[function(_dereq_,module,exports){
  41872. /*
  41873. * Copyright 2015 Google Inc. All Rights Reserved.
  41874. * Licensed under the Apache License, Version 2.0 (the "License");
  41875. * you may not use this file except in compliance with the License.
  41876. * You may obtain a copy of the License at
  41877. *
  41878. * http://www.apache.org/licenses/LICENSE-2.0
  41879. *
  41880. * Unless required by applicable law or agreed to in writing, software
  41881. * distributed under the License is distributed on an "AS IS" BASIS,
  41882. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41883. * See the License for the specific language governing permissions and
  41884. * limitations under the License.
  41885. */
  41886. var ComplementaryFilter = _dereq_('./complementary-filter.js');
  41887. var PosePredictor = _dereq_('./pose-predictor.js');
  41888. var TouchPanner = _dereq_('../touch-panner.js');
  41889. var MathUtil = _dereq_('../math-util.js');
  41890. var Util = _dereq_('../util.js');
  41891. /**
  41892. * The pose sensor, implemented using DeviceMotion APIs.
  41893. */
  41894. function FusionPoseSensor() {
  41895. this.deviceId = 'webvr-polyfill:fused';
  41896. this.deviceName = 'VR Position Device (webvr-polyfill:fused)';
  41897. this.accelerometer = new MathUtil.Vector3();
  41898. this.gyroscope = new MathUtil.Vector3();
  41899. this.start();
  41900. this.filter = new ComplementaryFilter(WebVRConfig.K_FILTER);
  41901. this.posePredictor = new PosePredictor(WebVRConfig.PREDICTION_TIME_S);
  41902. this.touchPanner = new TouchPanner();
  41903. this.filterToWorldQ = new MathUtil.Quaternion();
  41904. // Set the filter to world transform, depending on OS.
  41905. if (Util.isIOS()) {
  41906. this.filterToWorldQ.setFromAxisAngle(new MathUtil.Vector3(1, 0, 0), Math.PI / 2);
  41907. } else {
  41908. this.filterToWorldQ.setFromAxisAngle(new MathUtil.Vector3(1, 0, 0), -Math.PI / 2);
  41909. }
  41910. this.inverseWorldToScreenQ = new MathUtil.Quaternion();
  41911. this.worldToScreenQ = new MathUtil.Quaternion();
  41912. this.originalPoseAdjustQ = new MathUtil.Quaternion();
  41913. this.originalPoseAdjustQ.setFromAxisAngle(new MathUtil.Vector3(0, 0, 1),
  41914. -window.orientation * Math.PI / 180);
  41915. this.setScreenTransform_();
  41916. // Adjust this filter for being in landscape mode.
  41917. if (Util.isLandscapeMode()) {
  41918. this.filterToWorldQ.multiply(this.inverseWorldToScreenQ);
  41919. }
  41920. // Keep track of a reset transform for resetSensor.
  41921. this.resetQ = new MathUtil.Quaternion();
  41922. this.isFirefoxAndroid = Util.isFirefoxAndroid();
  41923. this.isIOS = Util.isIOS();
  41924. this.orientationOut_ = new Float32Array(4);
  41925. }
  41926. FusionPoseSensor.prototype.getPosition = function() {
  41927. // This PoseSensor doesn't support position
  41928. return null;
  41929. };
  41930. FusionPoseSensor.prototype.getOrientation = function() {
  41931. // Convert from filter space to the the same system used by the
  41932. // deviceorientation event.
  41933. var orientation = this.filter.getOrientation();
  41934. // Predict orientation.
  41935. this.predictedQ = this.posePredictor.getPrediction(orientation, this.gyroscope, this.previousTimestampS);
  41936. // Convert to THREE coordinate system: -Z forward, Y up, X right.
  41937. var out = new MathUtil.Quaternion();
  41938. out.copy(this.filterToWorldQ);
  41939. out.multiply(this.resetQ);
  41940. if (!WebVRConfig.TOUCH_PANNER_DISABLED) {
  41941. out.multiply(this.touchPanner.getOrientation());
  41942. }
  41943. out.multiply(this.predictedQ);
  41944. out.multiply(this.worldToScreenQ);
  41945. // Handle the yaw-only case.
  41946. if (WebVRConfig.YAW_ONLY) {
  41947. // Make a quaternion that only turns around the Y-axis.
  41948. out.x = 0;
  41949. out.z = 0;
  41950. out.normalize();
  41951. }
  41952. this.orientationOut_[0] = out.x;
  41953. this.orientationOut_[1] = out.y;
  41954. this.orientationOut_[2] = out.z;
  41955. this.orientationOut_[3] = out.w;
  41956. return this.orientationOut_;
  41957. };
  41958. FusionPoseSensor.prototype.resetPose = function() {
  41959. // Reduce to inverted yaw-only.
  41960. this.resetQ.copy(this.filter.getOrientation());
  41961. this.resetQ.x = 0;
  41962. this.resetQ.y = 0;
  41963. this.resetQ.z *= -1;
  41964. this.resetQ.normalize();
  41965. // Take into account extra transformations in landscape mode.
  41966. if (Util.isLandscapeMode()) {
  41967. this.resetQ.multiply(this.inverseWorldToScreenQ);
  41968. }
  41969. // Take into account original pose.
  41970. this.resetQ.multiply(this.originalPoseAdjustQ);
  41971. if (!WebVRConfig.TOUCH_PANNER_DISABLED) {
  41972. this.touchPanner.resetSensor();
  41973. }
  41974. };
  41975. FusionPoseSensor.prototype.onDeviceMotion_ = function(deviceMotion) {
  41976. this.updateDeviceMotion_(deviceMotion);
  41977. };
  41978. FusionPoseSensor.prototype.updateDeviceMotion_ = function(deviceMotion) {
  41979. var accGravity = deviceMotion.accelerationIncludingGravity;
  41980. var rotRate = deviceMotion.rotationRate;
  41981. var timestampS = deviceMotion.timeStamp / 1000;
  41982. // Firefox Android timeStamp returns one thousandth of a millisecond.
  41983. if (this.isFirefoxAndroid) {
  41984. timestampS /= 1000;
  41985. }
  41986. var deltaS = timestampS - this.previousTimestampS;
  41987. if (deltaS <= Util.MIN_TIMESTEP || deltaS > Util.MAX_TIMESTEP) {
  41988. console.warn('Invalid timestamps detected. Time step between successive ' +
  41989. 'gyroscope sensor samples is very small or not monotonic');
  41990. this.previousTimestampS = timestampS;
  41991. return;
  41992. }
  41993. this.accelerometer.set(-accGravity.x, -accGravity.y, -accGravity.z);
  41994. this.gyroscope.set(rotRate.alpha, rotRate.beta, rotRate.gamma);
  41995. // With iOS and Firefox Android, rotationRate is reported in degrees,
  41996. // so we first convert to radians.
  41997. if (this.isIOS || this.isFirefoxAndroid) {
  41998. this.gyroscope.multiplyScalar(Math.PI / 180);
  41999. }
  42000. this.filter.addAccelMeasurement(this.accelerometer, timestampS);
  42001. this.filter.addGyroMeasurement(this.gyroscope, timestampS);
  42002. this.previousTimestampS = timestampS;
  42003. };
  42004. FusionPoseSensor.prototype.onOrientationChange_ = function(screenOrientation) {
  42005. this.setScreenTransform_();
  42006. };
  42007. /**
  42008. * This is only needed if we are in an cross origin iframe on iOS to work around
  42009. * this issue: https://bugs.webkit.org/show_bug.cgi?id=152299.
  42010. */
  42011. FusionPoseSensor.prototype.onMessage_ = function(event) {
  42012. var message = event.data;
  42013. // If there's no message type, ignore it.
  42014. if (!message || !message.type) {
  42015. return;
  42016. }
  42017. // Ignore all messages that aren't devicemotion.
  42018. var type = message.type.toLowerCase();
  42019. if (type !== 'devicemotion') {
  42020. return;
  42021. }
  42022. // Update device motion.
  42023. this.updateDeviceMotion_(message.deviceMotionEvent);
  42024. };
  42025. FusionPoseSensor.prototype.setScreenTransform_ = function() {
  42026. this.worldToScreenQ.set(0, 0, 0, 1);
  42027. switch (window.orientation) {
  42028. case 0:
  42029. break;
  42030. case 90:
  42031. this.worldToScreenQ.setFromAxisAngle(new MathUtil.Vector3(0, 0, 1), -Math.PI / 2);
  42032. break;
  42033. case -90:
  42034. this.worldToScreenQ.setFromAxisAngle(new MathUtil.Vector3(0, 0, 1), Math.PI / 2);
  42035. break;
  42036. case 180:
  42037. // TODO.
  42038. break;
  42039. }
  42040. this.inverseWorldToScreenQ.copy(this.worldToScreenQ);
  42041. this.inverseWorldToScreenQ.inverse();
  42042. };
  42043. FusionPoseSensor.prototype.start = function() {
  42044. this.onDeviceMotionCallback_ = this.onDeviceMotion_.bind(this);
  42045. this.onOrientationChangeCallback_ = this.onOrientationChange_.bind(this);
  42046. this.onMessageCallback_ = this.onMessage_.bind(this);
  42047. // Only listen for postMessages if we're in an iOS and embedded inside a cross
  42048. // domain IFrame. In this case, the polyfill can still work if the containing
  42049. // page sends synthetic devicemotion events. For an example of this, see
  42050. // iframe-message-sender.js in VR View: https://goo.gl/XDtvFZ
  42051. if (Util.isIOS() && Util.isInsideCrossDomainIFrame()) {
  42052. window.addEventListener('message', this.onMessageCallback_);
  42053. }
  42054. window.addEventListener('orientationchange', this.onOrientationChangeCallback_);
  42055. window.addEventListener('devicemotion', this.onDeviceMotionCallback_);
  42056. };
  42057. FusionPoseSensor.prototype.stop = function() {
  42058. window.removeEventListener('devicemotion', this.onDeviceMotionCallback_);
  42059. window.removeEventListener('orientationchange', this.onOrientationChangeCallback_);
  42060. window.removeEventListener('message', this.onMessageCallback_);
  42061. };
  42062. module.exports = FusionPoseSensor;
  42063. },{"../math-util.js":15,"../touch-panner.js":22,"../util.js":23,"./complementary-filter.js":18,"./pose-predictor.js":20}],20:[function(_dereq_,module,exports){
  42064. /*
  42065. * Copyright 2015 Google Inc. All Rights Reserved.
  42066. * Licensed under the Apache License, Version 2.0 (the "License");
  42067. * you may not use this file except in compliance with the License.
  42068. * You may obtain a copy of the License at
  42069. *
  42070. * http://www.apache.org/licenses/LICENSE-2.0
  42071. *
  42072. * Unless required by applicable law or agreed to in writing, software
  42073. * distributed under the License is distributed on an "AS IS" BASIS,
  42074. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  42075. * See the License for the specific language governing permissions and
  42076. * limitations under the License.
  42077. */
  42078. var MathUtil = _dereq_('../math-util');
  42079. var Util = _dereq_('../util');
  42080. /**
  42081. * Given an orientation and the gyroscope data, predicts the future orientation
  42082. * of the head. This makes rendering appear faster.
  42083. *
  42084. * Also see: http://msl.cs.uiuc.edu/~lavalle/papers/LavYerKatAnt14.pdf
  42085. *
  42086. * @param {Number} predictionTimeS time from head movement to the appearance of
  42087. * the corresponding image.
  42088. */
  42089. function PosePredictor(predictionTimeS) {
  42090. this.predictionTimeS = predictionTimeS;
  42091. // The quaternion corresponding to the previous state.
  42092. this.previousQ = new MathUtil.Quaternion();
  42093. // Previous time a prediction occurred.
  42094. this.previousTimestampS = null;
  42095. // The delta quaternion that adjusts the current pose.
  42096. this.deltaQ = new MathUtil.Quaternion();
  42097. // The output quaternion.
  42098. this.outQ = new MathUtil.Quaternion();
  42099. }
  42100. PosePredictor.prototype.getPrediction = function(currentQ, gyro, timestampS) {
  42101. if (!this.previousTimestampS) {
  42102. this.previousQ.copy(currentQ);
  42103. this.previousTimestampS = timestampS;
  42104. return currentQ;
  42105. }
  42106. // Calculate axis and angle based on gyroscope rotation rate data.
  42107. var axis = new MathUtil.Vector3();
  42108. axis.copy(gyro);
  42109. axis.normalize();
  42110. var angularSpeed = gyro.length();
  42111. // If we're rotating slowly, don't do prediction.
  42112. if (angularSpeed < MathUtil.degToRad * 20) {
  42113. if (Util.isDebug()) {
  42114. console.log('Moving slowly, at %s deg/s: no prediction',
  42115. (MathUtil.radToDeg * angularSpeed).toFixed(1));
  42116. }
  42117. this.outQ.copy(currentQ);
  42118. this.previousQ.copy(currentQ);
  42119. return this.outQ;
  42120. }
  42121. // Get the predicted angle based on the time delta and latency.
  42122. var deltaT = timestampS - this.previousTimestampS;
  42123. var predictAngle = angularSpeed * this.predictionTimeS;
  42124. this.deltaQ.setFromAxisAngle(axis, predictAngle);
  42125. this.outQ.copy(this.previousQ);
  42126. this.outQ.multiply(this.deltaQ);
  42127. this.previousQ.copy(currentQ);
  42128. this.previousTimestampS = timestampS;
  42129. return this.outQ;
  42130. };
  42131. module.exports = PosePredictor;
  42132. },{"../math-util":15,"../util":23}],21:[function(_dereq_,module,exports){
  42133. function SensorSample(sample, timestampS) {
  42134. this.set(sample, timestampS);
  42135. };
  42136. SensorSample.prototype.set = function(sample, timestampS) {
  42137. this.sample = sample;
  42138. this.timestampS = timestampS;
  42139. };
  42140. SensorSample.prototype.copy = function(sensorSample) {
  42141. this.set(sensorSample.sample, sensorSample.timestampS);
  42142. };
  42143. module.exports = SensorSample;
  42144. },{}],22:[function(_dereq_,module,exports){
  42145. /*
  42146. * Copyright 2015 Google Inc. All Rights Reserved.
  42147. * Licensed under the Apache License, Version 2.0 (the "License");
  42148. * you may not use this file except in compliance with the License.
  42149. * You may obtain a copy of the License at
  42150. *
  42151. * http://www.apache.org/licenses/LICENSE-2.0
  42152. *
  42153. * Unless required by applicable law or agreed to in writing, software
  42154. * distributed under the License is distributed on an "AS IS" BASIS,
  42155. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  42156. * See the License for the specific language governing permissions and
  42157. * limitations under the License.
  42158. */
  42159. var MathUtil = _dereq_('./math-util.js');
  42160. var Util = _dereq_('./util.js');
  42161. var ROTATE_SPEED = 0.5;
  42162. /**
  42163. * Provides a quaternion responsible for pre-panning the scene before further
  42164. * transformations due to device sensors.
  42165. */
  42166. function TouchPanner() {
  42167. window.addEventListener('touchstart', this.onTouchStart_.bind(this));
  42168. window.addEventListener('touchmove', this.onTouchMove_.bind(this));
  42169. window.addEventListener('touchend', this.onTouchEnd_.bind(this));
  42170. this.isTouching = false;
  42171. this.rotateStart = new MathUtil.Vector2();
  42172. this.rotateEnd = new MathUtil.Vector2();
  42173. this.rotateDelta = new MathUtil.Vector2();
  42174. this.theta = 0;
  42175. this.orientation = new MathUtil.Quaternion();
  42176. }
  42177. TouchPanner.prototype.getOrientation = function() {
  42178. this.orientation.setFromEulerXYZ(0, 0, this.theta);
  42179. return this.orientation;
  42180. };
  42181. TouchPanner.prototype.resetSensor = function() {
  42182. this.theta = 0;
  42183. };
  42184. TouchPanner.prototype.onTouchStart_ = function(e) {
  42185. // Only respond if there is exactly one touch.
  42186. if (e.touches.length != 1) {
  42187. return;
  42188. }
  42189. this.rotateStart.set(e.touches[0].pageX, e.touches[0].pageY);
  42190. this.isTouching = true;
  42191. };
  42192. TouchPanner.prototype.onTouchMove_ = function(e) {
  42193. if (!this.isTouching) {
  42194. return;
  42195. }
  42196. this.rotateEnd.set(e.touches[0].pageX, e.touches[0].pageY);
  42197. this.rotateDelta.subVectors(this.rotateEnd, this.rotateStart);
  42198. this.rotateStart.copy(this.rotateEnd);
  42199. // On iOS, direction is inverted.
  42200. if (Util.isIOS()) {
  42201. this.rotateDelta.x *= -1;
  42202. }
  42203. var element = document.body;
  42204. this.theta += 2 * Math.PI * this.rotateDelta.x / element.clientWidth * ROTATE_SPEED;
  42205. };
  42206. TouchPanner.prototype.onTouchEnd_ = function(e) {
  42207. this.isTouching = false;
  42208. };
  42209. module.exports = TouchPanner;
  42210. },{"./math-util.js":15,"./util.js":23}],23:[function(_dereq_,module,exports){
  42211. /*
  42212. * Copyright 2015 Google Inc. All Rights Reserved.
  42213. * Licensed under the Apache License, Version 2.0 (the "License");
  42214. * you may not use this file except in compliance with the License.
  42215. * You may obtain a copy of the License at
  42216. *
  42217. * http://www.apache.org/licenses/LICENSE-2.0
  42218. *
  42219. * Unless required by applicable law or agreed to in writing, software
  42220. * distributed under the License is distributed on an "AS IS" BASIS,
  42221. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  42222. * See the License for the specific language governing permissions and
  42223. * limitations under the License.
  42224. */
  42225. var objectAssign = _dereq_('object-assign');
  42226. var Util = window.Util || {};
  42227. Util.MIN_TIMESTEP = 0.001;
  42228. Util.MAX_TIMESTEP = 1;
  42229. Util.base64 = function(mimeType, base64) {
  42230. return 'data:' + mimeType + ';base64,' + base64;
  42231. };
  42232. Util.clamp = function(value, min, max) {
  42233. return Math.min(Math.max(min, value), max);
  42234. };
  42235. Util.lerp = function(a, b, t) {
  42236. return a + ((b - a) * t);
  42237. };
  42238. Util.isIOS = (function() {
  42239. var isIOS = /iPad|iPhone|iPod/.test(navigator.platform);
  42240. return function() {
  42241. return isIOS;
  42242. };
  42243. })();
  42244. Util.isWebViewAndroid = (function() {
  42245. var isWebViewAndroid = navigator.userAgent.indexOf('Version') !== -1 &&
  42246. navigator.userAgent.indexOf('Android') !== -1 &&
  42247. navigator.userAgent.indexOf('Chrome') !== -1;
  42248. return function() {
  42249. return isWebViewAndroid;
  42250. };
  42251. })();
  42252. Util.isSafari = (function() {
  42253. var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  42254. return function() {
  42255. return isSafari;
  42256. };
  42257. })();
  42258. Util.isFirefoxAndroid = (function() {
  42259. var isFirefoxAndroid = navigator.userAgent.indexOf('Firefox') !== -1 &&
  42260. navigator.userAgent.indexOf('Android') !== -1;
  42261. return function() {
  42262. return isFirefoxAndroid;
  42263. };
  42264. })();
  42265. Util.isLandscapeMode = function() {
  42266. return (window.orientation == 90 || window.orientation == -90);
  42267. };
  42268. // Helper method to validate the time steps of sensor timestamps.
  42269. Util.isTimestampDeltaValid = function(timestampDeltaS) {
  42270. if (isNaN(timestampDeltaS)) {
  42271. return false;
  42272. }
  42273. if (timestampDeltaS <= Util.MIN_TIMESTEP) {
  42274. return false;
  42275. }
  42276. if (timestampDeltaS > Util.MAX_TIMESTEP) {
  42277. return false;
  42278. }
  42279. return true;
  42280. };
  42281. Util.getScreenWidth = function() {
  42282. return Math.max(window.screen.width, window.screen.height) *
  42283. window.devicePixelRatio;
  42284. };
  42285. Util.getScreenHeight = function() {
  42286. return Math.min(window.screen.width, window.screen.height) *
  42287. window.devicePixelRatio;
  42288. };
  42289. Util.requestFullscreen = function(element) {
  42290. if (Util.isWebViewAndroid()) {
  42291. return false;
  42292. }
  42293. if (element.requestFullscreen) {
  42294. element.requestFullscreen();
  42295. } else if (element.webkitRequestFullscreen) {
  42296. element.webkitRequestFullscreen();
  42297. } else if (element.mozRequestFullScreen) {
  42298. element.mozRequestFullScreen();
  42299. } else if (element.msRequestFullscreen) {
  42300. element.msRequestFullscreen();
  42301. } else {
  42302. return false;
  42303. }
  42304. return true;
  42305. };
  42306. Util.exitFullscreen = function() {
  42307. if (document.exitFullscreen) {
  42308. document.exitFullscreen();
  42309. } else if (document.webkitExitFullscreen) {
  42310. document.webkitExitFullscreen();
  42311. } else if (document.mozCancelFullScreen) {
  42312. document.mozCancelFullScreen();
  42313. } else if (document.msExitFullscreen) {
  42314. document.msExitFullscreen();
  42315. } else {
  42316. return false;
  42317. }
  42318. return true;
  42319. };
  42320. Util.getFullscreenElement = function() {
  42321. return document.fullscreenElement ||
  42322. document.webkitFullscreenElement ||
  42323. document.mozFullScreenElement ||
  42324. document.msFullscreenElement;
  42325. };
  42326. Util.linkProgram = function(gl, vertexSource, fragmentSource, attribLocationMap) {
  42327. // No error checking for brevity.
  42328. var vertexShader = gl.createShader(gl.VERTEX_SHADER);
  42329. gl.shaderSource(vertexShader, vertexSource);
  42330. gl.compileShader(vertexShader);
  42331. var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
  42332. gl.shaderSource(fragmentShader, fragmentSource);
  42333. gl.compileShader(fragmentShader);
  42334. var program = gl.createProgram();
  42335. gl.attachShader(program, vertexShader);
  42336. gl.attachShader(program, fragmentShader);
  42337. for (var attribName in attribLocationMap)
  42338. gl.bindAttribLocation(program, attribLocationMap[attribName], attribName);
  42339. gl.linkProgram(program);
  42340. gl.deleteShader(vertexShader);
  42341. gl.deleteShader(fragmentShader);
  42342. return program;
  42343. };
  42344. Util.getProgramUniforms = function(gl, program) {
  42345. var uniforms = {};
  42346. var uniformCount = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  42347. var uniformName = '';
  42348. for (var i = 0; i < uniformCount; i++) {
  42349. var uniformInfo = gl.getActiveUniform(program, i);
  42350. uniformName = uniformInfo.name.replace('[0]', '');
  42351. uniforms[uniformName] = gl.getUniformLocation(program, uniformName);
  42352. }
  42353. return uniforms;
  42354. };
  42355. Util.orthoMatrix = function (out, left, right, bottom, top, near, far) {
  42356. var lr = 1 / (left - right),
  42357. bt = 1 / (bottom - top),
  42358. nf = 1 / (near - far);
  42359. out[0] = -2 * lr;
  42360. out[1] = 0;
  42361. out[2] = 0;
  42362. out[3] = 0;
  42363. out[4] = 0;
  42364. out[5] = -2 * bt;
  42365. out[6] = 0;
  42366. out[7] = 0;
  42367. out[8] = 0;
  42368. out[9] = 0;
  42369. out[10] = 2 * nf;
  42370. out[11] = 0;
  42371. out[12] = (left + right) * lr;
  42372. out[13] = (top + bottom) * bt;
  42373. out[14] = (far + near) * nf;
  42374. out[15] = 1;
  42375. return out;
  42376. };
  42377. Util.isMobile = function() {
  42378. var check = false;
  42379. (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);
  42380. return check;
  42381. };
  42382. Util.extend = objectAssign;
  42383. Util.safariCssSizeWorkaround = function(canvas) {
  42384. // TODO(smus): Remove this workaround when Safari for iOS is fixed.
  42385. // iOS only workaround (for https://bugs.webkit.org/show_bug.cgi?id=152556).
  42386. //
  42387. // "To the last I grapple with thee;
  42388. // from hell's heart I stab at thee;
  42389. // for hate's sake I spit my last breath at thee."
  42390. // -- Moby Dick, by Herman Melville
  42391. if (Util.isIOS()) {
  42392. var width = canvas.style.width;
  42393. var height = canvas.style.height;
  42394. canvas.style.width = (parseInt(width) + 1) + 'px';
  42395. canvas.style.height = (parseInt(height)) + 'px';
  42396. setTimeout(function() {
  42397. canvas.style.width = width;
  42398. canvas.style.height = height;
  42399. }, 100);
  42400. }
  42401. // Debug only.
  42402. window.Util = Util;
  42403. window.canvas = canvas;
  42404. };
  42405. Util.isDebug = function() {
  42406. return Util.getQueryParameter('debug');
  42407. };
  42408. Util.getQueryParameter = function(name) {
  42409. var name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  42410. var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
  42411. results = regex.exec(location.search);
  42412. return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  42413. };
  42414. Util.frameDataFromPose = (function() {
  42415. var piOver180 = Math.PI / 180.0;
  42416. var rad45 = Math.PI * 0.25;
  42417. // Borrowed from glMatrix.
  42418. function mat4_perspectiveFromFieldOfView(out, fov, near, far) {
  42419. var upTan = Math.tan(fov ? (fov.upDegrees * piOver180) : rad45),
  42420. downTan = Math.tan(fov ? (fov.downDegrees * piOver180) : rad45),
  42421. leftTan = Math.tan(fov ? (fov.leftDegrees * piOver180) : rad45),
  42422. rightTan = Math.tan(fov ? (fov.rightDegrees * piOver180) : rad45),
  42423. xScale = 2.0 / (leftTan + rightTan),
  42424. yScale = 2.0 / (upTan + downTan);
  42425. out[0] = xScale;
  42426. out[1] = 0.0;
  42427. out[2] = 0.0;
  42428. out[3] = 0.0;
  42429. out[4] = 0.0;
  42430. out[5] = yScale;
  42431. out[6] = 0.0;
  42432. out[7] = 0.0;
  42433. out[8] = -((leftTan - rightTan) * xScale * 0.5);
  42434. out[9] = ((upTan - downTan) * yScale * 0.5);
  42435. out[10] = far / (near - far);
  42436. out[11] = -1.0;
  42437. out[12] = 0.0;
  42438. out[13] = 0.0;
  42439. out[14] = (far * near) / (near - far);
  42440. out[15] = 0.0;
  42441. return out;
  42442. }
  42443. function mat4_fromRotationTranslation(out, q, v) {
  42444. // Quaternion math
  42445. var x = q[0], y = q[1], z = q[2], w = q[3],
  42446. x2 = x + x,
  42447. y2 = y + y,
  42448. z2 = z + z,
  42449. xx = x * x2,
  42450. xy = x * y2,
  42451. xz = x * z2,
  42452. yy = y * y2,
  42453. yz = y * z2,
  42454. zz = z * z2,
  42455. wx = w * x2,
  42456. wy = w * y2,
  42457. wz = w * z2;
  42458. out[0] = 1 - (yy + zz);
  42459. out[1] = xy + wz;
  42460. out[2] = xz - wy;
  42461. out[3] = 0;
  42462. out[4] = xy - wz;
  42463. out[5] = 1 - (xx + zz);
  42464. out[6] = yz + wx;
  42465. out[7] = 0;
  42466. out[8] = xz + wy;
  42467. out[9] = yz - wx;
  42468. out[10] = 1 - (xx + yy);
  42469. out[11] = 0;
  42470. out[12] = v[0];
  42471. out[13] = v[1];
  42472. out[14] = v[2];
  42473. out[15] = 1;
  42474. return out;
  42475. };
  42476. function mat4_translate(out, a, v) {
  42477. var x = v[0], y = v[1], z = v[2],
  42478. a00, a01, a02, a03,
  42479. a10, a11, a12, a13,
  42480. a20, a21, a22, a23;
  42481. if (a === out) {
  42482. out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
  42483. out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
  42484. out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
  42485. out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
  42486. } else {
  42487. a00 = a[0]; a01 = a[1]; a02 = a[2]; a03 = a[3];
  42488. a10 = a[4]; a11 = a[5]; a12 = a[6]; a13 = a[7];
  42489. a20 = a[8]; a21 = a[9]; a22 = a[10]; a23 = a[11];
  42490. out[0] = a00; out[1] = a01; out[2] = a02; out[3] = a03;
  42491. out[4] = a10; out[5] = a11; out[6] = a12; out[7] = a13;
  42492. out[8] = a20; out[9] = a21; out[10] = a22; out[11] = a23;
  42493. out[12] = a00 * x + a10 * y + a20 * z + a[12];
  42494. out[13] = a01 * x + a11 * y + a21 * z + a[13];
  42495. out[14] = a02 * x + a12 * y + a22 * z + a[14];
  42496. out[15] = a03 * x + a13 * y + a23 * z + a[15];
  42497. }
  42498. return out;
  42499. };
  42500. function mat4_invert(out, a) {
  42501. var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3],
  42502. a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7],
  42503. a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11],
  42504. a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15],
  42505. b00 = a00 * a11 - a01 * a10,
  42506. b01 = a00 * a12 - a02 * a10,
  42507. b02 = a00 * a13 - a03 * a10,
  42508. b03 = a01 * a12 - a02 * a11,
  42509. b04 = a01 * a13 - a03 * a11,
  42510. b05 = a02 * a13 - a03 * a12,
  42511. b06 = a20 * a31 - a21 * a30,
  42512. b07 = a20 * a32 - a22 * a30,
  42513. b08 = a20 * a33 - a23 * a30,
  42514. b09 = a21 * a32 - a22 * a31,
  42515. b10 = a21 * a33 - a23 * a31,
  42516. b11 = a22 * a33 - a23 * a32,
  42517. // Calculate the determinant
  42518. det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  42519. if (!det) {
  42520. return null;
  42521. }
  42522. det = 1.0 / det;
  42523. out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
  42524. out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
  42525. out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
  42526. out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
  42527. out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
  42528. out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
  42529. out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
  42530. out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
  42531. out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
  42532. out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
  42533. out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
  42534. out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
  42535. out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
  42536. out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
  42537. out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
  42538. out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
  42539. return out;
  42540. };
  42541. var defaultOrientation = new Float32Array([0, 0, 0, 1]);
  42542. var defaultPosition = new Float32Array([0, 0, 0]);
  42543. function updateEyeMatrices(projection, view, pose, parameters, vrDisplay) {
  42544. mat4_perspectiveFromFieldOfView(projection, parameters ? parameters.fieldOfView : null, vrDisplay.depthNear, vrDisplay.depthFar);
  42545. var orientation = pose.orientation || defaultOrientation;
  42546. var position = pose.position || defaultPosition;
  42547. mat4_fromRotationTranslation(view, orientation, position);
  42548. if (parameters)
  42549. mat4_translate(view, view, parameters.offset);
  42550. mat4_invert(view, view);
  42551. }
  42552. return function(frameData, pose, vrDisplay) {
  42553. if (!frameData || !pose)
  42554. return false;
  42555. frameData.pose = pose;
  42556. frameData.timestamp = pose.timestamp;
  42557. updateEyeMatrices(
  42558. frameData.leftProjectionMatrix, frameData.leftViewMatrix,
  42559. pose, vrDisplay.getEyeParameters("left"), vrDisplay);
  42560. updateEyeMatrices(
  42561. frameData.rightProjectionMatrix, frameData.rightViewMatrix,
  42562. pose, vrDisplay.getEyeParameters("right"), vrDisplay);
  42563. return true;
  42564. };
  42565. })();
  42566. Util.isInsideCrossDomainIFrame = function() {
  42567. var isFramed = (window.self !== window.top);
  42568. var refDomain = Util.getDomainFromUrl(document.referrer);
  42569. var thisDomain = Util.getDomainFromUrl(window.location.href);
  42570. return isFramed && (refDomain !== thisDomain);
  42571. };
  42572. // From http://stackoverflow.com/a/23945027.
  42573. Util.getDomainFromUrl = function(url) {
  42574. var domain;
  42575. // Find & remove protocol (http, ftp, etc.) and get domain.
  42576. if (url.indexOf("://") > -1) {
  42577. domain = url.split('/')[2];
  42578. }
  42579. else {
  42580. domain = url.split('/')[0];
  42581. }
  42582. //find & remove port number
  42583. domain = domain.split(':')[0];
  42584. return domain;
  42585. }
  42586. module.exports = Util;
  42587. },{"object-assign":2}],24:[function(_dereq_,module,exports){
  42588. /*
  42589. * Copyright 2015 Google Inc. All Rights Reserved.
  42590. * Licensed under the Apache License, Version 2.0 (the "License");
  42591. * you may not use this file except in compliance with the License.
  42592. * You may obtain a copy of the License at
  42593. *
  42594. * http://www.apache.org/licenses/LICENSE-2.0
  42595. *
  42596. * Unless required by applicable law or agreed to in writing, software
  42597. * distributed under the License is distributed on an "AS IS" BASIS,
  42598. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  42599. * See the License for the specific language governing permissions and
  42600. * limitations under the License.
  42601. */
  42602. var DeviceInfo = _dereq_('./device-info.js');
  42603. var EventEmitter3 = _dereq_('eventemitter3');
  42604. var Util = _dereq_('./util.js');
  42605. var DEFAULT_VIEWER = 'CardboardV1';
  42606. var VIEWER_KEY = 'WEBVR_CARDBOARD_VIEWER';
  42607. var CLASS_NAME = 'webvr-polyfill-viewer-selector';
  42608. /**
  42609. * Creates a viewer selector with the options specified. Supports being shown
  42610. * and hidden. Generates events when viewer parameters change. Also supports
  42611. * saving the currently selected index in localStorage.
  42612. */
  42613. function ViewerSelector() {
  42614. // Try to load the selected key from local storage. If none exists, use the
  42615. // default key.
  42616. try {
  42617. this.selectedKey = localStorage.getItem(VIEWER_KEY) || DEFAULT_VIEWER;
  42618. } catch (error) {
  42619. console.error('Failed to load viewer profile: %s', error);
  42620. }
  42621. this.dialog = this.createDialog_(DeviceInfo.Viewers);
  42622. this.root = null;
  42623. }
  42624. ViewerSelector.prototype = new EventEmitter3();
  42625. ViewerSelector.prototype.show = function(root) {
  42626. this.root = root;
  42627. root.appendChild(this.dialog);
  42628. // Ensure the currently selected item is checked.
  42629. var selected = this.dialog.querySelector('#' + this.selectedKey);
  42630. selected.checked = true;
  42631. // Show the UI.
  42632. this.dialog.style.display = 'block';
  42633. };
  42634. ViewerSelector.prototype.hide = function() {
  42635. if (this.root && this.root.contains(this.dialog)) {
  42636. this.root.removeChild(this.dialog);
  42637. }
  42638. this.dialog.style.display = 'none';
  42639. };
  42640. ViewerSelector.prototype.getCurrentViewer = function() {
  42641. return DeviceInfo.Viewers[this.selectedKey];
  42642. };
  42643. ViewerSelector.prototype.getSelectedKey_ = function() {
  42644. var input = this.dialog.querySelector('input[name=field]:checked');
  42645. if (input) {
  42646. return input.id;
  42647. }
  42648. return null;
  42649. };
  42650. ViewerSelector.prototype.onSave_ = function() {
  42651. this.selectedKey = this.getSelectedKey_();
  42652. if (!this.selectedKey || !DeviceInfo.Viewers[this.selectedKey]) {
  42653. console.error('ViewerSelector.onSave_: this should never happen!');
  42654. return;
  42655. }
  42656. this.emit('change', DeviceInfo.Viewers[this.selectedKey]);
  42657. // Attempt to save the viewer profile, but fails in private mode.
  42658. try {
  42659. localStorage.setItem(VIEWER_KEY, this.selectedKey);
  42660. } catch(error) {
  42661. console.error('Failed to save viewer profile: %s', error);
  42662. }
  42663. this.hide();
  42664. };
  42665. /**
  42666. * Creates the dialog.
  42667. */
  42668. ViewerSelector.prototype.createDialog_ = function(options) {
  42669. var container = document.createElement('div');
  42670. container.classList.add(CLASS_NAME);
  42671. container.style.display = 'none';
  42672. // Create an overlay that dims the background, and which goes away when you
  42673. // tap it.
  42674. var overlay = document.createElement('div');
  42675. var s = overlay.style;
  42676. s.position = 'fixed';
  42677. s.left = 0;
  42678. s.top = 0;
  42679. s.width = '100%';
  42680. s.height = '100%';
  42681. s.background = 'rgba(0, 0, 0, 0.3)';
  42682. overlay.addEventListener('click', this.hide.bind(this));
  42683. var width = 280;
  42684. var dialog = document.createElement('div');
  42685. var s = dialog.style;
  42686. s.boxSizing = 'border-box';
  42687. s.position = 'fixed';
  42688. s.top = '24px';
  42689. s.left = '50%';
  42690. s.marginLeft = (-width/2) + 'px';
  42691. s.width = width + 'px';
  42692. s.padding = '24px';
  42693. s.overflow = 'hidden';
  42694. s.background = '#fafafa';
  42695. s.fontFamily = "'Roboto', sans-serif";
  42696. s.boxShadow = '0px 5px 20px #666';
  42697. dialog.appendChild(this.createH1_('Select your viewer'));
  42698. for (var id in options) {
  42699. dialog.appendChild(this.createChoice_(id, options[id].label));
  42700. }
  42701. dialog.appendChild(this.createButton_('Save', this.onSave_.bind(this)));
  42702. container.appendChild(overlay);
  42703. container.appendChild(dialog);
  42704. return container;
  42705. };
  42706. ViewerSelector.prototype.createH1_ = function(name) {
  42707. var h1 = document.createElement('h1');
  42708. var s = h1.style;
  42709. s.color = 'black';
  42710. s.fontSize = '20px';
  42711. s.fontWeight = 'bold';
  42712. s.marginTop = 0;
  42713. s.marginBottom = '24px';
  42714. h1.innerHTML = name;
  42715. return h1;
  42716. };
  42717. ViewerSelector.prototype.createChoice_ = function(id, name) {
  42718. /*
  42719. <div class="choice">
  42720. <input id="v1" type="radio" name="field" value="v1">
  42721. <label for="v1">Cardboard V1</label>
  42722. </div>
  42723. */
  42724. var div = document.createElement('div');
  42725. div.style.marginTop = '8px';
  42726. div.style.color = 'black';
  42727. var input = document.createElement('input');
  42728. input.style.fontSize = '30px';
  42729. input.setAttribute('id', id);
  42730. input.setAttribute('type', 'radio');
  42731. input.setAttribute('value', id);
  42732. input.setAttribute('name', 'field');
  42733. var label = document.createElement('label');
  42734. label.style.marginLeft = '4px';
  42735. label.setAttribute('for', id);
  42736. label.innerHTML = name;
  42737. div.appendChild(input);
  42738. div.appendChild(label);
  42739. return div;
  42740. };
  42741. ViewerSelector.prototype.createButton_ = function(label, onclick) {
  42742. var button = document.createElement('button');
  42743. button.innerHTML = label;
  42744. var s = button.style;
  42745. s.float = 'right';
  42746. s.textTransform = 'uppercase';
  42747. s.color = '#1094f7';
  42748. s.fontSize = '14px';
  42749. s.letterSpacing = 0;
  42750. s.border = 0;
  42751. s.background = 'none';
  42752. s.marginTop = '16px';
  42753. button.addEventListener('click', onclick);
  42754. return button;
  42755. };
  42756. module.exports = ViewerSelector;
  42757. },{"./device-info.js":8,"./util.js":23,"eventemitter3":1}],25:[function(_dereq_,module,exports){
  42758. /*
  42759. * Copyright 2015 Google Inc. All Rights Reserved.
  42760. * Licensed under the Apache License, Version 2.0 (the "License");
  42761. * you may not use this file except in compliance with the License.
  42762. * You may obtain a copy of the License at
  42763. *
  42764. * http://www.apache.org/licenses/LICENSE-2.0
  42765. *
  42766. * Unless required by applicable law or agreed to in writing, software
  42767. * distributed under the License is distributed on an "AS IS" BASIS,
  42768. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  42769. * See the License for the specific language governing permissions and
  42770. * limitations under the License.
  42771. */
  42772. var Util = _dereq_('./util.js');
  42773. /**
  42774. * Android and iOS compatible wakelock implementation.
  42775. *
  42776. * Refactored thanks to dkovalev@.
  42777. */
  42778. function AndroidWakeLock() {
  42779. var video = document.createElement('video');
  42780. video.addEventListener('ended', function() {
  42781. video.play();
  42782. });
  42783. this.request = function() {
  42784. if (video.paused) {
  42785. // Base64 version of videos_src/no-sleep-120s.mp4.
  42786. video.src = Util.base64('video/mp4', 'AAAAGGZ0eXBpc29tAAAAAG1wNDFhdmMxAAAIA21vb3YAAABsbXZoZAAAAADSa9v60mvb+gABX5AAlw/gAAEAAAEAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAdkdHJhawAAAFx0a2hkAAAAAdJr2/rSa9v6AAAAAQAAAAAAlw/gAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAQAAAAHAAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAJcP4AAAAAAAAQAAAAAG3G1kaWEAAAAgbWRoZAAAAADSa9v60mvb+gAPQkAGjneAFccAAAAAAC1oZGxyAAAAAAAAAAB2aWRlAAAAAAAAAAAAAAAAVmlkZW9IYW5kbGVyAAAABodtaW5mAAAAFHZtaGQAAAABAAAAAAAAAAAAAAAkZGluZgAAABxkcmVmAAAAAAAAAAEAAAAMdXJsIAAAAAEAAAZHc3RibAAAAJdzdHNkAAAAAAAAAAEAAACHYXZjMQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAMABwASAAAAEgAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABj//wAAADFhdmNDAWQAC//hABlnZAALrNlfllw4QAAAAwBAAAADAKPFCmWAAQAFaOvssiwAAAAYc3R0cwAAAAAAAAABAAAAbgAPQkAAAAAUc3RzcwAAAAAAAAABAAAAAQAAA4BjdHRzAAAAAAAAAG4AAAABAD0JAAAAAAEAehIAAAAAAQA9CQAAAAABAAAAAAAAAAEAD0JAAAAAAQBMS0AAAAABAB6EgAAAAAEAAAAAAAAAAQAPQkAAAAABAExLQAAAAAEAHoSAAAAAAQAAAAAAAAABAA9CQAAAAAEATEtAAAAAAQAehIAAAAABAAAAAAAAAAEAD0JAAAAAAQBMS0AAAAABAB6EgAAAAAEAAAAAAAAAAQAPQkAAAAABAExLQAAAAAEAHoSAAAAAAQAAAAAAAAABAA9CQAAAAAEATEtAAAAAAQAehIAAAAABAAAAAAAAAAEAD0JAAAAAAQBMS0AAAAABAB6EgAAAAAEAAAAAAAAAAQAPQkAAAAABAExLQAAAAAEAHoSAAAAAAQAAAAAAAAABAA9CQAAAAAEATEtAAAAAAQAehIAAAAABAAAAAAAAAAEAD0JAAAAAAQBMS0AAAAABAB6EgAAAAAEAAAAAAAAAAQAPQkAAAAABAExLQAAAAAEAHoSAAAAAAQAAAAAAAAABAA9CQAAAAAEATEtAAAAAAQAehIAAAAABAAAAAAAAAAEAD0JAAAAAAQBMS0AAAAABAB6EgAAAAAEAAAAAAAAAAQAPQkAAAAABAExLQAAAAAEAHoSAAAAAAQAAAAAAAAABAA9CQAAAAAEATEtAAAAAAQAehIAAAAABAAAAAAAAAAEAD0JAAAAAAQBMS0AAAAABAB6EgAAAAAEAAAAAAAAAAQAPQkAAAAABAExLQAAAAAEAHoSAAAAAAQAAAAAAAAABAA9CQAAAAAEATEtAAAAAAQAehIAAAAABAAAAAAAAAAEAD0JAAAAAAQBMS0AAAAABAB6EgAAAAAEAAAAAAAAAAQAPQkAAAAABAExLQAAAAAEAHoSAAAAAAQAAAAAAAAABAA9CQAAAAAEATEtAAAAAAQAehIAAAAABAAAAAAAAAAEAD0JAAAAAAQBMS0AAAAABAB6EgAAAAAEAAAAAAAAAAQAPQkAAAAABAExLQAAAAAEAHoSAAAAAAQAAAAAAAAABAA9CQAAAAAEATEtAAAAAAQAehIAAAAABAAAAAAAAAAEAD0JAAAAAAQBMS0AAAAABAB6EgAAAAAEAAAAAAAAAAQAPQkAAAAABAExLQAAAAAEAHoSAAAAAAQAAAAAAAAABAA9CQAAAAAEALcbAAAAAHHN0c2MAAAAAAAAAAQAAAAEAAABuAAAAAQAAAcxzdHN6AAAAAAAAAAAAAABuAAADCQAAABgAAAAOAAAADgAAAAwAAAASAAAADgAAAAwAAAAMAAAAEgAAAA4AAAAMAAAADAAAABIAAAAOAAAADAAAAAwAAAASAAAADgAAAAwAAAAMAAAAEgAAAA4AAAAMAAAADAAAABIAAAAOAAAADAAAAAwAAAASAAAADgAAAAwAAAAMAAAAEgAAAA4AAAAMAAAADAAAABIAAAAOAAAADAAAAAwAAAASAAAADgAAAAwAAAAMAAAAEgAAAA4AAAAMAAAADAAAABIAAAAOAAAADAAAAAwAAAASAAAADgAAAAwAAAAMAAAAEgAAAA4AAAAMAAAADAAAABIAAAAOAAAADAAAAAwAAAASAAAADgAAAAwAAAAMAAAAEgAAAA4AAAAMAAAADAAAABIAAAAOAAAADAAAAAwAAAASAAAADgAAAAwAAAAMAAAAEgAAAA4AAAAMAAAADAAAABIAAAAOAAAADAAAAAwAAAASAAAADgAAAAwAAAAMAAAAEgAAAA4AAAAMAAAADAAAABIAAAAOAAAADAAAAAwAAAASAAAADgAAAAwAAAAMAAAAEgAAAA4AAAAMAAAADAAAABMAAAAUc3RjbwAAAAAAAAABAAAIKwAAACt1ZHRhAAAAI6llbmMAFwAAdmxjIDIuMi4xIHN0cmVhbSBvdXRwdXQAAAAId2lkZQAACRRtZGF0AAACrgX//6vcRem95tlIt5Ys2CDZI+7veDI2NCAtIGNvcmUgMTQyIC0gSC4yNjQvTVBFRy00IEFWQyBjb2RlYyAtIENvcHlsZWZ0IDIwMDMtMjAxNCAtIGh0dHA6Ly93d3cudmlkZW9sYW4ub3JnL3gyNjQuaHRtbCAtIG9wdGlvbnM6IGNhYmFjPTEgcmVmPTMgZGVibG9jaz0xOjA6MCBhbmFseXNlPTB4MzoweDEzIG1lPWhleCBzdWJtZT03IHBzeT0xIHBzeV9yZD0xLjAwOjAuMDAgbWl4ZWRfcmVmPTEgbWVfcmFuZ2U9MTYgY2hyb21hX21lPTEgdHJlbGxpcz0xIDh4OGRjdD0xIGNxbT0wIGRlYWR6b25lPTIxLDExIGZhc3RfcHNraXA9MSBjaHJvbWFfcXBfb2Zmc2V0PS0yIHRocmVhZHM9MTIgbG9va2FoZWFkX3RocmVhZHM9MSBzbGljZWRfdGhyZWFkcz0wIG5yPTAgZGVjaW1hdGU9MSBpbnRlcmxhY2VkPTAgYmx1cmF5X2NvbXBhdD0wIGNvbnN0cmFpbmVkX2ludHJhPTAgYmZyYW1lcz0zIGJfcHlyYW1pZD0yIGJfYWRhcHQ9MSBiX2JpYXM9MCBkaXJlY3Q9MSB3ZWlnaHRiPTEgb3Blbl9nb3A9MCB3ZWlnaHRwPTIga2V5aW50PTI1MCBrZXlpbnRfbWluPTEgc2NlbmVjdXQ9NDAgaW50cmFfcmVmcmVzaD0wIHJjX2xvb2thaGVhZD00MCByYz1hYnIgbWJ0cmVlPTEgYml0cmF0ZT0xMDAgcmF0ZXRvbD0xLjAgcWNvbXA9MC42MCBxcG1pbj0xMCBxcG1heD01MSBxcHN0ZXA9NCBpcF9yYXRpbz0xLjQwIGFxPTE6MS4wMACAAAAAU2WIhAAQ/8ltlOe+cTZuGkKg+aRtuivcDZ0pBsfsEi9p/i1yU9DxS2lq4dXTinViF1URBKXgnzKBd/Uh1bkhHtMrwrRcOJslD01UB+fyaL6ef+DBAAAAFEGaJGxBD5B+v+a+4QqF3MgBXz9MAAAACkGeQniH/+94r6EAAAAKAZ5hdEN/8QytwAAAAAgBnmNqQ3/EgQAAAA5BmmhJqEFomUwIIf/+4QAAAApBnoZFESw//76BAAAACAGepXRDf8SBAAAACAGep2pDf8SAAAAADkGarEmoQWyZTAgh//7gAAAACkGeykUVLD//voEAAAAIAZ7pdEN/xIAAAAAIAZ7rakN/xIAAAAAOQZrwSahBbJlMCCH//uEAAAAKQZ8ORRUsP/++gQAAAAgBny10Q3/EgQAAAAgBny9qQ3/EgAAAAA5BmzRJqEFsmUwIIf/+4AAAAApBn1JFFSw//76BAAAACAGfcXRDf8SAAAAACAGfc2pDf8SAAAAADkGbeEmoQWyZTAgh//7hAAAACkGflkUVLD//voAAAAAIAZ+1dEN/xIEAAAAIAZ+3akN/xIEAAAAOQZu8SahBbJlMCCH//uAAAAAKQZ/aRRUsP/++gQAAAAgBn/l0Q3/EgAAAAAgBn/tqQ3/EgQAAAA5Bm+BJqEFsmUwIIf/+4QAAAApBnh5FFSw//76AAAAACAGePXRDf8SAAAAACAGeP2pDf8SBAAAADkGaJEmoQWyZTAgh//7gAAAACkGeQkUVLD//voEAAAAIAZ5hdEN/xIAAAAAIAZ5jakN/xIEAAAAOQZpoSahBbJlMCCH//uEAAAAKQZ6GRRUsP/++gQAAAAgBnqV0Q3/EgQAAAAgBnqdqQ3/EgAAAAA5BmqxJqEFsmUwIIf/+4AAAAApBnspFFSw//76BAAAACAGe6XRDf8SAAAAACAGe62pDf8SAAAAADkGa8EmoQWyZTAgh//7hAAAACkGfDkUVLD//voEAAAAIAZ8tdEN/xIEAAAAIAZ8vakN/xIAAAAAOQZs0SahBbJlMCCH//uAAAAAKQZ9SRRUsP/++gQAAAAgBn3F0Q3/EgAAAAAgBn3NqQ3/EgAAAAA5Bm3hJqEFsmUwIIf/+4QAAAApBn5ZFFSw//76AAAAACAGftXRDf8SBAAAACAGft2pDf8SBAAAADkGbvEmoQWyZTAgh//7gAAAACkGf2kUVLD//voEAAAAIAZ/5dEN/xIAAAAAIAZ/7akN/xIEAAAAOQZvgSahBbJlMCCH//uEAAAAKQZ4eRRUsP/++gAAAAAgBnj10Q3/EgAAAAAgBnj9qQ3/EgQAAAA5BmiRJqEFsmUwIIf/+4AAAAApBnkJFFSw//76BAAAACAGeYXRDf8SAAAAACAGeY2pDf8SBAAAADkGaaEmoQWyZTAgh//7hAAAACkGehkUVLD//voEAAAAIAZ6ldEN/xIEAAAAIAZ6nakN/xIAAAAAOQZqsSahBbJlMCCH//uAAAAAKQZ7KRRUsP/++gQAAAAgBnul0Q3/EgAAAAAgBnutqQ3/EgAAAAA5BmvBJqEFsmUwIIf/+4QAAAApBnw5FFSw//76BAAAACAGfLXRDf8SBAAAACAGfL2pDf8SAAAAADkGbNEmoQWyZTAgh//7gAAAACkGfUkUVLD//voEAAAAIAZ9xdEN/xIAAAAAIAZ9zakN/xIAAAAAOQZt4SahBbJlMCCH//uEAAAAKQZ+WRRUsP/++gAAAAAgBn7V0Q3/EgQAAAAgBn7dqQ3/EgQAAAA5Bm7xJqEFsmUwIIf/+4AAAAApBn9pFFSw//76BAAAACAGf+XRDf8SAAAAACAGf+2pDf8SBAAAADkGb4EmoQWyZTAgh//7hAAAACkGeHkUVLD//voAAAAAIAZ49dEN/xIAAAAAIAZ4/akN/xIEAAAAOQZokSahBbJlMCCH//uAAAAAKQZ5CRRUsP/++gQAAAAgBnmF0Q3/EgAAAAAgBnmNqQ3/EgQAAAA5BmmhJqEFsmUwIIf/+4QAAAApBnoZFFSw//76BAAAACAGepXRDf8SBAAAACAGep2pDf8SAAAAADkGarEmoQWyZTAgh//7gAAAACkGeykUVLD//voEAAAAIAZ7pdEN/xIAAAAAIAZ7rakN/xIAAAAAPQZruSahBbJlMFEw3//7B');
  42787. video.play();
  42788. }
  42789. };
  42790. this.release = function() {
  42791. video.pause();
  42792. video.src = '';
  42793. };
  42794. }
  42795. function iOSWakeLock() {
  42796. var timer = null;
  42797. this.request = function() {
  42798. if (!timer) {
  42799. timer = setInterval(function() {
  42800. window.location = window.location;
  42801. setTimeout(window.stop, 0);
  42802. }, 30000);
  42803. }
  42804. }
  42805. this.release = function() {
  42806. if (timer) {
  42807. clearInterval(timer);
  42808. timer = null;
  42809. }
  42810. }
  42811. }
  42812. function getWakeLock() {
  42813. var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  42814. if (userAgent.match(/iPhone/i) || userAgent.match(/iPod/i)) {
  42815. return iOSWakeLock;
  42816. } else {
  42817. return AndroidWakeLock;
  42818. }
  42819. }
  42820. module.exports = getWakeLock();
  42821. },{"./util.js":23}],26:[function(_dereq_,module,exports){
  42822. /*
  42823. * Copyright 2015 Google Inc. All Rights Reserved.
  42824. * Licensed under the Apache License, Version 2.0 (the "License");
  42825. * you may not use this file except in compliance with the License.
  42826. * You may obtain a copy of the License at
  42827. *
  42828. * http://www.apache.org/licenses/LICENSE-2.0
  42829. *
  42830. * Unless required by applicable law or agreed to in writing, software
  42831. * distributed under the License is distributed on an "AS IS" BASIS,
  42832. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  42833. * See the License for the specific language governing permissions and
  42834. * limitations under the License.
  42835. */
  42836. var Util = _dereq_('./util.js');
  42837. var CardboardVRDisplay = _dereq_('./cardboard-vr-display.js');
  42838. var MouseKeyboardVRDisplay = _dereq_('./mouse-keyboard-vr-display.js');
  42839. // Uncomment to add positional tracking via webcam.
  42840. //var WebcamPositionSensorVRDevice = require('./webcam-position-sensor-vr-device.js');
  42841. var VRDisplay = _dereq_('./base.js').VRDisplay;
  42842. var VRFrameData = _dereq_('./base.js').VRFrameData;
  42843. var HMDVRDevice = _dereq_('./base.js').HMDVRDevice;
  42844. var PositionSensorVRDevice = _dereq_('./base.js').PositionSensorVRDevice;
  42845. var VRDisplayHMDDevice = _dereq_('./display-wrappers.js').VRDisplayHMDDevice;
  42846. var VRDisplayPositionSensorDevice = _dereq_('./display-wrappers.js').VRDisplayPositionSensorDevice;
  42847. function WebVRPolyfill() {
  42848. this.displays = [];
  42849. this.devices = []; // For deprecated objects
  42850. this.devicesPopulated = false;
  42851. this.nativeWebVRAvailable = this.isWebVRAvailable();
  42852. this.nativeLegacyWebVRAvailable = this.isDeprecatedWebVRAvailable();
  42853. this.nativeGetVRDisplaysFunc = this.nativeWebVRAvailable ?
  42854. navigator.getVRDisplays :
  42855. null;
  42856. if (!this.nativeLegacyWebVRAvailable) {
  42857. this.enablePolyfill();
  42858. if (WebVRConfig.ENABLE_DEPRECATED_API) {
  42859. this.enableDeprecatedPolyfill();
  42860. }
  42861. }
  42862. // Put a shim in place to update the API to 1.1 if needed.
  42863. InstallWebVRSpecShim();
  42864. }
  42865. WebVRPolyfill.prototype.isWebVRAvailable = function() {
  42866. return ('getVRDisplays' in navigator);
  42867. };
  42868. WebVRPolyfill.prototype.isDeprecatedWebVRAvailable = function() {
  42869. return ('getVRDevices' in navigator) || ('mozGetVRDevices' in navigator);
  42870. };
  42871. WebVRPolyfill.prototype.populateDevices = function() {
  42872. if (this.devicesPopulated) {
  42873. return;
  42874. }
  42875. // Initialize our virtual VR devices.
  42876. var vrDisplay = null;
  42877. // Add a Cardboard VRDisplay on compatible mobile devices
  42878. if (this.isCardboardCompatible()) {
  42879. vrDisplay = new CardboardVRDisplay();
  42880. this.displays.push(vrDisplay);
  42881. // For backwards compatibility
  42882. if (WebVRConfig.ENABLE_DEPRECATED_API) {
  42883. this.devices.push(new VRDisplayHMDDevice(vrDisplay));
  42884. this.devices.push(new VRDisplayPositionSensorDevice(vrDisplay));
  42885. }
  42886. }
  42887. // Add a Mouse and Keyboard driven VRDisplay for desktops/laptops
  42888. if (!this.isMobile() && !WebVRConfig.MOUSE_KEYBOARD_CONTROLS_DISABLED) {
  42889. vrDisplay = new MouseKeyboardVRDisplay();
  42890. this.displays.push(vrDisplay);
  42891. // For backwards compatibility
  42892. if (WebVRConfig.ENABLE_DEPRECATED_API) {
  42893. this.devices.push(new VRDisplayHMDDevice(vrDisplay));
  42894. this.devices.push(new VRDisplayPositionSensorDevice(vrDisplay));
  42895. }
  42896. }
  42897. // Uncomment to add positional tracking via webcam.
  42898. //if (!this.isMobile() && WebVRConfig.ENABLE_DEPRECATED_API) {
  42899. // positionDevice = new WebcamPositionSensorVRDevice();
  42900. // this.devices.push(positionDevice);
  42901. //}
  42902. this.devicesPopulated = true;
  42903. };
  42904. WebVRPolyfill.prototype.enablePolyfill = function() {
  42905. // Provide navigator.getVRDisplays.
  42906. navigator.getVRDisplays = this.getVRDisplays.bind(this);
  42907. // Provide the VRDisplay object.
  42908. window.VRDisplay = VRDisplay;
  42909. // Provide navigator.vrEnabled.
  42910. var self = this;
  42911. Object.defineProperty(navigator, 'vrEnabled', {
  42912. get: function () {
  42913. return self.isCardboardCompatible() &&
  42914. (self.isFullScreenAvailable() || Util.isIOS());
  42915. }
  42916. });
  42917. if (!'VRFrameData' in window) {
  42918. // Provide the VRFrameData object.
  42919. window.VRFrameData = VRFrameData;
  42920. }
  42921. };
  42922. WebVRPolyfill.prototype.enableDeprecatedPolyfill = function() {
  42923. // Provide navigator.getVRDevices.
  42924. navigator.getVRDevices = this.getVRDevices.bind(this);
  42925. // Provide the CardboardHMDVRDevice and PositionSensorVRDevice objects.
  42926. window.HMDVRDevice = HMDVRDevice;
  42927. window.PositionSensorVRDevice = PositionSensorVRDevice;
  42928. };
  42929. WebVRPolyfill.prototype.getVRDisplays = function() {
  42930. this.populateDevices();
  42931. var polyfillDisplays = this.displays;
  42932. if (this.nativeWebVRAvailable) {
  42933. return this.nativeGetVRDisplaysFunc.call(navigator).then(function(nativeDisplays) {
  42934. if (WebVRConfig.ALWAYS_APPEND_POLYFILL_DISPLAY) {
  42935. return nativeDisplays.concat(polyfillDisplays);
  42936. } else {
  42937. return nativeDisplays.length > 0 ? nativeDisplays : polyfillDisplays;
  42938. }
  42939. });
  42940. } else {
  42941. return new Promise(function(resolve, reject) {
  42942. try {
  42943. resolve(polyfillDisplays);
  42944. } catch (e) {
  42945. reject(e);
  42946. }
  42947. });
  42948. }
  42949. };
  42950. WebVRPolyfill.prototype.getVRDevices = function() {
  42951. console.warn('getVRDevices is deprecated. Please update your code to use getVRDisplays instead.');
  42952. var self = this;
  42953. return new Promise(function(resolve, reject) {
  42954. try {
  42955. if (!self.devicesPopulated) {
  42956. if (self.nativeWebVRAvailable) {
  42957. return navigator.getVRDisplays(function(displays) {
  42958. for (var i = 0; i < displays.length; ++i) {
  42959. self.devices.push(new VRDisplayHMDDevice(displays[i]));
  42960. self.devices.push(new VRDisplayPositionSensorDevice(displays[i]));
  42961. }
  42962. self.devicesPopulated = true;
  42963. resolve(self.devices);
  42964. }, reject);
  42965. }
  42966. if (self.nativeLegacyWebVRAvailable) {
  42967. return (navigator.getVRDDevices || navigator.mozGetVRDevices)(function(devices) {
  42968. for (var i = 0; i < devices.length; ++i) {
  42969. if (devices[i] instanceof HMDVRDevice) {
  42970. self.devices.push(devices[i]);
  42971. }
  42972. if (devices[i] instanceof PositionSensorVRDevice) {
  42973. self.devices.push(devices[i]);
  42974. }
  42975. }
  42976. self.devicesPopulated = true;
  42977. resolve(self.devices);
  42978. }, reject);
  42979. }
  42980. }
  42981. self.populateDevices();
  42982. resolve(self.devices);
  42983. } catch (e) {
  42984. reject(e);
  42985. }
  42986. });
  42987. };
  42988. /**
  42989. * Determine if a device is mobile.
  42990. */
  42991. WebVRPolyfill.prototype.isMobile = function() {
  42992. return /Android/i.test(navigator.userAgent) ||
  42993. /iPhone|iPad|iPod/i.test(navigator.userAgent);
  42994. };
  42995. WebVRPolyfill.prototype.isCardboardCompatible = function() {
  42996. // For now, support all iOS and Android devices.
  42997. // Also enable the WebVRConfig.FORCE_VR flag for debugging.
  42998. return this.isMobile() || WebVRConfig.FORCE_ENABLE_VR;
  42999. };
  43000. WebVRPolyfill.prototype.isFullScreenAvailable = function() {
  43001. return (document.fullscreenEnabled ||
  43002. document.mozFullScreenEnabled ||
  43003. document.webkitFullscreenEnabled ||
  43004. false);
  43005. };
  43006. // Installs a shim that updates a WebVR 1.0 spec implementation to WebVR 1.1
  43007. function InstallWebVRSpecShim() {
  43008. if ('VRDisplay' in window && !('VRFrameData' in window)) {
  43009. // Provide the VRFrameData object.
  43010. window.VRFrameData = VRFrameData;
  43011. // A lot of Chrome builds don't have depthNear and depthFar, even
  43012. // though they're in the WebVR 1.0 spec. Patch them in if they're not present.
  43013. if(!('depthNear' in window.VRDisplay.prototype)) {
  43014. window.VRDisplay.prototype.depthNear = 0.01;
  43015. }
  43016. if(!('depthFar' in window.VRDisplay.prototype)) {
  43017. window.VRDisplay.prototype.depthFar = 10000.0;
  43018. }
  43019. window.VRDisplay.prototype.getFrameData = function(frameData) {
  43020. return Util.frameDataFromPose(frameData, this.getPose(), this);
  43021. }
  43022. }
  43023. };
  43024. module.exports.WebVRPolyfill = WebVRPolyfill;
  43025. },{"./base.js":3,"./cardboard-vr-display.js":6,"./display-wrappers.js":9,"./mouse-keyboard-vr-display.js":16,"./util.js":23}]},{},[14])(14)
  43026. });
  43027. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  43028. },{}],50:[function(_dereq_,module,exports){
  43029. var newline = /\n/
  43030. var newlineChar = '\n'
  43031. var whitespace = /\s/
  43032. module.exports = function(text, opt) {
  43033. var lines = module.exports.lines(text, opt)
  43034. return lines.map(function(line) {
  43035. return text.substring(line.start, line.end)
  43036. }).join('\n')
  43037. }
  43038. module.exports.lines = function wordwrap(text, opt) {
  43039. opt = opt||{}
  43040. //zero width results in nothing visible
  43041. if (opt.width === 0 && opt.mode !== 'nowrap')
  43042. return []
  43043. text = text||''
  43044. var width = typeof opt.width === 'number' ? opt.width : Number.MAX_VALUE
  43045. var start = Math.max(0, opt.start||0)
  43046. var end = typeof opt.end === 'number' ? opt.end : text.length
  43047. var mode = opt.mode
  43048. var measure = opt.measure || monospace
  43049. if (mode === 'pre')
  43050. return pre(measure, text, start, end, width)
  43051. else
  43052. return greedy(measure, text, start, end, width, mode)
  43053. }
  43054. function idxOf(text, chr, start, end) {
  43055. var idx = text.indexOf(chr, start)
  43056. if (idx === -1 || idx > end)
  43057. return end
  43058. return idx
  43059. }
  43060. function isWhitespace(chr) {
  43061. return whitespace.test(chr)
  43062. }
  43063. function pre(measure, text, start, end, width) {
  43064. var lines = []
  43065. var lineStart = start
  43066. for (var i=start; i<end && i<text.length; i++) {
  43067. var chr = text.charAt(i)
  43068. var isNewline = newline.test(chr)
  43069. //If we've reached a newline, then step down a line
  43070. //Or if we've reached the EOF
  43071. if (isNewline || i===end-1) {
  43072. var lineEnd = isNewline ? i : i+1
  43073. var measured = measure(text, lineStart, lineEnd, width)
  43074. lines.push(measured)
  43075. lineStart = i+1
  43076. }
  43077. }
  43078. return lines
  43079. }
  43080. function greedy(measure, text, start, end, width, mode) {
  43081. //A greedy word wrapper based on LibGDX algorithm
  43082. //https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/BitmapFontCache.java
  43083. var lines = []
  43084. var testWidth = width
  43085. //if 'nowrap' is specified, we only wrap on newline chars
  43086. if (mode === 'nowrap')
  43087. testWidth = Number.MAX_VALUE
  43088. while (start < end && start < text.length) {
  43089. //get next newline position
  43090. var newLine = idxOf(text, newlineChar, start, end)
  43091. //eat whitespace at start of line
  43092. while (start < newLine) {
  43093. if (!isWhitespace( text.charAt(start) ))
  43094. break
  43095. start++
  43096. }
  43097. //determine visible # of glyphs for the available width
  43098. var measured = measure(text, start, newLine, testWidth)
  43099. var lineEnd = start + (measured.end-measured.start)
  43100. var nextStart = lineEnd + newlineChar.length
  43101. //if we had to cut the line before the next newline...
  43102. if (lineEnd < newLine) {
  43103. //find char to break on
  43104. while (lineEnd > start) {
  43105. if (isWhitespace(text.charAt(lineEnd)))
  43106. break
  43107. lineEnd--
  43108. }
  43109. if (lineEnd === start) {
  43110. if (nextStart > start + newlineChar.length) nextStart--
  43111. lineEnd = nextStart // If no characters to break, show all.
  43112. } else {
  43113. nextStart = lineEnd
  43114. //eat whitespace at end of line
  43115. while (lineEnd > start) {
  43116. if (!isWhitespace(text.charAt(lineEnd - newlineChar.length)))
  43117. break
  43118. lineEnd--
  43119. }
  43120. }
  43121. }
  43122. if (lineEnd >= start) {
  43123. var result = measure(text, start, lineEnd, testWidth)
  43124. lines.push(result)
  43125. }
  43126. start = nextStart
  43127. }
  43128. return lines
  43129. }
  43130. //determines the visible number of glyphs within a given width
  43131. function monospace(text, start, end, width) {
  43132. var glyphs = Math.min(width, end-start)
  43133. return {
  43134. start: start,
  43135. end: start+glyphs
  43136. }
  43137. }
  43138. },{}],51:[function(_dereq_,module,exports){
  43139. "use strict";
  43140. var window = _dereq_("global/window")
  43141. var isFunction = _dereq_("is-function")
  43142. var parseHeaders = _dereq_("parse-headers")
  43143. var xtend = _dereq_("xtend")
  43144. module.exports = createXHR
  43145. createXHR.XMLHttpRequest = window.XMLHttpRequest || noop
  43146. createXHR.XDomainRequest = "withCredentials" in (new createXHR.XMLHttpRequest()) ? createXHR.XMLHttpRequest : window.XDomainRequest
  43147. forEachArray(["get", "put", "post", "patch", "head", "delete"], function(method) {
  43148. createXHR[method === "delete" ? "del" : method] = function(uri, options, callback) {
  43149. options = initParams(uri, options, callback)
  43150. options.method = method.toUpperCase()
  43151. return _createXHR(options)
  43152. }
  43153. })
  43154. function forEachArray(array, iterator) {
  43155. for (var i = 0; i < array.length; i++) {
  43156. iterator(array[i])
  43157. }
  43158. }
  43159. function isEmpty(obj){
  43160. for(var i in obj){
  43161. if(obj.hasOwnProperty(i)) return false
  43162. }
  43163. return true
  43164. }
  43165. function initParams(uri, options, callback) {
  43166. var params = uri
  43167. if (isFunction(options)) {
  43168. callback = options
  43169. if (typeof uri === "string") {
  43170. params = {uri:uri}
  43171. }
  43172. } else {
  43173. params = xtend(options, {uri: uri})
  43174. }
  43175. params.callback = callback
  43176. return params
  43177. }
  43178. function createXHR(uri, options, callback) {
  43179. options = initParams(uri, options, callback)
  43180. return _createXHR(options)
  43181. }
  43182. function _createXHR(options) {
  43183. if(typeof options.callback === "undefined"){
  43184. throw new Error("callback argument missing")
  43185. }
  43186. var called = false
  43187. var callback = function cbOnce(err, response, body){
  43188. if(!called){
  43189. called = true
  43190. options.callback(err, response, body)
  43191. }
  43192. }
  43193. function readystatechange() {
  43194. if (xhr.readyState === 4) {
  43195. loadFunc()
  43196. }
  43197. }
  43198. function getBody() {
  43199. // Chrome with requestType=blob throws errors arround when even testing access to responseText
  43200. var body = undefined
  43201. if (xhr.response) {
  43202. body = xhr.response
  43203. } else {
  43204. body = xhr.responseText || getXml(xhr)
  43205. }
  43206. if (isJson) {
  43207. try {
  43208. body = JSON.parse(body)
  43209. } catch (e) {}
  43210. }
  43211. return body
  43212. }
  43213. function errorFunc(evt) {
  43214. clearTimeout(timeoutTimer)
  43215. if(!(evt instanceof Error)){
  43216. evt = new Error("" + (evt || "Unknown XMLHttpRequest Error") )
  43217. }
  43218. evt.statusCode = 0
  43219. return callback(evt, failureResponse)
  43220. }
  43221. // will load the data & process the response in a special response object
  43222. function loadFunc() {
  43223. if (aborted) return
  43224. var status
  43225. clearTimeout(timeoutTimer)
  43226. if(options.useXDR && xhr.status===undefined) {
  43227. //IE8 CORS GET successful response doesn't have a status field, but body is fine
  43228. status = 200
  43229. } else {
  43230. status = (xhr.status === 1223 ? 204 : xhr.status)
  43231. }
  43232. var response = failureResponse
  43233. var err = null
  43234. if (status !== 0){
  43235. response = {
  43236. body: getBody(),
  43237. statusCode: status,
  43238. method: method,
  43239. headers: {},
  43240. url: uri,
  43241. rawRequest: xhr
  43242. }
  43243. if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE
  43244. response.headers = parseHeaders(xhr.getAllResponseHeaders())
  43245. }
  43246. } else {
  43247. err = new Error("Internal XMLHttpRequest Error")
  43248. }
  43249. return callback(err, response, response.body)
  43250. }
  43251. var xhr = options.xhr || null
  43252. if (!xhr) {
  43253. if (options.cors || options.useXDR) {
  43254. xhr = new createXHR.XDomainRequest()
  43255. }else{
  43256. xhr = new createXHR.XMLHttpRequest()
  43257. }
  43258. }
  43259. var key
  43260. var aborted
  43261. var uri = xhr.url = options.uri || options.url
  43262. var method = xhr.method = options.method || "GET"
  43263. var body = options.body || options.data
  43264. var headers = xhr.headers = options.headers || {}
  43265. var sync = !!options.sync
  43266. var isJson = false
  43267. var timeoutTimer
  43268. var failureResponse = {
  43269. body: undefined,
  43270. headers: {},
  43271. statusCode: 0,
  43272. method: method,
  43273. url: uri,
  43274. rawRequest: xhr
  43275. }
  43276. if ("json" in options && options.json !== false) {
  43277. isJson = true
  43278. headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json") //Don't override existing accept header declared by user
  43279. if (method !== "GET" && method !== "HEAD") {
  43280. headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json") //Don't override existing accept header declared by user
  43281. body = JSON.stringify(options.json === true ? body : options.json)
  43282. }
  43283. }
  43284. xhr.onreadystatechange = readystatechange
  43285. xhr.onload = loadFunc
  43286. xhr.onerror = errorFunc
  43287. // IE9 must have onprogress be set to a unique function.
  43288. xhr.onprogress = function () {
  43289. // IE must die
  43290. }
  43291. xhr.onabort = function(){
  43292. aborted = true;
  43293. }
  43294. xhr.ontimeout = errorFunc
  43295. xhr.open(method, uri, !sync, options.username, options.password)
  43296. //has to be after open
  43297. if(!sync) {
  43298. xhr.withCredentials = !!options.withCredentials
  43299. }
  43300. // Cannot set timeout with sync request
  43301. // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly
  43302. // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent
  43303. if (!sync && options.timeout > 0 ) {
  43304. timeoutTimer = setTimeout(function(){
  43305. if (aborted) return
  43306. aborted = true//IE9 may still call readystatechange
  43307. xhr.abort("timeout")
  43308. var e = new Error("XMLHttpRequest timeout")
  43309. e.code = "ETIMEDOUT"
  43310. errorFunc(e)
  43311. }, options.timeout )
  43312. }
  43313. if (xhr.setRequestHeader) {
  43314. for(key in headers){
  43315. if(headers.hasOwnProperty(key)){
  43316. xhr.setRequestHeader(key, headers[key])
  43317. }
  43318. }
  43319. } else if (options.headers && !isEmpty(options.headers)) {
  43320. throw new Error("Headers cannot be set on an XDomainRequest object")
  43321. }
  43322. if ("responseType" in options) {
  43323. xhr.responseType = options.responseType
  43324. }
  43325. if ("beforeSend" in options &&
  43326. typeof options.beforeSend === "function"
  43327. ) {
  43328. options.beforeSend(xhr)
  43329. }
  43330. // Microsoft Edge browser sends "undefined" when send is called with undefined value.
  43331. // XMLHttpRequest spec says to pass null as body to indicate no body
  43332. // See https://github.com/naugtur/xhr/issues/100.
  43333. xhr.send(body || null)
  43334. return xhr
  43335. }
  43336. function getXml(xhr) {
  43337. if (xhr.responseType === "document") {
  43338. return xhr.responseXML
  43339. }
  43340. var firefoxBugTakenEffect = xhr.status === 204 && xhr.responseXML && xhr.responseXML.documentElement.nodeName === "parsererror"
  43341. if (xhr.responseType === "" && !firefoxBugTakenEffect) {
  43342. return xhr.responseXML
  43343. }
  43344. return null
  43345. }
  43346. function noop() {}
  43347. },{"global/window":14,"is-function":19,"parse-headers":30,"xtend":53}],52:[function(_dereq_,module,exports){
  43348. module.exports = (function xmlparser() {
  43349. //common browsers
  43350. if (typeof window.DOMParser !== 'undefined') {
  43351. return function(str) {
  43352. var parser = new window.DOMParser()
  43353. return parser.parseFromString(str, 'application/xml')
  43354. }
  43355. }
  43356. //IE8 fallback
  43357. if (typeof window.ActiveXObject !== 'undefined'
  43358. && new window.ActiveXObject('Microsoft.XMLDOM')) {
  43359. return function(str) {
  43360. var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM")
  43361. xmlDoc.async = "false"
  43362. xmlDoc.loadXML(str)
  43363. return xmlDoc
  43364. }
  43365. }
  43366. //last resort fallback
  43367. return function(str) {
  43368. var div = document.createElement('div')
  43369. div.innerHTML = str
  43370. return div
  43371. }
  43372. })()
  43373. },{}],53:[function(_dereq_,module,exports){
  43374. module.exports = extend
  43375. var hasOwnProperty = Object.prototype.hasOwnProperty;
  43376. function extend() {
  43377. var target = {}
  43378. for (var i = 0; i < arguments.length; i++) {
  43379. var source = arguments[i]
  43380. for (var key in source) {
  43381. if (hasOwnProperty.call(source, key)) {
  43382. target[key] = source[key]
  43383. }
  43384. }
  43385. }
  43386. return target
  43387. }
  43388. },{}],54:[function(_dereq_,module,exports){
  43389. module.exports={
  43390. "name": "aframe",
  43391. "version": "0.5.0",
  43392. "description": "A web framework for building virtual reality experiences.",
  43393. "homepage": "https://aframe.io/",
  43394. "main": "dist/aframe-master.js",
  43395. "scripts": {
  43396. "browserify": "browserify src/index.js -s 'AFRAME' -p browserify-derequire",
  43397. "build": "shx mkdir -p build/ && npm run browserify -- --debug -t [envify --INSPECTOR_VERSION dev] -o build/aframe.js",
  43398. "codecov": "codecov",
  43399. "dev": "npm run build && cross-env INSPECTOR_VERSION=dev node ./scripts/budo -t envify",
  43400. "dist": "node scripts/updateVersionLog.js && npm run dist:min && npm run dist:max",
  43401. "dist:max": "npm run browserify -s -- --debug | exorcist dist/aframe-master.js.map > dist/aframe-master.js",
  43402. "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",
  43403. "docs": "markserv --dir docs --port 9001",
  43404. "preghpages": "node ./scripts/preghpages.js",
  43405. "ghpages": "ghpages -p gh-pages/",
  43406. "lint": "semistandard -v | snazzy",
  43407. "lint:fix": "semistandard --fix",
  43408. "precommit": "npm run lint",
  43409. "prerelease": "npm run dist && node scripts/release.js 0.4.0 0.5.0",
  43410. "start": "npm run dev",
  43411. "test": "karma start ./tests/karma.conf.js",
  43412. "test:docs": "node scripts/docsLint.js",
  43413. "test:firefox": "npm test -- --browsers Firefox",
  43414. "test:chrome": "npm test -- --browsers Chrome",
  43415. "test:node": "mocha --ui tdd tests/node"
  43416. },
  43417. "repository": "aframevr/aframe",
  43418. "license": "MIT",
  43419. "dependencies": {
  43420. "browserify-css": "^0.8.2",
  43421. "debug": "ngokevin/debug#noTimestamp",
  43422. "deep-assign": "^2.0.0",
  43423. "document-register-element": "dmarcos/document-register-element#8ccc532b7",
  43424. "envify": "^3.4.1",
  43425. "load-bmfont": "^1.2.3",
  43426. "object-assign": "^4.0.1",
  43427. "present": "0.0.6",
  43428. "promise-polyfill": "^3.1.0",
  43429. "style-attr": "^1.0.2",
  43430. "three": "^0.84.0",
  43431. "three-bmfont-text": "^2.1.0",
  43432. "tween.js": "^15.0.0",
  43433. "webvr-polyfill": "dmarcos/webvr-polyfill#a02a8089b"
  43434. },
  43435. "devDependencies": {
  43436. "browserify": "^13.1.0",
  43437. "browserify-derequire": "^0.9.4",
  43438. "browserify-istanbul": "^2.0.0",
  43439. "budo": "^9.2.0",
  43440. "chai": "^3.5.0",
  43441. "chai-shallow-deep-equal": "^1.4.0",
  43442. "chalk": "^1.1.3",
  43443. "codecov": "^1.0.1",
  43444. "cross-env": "^4.0.0",
  43445. "exorcist": "^0.4.0",
  43446. "ghpages": "0.0.8",
  43447. "git-rev": "^0.2.1",
  43448. "glob": "^7.1.1",
  43449. "husky": "^0.11.7",
  43450. "istanbul": "^0.4.5",
  43451. "jsdom": "^9.11.0",
  43452. "karma": "1.4.1",
  43453. "karma-browserify": "^5.1.0",
  43454. "karma-chai-shallow-deep-equal": "0.0.4",
  43455. "karma-chrome-launcher": "^2.0.0",
  43456. "karma-coverage": "^1.1.1",
  43457. "karma-env-preprocessor": "^0.1.1",
  43458. "karma-firefox-launcher": "^1.0.0",
  43459. "karma-mocha": "^1.1.1",
  43460. "karma-mocha-reporter": "^2.1.0",
  43461. "karma-sinon-chai": "^1.2.4",
  43462. "lolex": "^1.5.1",
  43463. "markserv": "0.0.20",
  43464. "minifyify": "^7.3.3",
  43465. "mocha": "^3.0.2",
  43466. "mozilla-download": "^1.1.1",
  43467. "replace": "^0.3.0",
  43468. "semistandard": "^9.0.0",
  43469. "shelljs": "^0.7.7",
  43470. "shx": "^0.2.2",
  43471. "sinon": "^1.17.5",
  43472. "sinon-chai": "^2.8.0",
  43473. "snazzy": "^5.0.0",
  43474. "too-wordy": "ngokevin/too-wordy",
  43475. "uglifyjs": "^2.4.10",
  43476. "write-good": "^0.9.1"
  43477. },
  43478. "link": true,
  43479. "browserify": {
  43480. "transform": [
  43481. "browserify-css",
  43482. "envify"
  43483. ]
  43484. },
  43485. "semistandard": {
  43486. "ignore": [
  43487. "build/**",
  43488. "dist/**",
  43489. "examples/**/shaders/*.js",
  43490. "**/vendor/**"
  43491. ]
  43492. },
  43493. "keywords": [
  43494. "3d",
  43495. "aframe",
  43496. "cardboard",
  43497. "components",
  43498. "oculus",
  43499. "three",
  43500. "three.js",
  43501. "rift",
  43502. "vive",
  43503. "vr",
  43504. "web-components",
  43505. "webvr"
  43506. ],
  43507. "browserify-css": {
  43508. "minify": true
  43509. },
  43510. "engines": {
  43511. "node": ">= 4.6.0",
  43512. "npm": "^2.15.9"
  43513. }
  43514. }
  43515. },{}],55:[function(_dereq_,module,exports){
  43516. var registerComponent = _dereq_('../core/component').registerComponent;
  43517. var THREE = _dereq_('../lib/three');
  43518. /**
  43519. * Blend character model component.
  43520. * Loads a model with skeletal animation blending.
  43521. */
  43522. module.exports.Component = registerComponent('blend-character-model', {
  43523. schema: {type: 'asset'},
  43524. init: function () {
  43525. this.model = null;
  43526. },
  43527. update: function () {
  43528. var self = this;
  43529. var el = this.el;
  43530. var src = this.data;
  43531. if (!src) { return; }
  43532. this.remove();
  43533. this.model = new THREE.BlendCharacter();
  43534. this.model.load(src, function () {
  43535. el.setObject3D('mesh', self.model);
  43536. el.emit('model-loaded', {format: 'blend', model: self.model});
  43537. self.model.castShadow = true;
  43538. self.model.receiveShadow = true;
  43539. self.model.material.shading = THREE.FlatShading;
  43540. self.model.geometry.computeBoundingBox();
  43541. });
  43542. },
  43543. remove: function () {
  43544. if (!this.model) { return; }
  43545. this.el.removeObject3D('mesh');
  43546. }
  43547. });
  43548. },{"../core/component":102,"../lib/three":149}],56:[function(_dereq_,module,exports){
  43549. var registerComponent = _dereq_('../core/component').registerComponent;
  43550. var THREE = _dereq_('../lib/three');
  43551. var utils = _dereq_('../utils/');
  43552. var bind = utils.bind;
  43553. var checkHasPositionalTracking = utils.device.checkHasPositionalTracking;
  43554. /**
  43555. * Camera component.
  43556. * Pairs along with camera system to handle tracking the active camera.
  43557. */
  43558. module.exports.Component = registerComponent('camera', {
  43559. schema: {
  43560. active: {default: true},
  43561. far: {default: 10000},
  43562. fov: {default: 80, min: 0},
  43563. near: {default: 0.005, min: 0},
  43564. userHeight: {default: 0, min: 0},
  43565. zoom: {default: 1, min: 0}
  43566. },
  43567. /**
  43568. * Initialize three.js camera and add it to the entity.
  43569. * Add reference from scene to this entity as the camera.
  43570. */
  43571. init: function () {
  43572. var camera;
  43573. var el = this.el;
  43574. var sceneEl = el.sceneEl;
  43575. this.savedPose = null;
  43576. // Create camera.
  43577. camera = this.camera = new THREE.PerspectiveCamera();
  43578. el.setObject3D('camera', camera);
  43579. // Add listeners to save and restore camera pose if headset is present.
  43580. this.onEnterVR = bind(this.onEnterVR, this);
  43581. this.onExitVR = bind(this.onExitVR, this);
  43582. sceneEl.addEventListener('enter-vr', this.onEnterVR);
  43583. sceneEl.addEventListener('exit-vr', this.onExitVR);
  43584. },
  43585. /**
  43586. * Update three.js camera.
  43587. */
  43588. update: function (oldData) {
  43589. var el = this.el;
  43590. var data = this.data;
  43591. var camera = this.camera;
  43592. var system = this.system;
  43593. // Update height offset.
  43594. this.addHeightOffset(oldData.userHeight);
  43595. // Update properties.
  43596. camera.aspect = data.aspect || (window.innerWidth / window.innerHeight);
  43597. camera.far = data.far;
  43598. camera.fov = data.fov;
  43599. camera.near = data.near;
  43600. camera.zoom = data.zoom;
  43601. camera.updateProjectionMatrix();
  43602. // Active property did not change.
  43603. if (oldData && oldData.active === data.active) { return; }
  43604. // If `active` property changes, or first update, handle active camera with system.
  43605. if (data.active && system.activeCameraEl !== el) {
  43606. // Camera enabled. Set camera to this camera.
  43607. system.setActiveCamera(el);
  43608. } else if (!data.active && system.activeCameraEl === el) {
  43609. // Camera disabled. Set camera to another camera.
  43610. system.disableActiveCamera();
  43611. }
  43612. },
  43613. /**
  43614. * Remove camera on remove (callback).
  43615. */
  43616. remove: function () {
  43617. var sceneEl = this.el.sceneEl;
  43618. this.el.removeObject3D('camera');
  43619. sceneEl.removeEventListener('enter-vr', this.onEnterVR);
  43620. sceneEl.removeEventListener('exit-vr', this.onExitVR);
  43621. },
  43622. /**
  43623. * Save pose and remove the offset.
  43624. */
  43625. onEnterVR: function () {
  43626. this.saveCameraPose();
  43627. this.removeHeightOffset();
  43628. },
  43629. /**
  43630. * Restore the pose. Do not need to re-add the offset because it was saved on entering VR.
  43631. */
  43632. onExitVR: function () {
  43633. this.restoreCameraPose();
  43634. },
  43635. /**
  43636. * Offsets the position of the camera to set a human scale perspective
  43637. * This offset is not necessary when using a headset because the SDK
  43638. * will return the real user's head height and position.
  43639. */
  43640. addHeightOffset: function (oldOffset) {
  43641. var el = this.el;
  43642. var currentPosition;
  43643. var userHeightOffset = this.data.userHeight;
  43644. oldOffset = oldOffset || 0;
  43645. currentPosition = el.getAttribute('position') || {x: 0, y: 0, z: 0};
  43646. el.setAttribute('position', {
  43647. x: currentPosition.x,
  43648. y: currentPosition.y - oldOffset + userHeightOffset,
  43649. z: currentPosition.z
  43650. });
  43651. },
  43652. /**
  43653. * Remove the height offset (called when entering VR) since WebVR API gives absolute
  43654. * position.
  43655. */
  43656. removeHeightOffset: function () {
  43657. var currentPosition;
  43658. var el = this.el;
  43659. var hasPositionalTracking;
  43660. var userHeightOffset = this.data.userHeight;
  43661. // Remove the offset if there is positional tracking when entering VR.
  43662. // Necessary for fullscreen mode with no headset.
  43663. // Checking this.hasPositionalTracking to make the value injectable for unit tests.
  43664. hasPositionalTracking = this.hasPositionalTracking !== undefined ? this.hasPositionalTracking : checkHasPositionalTracking();
  43665. if (!userHeightOffset || !hasPositionalTracking) { return; }
  43666. currentPosition = el.getAttribute('position') || {x: 0, y: 0, z: 0};
  43667. el.setAttribute('position', {
  43668. x: currentPosition.x,
  43669. y: currentPosition.y - userHeightOffset,
  43670. z: currentPosition.z
  43671. });
  43672. },
  43673. /**
  43674. * Save camera pose before entering VR to restore later if exiting.
  43675. */
  43676. saveCameraPose: function () {
  43677. var el = this.el;
  43678. var hasPositionalTracking = this.hasPositionalTracking !== undefined ? this.hasPositionalTracking : checkHasPositionalTracking();
  43679. if (this.savedPose || !hasPositionalTracking) { return; }
  43680. this.savedPose = {
  43681. position: el.getAttribute('position'),
  43682. rotation: el.getAttribute('rotation')
  43683. };
  43684. },
  43685. /**
  43686. * Reset camera pose to before entering VR.
  43687. */
  43688. restoreCameraPose: function () {
  43689. var el = this.el;
  43690. var savedPose = this.savedPose;
  43691. var hasPositionalTracking = this.hasPositionalTracking !== undefined ? this.hasPositionalTracking : checkHasPositionalTracking();
  43692. if (!savedPose || !hasPositionalTracking) { return; }
  43693. // Reset camera orientation.
  43694. el.setAttribute('position', savedPose.position);
  43695. el.setAttribute('rotation', savedPose.rotation);
  43696. this.savedPose = null;
  43697. }
  43698. });
  43699. },{"../core/component":102,"../lib/three":149,"../utils/":172}],57:[function(_dereq_,module,exports){
  43700. var registerComponent = _dereq_('../core/component').registerComponent;
  43701. var THREE = _dereq_('../lib/three');
  43702. module.exports.Component = registerComponent('collada-model', {
  43703. schema: {type: 'asset'},
  43704. init: function () {
  43705. this.model = null;
  43706. this.loader = new THREE.ColladaLoader();
  43707. this.loader.options.convertUpAxis = true;
  43708. },
  43709. update: function () {
  43710. var self = this;
  43711. var el = this.el;
  43712. var src = this.data;
  43713. if (!src) { return; }
  43714. this.remove();
  43715. this.loader.load(src, function (colladaModel) {
  43716. self.model = colladaModel.scene;
  43717. el.setObject3D('mesh', self.model);
  43718. el.emit('model-loaded', {format: 'collada', model: self.model});
  43719. });
  43720. },
  43721. remove: function () {
  43722. if (!this.model) { return; }
  43723. this.el.removeObject3D('mesh');
  43724. }
  43725. });
  43726. },{"../core/component":102,"../lib/three":149}],58:[function(_dereq_,module,exports){
  43727. var registerComponent = _dereq_('../core/component').registerComponent;
  43728. var utils = _dereq_('../utils/');
  43729. var bind = utils.bind;
  43730. var EVENTS = {
  43731. CLICK: 'click',
  43732. FUSING: 'fusing',
  43733. MOUSEENTER: 'mouseenter',
  43734. MOUSEDOWN: 'mousedown',
  43735. MOUSELEAVE: 'mouseleave',
  43736. MOUSEUP: 'mouseup'
  43737. };
  43738. var STATES = {
  43739. FUSING: 'cursor-fusing',
  43740. HOVERING: 'cursor-hovering',
  43741. HOVERED: 'cursor-hovered'
  43742. };
  43743. /**
  43744. * Cursor component. Applies the raycaster component specifically for starting the raycaster
  43745. * from the camera and pointing from camera's facing direction, and then only returning the
  43746. * closest intersection. Cursor can be fine-tuned by setting raycaster properties.
  43747. *
  43748. * @member {object} fuseTimeout - Timeout to trigger fuse-click.
  43749. * @member {Element} mouseDownEl - Entity that was last mousedowned during current click.
  43750. * @member {object} intersection - Attributes of the current intersection event, including
  43751. * 3D- and 2D-space coordinates. See: http://threejs.org/docs/api/core/Raycaster.html
  43752. * @member {Element} intersectedEl - Currently-intersected entity. Used to keep track to
  43753. * emit events when unintersecting.
  43754. */
  43755. module.exports.Component = registerComponent('cursor', {
  43756. dependencies: ['raycaster'],
  43757. schema: {
  43758. fuse: {default: utils.device.isMobile()},
  43759. fuseTimeout: {default: 1500, min: 0}
  43760. },
  43761. init: function () {
  43762. var el = this.el;
  43763. var canvas = el.sceneEl.canvas;
  43764. this.fuseTimeout = undefined;
  43765. this.mouseDownEl = null;
  43766. this.intersection = null;
  43767. this.intersectedEl = null;
  43768. // Wait for canvas to load.
  43769. if (!canvas) {
  43770. el.sceneEl.addEventListener('render-target-loaded', bind(this.init, this));
  43771. return;
  43772. }
  43773. // Bind methods.
  43774. this.onMouseDown = bind(this.onMouseDown, this);
  43775. this.onMouseUp = bind(this.onMouseUp, this);
  43776. this.onIntersection = bind(this.onIntersection, this);
  43777. this.onIntersectionCleared = bind(this.onIntersectionCleared, this);
  43778. // Attach event listeners.
  43779. canvas.addEventListener('mousedown', this.onMouseDown);
  43780. canvas.addEventListener('mouseup', this.onMouseUp);
  43781. el.addEventListener('raycaster-intersection', this.onIntersection);
  43782. el.addEventListener('raycaster-intersection-cleared', this.onIntersectionCleared);
  43783. },
  43784. remove: function () {
  43785. var el = this.el;
  43786. var canvas = el.sceneEl.canvas;
  43787. el.removeState(STATES.HOVERING);
  43788. el.removeState(STATES.FUSING);
  43789. el.removeEventListener('raycaster-intersection', this.onIntersection);
  43790. el.removeEventListener('raycaster-intersection-cleared', this.onIntersectionCleared);
  43791. clearTimeout(this.fuseTimeout);
  43792. if (this.intersectedEl) { this.intersectedEl.removeState(STATES.HOVERED); }
  43793. if (canvas) {
  43794. canvas.removeEventListener('mousedown', this.onMouseDown);
  43795. canvas.removeEventListener('mouseup', this.onMouseUp);
  43796. }
  43797. },
  43798. /**
  43799. * Trigger mousedown and keep track of the mousedowned entity.
  43800. */
  43801. onMouseDown: function (evt) {
  43802. this.twoWayEmit(EVENTS.MOUSEDOWN);
  43803. this.mouseDownEl = this.intersectedEl;
  43804. },
  43805. /**
  43806. * Trigger mouseup if:
  43807. * - Not fusing (mobile has no mouse).
  43808. * - Currently intersecting an entity.
  43809. * - Currently-intersected entity is the same as the one when mousedown was triggered,
  43810. * in case user mousedowned one entity, dragged to another, and mouseupped.
  43811. */
  43812. onMouseUp: function (evt) {
  43813. this.twoWayEmit(EVENTS.MOUSEUP);
  43814. if (this.data.fuse || !this.intersectedEl ||
  43815. this.mouseDownEl !== this.intersectedEl) { return; }
  43816. this.twoWayEmit(EVENTS.CLICK);
  43817. },
  43818. /**
  43819. * Handle intersection.
  43820. */
  43821. onIntersection: function (evt) {
  43822. var self = this;
  43823. var cursorEl = this.el;
  43824. var data = this.data;
  43825. var index;
  43826. var intersectedEl;
  43827. var intersection;
  43828. // Select closest object, excluding the cursor.
  43829. index = evt.detail.els[0] === cursorEl ? 1 : 0;
  43830. intersection = evt.detail.intersections[index];
  43831. intersectedEl = evt.detail.els[index];
  43832. // If cursor is the only intersected object, ignore the event.
  43833. if (!intersectedEl) { return; }
  43834. // Already intersecting this entity.
  43835. if (this.intersectedEl === intersectedEl) {
  43836. this.intersection = intersection;
  43837. return;
  43838. }
  43839. // Unset current intersection.
  43840. if (this.intersectedEl) { this.clearCurrentIntersection(); }
  43841. // Set new intersection.
  43842. this.intersection = intersection;
  43843. this.intersectedEl = intersectedEl;
  43844. // Hovering.
  43845. cursorEl.addState(STATES.HOVERING);
  43846. intersectedEl.addState(STATES.HOVERED);
  43847. self.twoWayEmit(EVENTS.MOUSEENTER);
  43848. // Begin fuse if necessary.
  43849. if (data.fuseTimeout === 0 || !data.fuse) { return; }
  43850. cursorEl.addState(STATES.FUSING);
  43851. this.twoWayEmit(EVENTS.FUSING);
  43852. this.fuseTimeout = setTimeout(function fuse () {
  43853. cursorEl.removeState(STATES.FUSING);
  43854. self.twoWayEmit(EVENTS.CLICK);
  43855. }, data.fuseTimeout);
  43856. },
  43857. /**
  43858. * Handle intersection cleared.
  43859. */
  43860. onIntersectionCleared: function (evt) {
  43861. var cursorEl = this.el;
  43862. var intersectedEl = evt.detail.el;
  43863. // Ignore the cursor.
  43864. if (cursorEl === intersectedEl) { return; }
  43865. // Ignore if the event didn't occur on the current intersection.
  43866. if (intersectedEl !== this.intersectedEl) { return; }
  43867. this.clearCurrentIntersection();
  43868. },
  43869. clearCurrentIntersection: function () {
  43870. var cursorEl = this.el;
  43871. // No longer hovering (or fusing).
  43872. this.intersectedEl.removeState(STATES.HOVERED);
  43873. cursorEl.removeState(STATES.HOVERING);
  43874. cursorEl.removeState(STATES.FUSING);
  43875. this.twoWayEmit(EVENTS.MOUSELEAVE);
  43876. // Unset intersected entity (after emitting the event).
  43877. this.intersection = null;
  43878. this.intersectedEl = null;
  43879. // Clear fuseTimeout.
  43880. clearTimeout(this.fuseTimeout);
  43881. },
  43882. /**
  43883. * Helper to emit on both the cursor and the intersected entity (if exists).
  43884. */
  43885. twoWayEmit: function (evtName) {
  43886. var el = this.el;
  43887. var intersectedEl = this.intersectedEl;
  43888. var intersection = this.intersection;
  43889. el.emit(evtName, {intersectedEl: intersectedEl, intersection: intersection});
  43890. if (!intersectedEl) { return; }
  43891. intersectedEl.emit(evtName, {cursorEl: el, intersection: intersection});
  43892. }
  43893. });
  43894. },{"../core/component":102,"../utils/":172}],59:[function(_dereq_,module,exports){
  43895. var registerComponent = _dereq_('../core/component').registerComponent;
  43896. var bind = _dereq_('../utils/bind');
  43897. var checkControllerPresentAndSetup = _dereq_('../utils/tracked-controls').checkControllerPresentAndSetup;
  43898. var emitIfAxesChanged = _dereq_('../utils/tracked-controls').emitIfAxesChanged;
  43899. var DAYDREAM_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/google/';
  43900. var DAYDREAM_CONTROLLER_MODEL_OBJ_URL = DAYDREAM_CONTROLLER_MODEL_BASE_URL + 'vr_controller_daydream.obj';
  43901. var DAYDREAM_CONTROLLER_MODEL_OBJ_MTL = DAYDREAM_CONTROLLER_MODEL_BASE_URL + 'vr_controller_daydream.mtl';
  43902. var GAMEPAD_ID_PREFIX = 'Daydream Controller';
  43903. /**
  43904. * Daydream controls.
  43905. */
  43906. module.exports.Component = registerComponent('daydream-controls', {
  43907. schema: {
  43908. hand: {default: ''}, // Informs the degenerate arm model.
  43909. buttonColor: {type: 'color', default: '#000000'},
  43910. buttonTouchedColor: {type: 'color', default: '#777777'},
  43911. buttonHighlightColor: {type: 'color', default: '#FFFFFF'},
  43912. model: {default: true},
  43913. // Use -999 as sentinel value to auto-determine based on hand.
  43914. rotationOffset: {default: 0}
  43915. },
  43916. // buttonId
  43917. // 0 - trackpad
  43918. // 1 - menu (never dispatched on this layer)
  43919. // 2 - system (never dispatched on this layer)
  43920. mapping: {
  43921. axes: {'trackpad': [0, 1]},
  43922. buttons: ['trackpad', 'menu', 'system']
  43923. },
  43924. // Use these labels for detail on axis events such as thumbstickmoved.
  43925. // e.g. for thumbstickmoved detail, the first axis returned is labeled x, and the second is labeled y.
  43926. axisLabels: ['x', 'y', 'z', 'w'],
  43927. bindMethods: function () {
  43928. this.onModelLoaded = bind(this.onModelLoaded, this);
  43929. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  43930. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  43931. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  43932. this.onAxisMoved = bind(this.onAxisMoved, this);
  43933. this.onGamepadConnectionEvent = bind(this.onGamepadConnectionEvent, this);
  43934. },
  43935. init: function () {
  43936. var self = this;
  43937. this.animationActive = 'pointing';
  43938. this.onButtonDown = function (evt) { self.onButtonEvent(evt.detail.id, 'down'); };
  43939. this.onButtonUp = function (evt) { self.onButtonEvent(evt.detail.id, 'up'); };
  43940. this.onButtonTouchStart = function (evt) { self.onButtonEvent(evt.detail.id, 'touchstart'); };
  43941. this.onButtonTouchEnd = function (evt) { self.onButtonEvent(evt.detail.id, 'touchend'); };
  43942. this.onAxisMoved = bind(this.onAxisMoved, this);
  43943. this.controllerPresent = false;
  43944. this.everGotGamepadEvent = false;
  43945. this.lastControllerCheck = 0;
  43946. this.bindMethods();
  43947. this.checkControllerPresentAndSetup = checkControllerPresentAndSetup; // to allow mock
  43948. this.emitIfAxesChanged = emitIfAxesChanged; // to allow mock
  43949. },
  43950. addEventListeners: function () {
  43951. var el = this.el;
  43952. el.addEventListener('buttondown', this.onButtonDown);
  43953. el.addEventListener('buttonup', this.onButtonUp);
  43954. el.addEventListener('touchstart', this.onButtonTouchStart);
  43955. el.addEventListener('touchend', this.onButtonTouchEnd);
  43956. el.addEventListener('model-loaded', this.onModelLoaded);
  43957. el.addEventListener('axismove', this.onAxisMoved);
  43958. },
  43959. removeEventListeners: function () {
  43960. var el = this.el;
  43961. el.removeEventListener('buttondown', this.onButtonDown);
  43962. el.removeEventListener('buttonup', this.onButtonUp);
  43963. el.removeEventListener('touchstart', this.onButtonTouchStart);
  43964. el.removeEventListener('touchend', this.onButtonTouchEnd);
  43965. el.removeEventListener('model-loaded', this.onModelLoaded);
  43966. el.removeEventListener('axismove', this.onAxisMoved);
  43967. },
  43968. checkIfControllerPresent: function () {
  43969. this.checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {hand: this.data.hand});
  43970. },
  43971. onGamepadConnectionEvent: function (evt) {
  43972. this.everGotGamepadEvent = true;
  43973. // Due to an apparent bug in FF Nightly
  43974. // where only one gamepadconnected / disconnected event is fired,
  43975. // which makes it difficult to handle in individual controller entities,
  43976. // we no longer remove the controllersupdate listener as a result.
  43977. this.checkIfControllerPresent();
  43978. },
  43979. play: function () {
  43980. this.checkIfControllerPresent();
  43981. this.addControllersUpdateListener();
  43982. window.addEventListener('gamepadconnected', this.onGamepadConnectionEvent, false);
  43983. window.addEventListener('gamepaddisconnected', this.onGamepadConnectionEvent, false);
  43984. },
  43985. pause: function () {
  43986. this.removeEventListeners();
  43987. this.removeControllersUpdateListener();
  43988. window.removeEventListener('gamepadconnected', this.onGamepadConnectionEvent, false);
  43989. window.removeEventListener('gamepaddisconnected', this.onGamepadConnectionEvent, false);
  43990. },
  43991. injectTrackedControls: function () {
  43992. var el = this.el;
  43993. var data = this.data;
  43994. el.setAttribute('tracked-controls', {idPrefix: GAMEPAD_ID_PREFIX, hand: data.hand, rotationOffset: data.rotationOffset});
  43995. if (!this.data.model) { return; }
  43996. this.el.setAttribute('obj-model', {
  43997. obj: DAYDREAM_CONTROLLER_MODEL_OBJ_URL,
  43998. mtl: DAYDREAM_CONTROLLER_MODEL_OBJ_MTL
  43999. });
  44000. },
  44001. addControllersUpdateListener: function () {
  44002. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  44003. },
  44004. removeControllersUpdateListener: function () {
  44005. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  44006. },
  44007. onControllersUpdate: function () {
  44008. if (!this.everGotGamepadEvent) { this.checkIfControllerPresent(); }
  44009. },
  44010. // No need for onButtonChanged, since Daydream controller has no analog buttons.
  44011. onModelLoaded: function (evt) {
  44012. var controllerObject3D = evt.detail.model;
  44013. var buttonMeshes;
  44014. if (!this.data.model) { return; }
  44015. buttonMeshes = this.buttonMeshes = {};
  44016. buttonMeshes.menu = controllerObject3D.getObjectByName('AppButton_AppButton_Cylinder.004');
  44017. buttonMeshes.system = controllerObject3D.getObjectByName('HomeButton_HomeButton_Cylinder.005');
  44018. buttonMeshes.trackpad = controllerObject3D.getObjectByName('TouchPad_TouchPad_Cylinder.003');
  44019. // Offset pivot point
  44020. controllerObject3D.position.set(0, 0, -0.04);
  44021. },
  44022. onAxisMoved: function (evt) { this.emitIfAxesChanged(this, this.mapping.axes, evt); },
  44023. onButtonEvent: function (id, evtName) {
  44024. var buttonName = this.mapping.buttons[id];
  44025. var i;
  44026. if (Array.isArray(buttonName)) {
  44027. for (i = 0; i < buttonName.length; i++) {
  44028. this.el.emit(buttonName[i] + evtName);
  44029. }
  44030. } else {
  44031. this.el.emit(buttonName + evtName);
  44032. }
  44033. this.updateModel(buttonName, evtName);
  44034. },
  44035. updateModel: function (buttonName, evtName) {
  44036. var i;
  44037. if (!this.data.model) { return; }
  44038. if (Array.isArray(buttonName)) {
  44039. for (i = 0; i < buttonName.length; i++) {
  44040. this.updateButtonModel(buttonName[i], evtName);
  44041. }
  44042. } else {
  44043. this.updateButtonModel(buttonName, evtName);
  44044. }
  44045. },
  44046. updateButtonModel: function (buttonName, state) {
  44047. var buttonMeshes = this.buttonMeshes;
  44048. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  44049. var color;
  44050. switch (state) {
  44051. case 'down':
  44052. color = this.data.buttonHighlightColor;
  44053. break;
  44054. case 'touchstart':
  44055. color = this.data.buttonTouchedColor;
  44056. break;
  44057. default:
  44058. color = this.data.buttonColor;
  44059. }
  44060. buttonMeshes[buttonName].material.color.set(color);
  44061. }
  44062. });
  44063. },{"../core/component":102,"../utils/bind":166,"../utils/tracked-controls":176}],60:[function(_dereq_,module,exports){
  44064. var registerComponent = _dereq_('../core/component').registerComponent;
  44065. var bind = _dereq_('../utils/bind');
  44066. var checkControllerPresentAndSetup = _dereq_('../utils/tracked-controls').checkControllerPresentAndSetup;
  44067. var emitIfAxesChanged = _dereq_('../utils/tracked-controls').emitIfAxesChanged;
  44068. var GEARVR_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/samsung/';
  44069. var GEARVR_CONTROLLER_MODEL_OBJ_URL = GEARVR_CONTROLLER_MODEL_BASE_URL + 'gear_vr_controller.obj';
  44070. var GEARVR_CONTROLLER_MODEL_OBJ_MTL = GEARVR_CONTROLLER_MODEL_BASE_URL + 'gear_vr_controller.mtl';
  44071. var GAMEPAD_ID_PREFIX = 'Gear VR';
  44072. /**
  44073. * Vive Controls Component
  44074. * Interfaces with vive controllers and maps Gamepad events to
  44075. * common controller buttons: trackpad, trigger, grip, menu and system
  44076. * It loads a controller model and highlights the pressed buttons
  44077. */
  44078. module.exports.Component = registerComponent('gearvr-controls', {
  44079. schema: {
  44080. hand: {default: ''}, // This informs the degenerate arm model.
  44081. buttonColor: {type: 'color', default: '#000000'},
  44082. buttonTouchedColor: {type: 'color', default: '#777777'},
  44083. buttonHighlightColor: {type: 'color', default: '#FFFFFF'},
  44084. model: {default: true},
  44085. rotationOffset: {default: 0} // use -999 as sentinel value to auto-determine based on hand
  44086. },
  44087. // buttonId
  44088. // 0 - trackpad
  44089. // 1 - triggeri
  44090. mapping: {
  44091. axes: {'trackpad': [0, 1]},
  44092. buttons: ['trackpad', 'trigger']
  44093. },
  44094. // Use these labels for detail on axis events such as thumbstickmoved.
  44095. // e.g. for thumbstickmoved detail, the first axis returned is labeled x, and the second is labeled y.
  44096. axisLabels: ['x', 'y', 'z', 'w'],
  44097. bindMethods: function () {
  44098. this.onModelLoaded = bind(this.onModelLoaded, this);
  44099. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  44100. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  44101. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  44102. this.onAxisMoved = bind(this.onAxisMoved, this);
  44103. this.onGamepadConnectionEvent = bind(this.onGamepadConnectionEvent, this);
  44104. },
  44105. init: function () {
  44106. var self = this;
  44107. this.animationActive = 'pointing';
  44108. this.onButtonDown = function (evt) { self.onButtonEvent(evt.detail.id, 'down'); };
  44109. this.onButtonUp = function (evt) { self.onButtonEvent(evt.detail.id, 'up'); };
  44110. this.onButtonTouchStart = function (evt) { self.onButtonEvent(evt.detail.id, 'touchstart'); };
  44111. this.onButtonTouchEnd = function (evt) { self.onButtonEvent(evt.detail.id, 'touchend'); };
  44112. this.onAxisMoved = bind(this.onAxisMoved, this);
  44113. this.controllerPresent = false;
  44114. this.everGotGamepadEvent = false;
  44115. this.lastControllerCheck = 0;
  44116. this.bindMethods();
  44117. this.checkControllerPresentAndSetup = checkControllerPresentAndSetup; // to allow mock
  44118. this.emitIfAxesChanged = emitIfAxesChanged; // to allow mock
  44119. },
  44120. addEventListeners: function () {
  44121. var el = this.el;
  44122. el.addEventListener('buttondown', this.onButtonDown);
  44123. el.addEventListener('buttonup', this.onButtonUp);
  44124. el.addEventListener('touchstart', this.onButtonTouchStart);
  44125. el.addEventListener('touchend', this.onButtonTouchEnd);
  44126. el.addEventListener('model-loaded', this.onModelLoaded);
  44127. el.addEventListener('axismove', this.onAxisMoved);
  44128. this.addControllersUpdateListener();
  44129. },
  44130. removeEventListeners: function () {
  44131. var el = this.el;
  44132. el.removeEventListener('buttondown', this.onButtonDown);
  44133. el.removeEventListener('buttonup', this.onButtonUp);
  44134. el.removeEventListener('touchstart', this.onButtonTouchStart);
  44135. el.removeEventListener('touchend', this.onButtonTouchEnd);
  44136. el.removeEventListener('model-loaded', this.onModelLoaded);
  44137. el.removeEventListener('axismove', this.onAxisMoved);
  44138. this.removeControllersUpdateListener();
  44139. },
  44140. checkIfControllerPresent: function () {
  44141. this.checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, this.data.hand ? {hand: this.data.hand} : {});
  44142. },
  44143. onGamepadConnectionEvent: function (evt) {
  44144. this.checkIfControllerPresent();
  44145. },
  44146. play: function () {
  44147. this.checkIfControllerPresent();
  44148. // Note that due to gamepadconnected event propagation issues, we don't rely on events.
  44149. window.addEventListener('gamepaddisconnected', this.checkIfControllerPresent, false);
  44150. this.addControllersUpdateListener();
  44151. },
  44152. pause: function () {
  44153. this.removeEventListeners();
  44154. this.removeControllersUpdateListener();
  44155. // Note that due to gamepadconnected event propagation issues, we don't rely on events.
  44156. window.removeEventListener('gamepaddisconnected', this.checkIfControllerPresent, false);
  44157. },
  44158. injectTrackedControls: function () {
  44159. var el = this.el;
  44160. var data = this.data;
  44161. el.setAttribute('tracked-controls', {idPrefix: GAMEPAD_ID_PREFIX, rotationOffset: data.rotationOffset});
  44162. if (!this.data.model) { return; }
  44163. this.el.setAttribute('obj-model', {
  44164. obj: GEARVR_CONTROLLER_MODEL_OBJ_URL,
  44165. mtl: GEARVR_CONTROLLER_MODEL_OBJ_MTL
  44166. });
  44167. },
  44168. addControllersUpdateListener: function () {
  44169. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  44170. },
  44171. removeControllersUpdateListener: function () {
  44172. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  44173. },
  44174. onControllersUpdate: function () {
  44175. // Note that due to gamepadconnected event propagation issues, we don't rely on events.
  44176. this.checkIfControllerPresent();
  44177. },
  44178. // No need for onButtonChanged, since Gear VR controller has no analog buttons.
  44179. onModelLoaded: function (evt) {
  44180. var controllerObject3D = evt.detail.model;
  44181. var buttonMeshes;
  44182. if (!this.data.model) { return; }
  44183. buttonMeshes = this.buttonMeshes = {};
  44184. buttonMeshes.trigger = controllerObject3D.getObjectByName('Trigger');
  44185. buttonMeshes.trackpad = controllerObject3D.getObjectByName('Touchpad');
  44186. },
  44187. onButtonEvent: function (id, evtName) {
  44188. var buttonName = this.mapping.buttons[id];
  44189. var i;
  44190. if (Array.isArray(buttonName)) {
  44191. for (i = 0; i < buttonName.length; i++) {
  44192. this.el.emit(buttonName[i] + evtName);
  44193. }
  44194. } else {
  44195. this.el.emit(buttonName + evtName);
  44196. }
  44197. this.updateModel(buttonName, evtName);
  44198. },
  44199. onAxisMoved: function (evt) { this.emitIfAxesChanged(this, this.mapping.axes, evt); },
  44200. updateModel: function (buttonName, evtName) {
  44201. var i;
  44202. if (!this.data.model) { return; }
  44203. if (Array.isArray(buttonName)) {
  44204. for (i = 0; i < buttonName.length; i++) {
  44205. this.updateButtonModel(buttonName[i], evtName);
  44206. }
  44207. } else {
  44208. this.updateButtonModel(buttonName, evtName);
  44209. }
  44210. },
  44211. updateButtonModel: function (buttonName, state) {
  44212. var buttonMeshes = this.buttonMeshes;
  44213. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  44214. var color;
  44215. switch (state) {
  44216. case 'down':
  44217. color = this.data.buttonHighlightColor;
  44218. break;
  44219. case 'touchstart':
  44220. color = this.data.buttonTouchedColor;
  44221. break;
  44222. default:
  44223. color = this.data.buttonColor;
  44224. }
  44225. buttonMeshes[buttonName].material.color.set(color);
  44226. }
  44227. });
  44228. },{"../core/component":102,"../utils/bind":166,"../utils/tracked-controls":176}],61:[function(_dereq_,module,exports){
  44229. var debug = _dereq_('../utils/debug');
  44230. var geometries = _dereq_('../core/geometry').geometries;
  44231. var geometryNames = _dereq_('../core/geometry').geometryNames;
  44232. var registerComponent = _dereq_('../core/component').registerComponent;
  44233. var THREE = _dereq_('../lib/three');
  44234. var dummyGeometry = new THREE.Geometry();
  44235. var warn = debug('components:geometry:warn');
  44236. /**
  44237. * Geometry component. Combined with material component to make a mesh in 3D object.
  44238. * Extended with registered geometries.
  44239. */
  44240. module.exports.Component = registerComponent('geometry', {
  44241. schema: {
  44242. buffer: {default: true},
  44243. mergeTo: {type: 'selector'},
  44244. primitive: {default: 'box', oneOf: geometryNames},
  44245. skipCache: {default: false}
  44246. },
  44247. init: function () {
  44248. this.geometry = null;
  44249. },
  44250. /**
  44251. * Talk to geometry system to get or create geometry.
  44252. */
  44253. update: function (previousData) {
  44254. var data = this.data;
  44255. var mesh = this.el.getOrCreateObject3D('mesh', THREE.Mesh);
  44256. var system = this.system;
  44257. // Dispose old geometry if we created one.
  44258. if (this.geometry) {
  44259. system.unuseGeometry(previousData);
  44260. this.geometry = null;
  44261. }
  44262. // Create new geometry.
  44263. this.geometry = mesh.geometry = system.getOrCreateGeometry(data);
  44264. if (data.mergeTo) {
  44265. this.mergeTo(data.mergeTo);
  44266. }
  44267. },
  44268. /**
  44269. * Merge geometry to another entity's geometry.
  44270. * Remove the entity from the scene. Not a reversible operation.
  44271. *
  44272. * @param {Element} toEl - Entity where the geometry will be merged to.
  44273. */
  44274. mergeTo: function (toEl) {
  44275. var el = this.el;
  44276. var mesh = el.getObject3D('mesh');
  44277. var toMesh;
  44278. if (!toEl || !toEl.isEntity) {
  44279. warn('There is not a valid entity to merge the geometry to');
  44280. return;
  44281. }
  44282. if (toEl === el) {
  44283. warn('Source and target geometries cannot be the same for merge');
  44284. return;
  44285. }
  44286. // Create mesh if entity does not have one.
  44287. toMesh = toEl.getObject3D('mesh');
  44288. if (!toMesh) {
  44289. toMesh = toEl.getOrCreateObject3D('mesh', THREE.Mesh);
  44290. toEl.setAttribute('material', el.getAttribute('material'));
  44291. return;
  44292. }
  44293. if (toMesh.geometry instanceof THREE.Geometry === false ||
  44294. mesh.geometry instanceof THREE.Geometry === false) {
  44295. warn('Geometry merge is only available for `THREE.Geometry` types. ' +
  44296. 'Check that both of the merging geometry and the target geometry have `buffer` ' +
  44297. 'set to false');
  44298. return;
  44299. }
  44300. if (this.data.skipCache === false) {
  44301. warn('Cached geometries are not allowed to merge. Set `skipCache` to true');
  44302. return;
  44303. }
  44304. mesh.parent.updateMatrixWorld();
  44305. toMesh.geometry.merge(mesh.geometry, mesh.matrixWorld);
  44306. el.emit('geometry-merged', {mergeTarget: toEl});
  44307. el.parentNode.removeChild(el);
  44308. },
  44309. /**
  44310. * Tell geometry system that entity is no longer using the geometry.
  44311. * Unset the geometry on the mesh
  44312. */
  44313. remove: function () {
  44314. this.system.unuseGeometry(this.data);
  44315. this.el.getObject3D('mesh').geometry = dummyGeometry;
  44316. this.geometry = null;
  44317. },
  44318. /**
  44319. * Update geometry component schema based on geometry type.
  44320. *
  44321. * @param {object} data - New data passed by Component.
  44322. */
  44323. updateSchema: function (data) {
  44324. var newGeometryType = data.primitive;
  44325. var currentGeometryType = this.data && this.data.primitive;
  44326. var schema = geometries[newGeometryType] && geometries[newGeometryType].schema;
  44327. // Geometry has no schema.
  44328. if (!schema) { throw new Error('Unknown geometry schema `' + newGeometryType + '`'); }
  44329. // Nothing has changed.
  44330. if (currentGeometryType && currentGeometryType === newGeometryType) { return; }
  44331. this.extendSchema(schema);
  44332. }
  44333. });
  44334. },{"../core/component":102,"../core/geometry":103,"../lib/three":149,"../utils/debug":168}],62:[function(_dereq_,module,exports){
  44335. var registerComponent = _dereq_('../core/component').registerComponent;
  44336. var THREE = _dereq_('../lib/three');
  44337. /**
  44338. * glTF model loader.
  44339. */
  44340. module.exports.Component = registerComponent('gltf-model', {
  44341. schema: {type: 'model'},
  44342. init: function () {
  44343. this.model = null;
  44344. this.loader = new THREE.GLTFLoader();
  44345. },
  44346. update: function () {
  44347. var self = this;
  44348. var el = this.el;
  44349. var src = this.data;
  44350. if (!src) { return; }
  44351. this.remove();
  44352. this.loader.load(src, function gltfLoaded (gltfModel) {
  44353. self.model = gltfModel.scene || gltfModel.scenes[0];
  44354. self.model.animations = gltfModel.animations;
  44355. self.system.registerModel(self.model);
  44356. el.setObject3D('mesh', self.model);
  44357. el.emit('model-loaded', {format: 'gltf', model: self.model});
  44358. });
  44359. },
  44360. remove: function () {
  44361. if (!this.model) { return; }
  44362. this.el.removeObject3D('mesh');
  44363. this.system.unregisterModel(this.model);
  44364. }
  44365. });
  44366. },{"../core/component":102,"../lib/three":149}],63:[function(_dereq_,module,exports){
  44367. /* global THREE */
  44368. var registerComponent = _dereq_('../core/component').registerComponent;
  44369. // Found at https://github.com/aframevr/assets.
  44370. var MODEL_URLS = {
  44371. left: 'https://cdn.aframe.io/controllers/oculus-hands/v2/leftHand.json',
  44372. right: 'https://cdn.aframe.io/controllers/oculus-hands/v2/rightHand.json'
  44373. };
  44374. // Poses.
  44375. var ANIMATIONS = {
  44376. open: 'Open',
  44377. // point: grip active, trackpad surface active, trigger inactive.
  44378. point: 'Point',
  44379. // pointThumb: grip active, trigger inactive, trackpad surface inactive.
  44380. pointThumb: 'Point + Thumb',
  44381. // fist: grip active, trigger active, trackpad surface active.
  44382. fist: 'Fist',
  44383. // hold: trigger active, grip inactive.
  44384. hold: 'Hold',
  44385. // thumbUp: grip active, trigger active, trackpad surface inactive.
  44386. thumbUp: 'Thumb Up'
  44387. };
  44388. // Map animation to public events for the API.
  44389. var EVENTS = {};
  44390. EVENTS[ANIMATIONS.fist] = 'grip';
  44391. EVENTS[ANIMATIONS.thumbUp] = 'pistol';
  44392. EVENTS[ANIMATIONS.point] = 'pointing';
  44393. EVENTS[ANIMATIONS.thumb] = 'thumb';
  44394. /**
  44395. * Hand controls component that abstracts 6DoF controls: oculus-touch-controls, vive-controls.
  44396. * Originally meant to be a sample implementation of applications-specific controls that
  44397. * abstracts multiple types of controllers.
  44398. *
  44399. * Auto-detect appropriate controller.
  44400. * Handle common events coming from the detected vendor-specific controls.
  44401. * Translate button events to semantic hand-related event names:
  44402. * (gripclose, gripopen, thumbup, thumbdown, pointup, pointdown)
  44403. * Load hand model with gestures that are applied based on the button pressed.
  44404. *
  44405. * @property {string} Hand mapping (`left`, `right`).
  44406. */
  44407. module.exports.Component = registerComponent('hand-controls', {
  44408. schema: {default: 'left'},
  44409. init: function () {
  44410. var self = this;
  44411. // Current pose.
  44412. this.gesture = ANIMATIONS.open;
  44413. // Active buttons populated by events provided by oculus-touch-controls and vive-controls.
  44414. this.pressedButtons = {};
  44415. this.touchedButtons = {};
  44416. this.onGripDown = function () { self.handleButton('grip', 'down'); };
  44417. this.onGripUp = function () { self.handleButton('grip', 'up'); };
  44418. this.onTrackpadDown = function () { self.handleButton('trackpad', 'down'); };
  44419. this.onTrackpadUp = function () { self.handleButton('trackpad', 'up'); };
  44420. this.onTrackpadTouchStart = function () { self.handleButton('trackpad', 'touchstart'); };
  44421. this.onTrackpadTouchEnd = function () { self.handleButton('trackpad', 'touchend'); };
  44422. this.onTriggerDown = function () { self.handleButton('trigger', 'down'); };
  44423. this.onTriggerUp = function () { self.handleButton('trigger', 'up'); };
  44424. this.onTriggerTouchStart = function () { self.handleButton('trigger', 'touchstart'); };
  44425. this.onTriggerTouchEnd = function () { self.handleButton('trigger', 'touchend'); };
  44426. this.onGripTouchStart = function () { self.handleButton('grip', 'touchstart'); };
  44427. this.onGripTouchEnd = function () { self.handleButton('grip', 'touchend'); };
  44428. this.onThumbstickDown = function () { self.handleButton('thumbstick', 'down'); };
  44429. this.onThumbstickUp = function () { self.handleButton('thumbstick', 'up'); };
  44430. this.onAorXTouchStart = function () { self.handleButton('AorX', 'touchstart'); };
  44431. this.onAorXTouchEnd = function () { self.handleButton('AorX', 'touchend'); };
  44432. this.onBorYTouchStart = function () { self.handleButton('BorY', 'touchstart'); };
  44433. this.onBorYTouchEnd = function () { self.handleButton('BorY', 'touchend'); };
  44434. this.onSurfaceTouchStart = function () { self.handleButton('surface', 'touchstart'); };
  44435. this.onSurfaceTouchEnd = function () { self.handleButton('surface', 'touchend'); };
  44436. },
  44437. play: function () {
  44438. this.addEventListeners();
  44439. },
  44440. pause: function () {
  44441. this.removeEventListeners();
  44442. },
  44443. addEventListeners: function () {
  44444. var el = this.el;
  44445. el.addEventListener('gripdown', this.onGripDown);
  44446. el.addEventListener('gripup', this.onGripUp);
  44447. el.addEventListener('trackpaddown', this.onTrackpadDown);
  44448. el.addEventListener('trackpadup', this.onTrackpadUp);
  44449. el.addEventListener('trackpadtouchstart', this.onTrackpadTouchStart);
  44450. el.addEventListener('trackpadtouchend', this.onTrackpadTouchEnd);
  44451. el.addEventListener('triggerdown', this.onTriggerDown);
  44452. el.addEventListener('triggerup', this.onTriggerUp);
  44453. el.addEventListener('triggertouchstart', this.onTriggerTouchStart);
  44454. el.addEventListener('triggertouchend', this.onTriggerTouchEnd);
  44455. el.addEventListener('griptouchstart', this.onGripTouchStart);
  44456. el.addEventListener('griptouchend', this.onGripTouchEnd);
  44457. el.addEventListener('thumbstickdown', this.onThumbstickDown);
  44458. el.addEventListener('thumbstickup', this.onThumbstickUp);
  44459. el.addEventListener('abuttontouchstart', this.onAorXTouchStart);
  44460. el.addEventListener('abuttontouchend', this.onAorXTouchEnd);
  44461. el.addEventListener('bbuttontouchstart', this.onBorYTouchStart);
  44462. el.addEventListener('bbuttontouchend', this.onBorYTouchEnd);
  44463. el.addEventListener('xbuttontouchstart', this.onAorXTouchStart);
  44464. el.addEventListener('xbuttontouchend', this.onAorXTouchEnd);
  44465. el.addEventListener('ybuttontouchstart', this.onBorYTouchStart);
  44466. el.addEventListener('ybuttontouchend', this.onBorYTouchEnd);
  44467. el.addEventListener('surfacetouchstart', this.onSurfaceTouchStart);
  44468. el.addEventListener('surfacetouchend', this.onSurfaceTouchEnd);
  44469. },
  44470. removeEventListeners: function () {
  44471. var el = this.el;
  44472. el.removeEventListener('gripdown', this.onGripDown);
  44473. el.removeEventListener('gripup', this.onGripUp);
  44474. el.removeEventListener('trackpaddown', this.onTrackpadDown);
  44475. el.removeEventListener('trackpadup', this.onTrackpadUp);
  44476. el.removeEventListener('trackpadtouchstart', this.onTrackpadTouchStart);
  44477. el.removeEventListener('trackpadtouchend', this.onTrackpadTouchEnd);
  44478. el.removeEventListener('triggerdown', this.onTriggerDown);
  44479. el.removeEventListener('triggerup', this.onTriggerUp);
  44480. el.removeEventListener('triggertouchstart', this.onTriggerTouchStart);
  44481. el.removeEventListener('triggertouchend', this.onTriggerTouchEnd);
  44482. el.removeEventListener('griptouchstart', this.onGripTouchStart);
  44483. el.removeEventListener('griptouchend', this.onGripTouchEnd);
  44484. el.removeEventListener('thumbstickdown', this.onThumbstickDown);
  44485. el.removeEventListener('thumbstickup', this.onThumbstickUp);
  44486. el.removeEventListener('abuttontouchstart', this.onAorXTouchStart);
  44487. el.removeEventListener('abuttontouchend', this.onAorXTouchEnd);
  44488. el.removeEventListener('bbuttontouchstart', this.onBorYTouchStart);
  44489. el.removeEventListener('bbuttontouchend', this.onBorYTouchEnd);
  44490. el.removeEventListener('xbuttontouchstart', this.onAorXTouchStart);
  44491. el.removeEventListener('xbuttontouchend', this.onAorXTouchEnd);
  44492. el.removeEventListener('ybuttontouchstart', this.onBorYTouchStart);
  44493. el.removeEventListener('ybuttontouchend', this.onBorYTouchEnd);
  44494. el.removeEventListener('surfacetouchstart', this.onSurfaceTouchStart);
  44495. el.removeEventListener('surfacetouchend', this.onSurfaceTouchEnd);
  44496. },
  44497. /**
  44498. * Update handler. More like the `init` handler since the only property is the hand, and
  44499. * that won't be changing much.
  44500. */
  44501. update: function () {
  44502. var controlConfiguration;
  44503. var el = this.el;
  44504. var hand = this.data;
  44505. // Get common configuration to abstract Vive and Oculus.
  44506. controlConfiguration = {
  44507. hand: hand,
  44508. model: false,
  44509. rotationOffset: hand === 'left' ? 90 : -90
  44510. };
  44511. el.setAttribute('vive-controls', controlConfiguration);
  44512. el.setAttribute('oculus-touch-controls', controlConfiguration);
  44513. el.setAttribute('daydream-controls', controlConfiguration);
  44514. el.setAttribute('gearvr-controls', controlConfiguration);
  44515. // Set model.
  44516. el.setAttribute('blend-character-model', MODEL_URLS[hand]);
  44517. },
  44518. /**
  44519. * Play model animation, based on which button was pressed and which kind of event.
  44520. *
  44521. * 1. Process buttons.
  44522. * 2. Determine gesture (this.determineGesture()).
  44523. * 3. Animation gesture (this.animationGesture()).
  44524. * 4. Emit gesture events (this.emitGestureEvents()).
  44525. *
  44526. * @param {string} button - Name of the button.
  44527. * @param {string} evt - Type of event for the button (i.e., down/up/touchstart/touchend).
  44528. */
  44529. handleButton: function (button, evt) {
  44530. var lastGesture;
  44531. var isPressed = evt === 'down';
  44532. var isTouched = evt === 'touchstart';
  44533. // Update objects.
  44534. if (evt.indexOf('touch') === 0) {
  44535. // Update touch object.
  44536. if (isTouched === this.touchedButtons[button]) { return; }
  44537. this.touchedButtons[button] = isTouched;
  44538. } else {
  44539. // Update button object.
  44540. if (isPressed === this.pressedButtons[button]) { return; }
  44541. this.pressedButtons[button] = isPressed;
  44542. }
  44543. // Determine the gesture.
  44544. lastGesture = this.gesture;
  44545. this.gesture = this.determineGesture();
  44546. // Same gesture.
  44547. if (this.gesture === lastGesture) { return; }
  44548. // Animate gesture.
  44549. this.animateGesture(this.gesture, lastGesture);
  44550. // Emit events.
  44551. this.emitGestureEvents(this.gesture, lastGesture);
  44552. },
  44553. /**
  44554. * Determine which pose hand should be in considering active and touched buttons.
  44555. */
  44556. determineGesture: function () {
  44557. var gesture;
  44558. var isGripActive = this.pressedButtons['grip'];
  44559. var isSurfaceActive = this.pressedButtons['surface'] || this.touchedButtons['surface'];
  44560. var isTrackpadActive = this.pressedButtons['trackpad'] || this.touchedButtons['trackpad'];
  44561. var isTriggerActive = this.pressedButtons['trigger'] || this.touchedButtons['trigger'];
  44562. var isABXYActive = this.touchedButtons['AorX'] || this.touchedButtons['BorY'];
  44563. var isOculusTouch = isOculusTouchController(this.el.components['tracked-controls']);
  44564. // Works well with Oculus Touch but Vive needs tweaks.
  44565. if (isGripActive) {
  44566. if (!isOculusTouch) {
  44567. gesture = ANIMATIONS.fist;
  44568. } else
  44569. if (isSurfaceActive || isABXYActive || isTrackpadActive) {
  44570. gesture = isTriggerActive ? ANIMATIONS.fist : ANIMATIONS.point;
  44571. } else {
  44572. gesture = isTriggerActive ? ANIMATIONS.thumbUp : ANIMATIONS.pointThumb;
  44573. }
  44574. } else {
  44575. if (isTriggerActive) {
  44576. gesture = isOculusTouch ? ANIMATIONS.hold : ANIMATIONS.fist;
  44577. } else if (!isOculusTouch && isTrackpadActive) {
  44578. gesture = ANIMATIONS.point;
  44579. }
  44580. }
  44581. return gesture;
  44582. },
  44583. /**
  44584. * Play gesture animation.
  44585. *
  44586. * @param {string} gesture - Which pose to animate to. If absent, then animate to open.
  44587. * @param {string} lastGesture - Previous gesture, to reverse back to open if needed.
  44588. */
  44589. animateGesture: function (gesture, lastGesture) {
  44590. if (gesture) {
  44591. this.playAnimation(gesture || ANIMATIONS.open, lastGesture, false);
  44592. return;
  44593. }
  44594. // If no gesture, then reverse the current gesture back to open pose.
  44595. this.playAnimation(lastGesture, lastGesture, true);
  44596. },
  44597. /**
  44598. * Emit `hand-controls`-specific events.
  44599. */
  44600. emitGestureEvents: function (gesture, lastGesture) {
  44601. var el = this.el;
  44602. var eventName;
  44603. if (lastGesture === gesture) { return; }
  44604. // Emit event for lastGesture not inactive.
  44605. eventName = getGestureEventName(lastGesture, false);
  44606. if (eventName) { el.emit(eventName); }
  44607. // Emit event for current gesture now active.
  44608. eventName = getGestureEventName(gesture, true);
  44609. if (eventName) { el.emit(eventName); }
  44610. },
  44611. /**
  44612. * Play hand animation based on button state.
  44613. *
  44614. * @param {string} gesture - Name of the animation as specified by the model.
  44615. * @param {string} lastGesture - Previous pose.
  44616. * @param {boolean} reverse - Whether animation should play in reverse.
  44617. */
  44618. playAnimation: function (gesture, lastGesture, reverse) {
  44619. var fromAction;
  44620. var mesh = this.el.getObject3D('mesh');
  44621. var toAction;
  44622. if (!mesh) { return; }
  44623. // Grab clip action.
  44624. toAction = mesh.mixer.clipAction(gesture);
  44625. toAction.clampWhenFinished = true;
  44626. toAction.loop = THREE.PingPong;
  44627. toAction.repetitions = 0;
  44628. toAction.timeScale = reverse ? -1 : 1;
  44629. // No gesture to gesture or gesture to no gesture.
  44630. if (!lastGesture || gesture === lastGesture) {
  44631. // Stop all current animations.
  44632. mesh.stopAll();
  44633. // Play animation.
  44634. mesh.play(gesture, 1);
  44635. return;
  44636. }
  44637. // Animate or crossfade from gesture to gesture.
  44638. fromAction = mesh.mixer.clipAction(lastGesture);
  44639. mesh.mixer.stopAllAction();
  44640. mesh.play(lastGesture, 0.15);
  44641. mesh.play(gesture, 1);
  44642. fromAction.crossFadeTo(toAction, 0.15, true);
  44643. }
  44644. });
  44645. /**
  44646. * Suffix gestures based on toggle state (e.g., open/close, up/down, start/end).
  44647. *
  44648. * @param {string} gesture
  44649. * @param {boolean} active
  44650. */
  44651. function getGestureEventName (gesture, active) {
  44652. var eventName;
  44653. if (!gesture) { return; }
  44654. eventName = EVENTS[gesture];
  44655. if (eventName === 'grip') {
  44656. return eventName + (active ? 'close' : 'open');
  44657. }
  44658. if (eventName === 'point' || eventName === 'thumb') {
  44659. return eventName + (active ? 'up' : 'down');
  44660. }
  44661. if (eventName === 'pointing' || eventName === 'pistol') {
  44662. return eventName + (active ? 'start' : 'end');
  44663. }
  44664. return;
  44665. }
  44666. function isOculusTouchController (trackedControls) {
  44667. var controllerId = trackedControls && trackedControls.controller &&
  44668. trackedControls.controller.id;
  44669. return controllerId && controllerId.indexOf('Oculus Touch') === 0;
  44670. }
  44671. },{"../core/component":102}],64:[function(_dereq_,module,exports){
  44672. _dereq_('./blend-character-model');
  44673. _dereq_('./camera');
  44674. _dereq_('./collada-model');
  44675. _dereq_('./cursor');
  44676. _dereq_('./daydream-controls');
  44677. _dereq_('./gearvr-controls');
  44678. _dereq_('./geometry');
  44679. _dereq_('./gltf-model');
  44680. _dereq_('./hand-controls');
  44681. _dereq_('./light');
  44682. _dereq_('./look-controls');
  44683. _dereq_('./material');
  44684. _dereq_('./obj-model');
  44685. _dereq_('./oculus-touch-controls');
  44686. _dereq_('./position');
  44687. _dereq_('./raycaster');
  44688. _dereq_('./rotation');
  44689. _dereq_('./scale');
  44690. _dereq_('./shadow');
  44691. _dereq_('./sound');
  44692. _dereq_('./text');
  44693. _dereq_('./tracked-controls');
  44694. _dereq_('./visible');
  44695. _dereq_('./vive-controls');
  44696. _dereq_('./wasd-controls');
  44697. _dereq_('./scene/auto-enter-vr');
  44698. _dereq_('./scene/canvas');
  44699. _dereq_('./scene/debug');
  44700. _dereq_('./scene/embedded');
  44701. _dereq_('./scene/inspector');
  44702. _dereq_('./scene/fog');
  44703. _dereq_('./scene/keyboard-shortcuts');
  44704. _dereq_('./scene/pool');
  44705. _dereq_('./scene/screenshot');
  44706. _dereq_('./scene/stats');
  44707. _dereq_('./scene/vr-mode-ui');
  44708. },{"./blend-character-model":55,"./camera":56,"./collada-model":57,"./cursor":58,"./daydream-controls":59,"./gearvr-controls":60,"./geometry":61,"./gltf-model":62,"./hand-controls":63,"./light":65,"./look-controls":66,"./material":67,"./obj-model":68,"./oculus-touch-controls":69,"./position":70,"./raycaster":71,"./rotation":72,"./scale":73,"./scene/auto-enter-vr":74,"./scene/canvas":75,"./scene/debug":76,"./scene/embedded":77,"./scene/fog":78,"./scene/inspector":79,"./scene/keyboard-shortcuts":80,"./scene/pool":81,"./scene/screenshot":82,"./scene/stats":83,"./scene/vr-mode-ui":84,"./shadow":85,"./sound":86,"./text":87,"./tracked-controls":88,"./visible":89,"./vive-controls":90,"./wasd-controls":91}],65:[function(_dereq_,module,exports){
  44709. var bind = _dereq_('../utils/bind');
  44710. var diff = _dereq_('../utils').diff;
  44711. var debug = _dereq_('../utils/debug');
  44712. var registerComponent = _dereq_('../core/component').registerComponent;
  44713. var THREE = _dereq_('../lib/three');
  44714. var degToRad = THREE.Math.degToRad;
  44715. var warn = debug('components:light:warn');
  44716. /**
  44717. * Light component.
  44718. */
  44719. module.exports.Component = registerComponent('light', {
  44720. schema: {
  44721. angle: {default: 60, if: {type: ['spot']}},
  44722. color: {type: 'color'},
  44723. groundColor: {type: 'color', if: {type: ['hemisphere']}},
  44724. decay: {default: 1, if: {type: ['point', 'spot']}},
  44725. distance: {default: 0.0, min: 0, if: {type: ['point', 'spot']}},
  44726. intensity: {default: 1.0, min: 0, if: {type: ['ambient', 'directional', 'hemisphere', 'point', 'spot']}},
  44727. penumbra: {default: 0, min: 0, max: 1, if: {type: ['spot']}},
  44728. type: {default: 'directional', oneOf: ['ambient', 'directional', 'hemisphere', 'point', 'spot']},
  44729. target: {type: 'selector', if: {type: ['spot', 'directional']}},
  44730. // Shadows.
  44731. castShadow: {default: false, if: {type: ['point', 'spot', 'directional']}},
  44732. shadowBias: {default: 0, if: {castShadow: true}},
  44733. shadowCameraFar: {default: 500, if: {castShadow: true}},
  44734. shadowCameraFov: {default: 90, if: {castShadow: true}},
  44735. shadowCameraNear: {default: 0.5, if: {castShadow: true}},
  44736. shadowCameraTop: {default: 5, if: {castShadow: true}},
  44737. shadowCameraRight: {default: 5, if: {castShadow: true}},
  44738. shadowCameraBottom: {default: -5, if: {castShadow: true}},
  44739. shadowCameraLeft: {default: -5, if: {castShadow: true}},
  44740. shadowCameraVisible: {default: false, if: {castShadow: true}},
  44741. shadowMapHeight: {default: 512, if: {castShadow: true}},
  44742. shadowMapWidth: {default: 512, if: {castShadow: true}}
  44743. },
  44744. /**
  44745. * Notifies scene a light has been added to remove default lighting.
  44746. */
  44747. init: function () {
  44748. var el = this.el;
  44749. this.light = null;
  44750. this.defaultTarget = null;
  44751. this.system.registerLight(el);
  44752. },
  44753. /**
  44754. * (Re)create or update light.
  44755. */
  44756. update: function (oldData) {
  44757. var data = this.data;
  44758. var diffData = diff(data, oldData);
  44759. var light = this.light;
  44760. var self = this;
  44761. // Existing light.
  44762. if (light && !('type' in diffData)) {
  44763. var shadowsLoaded = false;
  44764. // Light type has not changed. Update light.
  44765. Object.keys(diffData).forEach(function (key) {
  44766. var value = data[key];
  44767. switch (key) {
  44768. case 'color': {
  44769. light.color.set(value);
  44770. break;
  44771. }
  44772. case 'groundColor': {
  44773. light.groundColor.set(value);
  44774. break;
  44775. }
  44776. case 'angle': {
  44777. light.angle = degToRad(value);
  44778. break;
  44779. }
  44780. case 'target': {
  44781. // Reset target if selector is null.
  44782. if (value === null) {
  44783. if (data.type === 'spot' || data.type === 'directional') {
  44784. light.target = self.defaultTarget;
  44785. }
  44786. } else {
  44787. // Target specified, set target to entity's `object3D` when it is loaded.
  44788. if (value.hasLoaded) {
  44789. self.onSetTarget(value, light);
  44790. } else {
  44791. value.addEventListener('loaded', bind(self.onSetTarget, self, value, light));
  44792. }
  44793. }
  44794. break;
  44795. }
  44796. case 'castShadow':
  44797. case 'shadowBias':
  44798. case 'shadowCameraFar':
  44799. case 'shadowCameraFov':
  44800. case 'shadowCameraNear':
  44801. case 'shadowCameraTop':
  44802. case 'shadowCameraRight':
  44803. case 'shadowCameraBottom':
  44804. case 'shadowCameraLeft':
  44805. case 'shadowCameraVisible':
  44806. case 'shadowMapHeight':
  44807. case 'shadowMapWidth':
  44808. if (!shadowsLoaded) {
  44809. self.updateShadow();
  44810. shadowsLoaded = true;
  44811. }
  44812. break;
  44813. default: {
  44814. light[key] = value;
  44815. }
  44816. }
  44817. });
  44818. return;
  44819. }
  44820. // No light yet or light type has changed. Create and add light.
  44821. this.setLight(this.data);
  44822. this.updateShadow();
  44823. },
  44824. setLight: function (data) {
  44825. var el = this.el;
  44826. var newLight = this.getLight(data);
  44827. if (newLight) {
  44828. if (this.light) {
  44829. el.removeObject3D('light');
  44830. }
  44831. this.light = newLight;
  44832. this.light.el = el;
  44833. el.setObject3D('light', this.light);
  44834. // HACK solution for issue #1624
  44835. if (data.type === 'spot' || data.type === 'directional' || data.type === 'hemisphere') {
  44836. el.getObject3D('light').translateY(-1);
  44837. }
  44838. // set and position default lighttarget as a child to enable spotlight orientation
  44839. if (data.type === 'spot') {
  44840. el.setObject3D('light-target', this.defaultTarget);
  44841. el.getObject3D('light-target').position.set(0, 0, -1);
  44842. }
  44843. }
  44844. },
  44845. /**
  44846. * Updates shadow-related properties on the current light.
  44847. */
  44848. updateShadow: function () {
  44849. var el = this.el;
  44850. var data = this.data;
  44851. var light = this.light;
  44852. light.castShadow = data.castShadow;
  44853. // Shadow camera helper.
  44854. var cameraHelper = el.getObject3D('cameraHelper');
  44855. if (data.shadowCameraVisible && !cameraHelper) {
  44856. el.setObject3D('cameraHelper', new THREE.CameraHelper(light.shadow.camera));
  44857. } else if (!data.shadowCameraVisible && cameraHelper) {
  44858. el.removeObject3D('cameraHelper');
  44859. }
  44860. if (!data.castShadow) { return light; }
  44861. // Shadow appearance.
  44862. light.shadow.bias = data.shadowBias;
  44863. light.shadow.mapSize.height = data.shadowMapHeight;
  44864. light.shadow.mapSize.width = data.shadowMapWidth;
  44865. // Shadow camera.
  44866. light.shadow.camera.near = data.shadowCameraNear;
  44867. light.shadow.camera.far = data.shadowCameraFar;
  44868. if (light.shadow.camera instanceof THREE.OrthographicCamera) {
  44869. light.shadow.camera.top = data.shadowCameraTop;
  44870. light.shadow.camera.right = data.shadowCameraRight;
  44871. light.shadow.camera.bottom = data.shadowCameraBottom;
  44872. light.shadow.camera.left = data.shadowCameraLeft;
  44873. } else {
  44874. light.shadow.camera.fov = data.shadowCameraFov;
  44875. }
  44876. light.shadow.camera.updateProjectionMatrix();
  44877. if (cameraHelper) { cameraHelper.update(); }
  44878. },
  44879. /**
  44880. * Creates a new three.js light object given data object defining the light.
  44881. *
  44882. * @param {object} data
  44883. */
  44884. getLight: function (data) {
  44885. var angle = data.angle;
  44886. var color = new THREE.Color(data.color).getHex();
  44887. var decay = data.decay;
  44888. var distance = data.distance;
  44889. var groundColor = new THREE.Color(data.groundColor).getHex();
  44890. var intensity = data.intensity;
  44891. var type = data.type;
  44892. var target = data.target;
  44893. var light = null;
  44894. switch (type.toLowerCase()) {
  44895. case 'ambient': {
  44896. return new THREE.AmbientLight(color, intensity);
  44897. }
  44898. case 'directional': {
  44899. light = new THREE.DirectionalLight(color, intensity);
  44900. this.defaultTarget = light.target;
  44901. if (target) {
  44902. if (target.hasLoaded) {
  44903. this.onSetTarget(target, light);
  44904. } else {
  44905. target.addEventListener('loaded', bind(this.onSetTarget, this, target, light));
  44906. }
  44907. }
  44908. return light;
  44909. }
  44910. case 'hemisphere': {
  44911. return new THREE.HemisphereLight(color, groundColor, intensity);
  44912. }
  44913. case 'point': {
  44914. return new THREE.PointLight(color, intensity, distance, decay);
  44915. }
  44916. case 'spot': {
  44917. light = new THREE.SpotLight(color, intensity, distance, degToRad(angle), data.penumbra, decay);
  44918. this.defaultTarget = light.target;
  44919. if (target) {
  44920. if (target.hasLoaded) {
  44921. this.onSetTarget(target, light);
  44922. } else {
  44923. target.addEventListener('loaded', bind(this.onSetTarget, this, target, light));
  44924. }
  44925. }
  44926. return light;
  44927. }
  44928. default: {
  44929. warn('%s is not a valid light type. ' +
  44930. 'Choose from ambient, directional, hemisphere, point, spot.', type);
  44931. }
  44932. }
  44933. },
  44934. onSetTarget: function (targetEl, light) {
  44935. light.target = targetEl.object3D;
  44936. },
  44937. /**
  44938. * Remove light on remove (callback).
  44939. */
  44940. remove: function () {
  44941. var el = this.el;
  44942. el.removeObject3D('light');
  44943. if (el.getObject3D('cameraHelper')) {
  44944. el.removeObject3D('cameraHelper');
  44945. }
  44946. }
  44947. });
  44948. },{"../core/component":102,"../lib/three":149,"../utils":172,"../utils/bind":166,"../utils/debug":168}],66:[function(_dereq_,module,exports){
  44949. var registerComponent = _dereq_('../core/component').registerComponent;
  44950. var THREE = _dereq_('../lib/three');
  44951. var isMobile = _dereq_('../utils/').device.isMobile();
  44952. var bind = _dereq_('../utils/bind');
  44953. // To avoid recalculation at every mouse movement tick
  44954. var PI_2 = Math.PI / 2;
  44955. var radToDeg = THREE.Math.radToDeg;
  44956. module.exports.Component = registerComponent('look-controls', {
  44957. dependencies: ['position', 'rotation'],
  44958. schema: {
  44959. enabled: {default: true},
  44960. hmdEnabled: {default: true},
  44961. reverseMouseDrag: {default: false},
  44962. standing: {default: true}
  44963. },
  44964. init: function () {
  44965. var sceneEl = this.el.sceneEl;
  44966. // Aux variables
  44967. this.previousHMDPosition = new THREE.Vector3();
  44968. this.hmdQuaternion = new THREE.Quaternion();
  44969. this.hmdEuler = new THREE.Euler();
  44970. this.setupMouseControls();
  44971. this.setupHMDControls();
  44972. this.bindMethods();
  44973. this.setEnabled(this.data.enabled);
  44974. // Reset previous HMD position when we exit VR.
  44975. sceneEl.addEventListener('exit-vr', this.onExitVR);
  44976. },
  44977. update: function (oldData) {
  44978. var data = this.data;
  44979. var hmdEnabled = data.hmdEnabled;
  44980. if (oldData && data.enabled !== oldData.enabled) {
  44981. this.setEnabled(data.enabled);
  44982. }
  44983. if (!data.enabled) { return; }
  44984. if (!hmdEnabled && oldData && hmdEnabled !== oldData.hmdEnabled) {
  44985. this.pitchObject.rotation.set(0, 0, 0);
  44986. this.yawObject.rotation.set(0, 0, 0);
  44987. }
  44988. this.controls.standing = data.standing;
  44989. this.controls.update();
  44990. this.updateOrientation();
  44991. this.updatePosition();
  44992. },
  44993. setEnabled: function (enabled) {
  44994. var sceneEl = this.el.sceneEl;
  44995. function enableGrabCursor () {
  44996. sceneEl.canvas.classList.add('a-grab-cursor');
  44997. }
  44998. function disableGrabCursor () {
  44999. sceneEl.canvas.classList.remove('a-grab-cursor');
  45000. }
  45001. if (!sceneEl.canvas) {
  45002. if (enabled) {
  45003. sceneEl.addEventListener('render-target-loaded', enableGrabCursor);
  45004. } else {
  45005. sceneEl.addEventListener('render-target-loaded', disableGrabCursor);
  45006. }
  45007. } else {
  45008. if (enabled) {
  45009. enableGrabCursor();
  45010. } else {
  45011. disableGrabCursor();
  45012. }
  45013. }
  45014. },
  45015. play: function () {
  45016. this.addEventListeners();
  45017. },
  45018. pause: function () {
  45019. this.removeEventListeners();
  45020. },
  45021. tick: function (t) {
  45022. this.update();
  45023. },
  45024. remove: function () {
  45025. this.pause();
  45026. },
  45027. bindMethods: function () {
  45028. this.onMouseDown = bind(this.onMouseDown, this);
  45029. this.onMouseMove = bind(this.onMouseMove, this);
  45030. this.releaseMouse = bind(this.releaseMouse, this);
  45031. this.onTouchStart = bind(this.onTouchStart, this);
  45032. this.onTouchMove = bind(this.onTouchMove, this);
  45033. this.onTouchEnd = bind(this.onTouchEnd, this);
  45034. this.onExitVR = bind(this.onExitVR, this);
  45035. },
  45036. setupMouseControls: function () {
  45037. // The canvas where the scene is painted
  45038. this.mouseDown = false;
  45039. this.pitchObject = new THREE.Object3D();
  45040. this.yawObject = new THREE.Object3D();
  45041. this.yawObject.position.y = 10;
  45042. this.yawObject.add(this.pitchObject);
  45043. },
  45044. setupHMDControls: function () {
  45045. this.dolly = new THREE.Object3D();
  45046. this.euler = new THREE.Euler();
  45047. this.controls = new THREE.VRControls(this.dolly);
  45048. this.controls.userHeight = 0.0;
  45049. },
  45050. addEventListeners: function () {
  45051. var sceneEl = this.el.sceneEl;
  45052. var canvasEl = sceneEl.canvas;
  45053. // listen for canvas to load.
  45054. if (!canvasEl) {
  45055. sceneEl.addEventListener('render-target-loaded', bind(this.addEventListeners, this));
  45056. return;
  45057. }
  45058. // Mouse Events
  45059. canvasEl.addEventListener('mousedown', this.onMouseDown, false);
  45060. window.addEventListener('mousemove', this.onMouseMove, false);
  45061. window.addEventListener('mouseup', this.releaseMouse, false);
  45062. // Touch events
  45063. canvasEl.addEventListener('touchstart', this.onTouchStart);
  45064. window.addEventListener('touchmove', this.onTouchMove);
  45065. window.addEventListener('touchend', this.onTouchEnd);
  45066. },
  45067. removeEventListeners: function () {
  45068. var sceneEl = this.el.sceneEl;
  45069. var canvasEl = sceneEl && sceneEl.canvas;
  45070. if (!canvasEl) { return; }
  45071. // Mouse Events
  45072. canvasEl.removeEventListener('mousedown', this.onMouseDown);
  45073. canvasEl.removeEventListener('mousemove', this.onMouseMove);
  45074. canvasEl.removeEventListener('mouseup', this.releaseMouse);
  45075. canvasEl.removeEventListener('mouseout', this.releaseMouse);
  45076. // Touch events
  45077. canvasEl.removeEventListener('touchstart', this.onTouchStart);
  45078. canvasEl.removeEventListener('touchmove', this.onTouchMove);
  45079. canvasEl.removeEventListener('touchend', this.onTouchEnd);
  45080. },
  45081. updateOrientation: function () {
  45082. var currentRotation;
  45083. var deltaRotation;
  45084. var hmdEuler = this.hmdEuler;
  45085. var pitchObject = this.pitchObject;
  45086. var yawObject = this.yawObject;
  45087. var hmdQuaternion = this.calculateHMDQuaternion();
  45088. var sceneEl = this.el.sceneEl;
  45089. var rotation;
  45090. hmdEuler.setFromQuaternion(hmdQuaternion, 'YXZ');
  45091. if (isMobile) {
  45092. // In mobile we allow camera rotation with touch events and sensors
  45093. rotation = {
  45094. x: radToDeg(hmdEuler.x) + radToDeg(pitchObject.rotation.x),
  45095. y: radToDeg(hmdEuler.y) + radToDeg(yawObject.rotation.y),
  45096. z: radToDeg(hmdEuler.z)
  45097. };
  45098. } else if (!sceneEl.is('vr-mode') || isNullVector(hmdEuler) || !this.data.hmdEnabled) {
  45099. currentRotation = this.el.getAttribute('rotation');
  45100. deltaRotation = this.calculateDeltaRotation();
  45101. // Mouse look only if HMD disabled or no info coming from the sensors
  45102. if (this.data.reverseMouseDrag) {
  45103. rotation = {
  45104. x: currentRotation.x - deltaRotation.x,
  45105. y: currentRotation.y - deltaRotation.y,
  45106. z: currentRotation.z
  45107. };
  45108. } else {
  45109. rotation = {
  45110. x: currentRotation.x + deltaRotation.x,
  45111. y: currentRotation.y + deltaRotation.y,
  45112. z: currentRotation.z
  45113. };
  45114. }
  45115. } else {
  45116. // Mouse rotation ignored with an active headset. User head rotation takes priority.
  45117. rotation = {
  45118. x: radToDeg(hmdEuler.x),
  45119. y: radToDeg(hmdEuler.y),
  45120. z: radToDeg(hmdEuler.z)
  45121. };
  45122. }
  45123. this.el.setAttribute('rotation', rotation);
  45124. },
  45125. calculateDeltaRotation: function () {
  45126. var currentRotationX = radToDeg(this.pitchObject.rotation.x);
  45127. var currentRotationY = radToDeg(this.yawObject.rotation.y);
  45128. var deltaRotation;
  45129. this.previousRotationX = this.previousRotationX || currentRotationX;
  45130. this.previousRotationY = this.previousRotationY || currentRotationY;
  45131. deltaRotation = {
  45132. x: currentRotationX - this.previousRotationX,
  45133. y: currentRotationY - this.previousRotationY
  45134. };
  45135. this.previousRotationX = currentRotationX;
  45136. this.previousRotationY = currentRotationY;
  45137. return deltaRotation;
  45138. },
  45139. calculateHMDQuaternion: function () {
  45140. var hmdQuaternion = this.hmdQuaternion;
  45141. hmdQuaternion.copy(this.dolly.quaternion);
  45142. return hmdQuaternion;
  45143. },
  45144. updatePosition: (function () {
  45145. var deltaHMDPosition = new THREE.Vector3();
  45146. return function () {
  45147. var el = this.el;
  45148. var currentPosition = el.getAttribute('position');
  45149. var currentHMDPosition;
  45150. var previousHMDPosition = this.previousHMDPosition;
  45151. var sceneEl = this.el.sceneEl;
  45152. currentHMDPosition = this.calculateHMDPosition();
  45153. deltaHMDPosition.copy(currentHMDPosition).sub(previousHMDPosition);
  45154. if (!sceneEl.is('vr-mode') || isNullVector(deltaHMDPosition)) { return; }
  45155. previousHMDPosition.copy(currentHMDPosition);
  45156. // Do nothing if we have not moved.
  45157. if (!sceneEl.is('vr-mode')) { return; }
  45158. el.setAttribute('position', {
  45159. x: currentPosition.x + deltaHMDPosition.x,
  45160. y: currentPosition.y + deltaHMDPosition.y,
  45161. z: currentPosition.z + deltaHMDPosition.z
  45162. });
  45163. };
  45164. })(),
  45165. calculateHMDPosition: function () {
  45166. var dolly = this.dolly;
  45167. var position = new THREE.Vector3();
  45168. dolly.updateMatrix();
  45169. position.setFromMatrixPosition(dolly.matrix);
  45170. return position;
  45171. },
  45172. onMouseMove: function (event) {
  45173. var pitchObject = this.pitchObject;
  45174. var yawObject = this.yawObject;
  45175. var previousMouseEvent = this.previousMouseEvent;
  45176. if (!this.mouseDown || !this.data.enabled) { return; }
  45177. var movementX = event.movementX || event.mozMovementX;
  45178. var movementY = event.movementY || event.mozMovementY;
  45179. if (movementX === undefined || movementY === undefined) {
  45180. movementX = event.screenX - previousMouseEvent.screenX;
  45181. movementY = event.screenY - previousMouseEvent.screenY;
  45182. }
  45183. this.previousMouseEvent = event;
  45184. yawObject.rotation.y -= movementX * 0.002;
  45185. pitchObject.rotation.x -= movementY * 0.002;
  45186. pitchObject.rotation.x = Math.max(-PI_2, Math.min(PI_2, pitchObject.rotation.x));
  45187. },
  45188. onMouseDown: function (event) {
  45189. if (!this.data.enabled) { return; }
  45190. // Handle only primary button.
  45191. if (event.button !== 0) { return; }
  45192. this.mouseDown = true;
  45193. this.previousMouseEvent = event;
  45194. document.body.classList.add('a-grabbing');
  45195. },
  45196. releaseMouse: function () {
  45197. this.mouseDown = false;
  45198. document.body.classList.remove('a-grabbing');
  45199. },
  45200. onTouchStart: function (e) {
  45201. if (e.touches.length !== 1) { return; }
  45202. this.touchStart = {
  45203. x: e.touches[0].pageX,
  45204. y: e.touches[0].pageY
  45205. };
  45206. this.touchStarted = true;
  45207. },
  45208. onTouchMove: function (e) {
  45209. var deltaY;
  45210. var yawObject = this.yawObject;
  45211. if (!this.touchStarted) { return; }
  45212. deltaY = 2 * Math.PI * (e.touches[0].pageX - this.touchStart.x) /
  45213. this.el.sceneEl.canvas.clientWidth;
  45214. // Limits touch orientaion to to yaw (y axis)
  45215. yawObject.rotation.y -= deltaY * 0.5;
  45216. this.touchStart = {
  45217. x: e.touches[0].pageX,
  45218. y: e.touches[0].pageY
  45219. };
  45220. },
  45221. onTouchEnd: function () {
  45222. this.touchStarted = false;
  45223. },
  45224. onExitVR: function () {
  45225. this.previousHMDPosition.set(0, 0, 0);
  45226. }
  45227. });
  45228. function isNullVector (vector) {
  45229. return vector.x === 0 && vector.y === 0 && vector.z === 0;
  45230. }
  45231. },{"../core/component":102,"../lib/three":149,"../utils/":172,"../utils/bind":166}],67:[function(_dereq_,module,exports){
  45232. /* global Promise */
  45233. var utils = _dereq_('../utils/');
  45234. var component = _dereq_('../core/component');
  45235. var THREE = _dereq_('../lib/three');
  45236. var shader = _dereq_('../core/shader');
  45237. var error = utils.debug('components:material:error');
  45238. var registerComponent = component.registerComponent;
  45239. var shaders = shader.shaders;
  45240. var shaderNames = shader.shaderNames;
  45241. /**
  45242. * Material component.
  45243. *
  45244. * @member {object} shader - Determines how material is shaded. Defaults to `standard`,
  45245. * three.js's implementation of PBR. Another standard shading model is `flat` which
  45246. * uses MeshBasicMaterial.
  45247. */
  45248. module.exports.Component = registerComponent('material', {
  45249. schema: {
  45250. depthTest: {default: true},
  45251. depthWrite: {default: true},
  45252. alphaTest: {default: 0.0, min: 0.0, max: 1.0},
  45253. flatShading: {default: false},
  45254. opacity: {default: 1.0, min: 0.0, max: 1.0},
  45255. shader: {default: 'standard', oneOf: shaderNames},
  45256. side: {default: 'front', oneOf: ['front', 'back', 'double']},
  45257. transparent: {default: false},
  45258. visible: {default: true},
  45259. offset: {type: 'vec2', default: {x: 0, y: 0}},
  45260. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  45261. npot: {default: false}
  45262. },
  45263. init: function () {
  45264. this.material = null;
  45265. },
  45266. /**
  45267. * Update or create material.
  45268. *
  45269. * @param {object|null} oldData
  45270. */
  45271. update: function (oldData) {
  45272. var data = this.data;
  45273. if (!this.shader || data.shader !== oldData.shader) {
  45274. this.updateShader(data.shader);
  45275. }
  45276. this.shader.update(this.data);
  45277. this.updateMaterial();
  45278. },
  45279. updateSchema: function (data) {
  45280. var newShader = data.shader;
  45281. var currentShader = this.data && this.data.shader;
  45282. var shader = newShader || currentShader;
  45283. var schema = shaders[shader] && shaders[shader].schema;
  45284. if (!schema) { error('Unknown shader schema ' + shader); }
  45285. if (currentShader && newShader === currentShader) { return; }
  45286. this.extendSchema(schema);
  45287. this.updateBehavior();
  45288. },
  45289. updateBehavior: function () {
  45290. var schema = this.schema;
  45291. var self = this;
  45292. var sceneEl = this.el.sceneEl;
  45293. var tickProperties = {};
  45294. var tick = function (time, delta) {
  45295. Object.keys(tickProperties).forEach(function update (key) {
  45296. tickProperties[key] = time;
  45297. });
  45298. self.shader.update(tickProperties);
  45299. };
  45300. this.tick = undefined;
  45301. Object.keys(schema).forEach(function (key) {
  45302. if (schema[key].type === 'time') {
  45303. self.tick = tick;
  45304. tickProperties[key] = true;
  45305. }
  45306. });
  45307. if (!sceneEl) { return; }
  45308. if (!this.tick) {
  45309. sceneEl.removeBehavior(this);
  45310. } else {
  45311. sceneEl.addBehavior(this);
  45312. }
  45313. },
  45314. updateShader: function (shaderName) {
  45315. var data = this.data;
  45316. var Shader = shaders[shaderName] && shaders[shaderName].Shader;
  45317. var shaderInstance;
  45318. if (!Shader) { throw new Error('Unknown shader ' + shaderName); }
  45319. // Get material from A-Frame shader.
  45320. shaderInstance = this.shader = new Shader();
  45321. shaderInstance.el = this.el;
  45322. shaderInstance.init(data);
  45323. this.setMaterial(shaderInstance.material);
  45324. this.updateSchema(data);
  45325. },
  45326. updateMaterial: function () {
  45327. var data = this.data;
  45328. var material = this.material;
  45329. var needsUpdate = false;
  45330. var side = parseSide(data.side);
  45331. if (material.side === THREE.DoubleSide && side !== THREE.DoubleSide ||
  45332. material.side !== THREE.DoubleSide && side === THREE.DoubleSide) {
  45333. needsUpdate = true;
  45334. }
  45335. material.side = side;
  45336. material.opacity = data.opacity;
  45337. material.transparent = data.transparent !== false || data.opacity < 1.0;
  45338. material.depthTest = data.depthTest !== false;
  45339. material.depthWrite = data.depthWrite !== false;
  45340. material.shading = data.flatShading ? THREE.FlatShading : THREE.SmoothShading;
  45341. material.visible = data.visible;
  45342. if (data.alphaTest !== material.alphaTest) { needsUpdate = true; }
  45343. material.alphaTest = data.alphaTest;
  45344. if (needsUpdate) { material.needsUpdate = true; }
  45345. },
  45346. /**
  45347. * Remove material on remove (callback).
  45348. * Dispose of it from memory and unsubscribe from scene updates.
  45349. */
  45350. remove: function () {
  45351. var defaultMaterial = new THREE.MeshBasicMaterial();
  45352. var material = this.material;
  45353. var object3D = this.el.getObject3D('mesh');
  45354. if (object3D) { object3D.material = defaultMaterial; }
  45355. disposeMaterial(material, this.system);
  45356. },
  45357. /**
  45358. * (Re)create new material. Has side-effects of setting `this.material` and updating
  45359. * material registration in scene.
  45360. *
  45361. * @param {object} data - Material component data.
  45362. * @param {object} type - Material type to create.
  45363. * @returns {object} Material.
  45364. */
  45365. setMaterial: function (material) {
  45366. var mesh = this.el.getOrCreateObject3D('mesh', THREE.Mesh);
  45367. var system = this.system;
  45368. if (this.material) { disposeMaterial(this.material, system); }
  45369. this.material = mesh.material = material;
  45370. system.registerMaterial(material);
  45371. }
  45372. });
  45373. /**
  45374. * Returns a three.js constant determining which material face sides to render
  45375. * based on the side parameter (passed as a component property).
  45376. *
  45377. * @param {string} [side=front] - `front`, `back`, or `double`.
  45378. * @returns {number} THREE.FrontSide, THREE.BackSide, or THREE.DoubleSide.
  45379. */
  45380. function parseSide (side) {
  45381. switch (side) {
  45382. case 'back': {
  45383. return THREE.BackSide;
  45384. }
  45385. case 'double': {
  45386. return THREE.DoubleSide;
  45387. }
  45388. default: {
  45389. // Including case `front`.
  45390. return THREE.FrontSide;
  45391. }
  45392. }
  45393. }
  45394. /**
  45395. * Dispose of material from memory and unsubscribe material from scene updates like fog.
  45396. */
  45397. function disposeMaterial (material, system) {
  45398. material.dispose();
  45399. system.unregisterMaterial(material);
  45400. }
  45401. },{"../core/component":102,"../core/shader":111,"../lib/three":149,"../utils/":172}],68:[function(_dereq_,module,exports){
  45402. var debug = _dereq_('../utils/debug');
  45403. var registerComponent = _dereq_('../core/component').registerComponent;
  45404. var THREE = _dereq_('../lib/three');
  45405. var warn = debug('components:obj-model:warn');
  45406. module.exports.Component = registerComponent('obj-model', {
  45407. schema: {
  45408. mtl: {type: 'model'},
  45409. obj: {type: 'model'}
  45410. },
  45411. init: function () {
  45412. this.model = null;
  45413. this.objLoader = new THREE.OBJLoader();
  45414. this.mtlLoader = new THREE.MTLLoader(this.objLoader.manager);
  45415. // Allow cross-origin images to be loaded.
  45416. this.mtlLoader.crossOrigin = '';
  45417. },
  45418. update: function () {
  45419. var data = this.data;
  45420. if (!data.obj) { return; }
  45421. this.remove();
  45422. this.loadObj(data.obj, data.mtl);
  45423. },
  45424. remove: function () {
  45425. if (!this.model) { return; }
  45426. this.el.removeObject3D('mesh');
  45427. },
  45428. loadObj: function (objUrl, mtlUrl) {
  45429. var self = this;
  45430. var el = this.el;
  45431. var mtlLoader = this.mtlLoader;
  45432. var objLoader = this.objLoader;
  45433. if (mtlUrl) {
  45434. // .OBJ with an .MTL.
  45435. if (el.hasAttribute('material')) {
  45436. warn('Material component properties are ignored when a .MTL is provided');
  45437. }
  45438. mtlLoader.setTexturePath(mtlUrl.substr(0, mtlUrl.lastIndexOf('/') + 1));
  45439. mtlLoader.load(mtlUrl, function (materials) {
  45440. materials.preload();
  45441. objLoader.setMaterials(materials);
  45442. objLoader.load(objUrl, function (objModel) {
  45443. self.model = objModel;
  45444. el.setObject3D('mesh', objModel);
  45445. el.emit('model-loaded', {format: 'obj', model: objModel});
  45446. });
  45447. });
  45448. return;
  45449. }
  45450. // .OBJ only.
  45451. objLoader.load(objUrl, function loadObjOnly (objModel) {
  45452. // Apply material.
  45453. var material = el.components.material;
  45454. if (material) {
  45455. objModel.traverse(function (child) {
  45456. if (child instanceof THREE.Mesh) {
  45457. child.material = material.material;
  45458. }
  45459. });
  45460. }
  45461. self.model = objModel;
  45462. el.setObject3D('mesh', objModel);
  45463. el.emit('model-loaded', {format: 'obj', model: objModel});
  45464. });
  45465. }
  45466. });
  45467. },{"../core/component":102,"../lib/three":149,"../utils/debug":168}],69:[function(_dereq_,module,exports){
  45468. var bind = _dereq_('../utils/bind');
  45469. var registerComponent = _dereq_('../core/component').registerComponent;
  45470. var controllerUtils = _dereq_('../utils/tracked-controls');
  45471. var TOUCH_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/oculus/oculus-touch-controller-';
  45472. var TOUCH_CONTROLLER_MODEL_OBJ_URL_L = TOUCH_CONTROLLER_MODEL_BASE_URL + 'left.obj';
  45473. var TOUCH_CONTROLLER_MODEL_OBJ_MTL_L = TOUCH_CONTROLLER_MODEL_BASE_URL + 'left.mtl';
  45474. var TOUCH_CONTROLLER_MODEL_OBJ_URL_R = TOUCH_CONTROLLER_MODEL_BASE_URL + 'right.obj';
  45475. var TOUCH_CONTROLLER_MODEL_OBJ_MTL_R = TOUCH_CONTROLLER_MODEL_BASE_URL + 'right.mtl';
  45476. var GAMEPAD_ID_PREFIX = 'Oculus Touch';
  45477. var PIVOT_OFFSET = {x: 0, y: -0.015, z: 0.04};
  45478. /**
  45479. * Oculus Touch Controls Component
  45480. * Interfaces with Oculus Touch controllers and maps Gamepad events to
  45481. * common controller buttons: trackpad, trigger, grip, menu and system
  45482. * It loads a controller model and highlights the pressed buttons
  45483. */
  45484. module.exports.Component = registerComponent('oculus-touch-controls', {
  45485. schema: {
  45486. hand: {default: 'left'},
  45487. buttonColor: {type: 'color', default: '#999'}, // Off-white.
  45488. buttonTouchColor: {type: 'color', default: '#8AB'},
  45489. buttonHighlightColor: {type: 'color', default: '#2DF'}, // Light blue.
  45490. model: {default: true},
  45491. rotationOffset: {default: 0} // no default offset; -999 is sentinel value to auto-determine based on hand
  45492. },
  45493. // buttonId
  45494. // 0 - thumbstick (which has separate axismove / thumbstickmoved events)
  45495. // 1 - trigger (with analog value, which goes up to 1)
  45496. // 2 - grip (with analog value, which goes up to 1)
  45497. // 3 - X (left) or A (right)
  45498. // 4 - Y (left) or B (right)
  45499. // 5 - surface (touch only)
  45500. mapping: {
  45501. left: {
  45502. axes: {'thumbstick': [0, 1]},
  45503. buttons: ['thumbstick', 'trigger', 'grip', 'xbutton', 'ybutton', 'surface']
  45504. },
  45505. right: {
  45506. axes: {'thumbstick': [0, 1]},
  45507. buttons: ['thumbstick', 'trigger', 'grip', 'abutton', 'bbutton', 'surface']
  45508. }
  45509. },
  45510. // Use these labels for detail on axis events such as thumbstickmoved.
  45511. // e.g. for thumbstickmoved detail, the first axis returned is labeled x, and the second is labeled y.
  45512. axisLabels: ['x', 'y', 'z', 'w'],
  45513. bindMethods: function () {
  45514. this.onModelLoaded = bind(this.onModelLoaded, this);
  45515. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  45516. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  45517. this.onAxisMoved = bind(this.onAxisMoved, this);
  45518. },
  45519. init: function () {
  45520. var self = this;
  45521. this.onButtonChanged = bind(this.onButtonChanged, this);
  45522. this.onButtonDown = function (evt) { self.onButtonEvent(evt.detail.id, 'down'); };
  45523. this.onButtonUp = function (evt) { self.onButtonEvent(evt.detail.id, 'up'); };
  45524. this.onButtonTouchStart = function (evt) { self.onButtonEvent(evt.detail.id, 'touchstart'); };
  45525. this.onButtonTouchEnd = function (evt) { self.onButtonEvent(evt.detail.id, 'touchend'); };
  45526. this.controllerPresent = false;
  45527. this.lastControllerCheck = 0;
  45528. this.previousButtonValues = {};
  45529. this.bindMethods();
  45530. this.emitIfAxesChanged = controllerUtils.emitIfAxesChanged; // Allow mock.
  45531. this.checkControllerPresentAndSetup = controllerUtils.checkControllerPresentAndSetup; // Allow mock.
  45532. },
  45533. addEventListeners: function () {
  45534. var el = this.el;
  45535. el.addEventListener('buttonchanged', this.onButtonChanged);
  45536. el.addEventListener('buttondown', this.onButtonDown);
  45537. el.addEventListener('buttonup', this.onButtonUp);
  45538. el.addEventListener('touchstart', this.onButtonTouchStart);
  45539. el.addEventListener('touchend', this.onButtonTouchEnd);
  45540. el.addEventListener('axismove', this.onAxisMoved);
  45541. el.addEventListener('model-loaded', this.onModelLoaded);
  45542. },
  45543. removeEventListeners: function () {
  45544. var el = this.el;
  45545. el.removeEventListener('buttonchanged', this.onButtonChanged);
  45546. el.removeEventListener('buttondown', this.onButtonDown);
  45547. el.removeEventListener('buttonup', this.onButtonUp);
  45548. el.removeEventListener('touchstart', this.onButtonTouchStart);
  45549. el.removeEventListener('touchend', this.onButtonTouchEnd);
  45550. el.removeEventListener('axismove', this.onAxisMoved);
  45551. el.removeEventListener('model-loaded', this.onModelLoaded);
  45552. },
  45553. checkIfControllerPresent: function () {
  45554. this.checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {
  45555. hand: this.data.hand
  45556. });
  45557. },
  45558. play: function () {
  45559. this.checkIfControllerPresent();
  45560. this.addControllersUpdateListener();
  45561. // Note that due to gamepadconnected event propagation issues, we don't rely on events.
  45562. window.addEventListener('gamepaddisconnected', this.checkIfControllerPresent, false);
  45563. },
  45564. pause: function () {
  45565. this.removeEventListeners();
  45566. this.removeControllersUpdateListener();
  45567. // Note that due to gamepadconnected event propagation issues, we don't rely on events.
  45568. window.removeEventListener('gamepaddisconnected', this.checkIfControllerPresent, false);
  45569. },
  45570. updateControllerModel: function () {
  45571. var objUrl, mtlUrl;
  45572. if (!this.data.model) { return; }
  45573. if (this.data.hand === 'right') {
  45574. objUrl = 'url(' + TOUCH_CONTROLLER_MODEL_OBJ_URL_R + ')';
  45575. mtlUrl = 'url(' + TOUCH_CONTROLLER_MODEL_OBJ_MTL_R + ')';
  45576. } else {
  45577. objUrl = 'url(' + TOUCH_CONTROLLER_MODEL_OBJ_URL_L + ')';
  45578. mtlUrl = 'url(' + TOUCH_CONTROLLER_MODEL_OBJ_MTL_L + ')';
  45579. }
  45580. this.el.setAttribute('obj-model', {obj: objUrl, mtl: mtlUrl});
  45581. },
  45582. injectTrackedControls: function () {
  45583. var data = this.data;
  45584. var offset = data.hand === 'right' ? -90 : 90;
  45585. this.el.setAttribute('tracked-controls', {
  45586. id: data.hand === 'right' ? 'Oculus Touch (Right)' : 'Oculus Touch (Left)',
  45587. controller: 0,
  45588. rotationOffset: data.rotationOffset !== -999 ? data.rotationOffset : offset
  45589. });
  45590. this.updateControllerModel();
  45591. },
  45592. addControllersUpdateListener: function () {
  45593. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  45594. },
  45595. removeControllersUpdateListener: function () {
  45596. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  45597. },
  45598. onControllersUpdate: function () {
  45599. // Note that due to gamepadconnected event propagation issues, we don't rely on events.
  45600. this.checkIfControllerPresent();
  45601. },
  45602. onButtonChanged: function (evt) {
  45603. var button = this.mapping[this.data.hand].buttons[evt.detail.id];
  45604. var buttonMeshes = this.buttonMeshes;
  45605. var analogValue;
  45606. if (!button) { return; }
  45607. if (button === 'trigger' || button === 'grip') { analogValue = evt.detail.state.value; }
  45608. // Update trigger and/or grip meshes, if any.
  45609. if (buttonMeshes) {
  45610. if (button === 'trigger' && buttonMeshes.trigger) {
  45611. buttonMeshes.trigger.rotation.x = -analogValue * (Math.PI / 24);
  45612. }
  45613. if (button === 'grip' && buttonMeshes.grip) {
  45614. buttonMeshes.grip.rotation.y = (this.data.hand === 'left' ? -1 : 1) * analogValue * (Math.PI / 60);
  45615. }
  45616. }
  45617. // Pass along changed event with button state, using the buttom mapping for convenience.
  45618. this.el.emit(button + 'changed', evt.detail.state);
  45619. },
  45620. onModelLoaded: function (evt) {
  45621. var controllerObject3D = evt.detail.model;
  45622. var buttonMeshes;
  45623. if (!this.data.model) { return; }
  45624. var leftHand = this.data.hand === 'left';
  45625. buttonMeshes = this.buttonMeshes = {};
  45626. buttonMeshes.grip = controllerObject3D.getObjectByName(leftHand ? 'buttonHand_oculus-touch-controller-left.004' : 'buttonHand_oculus-touch-controller-right.005');
  45627. buttonMeshes.thumbstick = controllerObject3D.getObjectByName(leftHand ? 'stick_oculus-touch-controller-left.007' : 'stick_oculus-touch-controller-right.004');
  45628. buttonMeshes.trigger = controllerObject3D.getObjectByName(leftHand ? 'buttonTrigger_oculus-touch-controller-left.005' : 'buttonTrigger_oculus-touch-controller-right.006');
  45629. buttonMeshes.xbutton = controllerObject3D.getObjectByName('buttonX_oculus-touch-controller-left.002');
  45630. buttonMeshes.abutton = controllerObject3D.getObjectByName('buttonA_oculus-touch-controller-right.002');
  45631. buttonMeshes.ybutton = controllerObject3D.getObjectByName('buttonY_oculus-touch-controller-left.001');
  45632. buttonMeshes.bbutton = controllerObject3D.getObjectByName('buttonB_oculus-touch-controller-right.003');
  45633. // Offset pivot point
  45634. controllerObject3D.position = PIVOT_OFFSET;
  45635. },
  45636. onButtonEvent: function (id, evtName) {
  45637. var buttonName = this.mapping[this.data.hand].buttons[id];
  45638. var i;
  45639. if (Array.isArray(buttonName)) {
  45640. for (i = 0; i < buttonName.length; i++) {
  45641. this.el.emit(buttonName[i] + evtName);
  45642. }
  45643. } else {
  45644. this.el.emit(buttonName + evtName);
  45645. }
  45646. this.updateModel(buttonName, evtName);
  45647. },
  45648. onAxisMoved: function (evt) {
  45649. this.emitIfAxesChanged(this, this.mapping[this.data.hand].axes, evt);
  45650. },
  45651. updateModel: function (buttonName, evtName) {
  45652. var i;
  45653. if (Array.isArray(buttonName)) {
  45654. for (i = 0; i < buttonName.length; i++) {
  45655. this.updateButtonModel(buttonName[i], evtName);
  45656. }
  45657. } else {
  45658. this.updateButtonModel(buttonName, evtName);
  45659. }
  45660. },
  45661. updateButtonModel: function (buttonName, state) {
  45662. var color = (state === 'up' || state === 'touchend') ? this.data.buttonColor : state === 'touchstart' ? this.data.buttonTouchColor : this.data.buttonHighlightColor;
  45663. var buttonMeshes = this.buttonMeshes;
  45664. if (!this.data.model) { return; }
  45665. if (buttonMeshes && buttonMeshes[buttonName]) {
  45666. buttonMeshes[buttonName].material.color.set(color);
  45667. }
  45668. }
  45669. });
  45670. },{"../core/component":102,"../utils/bind":166,"../utils/tracked-controls":176}],70:[function(_dereq_,module,exports){
  45671. var registerComponent = _dereq_('../core/component').registerComponent;
  45672. module.exports.Component = registerComponent('position', {
  45673. schema: {type: 'vec3'},
  45674. update: function () {
  45675. var object3D = this.el.object3D;
  45676. var data = this.data;
  45677. object3D.position.set(data.x, data.y, data.z);
  45678. }
  45679. });
  45680. },{"../core/component":102}],71:[function(_dereq_,module,exports){
  45681. var registerComponent = _dereq_('../core/component').registerComponent;
  45682. var THREE = _dereq_('../lib/three');
  45683. var bind = _dereq_('../utils/').bind;
  45684. var scaleDummy = new THREE.Vector3();
  45685. /**
  45686. * Raycaster component.
  45687. *
  45688. * Pass options to three.js Raycaster including which objects to test.
  45689. * Poll for intersections.
  45690. * Emit event on origin entity and on target entity on intersect.
  45691. *
  45692. * @member {array} intersectedEls - List of currently intersected entities.
  45693. * @member {array} objects - Cached list of meshes to intersect.
  45694. * @member {number} prevCheckTime - Previous time intersection was checked. To help interval.
  45695. * @member {object} raycaster - three.js Raycaster.
  45696. */
  45697. module.exports.Component = registerComponent('raycaster', {
  45698. schema: {
  45699. far: {default: Infinity}, // Infinity.
  45700. interval: {default: 100},
  45701. near: {default: 0},
  45702. objects: {default: ''},
  45703. recursive: {default: true}
  45704. },
  45705. init: function () {
  45706. this.direction = new THREE.Vector3();
  45707. this.intersectedEls = [];
  45708. this.objects = null;
  45709. this.prevCheckTime = undefined;
  45710. this.raycaster = new THREE.Raycaster();
  45711. this.updateOriginDirection();
  45712. this.refreshObjects = bind(this.refreshObjects, this);
  45713. this.refreshOnceChildLoaded = bind(this.refreshOnceChildLoaded, this);
  45714. },
  45715. play: function () {
  45716. this.el.sceneEl.addEventListener('loaded', this.refreshObjects);
  45717. this.el.sceneEl.addEventListener('child-attached', this.refreshOnceChildLoaded);
  45718. this.el.sceneEl.addEventListener('child-detached', this.refreshObjects);
  45719. },
  45720. pause: function () {
  45721. this.el.sceneEl.removeEventListener('loaded', this.refreshObjects);
  45722. this.el.sceneEl.removeEventListener('child-attached', this.refreshOnceChildLoaded);
  45723. this.el.sceneEl.removeEventListener('child-detached', this.refreshObjects);
  45724. },
  45725. /**
  45726. * Create or update raycaster object.
  45727. */
  45728. update: function () {
  45729. var data = this.data;
  45730. var raycaster = this.raycaster;
  45731. // Set raycaster properties.
  45732. raycaster.far = data.far;
  45733. raycaster.near = data.near;
  45734. this.refreshObjects();
  45735. },
  45736. /**
  45737. * Update list of objects to test for intersection once child is loaded.
  45738. */
  45739. refreshOnceChildLoaded: function (evt) {
  45740. var self = this;
  45741. var childEl = evt.detail.el;
  45742. if (!childEl) { return; }
  45743. if (childEl.hasLoaded) {
  45744. this.refreshObjects();
  45745. } else {
  45746. childEl.addEventListener('loaded', function nowRefresh (evt) {
  45747. childEl.removeEventListener('loaded', nowRefresh);
  45748. self.refreshObjects();
  45749. });
  45750. }
  45751. },
  45752. /**
  45753. * Update list of objects to test for intersection.
  45754. */
  45755. refreshObjects: function () {
  45756. var children;
  45757. var data = this.data;
  45758. var i;
  45759. var objects;
  45760. // Target entitie .
  45761. var objectEls = data.objects ? this.el.sceneEl.querySelectorAll(data.objects) : null;
  45762. // Push meshes onto list of objects to intersect.
  45763. if (objectEls) {
  45764. objects = [];
  45765. for (i = 0; i < objectEls.length; i++) {
  45766. objects.push(objectEls[i].object3D);
  45767. }
  45768. } else {
  45769. // If objects not defined, intersect with everything.
  45770. objects = this.el.sceneEl.object3D.children;
  45771. }
  45772. this.objects = [];
  45773. for (i = 0; i < objects.length; i++) {
  45774. // A-Frame wraps everything (e.g. in a Group) so we want children.
  45775. children = objects[i].children;
  45776. // Add the object3D's children so non-recursive raycasting will work correctly.
  45777. // If there aren't any children, then until a refresh after geometry loads,
  45778. // raycast won't see this object... but that should happen automatically.
  45779. if (children) { this.objects.push.apply(this.objects, children); }
  45780. }
  45781. },
  45782. /**
  45783. * Check for intersections and cleared intersections on an interval.
  45784. */
  45785. tick: function (time) {
  45786. var el = this.el;
  45787. var data = this.data;
  45788. var intersectedEls;
  45789. var intersections;
  45790. var prevCheckTime = this.prevCheckTime;
  45791. var prevIntersectedEls;
  45792. // Only check for intersection if interval time has passed.
  45793. if (prevCheckTime && (time - prevCheckTime < data.interval)) { return; }
  45794. // Update check time.
  45795. this.prevCheckTime = time;
  45796. // Store old previously intersected entities.
  45797. prevIntersectedEls = this.intersectedEls.slice();
  45798. // Raycast.
  45799. this.updateOriginDirection();
  45800. intersections = this.raycaster.intersectObjects(this.objects, data.recursive);
  45801. // Only keep intersections against objects that have a reference to an entity.
  45802. intersections = intersections.filter(function hasEl (intersection) {
  45803. return !!intersection.object.el;
  45804. });
  45805. // Update intersectedEls.
  45806. intersectedEls = this.intersectedEls = intersections.map(function getEl (intersection) {
  45807. return intersection.object.el;
  45808. });
  45809. // Emit intersected on intersected entity per intersected entity.
  45810. intersections.forEach(function emitEvents (intersection) {
  45811. var intersectedEl = intersection.object.el;
  45812. intersectedEl.emit('raycaster-intersected', {el: el, intersection: intersection});
  45813. });
  45814. // Emit all intersections at once on raycasting entity.
  45815. if (intersections.length) {
  45816. el.emit('raycaster-intersection', {
  45817. els: intersectedEls.slice(),
  45818. intersections: intersections
  45819. });
  45820. }
  45821. // Emit intersection cleared on both entities per formerly intersected entity.
  45822. prevIntersectedEls.forEach(function checkStillIntersected (intersectedEl) {
  45823. if (intersectedEls.indexOf(intersectedEl) !== -1) { return; }
  45824. el.emit('raycaster-intersection-cleared', {el: intersectedEl});
  45825. intersectedEl.emit('raycaster-intersected-cleared', {el: el});
  45826. });
  45827. },
  45828. /**
  45829. * Set origin and direction of raycaster using entity position and rotation.
  45830. */
  45831. updateOriginDirection: (function () {
  45832. var directionHelper = new THREE.Quaternion();
  45833. var originVec3 = new THREE.Vector3();
  45834. // Closure to make quaternion/vector3 objects private.
  45835. return function updateOriginDirection () {
  45836. var el = this.el;
  45837. var object3D = el.object3D;
  45838. // Update matrix world.
  45839. object3D.updateMatrixWorld();
  45840. // Grab the position and rotation.
  45841. object3D.matrixWorld.decompose(originVec3, directionHelper, scaleDummy);
  45842. // Apply rotation to a 0, 0, -1 vector.
  45843. this.direction.set(0, 0, -1);
  45844. this.direction.applyQuaternion(directionHelper);
  45845. this.raycaster.set(originVec3, this.direction);
  45846. };
  45847. })()
  45848. });
  45849. },{"../core/component":102,"../lib/three":149,"../utils/":172}],72:[function(_dereq_,module,exports){
  45850. var degToRad = _dereq_('../lib/three').Math.degToRad;
  45851. var registerComponent = _dereq_('../core/component').registerComponent;
  45852. module.exports.Component = registerComponent('rotation', {
  45853. schema: {type: 'vec3'},
  45854. /**
  45855. * Updates object3D rotation.
  45856. */
  45857. update: function () {
  45858. var data = this.data;
  45859. var object3D = this.el.object3D;
  45860. object3D.rotation.set(degToRad(data.x), degToRad(data.y), degToRad(data.z));
  45861. object3D.rotation.order = 'YXZ';
  45862. }
  45863. });
  45864. },{"../core/component":102,"../lib/three":149}],73:[function(_dereq_,module,exports){
  45865. var registerComponent = _dereq_('../core/component').registerComponent;
  45866. // Avoids triggering a zero-determinant which makes object3D matrix non-invertible.
  45867. var zeroScale = 0.00001;
  45868. module.exports.Component = registerComponent('scale', {
  45869. schema: {
  45870. type: 'vec3',
  45871. default: {x: 1, y: 1, z: 1}
  45872. },
  45873. update: function () {
  45874. var data = this.data;
  45875. var object3D = this.el.object3D;
  45876. var x = data.x === 0 ? zeroScale : data.x;
  45877. var y = data.y === 0 ? zeroScale : data.y;
  45878. var z = data.z === 0 ? zeroScale : data.z;
  45879. object3D.scale.set(x, y, z);
  45880. }
  45881. });
  45882. },{"../core/component":102}],74:[function(_dereq_,module,exports){
  45883. var registerComponent = _dereq_('../../core/component').registerComponent;
  45884. var utils = _dereq_('../../utils');
  45885. /**
  45886. * Automatically enter VR, either upon vrdisplayactivate (e.g. putting on Rift headset)
  45887. * or immediately (if possible) if display name contains data string.
  45888. * The default data string is 'GearVR' for Carmel browser which only does VR.
  45889. */
  45890. module.exports.Component = registerComponent('auto-enter-vr', {
  45891. schema: {
  45892. display: {type: 'string', default: 'GearVR'},
  45893. enabled: {type: 'boolean', default: true}
  45894. },
  45895. init: function () {
  45896. var scene = this.el;
  45897. var self = this;
  45898. // define methods to allow mock testing
  45899. this.enterVR = scene.enterVR.bind(scene);
  45900. this.exitVR = scene.exitVR.bind(scene);
  45901. this.shouldAutoEnterVR = this.shouldAutoEnterVR.bind(this);
  45902. // don't do anything if false
  45903. if (utils.getUrlParameter('auto-enter-vr') === 'false') { return; }
  45904. // enter VR on vrdisplayactivate (e.g. putting on Rift headset)
  45905. window.addEventListener('vrdisplayactivate', function () { self.enterVR(); }, false);
  45906. // exit VR on vrdisplaydeactivate (e.g. taking off Rift headset)
  45907. window.addEventListener('vrdisplaydeactivate', function () { self.exitVR(); }, false);
  45908. // check if we should try to enter VR... turns out we need to wait for next tick
  45909. setTimeout(function () { if (self.shouldAutoEnterVR()) { self.enterVR(); } }, 0);
  45910. },
  45911. update: function () {
  45912. return this.shouldAutoEnterVR() ? this.enterVR() : this.exitVR();
  45913. },
  45914. shouldAutoEnterVR: function () {
  45915. var scene = this.el;
  45916. var data = this.data;
  45917. // if false, we should not auto-enter VR
  45918. if (!data.enabled) { return false; }
  45919. // if we have a data string to match against display name, try and get it;
  45920. // if we can't get display name, or it doesn't match, we should not auto-enter VR
  45921. if (data.display && data.display !== 'all') {
  45922. var display = scene.effect && scene.effect.getVRDisplay && scene.effect.getVRDisplay();
  45923. if (!display || !display.displayName || display.displayName.indexOf(data.display) < 0) { return false; }
  45924. }
  45925. // we should auto-enter VR
  45926. return true;
  45927. }
  45928. });
  45929. },{"../../core/component":102,"../../utils":172}],75:[function(_dereq_,module,exports){
  45930. var bind = _dereq_('../../utils/bind');
  45931. var registerComponent = _dereq_('../../core/component').registerComponent;
  45932. module.exports.Component = registerComponent('canvas', {
  45933. init: function () {
  45934. var canvasEl;
  45935. var sceneEl = this.el;
  45936. canvasEl = document.createElement('canvas');
  45937. canvasEl.classList.add('a-canvas');
  45938. // Mark canvas as provided/injected by A-Frame.
  45939. canvasEl.dataset.aframeCanvas = true;
  45940. sceneEl.appendChild(canvasEl);
  45941. document.addEventListener('fullscreenchange', onFullScreenChange);
  45942. document.addEventListener('mozfullscreenchange', onFullScreenChange);
  45943. document.addEventListener('webkitfullscreenchange', onFullScreenChange);
  45944. // Prevent overscroll on mobile.
  45945. canvasEl.addEventListener('touchmove', function (event) {
  45946. event.preventDefault();
  45947. });
  45948. // Set canvas on scene.
  45949. sceneEl.canvas = canvasEl;
  45950. sceneEl.emit('render-target-loaded', {target: canvasEl});
  45951. // For unknown reasons a syncrhonous resize does not work on desktop when
  45952. // entering/exiting fullscreen.
  45953. setTimeout(bind(sceneEl.resize, sceneEl), 0);
  45954. function onFullScreenChange () {
  45955. var fullscreenEl =
  45956. document.fullscreenElement ||
  45957. document.mozFullScreenElement ||
  45958. document.webkitFullscreenElement;
  45959. // No fullscren element === exit fullscreen
  45960. if (!fullscreenEl) { sceneEl.exitVR(); }
  45961. document.activeElement.blur();
  45962. document.body.focus();
  45963. }
  45964. }
  45965. });
  45966. },{"../../core/component":102,"../../utils/bind":166}],76:[function(_dereq_,module,exports){
  45967. var register = _dereq_('../../core/component').registerComponent;
  45968. module.exports.Component = register('debug', {
  45969. schema: {default: true}
  45970. });
  45971. },{"../../core/component":102}],77:[function(_dereq_,module,exports){
  45972. var registerComponent = _dereq_('../../core/component').registerComponent;
  45973. /**
  45974. * Component to embed an a-frame scene within the layout of a 2D page.
  45975. */
  45976. module.exports.Component = registerComponent('embedded', {
  45977. dependencies: ['vr-mode-ui'],
  45978. schema: {default: true},
  45979. update: function () {
  45980. var sceneEl = this.el;
  45981. var enterVREl = sceneEl.querySelector('.a-enter-vr');
  45982. if (this.data === true) {
  45983. if (enterVREl) { enterVREl.classList.add('embedded'); }
  45984. sceneEl.removeFullScreenStyles();
  45985. } else {
  45986. if (enterVREl) { enterVREl.classList.remove('embedded'); }
  45987. sceneEl.addFullScreenStyles();
  45988. }
  45989. }
  45990. });
  45991. },{"../../core/component":102}],78:[function(_dereq_,module,exports){
  45992. var register = _dereq_('../../core/component').registerComponent;
  45993. var THREE = _dereq_('../../lib/three');
  45994. var debug = _dereq_('../../utils/debug');
  45995. var warn = debug('components:fog:warn');
  45996. /**
  45997. * Fog component.
  45998. * Applies only to the scene entity.
  45999. */
  46000. module.exports.Component = register('fog', {
  46001. schema: {
  46002. color: {type: 'color', default: '#000'},
  46003. density: {default: 0.00025},
  46004. far: {default: 1000, min: 0},
  46005. near: {default: 1, min: 0},
  46006. type: {default: 'linear', oneOf: ['linear', 'exponential']}
  46007. },
  46008. update: function () {
  46009. var data = this.data;
  46010. var el = this.el;
  46011. var fog = this.el.object3D.fog;
  46012. if (!el.isScene) {
  46013. warn('Fog component can only be applied to <a-scene>');
  46014. return;
  46015. }
  46016. // (Re)create fog if fog doesn't exist or fog type changed.
  46017. if (!fog || data.type !== fog.name) {
  46018. el.object3D.fog = getFog(data);
  46019. el.systems.material.updateMaterials();
  46020. return;
  46021. }
  46022. // Fog data changed. Update fog.
  46023. Object.keys(this.schema).forEach(function (key) {
  46024. var value = data[key];
  46025. if (key === 'color') { value = new THREE.Color(value); }
  46026. fog[key] = value;
  46027. });
  46028. },
  46029. /**
  46030. * Remove fog on remove (callback).
  46031. */
  46032. remove: function () {
  46033. var fog = this.el.object3D.fog;
  46034. if (!fog) { return; }
  46035. fog.far = 0;
  46036. fog.near = 0.1;
  46037. }
  46038. });
  46039. /**
  46040. * Creates a fog object. Sets fog.name to be able to detect fog type changes.
  46041. *
  46042. * @param {object} data - Fog data.
  46043. * @returns {object} fog
  46044. */
  46045. function getFog (data) {
  46046. var fog;
  46047. if (data.type === 'exponential') {
  46048. fog = new THREE.FogExp2(data.color, data.density);
  46049. } else {
  46050. fog = new THREE.Fog(data.color, data.near, data.far);
  46051. }
  46052. fog.name = data.type;
  46053. return fog;
  46054. }
  46055. },{"../../core/component":102,"../../lib/three":149,"../../utils/debug":168}],79:[function(_dereq_,module,exports){
  46056. (function (process){
  46057. /* global AFRAME */
  46058. var AFRAME_INJECTED = _dereq_('../../constants').AFRAME_INJECTED;
  46059. var bind = _dereq_('../../utils/bind');
  46060. var pkg = _dereq_('../../../package');
  46061. var registerComponent = _dereq_('../../core/component').registerComponent;
  46062. /**
  46063. * 0.4.2 to 0.4.x
  46064. * Will need to update this when A-Frame goes to 1.x.x.
  46065. */
  46066. function getFuzzyPatchVersion (version) {
  46067. var split = version.split('.');
  46068. split[2] = 'x';
  46069. return split.join('.');
  46070. }
  46071. var INSPECTOR_DEV_URL = 'https://aframe.io/aframe-inspector/dist/aframe-inspector.js';
  46072. var INSPECTOR_RELEASE_URL = 'https://unpkg.com/aframe-inspector@' + getFuzzyPatchVersion(pkg.version) + '/dist/aframe-inspector.min.js';
  46073. var INSPECTOR_URL = process.env.INSPECTOR_VERSION === 'dev' ? INSPECTOR_DEV_URL : INSPECTOR_RELEASE_URL;
  46074. var LOADING_MESSAGE = 'Loading Inspector';
  46075. var LOADING_ERROR_MESSAGE = 'Error loading Inspector';
  46076. module.exports.Component = registerComponent('inspector', {
  46077. schema: {
  46078. url: {default: INSPECTOR_URL}
  46079. },
  46080. init: function () {
  46081. this.onKeydown = bind(this.onKeydown, this);
  46082. this.onMessage = bind(this.onMessage, this);
  46083. this.initOverlay();
  46084. window.addEventListener('keydown', this.onKeydown);
  46085. window.addEventListener('message', this.onMessage);
  46086. },
  46087. initOverlay: function () {
  46088. var dotsHTML = '<span class="dots"><span>.</span><span>.</span><span>.</span></span>';
  46089. this.loadingMessageEl = document.createElement('div');
  46090. this.loadingMessageEl.classList.add('a-inspector-loader');
  46091. this.loadingMessageEl.innerHTML = LOADING_MESSAGE + dotsHTML;
  46092. },
  46093. remove: function () {
  46094. this.removeEventListeners();
  46095. },
  46096. /**
  46097. * <ctrl> + <alt> + i keyboard shortcut.
  46098. */
  46099. onKeydown: function (evt) {
  46100. var shortcutPressed = evt.keyCode === 73 && evt.ctrlKey && evt.altKey;
  46101. if (!this.data || !shortcutPressed) { return; }
  46102. this.injectInspector();
  46103. },
  46104. showLoader: function () {
  46105. document.body.appendChild(this.loadingMessageEl);
  46106. },
  46107. hideLoader: function () {
  46108. document.body.removeChild(this.loadingMessageEl);
  46109. },
  46110. /**
  46111. * postMessage. aframe.io uses this to create a button on examples to open Inspector.
  46112. */
  46113. onMessage: function (evt) {
  46114. if (evt.data === 'INJECT_AFRAME_INSPECTOR') { this.injectInspector(); }
  46115. },
  46116. injectInspector: function () {
  46117. var self = this;
  46118. var script;
  46119. if (AFRAME.INSPECTOR || AFRAME.inspectorInjected) { return; }
  46120. this.showLoader();
  46121. // Inject.
  46122. script = document.createElement('script');
  46123. script.src = this.data.url;
  46124. script.setAttribute('data-name', 'aframe-inspector');
  46125. script.setAttribute(AFRAME_INJECTED, '');
  46126. script.onload = function () {
  46127. AFRAME.INSPECTOR.open();
  46128. self.hideLoader();
  46129. self.removeEventListeners();
  46130. };
  46131. script.onerror = function () {
  46132. self.loadingMessageEl.innerHTML = LOADING_ERROR_MESSAGE;
  46133. };
  46134. document.head.appendChild(script);
  46135. AFRAME.inspectorInjected = true;
  46136. },
  46137. removeEventListeners: function () {
  46138. window.removeEventListener('keydown', this.onKeydown);
  46139. window.removeEventListener('message', this.onMessage);
  46140. }
  46141. });
  46142. }).call(this,_dereq_('_process'))
  46143. },{"../../../package":54,"../../constants":93,"../../core/component":102,"../../utils/bind":166,"_process":33}],80:[function(_dereq_,module,exports){
  46144. var registerComponent = _dereq_('../../core/component').registerComponent;
  46145. var shouldCaptureKeyEvent = _dereq_('../../utils/').shouldCaptureKeyEvent;
  46146. module.exports.Component = registerComponent('keyboard-shortcuts', {
  46147. schema: {
  46148. enterVR: {default: true},
  46149. exitVR: {default: true}
  46150. },
  46151. init: function () {
  46152. var self = this;
  46153. var scene = this.el;
  46154. this.listener = window.addEventListener('keyup', function (event) {
  46155. if (!shouldCaptureKeyEvent(event)) { return; }
  46156. if (self.enterVREnabled && event.keyCode === 70) { // f.
  46157. scene.enterVR();
  46158. }
  46159. if (self.enterVREnabled && event.keyCode === 27) { // escape.
  46160. scene.exitVR();
  46161. }
  46162. }, false);
  46163. },
  46164. update: function (oldData) {
  46165. var data = this.data;
  46166. this.enterVREnabled = data.enterVR;
  46167. },
  46168. remove: function () {
  46169. window.removeEventListener('keyup', this.listener);
  46170. }
  46171. });
  46172. },{"../../core/component":102,"../../utils/":172}],81:[function(_dereq_,module,exports){
  46173. var debug = _dereq_('../../utils/debug');
  46174. var registerComponent = _dereq_('../../core/component').registerComponent;
  46175. var warn = debug('components:pool:warn');
  46176. /**
  46177. * Pool component.
  46178. * A pool of entities that will be reused.
  46179. * It avoids creating and destroying the same kind of entities
  46180. * in dynamic scenes. It will help reduce GC pauses. Useful for example
  46181. * in a game where you want to reuse enemies entities.
  46182. *
  46183. * @member {array} availableEls - Available entities in the pool.
  46184. * @member {array} usedEls - Entities of the pool in use.
  46185. *
  46186. */
  46187. module.exports.Component = registerComponent('pool', {
  46188. schema: {
  46189. mixin: {default: ''},
  46190. size: {default: 0},
  46191. dynamic: {default: false}
  46192. },
  46193. multiple: true,
  46194. initPool: function () {
  46195. var i;
  46196. var mixin = this.data.mixin;
  46197. if (!mixin) { return; }
  46198. this.availableEls = [];
  46199. this.usedEls = [];
  46200. for (i = 0; i < this.data.size; ++i) {
  46201. this.createEntity();
  46202. }
  46203. },
  46204. update: function (oldData) {
  46205. var data = this.data;
  46206. if (oldData.mixin !== data.mixin || oldData.size !== data.size) {
  46207. this.initPool();
  46208. }
  46209. },
  46210. /**
  46211. * Add a new entity to the list of available entities.
  46212. */
  46213. createEntity: function () {
  46214. var el = document.createElement('a-entity');
  46215. el.play = this.wrapPlay(el.play);
  46216. el.setAttribute('mixin', this.data.mixin);
  46217. el.setAttribute('visible', false);
  46218. this.el.appendChild(el);
  46219. this.availableEls.push(el);
  46220. },
  46221. /**
  46222. * Play wrapper for pooled entities. When pausing and playing
  46223. * a scene we don't want to play the entities that are not in use
  46224. */
  46225. wrapPlay: function (playMethod) {
  46226. var usedEls = this.usedEls;
  46227. return function () {
  46228. if (usedEls.indexOf(this) === -1) { return; }
  46229. playMethod.call(this);
  46230. };
  46231. },
  46232. /**
  46233. * Used to request one of the available entities of the pool
  46234. */
  46235. requestEntity: function () {
  46236. var el;
  46237. if (this.availableEls.length === 0) {
  46238. if (this.data.dynamic === false) {
  46239. warn('Requested entity from empty pool ' + this.name);
  46240. return;
  46241. } else {
  46242. warn('Requested entity from empty pool. This pool is dynamic' +
  46243. 'and will resize automatically. You might want to increase its initial size' + this.name);
  46244. }
  46245. this.createEntity();
  46246. }
  46247. el = this.availableEls.shift();
  46248. this.usedEls.push(el);
  46249. el.setAttribute('visible', true);
  46250. return el;
  46251. },
  46252. /**
  46253. * Used to return a used entity to the pool
  46254. */
  46255. returnEntity: function (el) {
  46256. var index = this.usedEls.indexOf(el);
  46257. if (index === -1) {
  46258. warn('The returned entity was not previously pooled from ' + this.name);
  46259. return;
  46260. }
  46261. this.usedEls.splice(index, 1);
  46262. this.availableEls.push(el);
  46263. el.setAttribute('visible', false);
  46264. el.pause();
  46265. }
  46266. });
  46267. },{"../../core/component":102,"../../utils/debug":168}],82:[function(_dereq_,module,exports){
  46268. /* global ImageData, URL */
  46269. var registerComponent = _dereq_('../../core/component').registerComponent;
  46270. var THREE = _dereq_('../../lib/three');
  46271. var VERTEX_SHADER = [
  46272. 'attribute vec3 position;',
  46273. 'attribute vec2 uv;',
  46274. 'uniform mat4 projectionMatrix;',
  46275. 'uniform mat4 modelViewMatrix;',
  46276. 'varying vec2 vUv;',
  46277. 'void main() {',
  46278. ' vUv = vec2( 1.- uv.x, uv.y );',
  46279. ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );',
  46280. '}'
  46281. ].join('\n');
  46282. var FRAGMENT_SHADER = [
  46283. 'precision mediump float;',
  46284. 'uniform samplerCube map;',
  46285. 'varying vec2 vUv;',
  46286. '#define M_PI 3.141592653589793238462643383279',
  46287. 'void main() {',
  46288. ' vec2 uv = vUv;',
  46289. ' float longitude = uv.x * 2. * M_PI - M_PI + M_PI / 2.;',
  46290. ' float latitude = uv.y * M_PI;',
  46291. ' vec3 dir = vec3(',
  46292. ' - sin( longitude ) * sin( latitude ),',
  46293. ' cos( latitude ),',
  46294. ' - cos( longitude ) * sin( latitude )',
  46295. ' );',
  46296. ' normalize( dir );',
  46297. ' gl_FragColor = vec4( textureCube( map, dir ).rgb, 1.0 );',
  46298. '}'
  46299. ].join('\n');
  46300. /**
  46301. * Component to take screenshots of the scene using a keboard shortcut (alt+s).
  46302. * It can be configured to either take 360&deg; captures (`equirectangular`)
  46303. * or regular screenshots (`projection`)
  46304. *
  46305. * This is based on https://github.com/spite/THREE.CubemapToEquirectangular
  46306. * To capture an equirectangular projection of the scene a THREE.CubeCamera is used
  46307. * The cube map produced by the CubeCamera is projected on a quad and then rendered to
  46308. * WebGLRenderTarget with an ortographic camera.
  46309. */
  46310. module.exports.Component = registerComponent('screenshot', {
  46311. schema: {
  46312. width: {default: 4096},
  46313. height: {default: 2048}
  46314. },
  46315. init: function () {
  46316. var el = this.el;
  46317. var self = this;
  46318. if (el.renderer) {
  46319. setup();
  46320. } else {
  46321. el.addEventListener('render-target-loaded', setup);
  46322. }
  46323. function setup () {
  46324. var gl = el.renderer.getContext();
  46325. self.cubeMapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  46326. self.material = new THREE.RawShaderMaterial({
  46327. uniforms: {map: {type: 't', value: null}},
  46328. vertexShader: VERTEX_SHADER,
  46329. fragmentShader: FRAGMENT_SHADER,
  46330. side: THREE.DoubleSide
  46331. });
  46332. self.quad = new THREE.Mesh(
  46333. new THREE.PlaneBufferGeometry(1, 1),
  46334. self.material
  46335. );
  46336. self.quad.visible = false;
  46337. self.camera = new THREE.OrthographicCamera(-1 / 2, 1 / 2, 1 / 2, -1 / 2, -10000, 10000);
  46338. self.canvas = document.createElement('canvas');
  46339. self.ctx = self.canvas.getContext('2d');
  46340. if (el.camera) { el.camera.add(self.quad); }
  46341. self.onKeyDown = self.onKeyDown.bind(self);
  46342. self.onCameraActive = self.onCameraActive.bind(self);
  46343. el.addEventListener('camera-set-active', self.onCameraActive);
  46344. }
  46345. },
  46346. getRenderTarget: function (width, height) {
  46347. return new THREE.WebGLRenderTarget(width, height, {
  46348. minFilter: THREE.LinearFilter,
  46349. magFilter: THREE.LinearFilter,
  46350. wrapS: THREE.ClampToEdgeWrapping,
  46351. wrapT: THREE.ClampToEdgeWrapping,
  46352. format: THREE.RGBAFormat,
  46353. type: THREE.UnsignedByteType
  46354. });
  46355. },
  46356. resize: function (width, height) {
  46357. // Resize quad.
  46358. this.quad.scale.set(width, height, 1);
  46359. // Resize camera.
  46360. this.camera.left = -1 * width / 2;
  46361. this.camera.right = width / 2;
  46362. this.camera.top = height / 2;
  46363. this.camera.bottom = -1 * height / 2;
  46364. this.camera.updateProjectionMatrix();
  46365. // Resize canvas.
  46366. this.canvas.width = width;
  46367. this.canvas.height = height;
  46368. },
  46369. play: function () {
  46370. window.addEventListener('keydown', this.onKeyDown);
  46371. },
  46372. onCameraActive: function (evt) {
  46373. var cameraParent = this.quad.parent;
  46374. if (cameraParent) { cameraParent.remove(this.quad); }
  46375. evt.detail.cameraEl.getObject3D('camera').add(this.quad);
  46376. },
  46377. /**
  46378. * <ctrl> + <alt> + s = Regular screenshot.
  46379. * <ctrl> + <alt> + <shift> + s = Equirectangular screenshot.
  46380. */
  46381. onKeyDown: function (evt) {
  46382. var shortcutPressed = evt.keyCode === 83 && evt.ctrlKey && evt.altKey;
  46383. if (!this.data || !shortcutPressed) { return; }
  46384. var projection = evt.shiftKey ? 'equirectangular' : 'perspective';
  46385. this.capture(projection);
  46386. },
  46387. /**
  46388. * Capture a screenshot of the scene.
  46389. *
  46390. * @param {string} projection - Screenshot projection (equirectangular or perspective).
  46391. */
  46392. setCapture: function (projection) {
  46393. var el = this.el;
  46394. var size;
  46395. var camera;
  46396. var cubeCamera;
  46397. // Configure camera.
  46398. if (projection === 'perspective') {
  46399. // Quad is only used in equirectangular mode. Hide it in this case.
  46400. this.quad.visible = false;
  46401. // Use scene camera.
  46402. camera = el.camera;
  46403. size = {width: this.data.width, height: this.data.height};
  46404. } else {
  46405. // Use ortho camera.
  46406. camera = this.camera;
  46407. // Copy position and rotation of scene camera into the ortho one.
  46408. camera.position.copy(el.camera.getWorldPosition());
  46409. camera.rotation.copy(el.camera.getWorldRotation());
  46410. // Create cube camera and copy position from scene camera.
  46411. cubeCamera = new THREE.CubeCamera(el.camera.near, el.camera.far,
  46412. Math.min(this.cubeMapSize, 2048));
  46413. cubeCamera.position.copy(el.camera.getWorldPosition());
  46414. cubeCamera.rotation.copy(el.camera.getWorldRotation());
  46415. // Render scene with cube camera.
  46416. cubeCamera.updateCubeMap(el.renderer, el.object3D);
  46417. this.quad.material.uniforms.map.value = cubeCamera.renderTarget.texture;
  46418. size = {width: this.data.width, height: this.data.height};
  46419. // Use quad to project image taken by the cube camera.
  46420. this.quad.visible = true;
  46421. }
  46422. return {
  46423. camera: camera,
  46424. size: size,
  46425. projection: projection
  46426. };
  46427. },
  46428. /**
  46429. * Maintained for backwards compatibility.
  46430. */
  46431. capture: function (projection) {
  46432. var params = this.setCapture(projection);
  46433. this.renderCapture(params.camera, params.size, params.projection);
  46434. // Trigger file download.
  46435. this.saveCapture();
  46436. },
  46437. /**
  46438. * Return canvas instead of triggering download (e.g., for uploading blob to server).
  46439. */
  46440. getCanvas: function (projection) {
  46441. var params = this.setCapture(projection);
  46442. this.renderCapture(params.camera, params.size, params.projection);
  46443. return this.canvas;
  46444. },
  46445. renderCapture: function (camera, size, projection) {
  46446. var autoClear = this.el.renderer.autoClear;
  46447. var el = this.el;
  46448. var imageData;
  46449. var output;
  46450. var pixels;
  46451. var renderer = this.el.renderer;
  46452. // Create rendering target and buffer to store the read pixels.
  46453. output = this.getRenderTarget(size.width, size.height);
  46454. pixels = new Uint8Array(4 * size.width * size.height);
  46455. // Resize quad, camera, and canvas.
  46456. this.resize(size.width, size.height);
  46457. // Render scene to render target.
  46458. renderer.autoClear = true;
  46459. renderer.render(el.object3D, camera, output, true);
  46460. renderer.autoClear = autoClear;
  46461. // Read image pizels back.
  46462. renderer.readRenderTargetPixels(output, 0, 0, size.width, size.height, pixels);
  46463. if (projection === 'perspective') {
  46464. pixels = this.flipPixelsVertically(pixels, size.width, size.height);
  46465. }
  46466. imageData = new ImageData(new Uint8ClampedArray(pixels), size.width, size.height);
  46467. // Hide quad after projecting the image.
  46468. this.quad.visible = false;
  46469. // Copy pixels into canvas.
  46470. this.ctx.putImageData(imageData, 0, 0);
  46471. },
  46472. flipPixelsVertically: function (pixels, width, height) {
  46473. var flippedPixels = pixels.slice(0);
  46474. for (var x = 0; x < width; ++x) {
  46475. for (var y = 0; y < height; ++y) {
  46476. flippedPixels[x * 4 + y * width * 4] = pixels[x * 4 + (height - y) * width * 4];
  46477. flippedPixels[x * 4 + 1 + y * width * 4] = pixels[x * 4 + 1 + (height - y) * width * 4];
  46478. flippedPixels[x * 4 + 2 + y * width * 4] = pixels[x * 4 + 2 + (height - y) * width * 4];
  46479. flippedPixels[x * 4 + 3 + y * width * 4] = pixels[x * 4 + 3 + (height - y) * width * 4];
  46480. }
  46481. }
  46482. return flippedPixels;
  46483. },
  46484. /**
  46485. * Download capture to file.
  46486. */
  46487. saveCapture: function () {
  46488. this.canvas.toBlob(function (blob) {
  46489. var fileName = 'screenshot-' + document.title.toLowerCase() + '-' + Date.now() + '.png';
  46490. var linkEl = document.createElement('a');
  46491. var url = URL.createObjectURL(blob);
  46492. linkEl.href = url;
  46493. linkEl.setAttribute('download', fileName);
  46494. linkEl.innerHTML = 'downloading...';
  46495. linkEl.style.display = 'none';
  46496. document.body.appendChild(linkEl);
  46497. setTimeout(function () {
  46498. linkEl.click();
  46499. document.body.removeChild(linkEl);
  46500. }, 1);
  46501. }, 'image/png');
  46502. }
  46503. });
  46504. },{"../../core/component":102,"../../lib/three":149}],83:[function(_dereq_,module,exports){
  46505. var registerComponent = _dereq_('../../core/component').registerComponent;
  46506. var RStats = _dereq_('../../../vendor/rStats');
  46507. var utils = _dereq_('../../utils');
  46508. _dereq_('../../../vendor/rStats.extras');
  46509. _dereq_('../../lib/rStatsAframe');
  46510. var AFrameStats = window.aframeStats;
  46511. var bind = utils.bind;
  46512. var HIDDEN_CLASS = 'a-hidden';
  46513. var ThreeStats = window.threeStats;
  46514. /**
  46515. * Stats appended to document.body by RStats.
  46516. */
  46517. module.exports.Component = registerComponent('stats', {
  46518. schema: {default: true},
  46519. init: function () {
  46520. var scene = this.el;
  46521. if (utils.getUrlParameter('stats') === 'false') { return; }
  46522. this.stats = createStats(scene);
  46523. this.statsEl = document.querySelector('.rs-base');
  46524. this.hideBound = bind(this.hide, this);
  46525. this.showBound = bind(this.show, this);
  46526. scene.addEventListener('enter-vr', this.hideBound);
  46527. scene.addEventListener('exit-vr', this.showBound);
  46528. },
  46529. update: function () {
  46530. if (!this.stats) { return; }
  46531. return (!this.data) ? this.hide() : this.show();
  46532. },
  46533. remove: function () {
  46534. this.el.removeEventListener('enter-vr', this.hideBound);
  46535. this.el.removeEventListener('exit-vr', this.showBound);
  46536. if (!this.statsEl) { return; } // Scene detached.
  46537. this.statsEl.parentNode.removeChild(this.statsEl);
  46538. },
  46539. tick: function () {
  46540. var stats = this.stats;
  46541. if (!stats) { return; }
  46542. stats('rAF').tick();
  46543. stats('FPS').frame();
  46544. stats().update();
  46545. },
  46546. hide: function () {
  46547. this.statsEl.classList.add(HIDDEN_CLASS);
  46548. },
  46549. show: function () {
  46550. this.statsEl.classList.remove(HIDDEN_CLASS);
  46551. }
  46552. });
  46553. function createStats (scene) {
  46554. var threeStats = new ThreeStats(scene.renderer);
  46555. var aframeStats = new AFrameStats(scene);
  46556. var plugins = scene.isMobile ? [] : [threeStats, aframeStats];
  46557. return new RStats({
  46558. css: [], // Our stylesheet is injected from `src/index.js`.
  46559. values: {
  46560. fps: {caption: 'fps', below: 30}
  46561. },
  46562. groups: [
  46563. {caption: 'Framerate', values: ['fps', 'raf']}
  46564. ],
  46565. plugins: plugins
  46566. });
  46567. }
  46568. },{"../../../vendor/rStats":180,"../../../vendor/rStats.extras":179,"../../core/component":102,"../../lib/rStatsAframe":148,"../../utils":172}],84:[function(_dereq_,module,exports){
  46569. var registerComponent = _dereq_('../../core/component').registerComponent;
  46570. var constants = _dereq_('../../constants/');
  46571. var utils = _dereq_('../../utils/');
  46572. var bind = utils.bind;
  46573. var ENTER_VR_CLASS = 'a-enter-vr';
  46574. var ENTER_VR_BTN_CLASS = 'a-enter-vr-button';
  46575. var HIDDEN_CLASS = 'a-hidden';
  46576. var ORIENTATION_MODAL_CLASS = 'a-orientation-modal';
  46577. /**
  46578. * UI for entering VR mode.
  46579. */
  46580. module.exports.Component = registerComponent('vr-mode-ui', {
  46581. dependencies: ['canvas'],
  46582. schema: {
  46583. enabled: {default: true}
  46584. },
  46585. init: function () {
  46586. var self = this;
  46587. var sceneEl = this.el;
  46588. if (utils.getUrlParameter('ui') === 'false') { return; }
  46589. this.enterVR = bind(sceneEl.enterVR, sceneEl);
  46590. this.exitVR = bind(sceneEl.exitVR, sceneEl);
  46591. this.insideLoader = false;
  46592. this.enterVREl = null;
  46593. this.orientationModalEl = null;
  46594. // Hide/show VR UI when entering/exiting VR mode.
  46595. sceneEl.addEventListener('enter-vr', bind(this.updateEnterVRInterface, this));
  46596. sceneEl.addEventListener('exit-vr', bind(this.updateEnterVRInterface, this));
  46597. window.addEventListener('message', function (event) {
  46598. if (event.data.type === 'loaderReady') {
  46599. self.insideLoader = true;
  46600. self.remove();
  46601. }
  46602. });
  46603. // Modal that tells the user to change orientation if in portrait.
  46604. window.addEventListener('orientationchange', bind(this.toggleOrientationModalIfNeeded, this));
  46605. },
  46606. update: function () {
  46607. var sceneEl = this.el;
  46608. if (!this.data.enabled || this.insideLoader || utils.getUrlParameter('ui') === 'false') {
  46609. return this.remove();
  46610. }
  46611. if (this.enterVREl || this.orientationModalEl) { return; }
  46612. // Add UI if enabled and not already present.
  46613. this.enterVREl = createEnterVRButton(this.enterVR);
  46614. sceneEl.appendChild(this.enterVREl);
  46615. this.orientationModalEl = createOrientationModal(this.exitVR);
  46616. sceneEl.appendChild(this.orientationModalEl);
  46617. this.updateEnterVRInterface();
  46618. },
  46619. remove: function () {
  46620. [this.enterVREl, this.orientationModalEl].forEach(function (uiElement) {
  46621. if (uiElement) {
  46622. uiElement.parentNode.removeChild(uiElement);
  46623. }
  46624. });
  46625. },
  46626. updateEnterVRInterface: function () {
  46627. this.toggleEnterVRButtonIfNeeded();
  46628. this.toggleOrientationModalIfNeeded();
  46629. },
  46630. toggleEnterVRButtonIfNeeded: function () {
  46631. var sceneEl = this.el;
  46632. if (!this.enterVREl) { return; }
  46633. if (sceneEl.is('vr-mode')) {
  46634. this.enterVREl.classList.add(HIDDEN_CLASS);
  46635. } else {
  46636. this.enterVREl.classList.remove(HIDDEN_CLASS);
  46637. }
  46638. },
  46639. toggleOrientationModalIfNeeded: function () {
  46640. var sceneEl = this.el;
  46641. var orientationModalEl = this.orientationModalEl;
  46642. if (!orientationModalEl || !sceneEl.isMobile) { return; }
  46643. if (!utils.device.isLandscape() && sceneEl.is('vr-mode')) {
  46644. // Show if in VR mode on portrait.
  46645. orientationModalEl.classList.remove(HIDDEN_CLASS);
  46646. } else {
  46647. orientationModalEl.classList.add(HIDDEN_CLASS);
  46648. }
  46649. }
  46650. });
  46651. /**
  46652. * Creates a button that when clicked will enter into stereo-rendering mode for VR.
  46653. *
  46654. * Structure: <div><button></div>
  46655. *
  46656. * @returns {Element} Wrapper <div>.
  46657. */
  46658. function createEnterVRButton (enterVRHandler) {
  46659. var vrButton;
  46660. var wrapper;
  46661. // Create elements.
  46662. wrapper = document.createElement('div');
  46663. wrapper.classList.add(ENTER_VR_CLASS);
  46664. wrapper.setAttribute(constants.AFRAME_INJECTED, '');
  46665. vrButton = document.createElement('button');
  46666. vrButton.className = ENTER_VR_BTN_CLASS;
  46667. vrButton.setAttribute(constants.AFRAME_INJECTED, '');
  46668. // Insert elements.
  46669. wrapper.appendChild(vrButton);
  46670. vrButton.addEventListener('click', enterVRHandler);
  46671. return wrapper;
  46672. }
  46673. /**
  46674. * Create a modal that tells mobile users to orient the phone to landscape.
  46675. * Add a close button that if clicked, exits VR and closes the modal.
  46676. */
  46677. function createOrientationModal (exitVRHandler) {
  46678. var modal = document.createElement('div');
  46679. modal.className = ORIENTATION_MODAL_CLASS;
  46680. modal.classList.add(HIDDEN_CLASS);
  46681. modal.setAttribute(constants.AFRAME_INJECTED, '');
  46682. var exit = document.createElement('button');
  46683. exit.setAttribute(constants.AFRAME_INJECTED, '');
  46684. exit.innerHTML = 'Exit VR';
  46685. // Exit VR on close.
  46686. exit.addEventListener('click', exitVRHandler);
  46687. modal.appendChild(exit);
  46688. return modal;
  46689. }
  46690. },{"../../constants/":93,"../../core/component":102,"../../utils/":172}],85:[function(_dereq_,module,exports){
  46691. var component = _dereq_('../core/component');
  46692. var THREE = _dereq_('../lib/three');
  46693. var bind = _dereq_('../utils/bind');
  46694. var registerComponent = component.registerComponent;
  46695. /**
  46696. * Shadow component.
  46697. *
  46698. * When applied to an entity, that entity's geometry and any descendants will cast or receive
  46699. * shadows as specified by the `cast` and `receive` properties.
  46700. */
  46701. module.exports.Component = registerComponent('shadow', {
  46702. schema: {
  46703. cast: {default: true},
  46704. receive: {default: true}
  46705. },
  46706. init: function () {
  46707. this.onMeshChanged = bind(this.update, this);
  46708. this.el.addEventListener('object3dset', this.onMeshChanged);
  46709. this.system.setShadowMapEnabled(true);
  46710. },
  46711. update: function () {
  46712. var data = this.data;
  46713. this.updateDescendants(data.cast, data.receive);
  46714. },
  46715. remove: function () {
  46716. var el = this.el;
  46717. el.removeEventListener('object3dset', this.onMeshChanged);
  46718. this.updateDescendants(false, false);
  46719. },
  46720. updateDescendants: function (cast, receive) {
  46721. var sceneEl = this.el.sceneEl;
  46722. this.el.object3D.traverse(function (node) {
  46723. if (!(node instanceof THREE.Mesh)) { return; }
  46724. node.castShadow = cast;
  46725. node.receiveShadow = receive;
  46726. // If scene has already rendered, materials must be updated.
  46727. if (sceneEl.hasLoaded && node.material) {
  46728. var materials = node.material.materials || [node.material];
  46729. for (var i = 0; i < materials.length; i++) {
  46730. materials[i].needsUpdate = true;
  46731. }
  46732. }
  46733. });
  46734. }
  46735. });
  46736. },{"../core/component":102,"../lib/three":149,"../utils/bind":166}],86:[function(_dereq_,module,exports){
  46737. var registerComponent = _dereq_('../core/component').registerComponent;
  46738. var debug = _dereq_('../utils/debug');
  46739. var bind = _dereq_('../utils/bind');
  46740. var THREE = _dereq_('../lib/three');
  46741. var warn = debug('components:sound:warn');
  46742. /**
  46743. * Sound component.
  46744. */
  46745. module.exports.Component = registerComponent('sound', {
  46746. schema: {
  46747. autoplay: {default: false},
  46748. distanceModel: {default: 'inverse',
  46749. oneOf: ['linear', 'inverse', 'exponential']},
  46750. loop: {default: false},
  46751. maxDistance: {default: 10000},
  46752. on: {default: ''},
  46753. poolSize: {default: 1},
  46754. positional: {default: true},
  46755. refDistance: {default: 1},
  46756. rolloffFactor: {default: 1},
  46757. src: {type: 'audio'},
  46758. volume: {default: 1}
  46759. },
  46760. multiple: true,
  46761. init: function () {
  46762. this.listener = null;
  46763. this.audioLoader = new THREE.AudioLoader();
  46764. this.pool = new THREE.Group();
  46765. this.loaded = false;
  46766. this.mustPlay = false;
  46767. this.playSound = bind(this.playSound, this);
  46768. },
  46769. update: function (oldData) {
  46770. var data = this.data;
  46771. var srcChanged = data.src !== oldData.src;
  46772. // Create new sound if not yet created or changing `src`.
  46773. if (srcChanged) {
  46774. if (!data.src) {
  46775. warn('Audio source was not specified with `src`');
  46776. return;
  46777. }
  46778. this.setupSound();
  46779. }
  46780. this.pool.children.forEach(function (sound) {
  46781. if (data.positional) {
  46782. sound.setDistanceModel(data.distanceModel);
  46783. sound.setMaxDistance(data.maxDistance);
  46784. sound.setRefDistance(data.refDistance);
  46785. sound.setRolloffFactor(data.rolloffFactor);
  46786. }
  46787. sound.setLoop(data.loop);
  46788. sound.setVolume(data.volume);
  46789. sound.isPaused = false;
  46790. });
  46791. if (data.on !== oldData.on) {
  46792. this.updateEventListener(oldData.on);
  46793. }
  46794. // All sound values set. Load in `src`.
  46795. if (srcChanged) {
  46796. var self = this;
  46797. this.loaded = false;
  46798. this.audioLoader.load(data.src, function (buffer) {
  46799. self.pool.children.forEach(function (sound) {
  46800. sound.setBuffer(buffer);
  46801. });
  46802. self.loaded = true;
  46803. // Remove this key from cache, otherwise we can't play it again
  46804. THREE.Cache.remove(data.src);
  46805. if (self.data.autoplay || self.mustPlay) { self.playSound(); }
  46806. self.el.emit('sound-loaded');
  46807. });
  46808. }
  46809. },
  46810. pause: function () {
  46811. this.stopSound();
  46812. this.removeEventListener();
  46813. },
  46814. play: function () {
  46815. if (this.data.autoplay) { this.playSound(); }
  46816. this.updateEventListener();
  46817. },
  46818. remove: function () {
  46819. this.removeEventListener();
  46820. this.el.removeObject3D(this.attrName);
  46821. try {
  46822. this.pool.children.forEach(function (sound) {
  46823. sound.disconnect();
  46824. });
  46825. } catch (e) {
  46826. // disconnect() will throw if it was never connected initially.
  46827. warn('Audio source not properly disconnected');
  46828. }
  46829. },
  46830. /**
  46831. * Update listener attached to the user defined on event.
  46832. */
  46833. updateEventListener: function (oldEvt) {
  46834. var el = this.el;
  46835. if (oldEvt) { el.removeEventListener(oldEvt, this.playSound); }
  46836. el.addEventListener(this.data.on, this.playSound);
  46837. },
  46838. removeEventListener: function () {
  46839. this.el.removeEventListener(this.data.on, this.playSound);
  46840. },
  46841. /**
  46842. * Removes current sound object, creates new sound object, adds to entity.
  46843. *
  46844. * @returns {object} sound
  46845. */
  46846. setupSound: function () {
  46847. var el = this.el;
  46848. var sceneEl = el.sceneEl;
  46849. if (this.pool.children.length > 0) {
  46850. this.stopSound();
  46851. el.removeObject3D('sound');
  46852. }
  46853. // Only want one AudioListener. Cache it on the scene.
  46854. var listener = this.listener = sceneEl.audioListener || new THREE.AudioListener();
  46855. sceneEl.audioListener = listener;
  46856. if (sceneEl.camera) {
  46857. sceneEl.camera.add(listener);
  46858. }
  46859. // Wait for camera if necessary.
  46860. sceneEl.addEventListener('camera-set-active', function (evt) {
  46861. evt.detail.cameraEl.getObject3D('camera').add(listener);
  46862. });
  46863. // Create [poolSize] audio instances and attach them to pool
  46864. this.pool = new THREE.Group();
  46865. for (var i = 0; i < this.data.poolSize; i++) {
  46866. var sound = this.data.positional ? new THREE.PositionalAudio(listener) : new THREE.Audio(listener);
  46867. this.pool.add(sound);
  46868. }
  46869. el.setObject3D(this.attrName, this.pool);
  46870. this.pool.children.forEach(function (sound) {
  46871. sound.onEnded = function () {
  46872. sound.isPlaying = false;
  46873. el.emit('sound-ended', {index: i});
  46874. };
  46875. });
  46876. },
  46877. /**
  46878. * Pause all the sounds in the pool.
  46879. */
  46880. pauseSound: function () {
  46881. this.isPlaying = false;
  46882. this.pool.children.forEach(function (sound) {
  46883. if (!sound.source || !sound.source.buffer || !sound.isPlaying || sound.isPaused) { return; }
  46884. sound.isPaused = true;
  46885. sound.pause();
  46886. });
  46887. },
  46888. /**
  46889. * Look for an unused sound in the pool and play it if found.
  46890. */
  46891. playSound: function () {
  46892. if (!this.loaded) {
  46893. warn('Sound not loaded yet. It will be played once it finished loading');
  46894. this.mustPlay = true;
  46895. return;
  46896. }
  46897. var found = false;
  46898. this.isPlaying = true;
  46899. this.pool.children.forEach(function (sound) {
  46900. if (!sound.isPlaying && sound.buffer && !found) {
  46901. sound.play();
  46902. sound.isPaused = false;
  46903. found = true;
  46904. return;
  46905. }
  46906. });
  46907. if (!found) {
  46908. warn('All the sounds are playing. If you need to play more sounds simultaneously ' +
  46909. 'consider increasing the size of pool with the `poolSize` attribute.', this.el);
  46910. return;
  46911. }
  46912. this.mustPlay = false;
  46913. },
  46914. /**
  46915. * Stop all the sounds in the pool.
  46916. */
  46917. stopSound: function () {
  46918. this.isPlaying = false;
  46919. this.pool.children.forEach(function (sound) {
  46920. if (!sound.source || !sound.source.buffer) { return; }
  46921. sound.stop();
  46922. });
  46923. }
  46924. });
  46925. },{"../core/component":102,"../lib/three":149,"../utils/bind":166,"../utils/debug":168}],87:[function(_dereq_,module,exports){
  46926. var createTextGeometry = _dereq_('three-bmfont-text');
  46927. var loadBMFont = _dereq_('load-bmfont');
  46928. var path = _dereq_('path');
  46929. var registerComponent = _dereq_('../core/component').registerComponent;
  46930. var coreShader = _dereq_('../core/shader');
  46931. var THREE = _dereq_('../lib/three');
  46932. var utils = _dereq_('../utils/');
  46933. var error = utils.debug('components:text:error');
  46934. var shaders = coreShader.shaders;
  46935. var warn = utils.debug('components:text:warn');
  46936. // 1 to match other A-Frame default widths.
  46937. var DEFAULT_WIDTH = 1;
  46938. // @bryik set anisotropy to 16. Improves look of large amounts of text when viewed from angle.
  46939. var MAX_ANISOTROPY = 16;
  46940. var FONT_BASE_URL = 'https://cdn.aframe.io/fonts/';
  46941. var FONTS = {
  46942. aileronsemibold: FONT_BASE_URL + 'Aileron-Semibold.fnt',
  46943. dejavu: FONT_BASE_URL + 'DejaVu-sdf.fnt',
  46944. exo2bold: FONT_BASE_URL + 'Exo2Bold.fnt',
  46945. exo2semibold: FONT_BASE_URL + 'Exo2SemiBold.fnt',
  46946. kelsonsans: FONT_BASE_URL + 'KelsonSans.fnt',
  46947. monoid: FONT_BASE_URL + 'Monoid.fnt',
  46948. mozillavr: FONT_BASE_URL + 'mozillavr.fnt',
  46949. roboto: FONT_BASE_URL + 'Roboto-msdf.json',
  46950. sourcecodepro: FONT_BASE_URL + 'SourceCodePro.fnt'
  46951. };
  46952. var MSDF_FONTS = ['roboto'];
  46953. var DEFAULT_FONT = 'roboto';
  46954. module.exports.FONTS = FONTS;
  46955. var cache = new PromiseCache();
  46956. var fontWidthFactors = {};
  46957. /**
  46958. * SDF-based text component.
  46959. * Based on https://github.com/Jam3/three-bmfont-text.
  46960. *
  46961. * All the stock fonts are for the `sdf` registered shader, an improved version of jam3's
  46962. * original `sdf` shader.
  46963. */
  46964. module.exports.Component = registerComponent('text', {
  46965. multiple: true,
  46966. schema: {
  46967. align: {type: 'string', default: 'left', oneOf: ['left', 'right', 'center']},
  46968. alphaTest: {default: 0.5},
  46969. // `anchor` defaults to center to match geometries.
  46970. anchor: {default: 'center', oneOf: ['left', 'right', 'center', 'align']},
  46971. baseline: {default: 'center', oneOf: ['top', 'center', 'bottom']},
  46972. color: {type: 'color', default: '#FFF'},
  46973. font: {type: 'string', default: DEFAULT_FONT},
  46974. // `fontImage` defaults to the font name as a .png (e.g., mozillavr.fnt -> mozillavr.png).
  46975. fontImage: {type: 'string'},
  46976. // `height` has no default, will be populated at layout.
  46977. height: {type: 'number'},
  46978. letterSpacing: {type: 'number', default: 0},
  46979. // `lineHeight` defaults to font's `lineHeight` value.
  46980. lineHeight: {type: 'number'},
  46981. opacity: {type: 'number', default: 1.0},
  46982. shader: {default: 'sdf', oneOf: shaders},
  46983. side: {default: 'front', oneOf: ['front', 'back', 'double']},
  46984. tabSize: {default: 4},
  46985. transparent: {default: true},
  46986. value: {type: 'string'},
  46987. whiteSpace: {default: 'normal', oneOf: ['normal', 'pre', 'nowrap']},
  46988. // `width` defaults to geometry width if present, else `DEFAULT_WIDTH`.
  46989. width: {type: 'number'},
  46990. // `wrapCount` units are about one default font character. Wrap roughly at this number.
  46991. wrapCount: {type: 'number', default: 40},
  46992. // `wrapPixels` will wrap using bmfont pixel units (e.g., dejavu's is 32 pixels).
  46993. wrapPixels: {type: 'number'},
  46994. // `yOffset` to adjust generated fonts from tools that may have incorrect metrics.
  46995. yOffset: {type: 'number', default: 0},
  46996. // `zOffset` will provide a small z offset to avoid z-fighting.
  46997. zOffset: {type: 'number', default: 0.001}
  46998. },
  46999. init: function () {
  47000. this.texture = new THREE.Texture();
  47001. this.texture.anisotropy = MAX_ANISOTROPY;
  47002. this.geometry = createTextGeometry();
  47003. this.createOrUpdateMaterial();
  47004. this.mesh = new THREE.Mesh(this.geometry, this.material);
  47005. this.el.setObject3D(this.attrName, this.mesh);
  47006. },
  47007. update: function (oldData) {
  47008. var data = coerceData(this.data);
  47009. var font = this.currentFont;
  47010. // Update material.
  47011. this.createOrUpdateMaterial();
  47012. // New font. `updateFont` will later change data and layout.
  47013. if (oldData.font !== data.font) {
  47014. this.updateFont();
  47015. return;
  47016. }
  47017. // Update geometry and layout.
  47018. if (font) {
  47019. updateGeometry(this.geometry, data, font);
  47020. this.updateLayout(data);
  47021. }
  47022. },
  47023. /**
  47024. * Clean up geometry, material, texture, mesh, objects.
  47025. */
  47026. remove: function () {
  47027. this.geometry.dispose();
  47028. this.geometry = null;
  47029. this.el.removeObject3D(this.attrName);
  47030. this.material.dispose();
  47031. this.material = null;
  47032. this.texture.dispose();
  47033. this.texture = null;
  47034. if (this.shaderObject) {
  47035. delete this.shaderObject;
  47036. }
  47037. },
  47038. /**
  47039. * Update the shader of the material.
  47040. */
  47041. createOrUpdateMaterial: function () {
  47042. var data = this.data;
  47043. var hasChangedShader;
  47044. var material = this.material;
  47045. var NewShader;
  47046. var shaderData;
  47047. var shaderName;
  47048. // Infer shader if using a stock font (or from `-msdf` filename convention).
  47049. shaderName = data.shader;
  47050. if (MSDF_FONTS.indexOf(data.font) !== -1 || data.font.indexOf('-msdf.') >= 0) {
  47051. shaderName = 'msdf';
  47052. } else if (data.font in FONTS && MSDF_FONTS.indexOf(data.font) === -1) {
  47053. shaderName = 'sdf';
  47054. }
  47055. hasChangedShader = (this.shaderObject && this.shaderObject.name) !== shaderName;
  47056. shaderData = {
  47057. alphaTest: data.alphaTest,
  47058. color: data.color,
  47059. map: this.texture,
  47060. opacity: data.opacity,
  47061. side: parseSide(data.side),
  47062. transparent: data.transparent
  47063. };
  47064. // Shader has not changed, do an update.
  47065. if (!hasChangedShader) {
  47066. // Update shader material.
  47067. this.shaderObject.update(shaderData);
  47068. // Apparently, was not set on `init` nor `update`.
  47069. material.transparent = shaderData.transparent;
  47070. updateBaseMaterial(material, shaderData);
  47071. return;
  47072. }
  47073. // Shader has changed. Create a shader material.
  47074. NewShader = createShader(this.el, shaderName, shaderData);
  47075. this.material = NewShader.material;
  47076. this.shaderObject = NewShader.shader;
  47077. // Set new shader material.
  47078. updateBaseMaterial(this.material, shaderData);
  47079. if (this.mesh) { this.mesh.material = this.material; }
  47080. },
  47081. /**
  47082. * Load font for geometry, load font image for material, and apply.
  47083. */
  47084. updateFont: function () {
  47085. var data = this.data;
  47086. var el = this.el;
  47087. var fontSrc;
  47088. var geometry = this.geometry;
  47089. var self = this;
  47090. if (!data.font) { warn('No font specified. Using the default font.'); }
  47091. // Make invisible during font swap.
  47092. this.mesh.visible = false;
  47093. // Look up font URL to use, and perform cached load.
  47094. fontSrc = this.lookupFont(data.font || DEFAULT_FONT) || data.font;
  47095. cache.get(fontSrc, function doLoadFont () {
  47096. return loadFont(fontSrc, data.yOffset);
  47097. }).then(function setFont (font) {
  47098. var coercedData;
  47099. var fontImgSrc;
  47100. if (font.pages.length !== 1) {
  47101. throw new Error('Currently only single-page bitmap fonts are supported.');
  47102. }
  47103. if (!fontWidthFactors[fontSrc]) {
  47104. font.widthFactor = fontWidthFactors[font] = computeFontWidthFactor(font);
  47105. }
  47106. // Update geometry given font metrics.
  47107. coercedData = coerceData(data);
  47108. updateGeometry(geometry, data, font);
  47109. // Set font and update layout.
  47110. self.currentFont = font;
  47111. self.updateLayout(coercedData);
  47112. // Look up font image URL to use, and perform cached load.
  47113. fontImgSrc = data.fontImage || fontSrc.replace(/(\.fnt)|(\.json)/, '.png') ||
  47114. path.dirname(data.font) + '/' + font.pages[0];
  47115. cache.get(fontImgSrc, function () {
  47116. return loadTexture(fontImgSrc);
  47117. }).then(function (image) {
  47118. // Make mesh visible and apply font image as texture.
  47119. self.mesh.visible = true;
  47120. self.texture.image = image;
  47121. self.texture.needsUpdate = true;
  47122. el.emit('textfontset', {font: data.font, fontObj: font});
  47123. }).catch(function (err) {
  47124. error(err);
  47125. throw err;
  47126. });
  47127. }).catch(function (err) {
  47128. error(err);
  47129. throw err;
  47130. });
  47131. },
  47132. /**
  47133. * Update layout with anchor, alignment, baseline, and considering any meshes.
  47134. */
  47135. updateLayout: function (data) {
  47136. var anchor;
  47137. var baseline;
  47138. var el = this.el;
  47139. var geometry = this.geometry;
  47140. var geometryComponent = el.getAttribute('geometry');
  47141. var height;
  47142. var layout = geometry.layout;
  47143. var mesh = this.mesh;
  47144. var textRenderWidth;
  47145. var textScale;
  47146. var width;
  47147. var x;
  47148. var y;
  47149. // Determine width to use (defined width, geometry's width, or default width).
  47150. geometryComponent = el.getAttribute('geometry');
  47151. width = data.width || (geometryComponent && geometryComponent.width) || DEFAULT_WIDTH;
  47152. // Determine wrap pixel count. Either specified or by experimental fudge factor.
  47153. // Note that experimental factor will never be correct for variable width fonts.
  47154. textRenderWidth = computeWidth(data.wrapPixels, data.wrapCount,
  47155. this.currentFont.widthFactor);
  47156. textScale = width / textRenderWidth;
  47157. // Determine height to use.
  47158. height = textScale * (layout.height + layout.descender);
  47159. // Update geometry dimensions to match text layout if width and height are set to 0.
  47160. // For example, scales a plane to fit text.
  47161. if (geometryComponent) {
  47162. if (!geometryComponent.width) { el.setAttribute('geometry', 'width', width); }
  47163. if (!geometryComponent.height) { el.setAttribute('geometry', 'height', height); }
  47164. }
  47165. // Calculate X position to anchor text left, center, or right.
  47166. anchor = data.anchor === 'align' ? data.align : data.anchor;
  47167. if (anchor === 'left') {
  47168. x = 0;
  47169. } else if (anchor === 'right') {
  47170. x = -1 * layout.width;
  47171. } else if (anchor === 'center') {
  47172. x = -1 * layout.width / 2;
  47173. } else {
  47174. throw new TypeError('Invalid text.anchor property value', anchor);
  47175. }
  47176. // Calculate Y position to anchor text top, center, or bottom.
  47177. baseline = data.baseline;
  47178. if (baseline === 'bottom') {
  47179. y = 0;
  47180. } else if (baseline === 'top') {
  47181. y = -1 * layout.height + layout.ascender;
  47182. } else if (baseline === 'center') {
  47183. y = -1 * layout.height / 2;
  47184. } else {
  47185. throw new TypeError('Invalid text.baseline property value', baseline);
  47186. }
  47187. // Position and scale mesh to apply layout.
  47188. mesh.position.x = x * textScale;
  47189. mesh.position.y = y * textScale;
  47190. // Place text slightly in front to avoid Z-fighting.
  47191. mesh.position.z = data.zOffset;
  47192. mesh.scale.set(textScale, -1 * textScale, textScale);
  47193. this.geometry.computeBoundingSphere();
  47194. },
  47195. /**
  47196. * Grab font from the constant.
  47197. * Set as a method for test stubbing purposes.
  47198. */
  47199. lookupFont: function (key) {
  47200. return FONTS[key];
  47201. }
  47202. });
  47203. function parseSide (side) {
  47204. switch (side) {
  47205. case 'back': {
  47206. return THREE.BackSide;
  47207. }
  47208. case 'double': {
  47209. return THREE.DoubleSide;
  47210. }
  47211. default: {
  47212. return THREE.FrontSide;
  47213. }
  47214. }
  47215. }
  47216. /**
  47217. * Coerce some data to numbers.
  47218. * as they will be passed directly into text creation and update
  47219. */
  47220. function coerceData (data) {
  47221. data = utils.clone(data);
  47222. if (data.lineHeight !== undefined) {
  47223. data.lineHeight = parseFloat(data.lineHeight);
  47224. if (!isFinite(data.lineHeight)) { data.lineHeight = undefined; }
  47225. }
  47226. if (data.width !== undefined) {
  47227. data.width = parseFloat(data.width);
  47228. if (!isFinite(data.width)) { data.width = undefined; }
  47229. }
  47230. return data;
  47231. }
  47232. /**
  47233. * @returns {Promise}
  47234. */
  47235. function loadFont (src, yOffset) {
  47236. return new Promise(function (resolve, reject) {
  47237. loadBMFont(src, function (err, font) {
  47238. if (err) {
  47239. error('Error loading font', src);
  47240. reject(err);
  47241. return;
  47242. }
  47243. // Fix negative Y offsets for Roboto MSDF font from tool. Experimentally determined.
  47244. if (src.indexOf('/Roboto-msdf.json') >= 0) { yOffset = 30; }
  47245. if (yOffset) { font.chars.map(function doOffset (ch) { ch.yoffset += yOffset; }); }
  47246. resolve(font);
  47247. });
  47248. });
  47249. }
  47250. /**
  47251. * @returns {Promise}
  47252. */
  47253. function loadTexture (src) {
  47254. return new Promise(function (resolve, reject) {
  47255. new THREE.ImageLoader().load(src, function (image) {
  47256. resolve(image);
  47257. }, undefined, function () {
  47258. error('Error loading font image', src);
  47259. reject(null);
  47260. });
  47261. });
  47262. }
  47263. function createShader (el, shaderName, data) {
  47264. var shader;
  47265. var shaderObject;
  47266. // Set up Shader.
  47267. shaderObject = new shaders[shaderName].Shader();
  47268. shaderObject.el = el;
  47269. shaderObject.init(data);
  47270. shaderObject.update(data);
  47271. // Get material.
  47272. shader = shaderObject.material;
  47273. // Apparently, was not set on `init` nor `update`.
  47274. shader.transparent = data.transparent;
  47275. return {
  47276. material: shader,
  47277. shader: shaderObject
  47278. };
  47279. }
  47280. /**
  47281. * @todo Add more supported material properties (e.g., `visible`).
  47282. */
  47283. function updateBaseMaterial (material, data) {
  47284. material.side = data.side;
  47285. }
  47286. /**
  47287. * Update the text geometry using `three-bmfont-text.update`.
  47288. */
  47289. function updateGeometry (geometry, data, font) {
  47290. geometry.update(utils.extend({}, data, {
  47291. font: font,
  47292. width: computeWidth(data.wrapPixels, data.wrapCount, font.widthFactor),
  47293. text: data.value.replace(/\\n/g, '\n').replace(/\\t/g, '\t'),
  47294. lineHeight: data.lineHeight || font.common.lineHeight
  47295. }));
  47296. }
  47297. /**
  47298. * Determine wrap pixel count. Either specified or by experimental fudge factor.
  47299. * Note that experimental factor will never be correct for variable width fonts.
  47300. */
  47301. function computeWidth (wrapPixels, wrapCount, widthFactor) {
  47302. return wrapPixels || ((0.5 + wrapCount) * widthFactor);
  47303. }
  47304. /**
  47305. * Compute default font width factor to use.
  47306. */
  47307. function computeFontWidthFactor (font) {
  47308. var sum = 0;
  47309. var digitsum = 0;
  47310. var digits = 0;
  47311. font.chars.map(function (ch) {
  47312. sum += ch.xadvance;
  47313. if (ch.id >= 48 && ch.id <= 57) {
  47314. digits++;
  47315. digitsum += ch.xadvance;
  47316. }
  47317. });
  47318. return digits ? digitsum / digits : sum / font.chars.length;
  47319. }
  47320. /**
  47321. * Get or create a promise given a key and promise generator.
  47322. * @todo Move to a utility and use in other parts of A-Frame.
  47323. */
  47324. function PromiseCache () {
  47325. var cache = this.cache = {};
  47326. this.get = function (key, promiseGenerator) {
  47327. if (key in cache) {
  47328. return cache[key];
  47329. }
  47330. cache[key] = promiseGenerator();
  47331. return cache[key];
  47332. };
  47333. }
  47334. },{"../core/component":102,"../core/shader":111,"../lib/three":149,"../utils/":172,"load-bmfont":23,"path":31,"three-bmfont-text":37}],88:[function(_dereq_,module,exports){
  47335. var registerComponent = _dereq_('../core/component').registerComponent;
  47336. var THREE = _dereq_('../lib/three');
  47337. var DEFAULT_USER_HEIGHT = _dereq_('../constants').DEFAULT_USER_HEIGHT;
  47338. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  47339. var EYES_TO_ELBOW = {x: 0.175, y: -0.3, z: -0.03}; // vector from eyes to elbow (divided by user height)
  47340. var FOREARM = {x: 0, y: 0, z: -0.175}; // vector from eyes to elbow (divided by user height)
  47341. /**
  47342. * Tracked controls component.
  47343. * Wrap the gamepad API for pose and button states.
  47344. * Select the appropriate controller and apply pose to the entity.
  47345. * Observe button states and emit appropriate events.
  47346. *
  47347. * @property {number} controller - Index of controller in array returned by Gamepad API.
  47348. * @property {string} id - Selected controller among those returned by Gamepad API.
  47349. */
  47350. module.exports.Component = registerComponent('tracked-controls', {
  47351. schema: {
  47352. controller: {default: 0},
  47353. id: {type: 'string', default: ''},
  47354. idPrefix: {type: 'string', default: ''},
  47355. rotationOffset: {default: 0},
  47356. // Arm model parameters, to use when not 6DOF. (pose hasPosition false, no position)
  47357. headElement: {type: 'selector'}
  47358. },
  47359. init: function () {
  47360. this.axis = [0, 0, 0];
  47361. this.buttonStates = {};
  47362. this.dolly = new THREE.Object3D();
  47363. this.controllerEuler = new THREE.Euler();
  47364. this.controllerEuler.order = 'YXZ';
  47365. this.controllerPosition = new THREE.Vector3();
  47366. this.controllerQuaternion = new THREE.Quaternion();
  47367. this.deltaControllerPosition = new THREE.Vector3();
  47368. this.standingMatrix = new THREE.Matrix4();
  47369. this.previousControllerPosition = new THREE.Vector3();
  47370. this.updateGamepad();
  47371. },
  47372. tick: function (time, delta) {
  47373. var mesh = this.el.getObject3D('mesh');
  47374. // Update mesh animations.
  47375. if (mesh && mesh.update) { mesh.update(delta / 1000); }
  47376. this.updateGamepad();
  47377. this.updatePose();
  47378. this.updateButtons();
  47379. },
  47380. /**
  47381. * Return default user height to use for non-6DOF arm model.
  47382. */
  47383. defaultUserHeight: function () { return DEFAULT_USER_HEIGHT; }, // default user height (for cameras with zero)
  47384. /**
  47385. * Return head element to use for non-6DOF arm model.
  47386. */
  47387. getHeadElement: function () { return this.data.headElement || this.el.sceneEl.camera.el; },
  47388. /**
  47389. * Handle update to `id` or `idPrefix.
  47390. */
  47391. updateGamepad: function () {
  47392. var controllers = this.system.controllers;
  47393. var data = this.data;
  47394. var matchingControllers;
  47395. // Hand IDs: 0 is right, 1 is left.
  47396. matchingControllers = controllers.filter(function hasIdOrPrefix (controller) {
  47397. if (data.idPrefix) { return controller.id.indexOf(data.idPrefix) === 0; }
  47398. return controller.id === data.id;
  47399. });
  47400. this.controller = matchingControllers[data.controller];
  47401. },
  47402. applyArmModel: function (controllerPosition) {
  47403. // Use controllerPosition and deltaControllerPosition to avoid creating yet more variables...
  47404. var controller = this.controller;
  47405. var pose = controller.pose;
  47406. var controllerQuaternion = this.controllerQuaternion;
  47407. var controllerEuler = this.controllerEuler;
  47408. var deltaControllerPosition = this.deltaControllerPosition;
  47409. var hand = (controller ? controller.hand : undefined) || DEFAULT_HANDEDNESS;
  47410. var headEl = this.getHeadElement();
  47411. var headObject3D = headEl.object3D;
  47412. var headCamera = headEl.components.camera;
  47413. var userHeight = (headCamera ? headCamera.data.userHeight : 0) || this.defaultUserHeight();
  47414. // Use camera position as head position.
  47415. controllerPosition.copy(headObject3D.position);
  47416. // Set offset for degenerate "arm model" to elbow.
  47417. deltaControllerPosition.set(
  47418. EYES_TO_ELBOW.x * (hand === 'left' ? -1 : hand === 'right' ? 1 : 0),
  47419. EYES_TO_ELBOW.y, // lower than your eyes
  47420. EYES_TO_ELBOW.z); // slightly out in front
  47421. // Scale offset by user height.
  47422. deltaControllerPosition.multiplyScalar(userHeight);
  47423. // Apply camera Y rotation (not X or Z, so you can look down at your hand).
  47424. deltaControllerPosition.applyAxisAngle(headObject3D.up, headObject3D.rotation.y);
  47425. // Apply rotated offset to position.
  47426. controllerPosition.add(deltaControllerPosition);
  47427. // Set offset for degenerate "arm model" forearm.
  47428. deltaControllerPosition.set(FOREARM.x, FOREARM.y, FOREARM.z); // forearm sticking out from elbow
  47429. // Scale offset by user height.
  47430. deltaControllerPosition.multiplyScalar(userHeight);
  47431. // Apply controller X and Y rotation (tilting up/down/left/right is usually moving the arm)
  47432. if (pose.orientation) {
  47433. controllerQuaternion.fromArray(pose.orientation);
  47434. } else {
  47435. controllerQuaternion.copy(headObject3D.quaternion);
  47436. }
  47437. controllerEuler.setFromQuaternion(controllerQuaternion);
  47438. controllerEuler.set(controllerEuler.x, controllerEuler.y, 0);
  47439. deltaControllerPosition.applyEuler(controllerEuler);
  47440. // Apply rotated offset to position.
  47441. controllerPosition.add(deltaControllerPosition);
  47442. },
  47443. /**
  47444. * Read pose from controller (from Gamepad API), apply transforms, apply to entity.
  47445. */
  47446. updatePose: function () {
  47447. var controller = this.controller;
  47448. var controllerEuler = this.controllerEuler;
  47449. var controllerPosition = this.controllerPosition;
  47450. var currentPosition;
  47451. var deltaControllerPosition = this.deltaControllerPosition;
  47452. var dolly = this.dolly;
  47453. var el = this.el;
  47454. var pose;
  47455. var standingMatrix = this.standingMatrix;
  47456. var vrDisplay = this.system.vrDisplay;
  47457. var headEl = this.getHeadElement();
  47458. var headObject3D = headEl.object3D;
  47459. var headCamera = headEl.components.camera;
  47460. var userHeight = (headCamera ? headCamera.data.userHeight : 0) || this.defaultUserHeight();
  47461. if (!controller) { return; }
  47462. // Compose pose from Gamepad.
  47463. pose = controller.pose;
  47464. // If no orientation, use camera.
  47465. if (pose.orientation) {
  47466. dolly.quaternion.fromArray(pose.orientation);
  47467. } else {
  47468. dolly.quaternion.copy(headObject3D.quaternion);
  47469. }
  47470. if (pose.position) {
  47471. dolly.position.fromArray(pose.position);
  47472. } else {
  47473. // The controller is not 6DOF, so apply arm model.
  47474. this.applyArmModel(controllerPosition);
  47475. dolly.position.copy(controllerPosition);
  47476. }
  47477. dolly.updateMatrix();
  47478. // Apply transforms, if 6DOF and in VR.
  47479. if (pose.position && vrDisplay) {
  47480. if (vrDisplay.stageParameters) {
  47481. standingMatrix.fromArray(vrDisplay.stageParameters.sittingToStandingTransform);
  47482. dolly.applyMatrix(standingMatrix);
  47483. } else {
  47484. // Apply default camera height
  47485. dolly.position.y += userHeight;
  47486. dolly.updateMatrix();
  47487. }
  47488. }
  47489. // Decompose.
  47490. controllerEuler.setFromRotationMatrix(dolly.matrix);
  47491. controllerPosition.setFromMatrixPosition(dolly.matrix);
  47492. // Apply rotation (as absolute, with rotation offset).
  47493. el.setAttribute('rotation', {
  47494. x: THREE.Math.radToDeg(controllerEuler.x),
  47495. y: THREE.Math.radToDeg(controllerEuler.y),
  47496. z: THREE.Math.radToDeg(controllerEuler.z) + this.data.rotationOffset
  47497. });
  47498. // Apply position (as delta from previous Gamepad position).
  47499. deltaControllerPosition.copy(controllerPosition).sub(this.previousControllerPosition);
  47500. this.previousControllerPosition.copy(controllerPosition);
  47501. currentPosition = el.getAttribute('position');
  47502. el.setAttribute('position', {
  47503. x: currentPosition.x + deltaControllerPosition.x,
  47504. y: currentPosition.y + deltaControllerPosition.y,
  47505. z: currentPosition.z + deltaControllerPosition.z
  47506. });
  47507. },
  47508. /**
  47509. * Handle button changes including axes, presses, touches, values.
  47510. */
  47511. updateButtons: function () {
  47512. var buttonState;
  47513. var controller = this.controller;
  47514. var id;
  47515. if (!controller) { return; }
  47516. // Check every button.
  47517. for (id = 0; id < controller.buttons.length; ++id) {
  47518. // Initialize button state.
  47519. if (!this.buttonStates[id]) {
  47520. this.buttonStates[id] = {pressed: false, touched: false, value: 0};
  47521. }
  47522. buttonState = controller.buttons[id];
  47523. this.handleButton(id, buttonState);
  47524. }
  47525. // Check axes.
  47526. this.handleAxes();
  47527. },
  47528. /**
  47529. * Handle presses and touches for a single button.
  47530. *
  47531. * @param {number} id - Index of button in Gamepad button array.
  47532. * @param {number} buttonState - Value of button state from 0 to 1.
  47533. * @returns {boolean} Whether button has changed in any way.
  47534. */
  47535. handleButton: function (id, buttonState) {
  47536. var changed = this.handlePress(id, buttonState) ||
  47537. this.handleTouch(id, buttonState) ||
  47538. this.handleValue(id, buttonState);
  47539. if (!changed) { return false; }
  47540. this.el.emit('buttonchanged', {id: id, state: buttonState});
  47541. return true;
  47542. },
  47543. /**
  47544. * An axis is an array of values from -1 (up, left) to 1 (down, right).
  47545. * Compare each component of the axis to the previous value to determine change.
  47546. *
  47547. * @returns {boolean} Whether axes changed.
  47548. */
  47549. handleAxes: function () {
  47550. var changed = false;
  47551. var controllerAxes = this.controller.axes;
  47552. var i;
  47553. var previousAxis = this.axis;
  47554. var changedAxes = [];
  47555. // Check if axis changed.
  47556. for (i = 0; i < controllerAxes.length; ++i) {
  47557. changedAxes.push(previousAxis[i] !== controllerAxes[i]);
  47558. if (changedAxes[i]) { changed = true; }
  47559. }
  47560. if (!changed) { return false; }
  47561. this.axis = controllerAxes.slice();
  47562. this.el.emit('axismove', {axis: this.axis, changed: changedAxes});
  47563. return true;
  47564. },
  47565. /**
  47566. * Determine whether a button press has occured and emit events as appropriate.
  47567. *
  47568. * @param {string} id - ID of the button to check.
  47569. * @param {object} buttonState - State of the button to check.
  47570. * @returns {boolean} Whether button press state changed.
  47571. */
  47572. handlePress: function (id, buttonState) {
  47573. var evtName;
  47574. var previousButtonState = this.buttonStates[id];
  47575. // Not changed.
  47576. if (buttonState.pressed === previousButtonState.pressed) { return false; }
  47577. evtName = buttonState.pressed ? 'down' : 'up';
  47578. this.el.emit('button' + evtName, {id: id, state: buttonState});
  47579. previousButtonState.pressed = buttonState.pressed;
  47580. return true;
  47581. },
  47582. /**
  47583. * Determine whether a button touch has occured and emit events as appropriate.
  47584. *
  47585. * @param {string} id - ID of the button to check.
  47586. * @param {object} buttonState - State of the button to check.
  47587. * @returns {boolean} Whether button touch state changed.
  47588. */
  47589. handleTouch: function (id, buttonState) {
  47590. var evtName;
  47591. var previousButtonState = this.buttonStates[id];
  47592. // Not changed.
  47593. if (buttonState.touched === previousButtonState.touched) { return false; }
  47594. evtName = buttonState.touched ? 'start' : 'end';
  47595. // Due to unfortunate name collision, add empty touches array to avoid Daydream error.
  47596. this.el.emit('touch' + evtName, {id: id, state: buttonState}, true, {touches: []});
  47597. previousButtonState.touched = buttonState.touched;
  47598. return true;
  47599. },
  47600. /**
  47601. * Determine whether a button value has changed.
  47602. *
  47603. * @param {string} id - Id of the button to check.
  47604. * @param {object} buttonState - State of the button to check.
  47605. * @returns {boolean} Whether button value changed.
  47606. */
  47607. handleValue: function (id, buttonState) {
  47608. var previousButtonState = this.buttonStates[id];
  47609. // Not changed.
  47610. if (buttonState.value === previousButtonState.value) { return false; }
  47611. previousButtonState.value = buttonState.value;
  47612. return true;
  47613. }
  47614. });
  47615. },{"../constants":93,"../core/component":102,"../lib/three":149}],89:[function(_dereq_,module,exports){
  47616. var registerComponent = _dereq_('../core/component').registerComponent;
  47617. /**
  47618. * Visibility component.
  47619. */
  47620. module.exports.Component = registerComponent('visible', {
  47621. schema: {default: true},
  47622. update: function () {
  47623. this.el.object3D.visible = this.data;
  47624. }
  47625. });
  47626. },{"../core/component":102}],90:[function(_dereq_,module,exports){
  47627. var registerComponent = _dereq_('../core/component').registerComponent;
  47628. var bind = _dereq_('../utils/bind');
  47629. var checkControllerPresentAndSetup = _dereq_('../utils/tracked-controls').checkControllerPresentAndSetup;
  47630. var emitIfAxesChanged = _dereq_('../utils/tracked-controls').emitIfAxesChanged;
  47631. var VIVE_CONTROLLER_MODEL_OBJ_URL = 'https://cdn.aframe.io/controllers/vive/vr_controller_vive.obj';
  47632. var VIVE_CONTROLLER_MODEL_OBJ_MTL = 'https://cdn.aframe.io/controllers/vive/vr_controller_vive.mtl';
  47633. var GAMEPAD_ID_PREFIX = 'OpenVR ';
  47634. /**
  47635. * Vive Controls Component
  47636. * Interfaces with vive controllers and maps Gamepad events to
  47637. * common controller buttons: trackpad, trigger, grip, menu and system
  47638. * It loads a controller model and highlights the pressed buttons
  47639. */
  47640. module.exports.Component = registerComponent('vive-controls', {
  47641. schema: {
  47642. hand: {default: 'left'},
  47643. buttonColor: {type: 'color', default: '#FAFAFA'}, // Off-white.
  47644. buttonHighlightColor: {type: 'color', default: '#22D1EE'}, // Light blue.
  47645. model: {default: true},
  47646. rotationOffset: {default: 0} // use -999 as sentinel value to auto-determine based on hand
  47647. },
  47648. // buttonId
  47649. // 0 - trackpad
  47650. // 1 - trigger ( intensity value from 0.5 to 1 )
  47651. // 2 - grip
  47652. // 3 - menu ( dispatch but better for menu options )
  47653. // 4 - system ( never dispatched on this layer )
  47654. mapping: {
  47655. axes: {'trackpad': [0, 1]},
  47656. buttons: ['trackpad', 'trigger', 'grip', 'menu', 'system']
  47657. },
  47658. // Use these labels for detail on axis events such as thumbstickmoved.
  47659. // e.g. for thumbstickmoved detail, the first axis returned is labeled x, and the second is labeled y.
  47660. axisLabels: ['x', 'y', 'z', 'w'],
  47661. bindMethods: function () {
  47662. this.onModelLoaded = bind(this.onModelLoaded, this);
  47663. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  47664. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  47665. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  47666. this.onAxisMoved = bind(this.onAxisMoved, this);
  47667. },
  47668. init: function () {
  47669. var self = this;
  47670. this.animationActive = 'pointing';
  47671. this.onButtonChanged = bind(this.onButtonChanged, this);
  47672. this.onButtonDown = function (evt) { self.onButtonEvent(evt.detail.id, 'down'); };
  47673. this.onButtonUp = function (evt) { self.onButtonEvent(evt.detail.id, 'up'); };
  47674. this.onButtonTouchStart = function (evt) { self.onButtonEvent(evt.detail.id, 'touchstart'); };
  47675. this.onButtonTouchEnd = function (evt) { self.onButtonEvent(evt.detail.id, 'touchend'); };
  47676. this.onAxisMoved = bind(this.onAxisMoved, this);
  47677. this.controllerPresent = false;
  47678. this.lastControllerCheck = 0;
  47679. this.previousButtonValues = {};
  47680. this.bindMethods();
  47681. this.checkControllerPresentAndSetup = checkControllerPresentAndSetup; // to allow mock
  47682. this.emitIfAxesChanged = emitIfAxesChanged; // to allow mock
  47683. },
  47684. addEventListeners: function () {
  47685. var el = this.el;
  47686. el.addEventListener('buttonchanged', this.onButtonChanged);
  47687. el.addEventListener('buttondown', this.onButtonDown);
  47688. el.addEventListener('buttonup', this.onButtonUp);
  47689. el.addEventListener('touchstart', this.onButtonTouchStart);
  47690. el.addEventListener('touchend', this.onButtonTouchEnd);
  47691. el.addEventListener('model-loaded', this.onModelLoaded);
  47692. el.addEventListener('axismove', this.onAxisMoved);
  47693. },
  47694. removeEventListeners: function () {
  47695. var el = this.el;
  47696. el.removeEventListener('buttonchanged', this.onButtonChanged);
  47697. el.removeEventListener('buttondown', this.onButtonDown);
  47698. el.removeEventListener('buttonup', this.onButtonUp);
  47699. el.removeEventListener('touchstart', this.onButtonTouchStart);
  47700. el.removeEventListener('touchend', this.onButtonTouchEnd);
  47701. el.removeEventListener('model-loaded', this.onModelLoaded);
  47702. el.removeEventListener('axismove', this.onAxisMoved);
  47703. },
  47704. checkIfControllerPresent: function () {
  47705. var data = this.data;
  47706. // Once OpenVR / SteamVR return correct hand data in the supporting browsers, we can use hand property.
  47707. // var isPresent = this.checkControllerPresentAndSetup(this.el.sceneEl, GAMEPAD_ID_PREFIX, { hand: data.hand });
  47708. // Until then, use hardcoded index.
  47709. var controllerIndex = data.hand === 'right' ? 0 : data.hand === 'left' ? 1 : 2;
  47710. this.checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, { index: controllerIndex });
  47711. },
  47712. play: function () {
  47713. this.checkIfControllerPresent();
  47714. this.addControllersUpdateListener();
  47715. // Note that due to gamepadconnected event propagation issues, we don't rely on events.
  47716. window.addEventListener('gamepaddisconnected', this.checkIfControllerPresent, false);
  47717. },
  47718. pause: function () {
  47719. this.removeEventListeners();
  47720. this.removeControllersUpdateListener();
  47721. // Note that due to gamepadconnected event propagation issues, we don't rely on events.
  47722. window.removeEventListener('gamepaddisconnected', this.checkIfControllerPresent, false);
  47723. },
  47724. injectTrackedControls: function () {
  47725. var el = this.el;
  47726. var data = this.data;
  47727. // handId: 0 - right, 1 - left, 2 - anything else...
  47728. var controller = data.hand === 'right' ? 0 : data.hand === 'left' ? 1 : 2;
  47729. // if we have an OpenVR Gamepad, use the fixed mapping
  47730. el.setAttribute('tracked-controls', {idPrefix: GAMEPAD_ID_PREFIX, controller: controller, rotationOffset: data.rotationOffset});
  47731. if (!this.data.model) { return; }
  47732. this.el.setAttribute('obj-model', {
  47733. obj: VIVE_CONTROLLER_MODEL_OBJ_URL,
  47734. mtl: VIVE_CONTROLLER_MODEL_OBJ_MTL
  47735. });
  47736. },
  47737. addControllersUpdateListener: function () {
  47738. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  47739. },
  47740. removeControllersUpdateListener: function () {
  47741. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  47742. },
  47743. onControllersUpdate: function () { this.checkIfControllerPresent(); },
  47744. onButtonChanged: function (evt) {
  47745. var button = this.mapping.buttons[evt.detail.id];
  47746. var buttonMeshes = this.buttonMeshes;
  47747. var analogValue;
  47748. if (!button) { return; }
  47749. if (button === 'trigger') {
  47750. analogValue = evt.detail.state.value;
  47751. // Update button mesh, if any.
  47752. if (buttonMeshes && buttonMeshes.trigger) {
  47753. buttonMeshes.trigger.rotation.x = -analogValue * (Math.PI / 12);
  47754. }
  47755. }
  47756. // Pass along changed event with button state, using button mapping for convenience.
  47757. this.el.emit(button + 'changed', evt.detail.state);
  47758. },
  47759. onModelLoaded: function (evt) {
  47760. var controllerObject3D = evt.detail.model;
  47761. var buttonMeshes;
  47762. if (!this.data.model) { return; }
  47763. buttonMeshes = this.buttonMeshes = {};
  47764. buttonMeshes.grip = {
  47765. left: controllerObject3D.getObjectByName('leftgrip'),
  47766. right: controllerObject3D.getObjectByName('rightgrip')
  47767. };
  47768. buttonMeshes.menu = controllerObject3D.getObjectByName('menubutton');
  47769. buttonMeshes.system = controllerObject3D.getObjectByName('systembutton');
  47770. buttonMeshes.trackpad = controllerObject3D.getObjectByName('touchpad');
  47771. buttonMeshes.trigger = controllerObject3D.getObjectByName('trigger');
  47772. // Offset pivot point
  47773. controllerObject3D.position.set(0, -0.015, 0.04);
  47774. },
  47775. onAxisMoved: function (evt) { this.emitIfAxesChanged(this, this.mapping.axes, evt); },
  47776. onButtonEvent: function (id, evtName) {
  47777. var buttonName = this.mapping.buttons[id];
  47778. var i;
  47779. if (Array.isArray(buttonName)) {
  47780. for (i = 0; i < buttonName.length; i++) {
  47781. this.el.emit(buttonName[i] + evtName);
  47782. }
  47783. } else {
  47784. this.el.emit(buttonName + evtName);
  47785. }
  47786. this.updateModel(buttonName, evtName);
  47787. },
  47788. updateModel: function (buttonName, evtName) {
  47789. var i;
  47790. if (!this.data.model) { return; }
  47791. if (Array.isArray(buttonName)) {
  47792. for (i = 0; i < buttonName.length; i++) {
  47793. this.updateButtonModel(buttonName[i], evtName);
  47794. }
  47795. } else {
  47796. this.updateButtonModel(buttonName, evtName);
  47797. }
  47798. },
  47799. updateButtonModel: function (buttonName, state) {
  47800. var color = state === 'up' ? this.data.buttonColor : this.data.buttonHighlightColor;
  47801. var buttonMeshes = this.buttonMeshes;
  47802. if (!buttonMeshes) { return; }
  47803. if (buttonName === 'grip') {
  47804. buttonMeshes.grip.left.material.color.set(color);
  47805. buttonMeshes.grip.right.material.color.set(color);
  47806. return;
  47807. }
  47808. buttonMeshes[buttonName].material.color.set(color);
  47809. }
  47810. });
  47811. },{"../core/component":102,"../utils/bind":166,"../utils/tracked-controls":176}],91:[function(_dereq_,module,exports){
  47812. var KEYCODE_TO_CODE = _dereq_('../constants').keyboardevent.KEYCODE_TO_CODE;
  47813. var registerComponent = _dereq_('../core/component').registerComponent;
  47814. var THREE = _dereq_('../lib/three');
  47815. var utils = _dereq_('../utils/');
  47816. var bind = utils.bind;
  47817. var shouldCaptureKeyEvent = utils.shouldCaptureKeyEvent;
  47818. var CLAMP_VELOCITY = 0.00001;
  47819. var MAX_DELTA = 0.2;
  47820. /**
  47821. * WASD component to control entities using WASD keys.
  47822. */
  47823. module.exports.Component = registerComponent('wasd-controls', {
  47824. schema: {
  47825. acceleration: {default: 65},
  47826. adAxis: {default: 'x', oneOf: ['x', 'y', 'z']},
  47827. adEnabled: {default: true},
  47828. adInverted: {default: false},
  47829. easing: {default: 20},
  47830. enabled: {default: true},
  47831. fly: {default: false},
  47832. wsAxis: {default: 'z', oneOf: ['x', 'y', 'z']},
  47833. wsEnabled: {default: true},
  47834. wsInverted: {default: false}
  47835. },
  47836. init: function () {
  47837. // To keep track of the pressed keys.
  47838. this.keys = {};
  47839. this.velocity = new THREE.Vector3();
  47840. // Bind methods and add event listeners.
  47841. this.onBlur = bind(this.onBlur, this);
  47842. this.onFocus = bind(this.onFocus, this);
  47843. this.onKeyDown = bind(this.onKeyDown, this);
  47844. this.onKeyUp = bind(this.onKeyUp, this);
  47845. this.onVisibilityChange = bind(this.onVisibilityChange, this);
  47846. this.attachVisibilityEventListeners();
  47847. },
  47848. tick: function (time, delta) {
  47849. var data = this.data;
  47850. var el = this.el;
  47851. var movementVector;
  47852. var position;
  47853. var velocity = this.velocity;
  47854. // Use seconds.
  47855. delta = delta / 1000;
  47856. // Get velocity.
  47857. this.updateVelocity(delta);
  47858. if (!velocity[data.adAxis] && !velocity[data.wsAxis]) { return; }
  47859. // Get movement vector and translate position.
  47860. movementVector = this.getMovementVector(delta);
  47861. position = el.getAttribute('position');
  47862. el.setAttribute('position', {
  47863. x: position.x + movementVector.x,
  47864. y: position.y + movementVector.y,
  47865. z: position.z + movementVector.z
  47866. });
  47867. },
  47868. remove: function () {
  47869. this.removeKeyEventListeners();
  47870. this.removeVisibilityEventListeners();
  47871. },
  47872. play: function () {
  47873. this.attachKeyEventListeners();
  47874. },
  47875. pause: function () {
  47876. this.keys = {};
  47877. this.removeKeyEventListeners();
  47878. },
  47879. updateVelocity: function (delta) {
  47880. var acceleration;
  47881. var adAxis;
  47882. var adSign;
  47883. var data = this.data;
  47884. var keys = this.keys;
  47885. var velocity = this.velocity;
  47886. var wsAxis;
  47887. var wsSign;
  47888. adAxis = data.adAxis;
  47889. wsAxis = data.wsAxis;
  47890. // If FPS too low, reset velocity.
  47891. if (delta > MAX_DELTA) {
  47892. velocity[adAxis] = 0;
  47893. velocity[wsAxis] = 0;
  47894. return;
  47895. }
  47896. // Decay velocity.
  47897. if (velocity[adAxis] !== 0) {
  47898. velocity[adAxis] -= velocity[adAxis] * data.easing * delta;
  47899. }
  47900. if (velocity[wsAxis] !== 0) {
  47901. velocity[wsAxis] -= velocity[wsAxis] * data.easing * delta;
  47902. }
  47903. // Clamp velocity easing.
  47904. if (Math.abs(velocity[adAxis]) < CLAMP_VELOCITY) { velocity[adAxis] = 0; }
  47905. if (Math.abs(velocity[wsAxis]) < CLAMP_VELOCITY) { velocity[wsAxis] = 0; }
  47906. if (!data.enabled) { return; }
  47907. // Update velocity using keys pressed.
  47908. acceleration = data.acceleration;
  47909. if (data.adEnabled) {
  47910. adSign = data.adInverted ? -1 : 1;
  47911. if (keys.KeyA || keys.ArrowLeft) { velocity[adAxis] -= adSign * acceleration * delta; }
  47912. if (keys.KeyD || keys.ArrowRight) { velocity[adAxis] += adSign * acceleration * delta; }
  47913. }
  47914. if (data.wsEnabled) {
  47915. wsSign = data.wsInverted ? -1 : 1;
  47916. if (keys.KeyW || keys.ArrowUp) { velocity[wsAxis] -= wsSign * acceleration * delta; }
  47917. if (keys.KeyS || keys.ArrowDown) { velocity[wsAxis] += wsSign * acceleration * delta; }
  47918. }
  47919. },
  47920. getMovementVector: (function () {
  47921. var directionVector = new THREE.Vector3(0, 0, 0);
  47922. var rotationEuler = new THREE.Euler(0, 0, 0, 'YXZ');
  47923. return function (delta) {
  47924. var rotation = this.el.getAttribute('rotation');
  47925. var velocity = this.velocity;
  47926. var xRotation;
  47927. directionVector.copy(velocity);
  47928. directionVector.multiplyScalar(delta);
  47929. // Absolute.
  47930. if (!rotation) { return directionVector; }
  47931. xRotation = this.data.fly ? rotation.x : 0;
  47932. // Transform direction relative to heading.
  47933. rotationEuler.set(THREE.Math.degToRad(xRotation), THREE.Math.degToRad(rotation.y), 0);
  47934. directionVector.applyEuler(rotationEuler);
  47935. return directionVector;
  47936. };
  47937. })(),
  47938. attachVisibilityEventListeners: function () {
  47939. window.addEventListener('blur', this.onBlur);
  47940. window.addEventListener('focus', this.onFocus);
  47941. document.addEventListener('visibilitychange', this.onVisibilityChange);
  47942. },
  47943. removeVisibilityEventListeners: function () {
  47944. window.removeEventListener('blur', this.onBlur);
  47945. window.removeEventListener('focus', this.onFocus);
  47946. document.removeEventListener('visibilitychange', this.onVisibilityChange);
  47947. },
  47948. attachKeyEventListeners: function () {
  47949. window.addEventListener('keydown', this.onKeyDown);
  47950. window.addEventListener('keyup', this.onKeyUp);
  47951. },
  47952. removeKeyEventListeners: function () {
  47953. window.removeEventListener('keydown', this.onKeyDown);
  47954. window.removeEventListener('keyup', this.onKeyUp);
  47955. },
  47956. onBlur: function () {
  47957. this.pause();
  47958. },
  47959. onFocus: function () {
  47960. this.play();
  47961. },
  47962. onVisibilityChange: function () {
  47963. if (document.hidden) {
  47964. this.onBlur();
  47965. } else {
  47966. this.onFocus();
  47967. }
  47968. },
  47969. onKeyDown: function (event) {
  47970. var code;
  47971. if (!shouldCaptureKeyEvent(event)) { return; }
  47972. code = event.code || KEYCODE_TO_CODE[event.keyCode];
  47973. this.keys[code] = true;
  47974. },
  47975. onKeyUp: function (event) {
  47976. var code;
  47977. code = event.code || KEYCODE_TO_CODE[event.keyCode];
  47978. this.keys[code] = false;
  47979. }
  47980. });
  47981. },{"../constants":93,"../core/component":102,"../lib/three":149,"../utils/":172}],92:[function(_dereq_,module,exports){
  47982. /**
  47983. * Animation configuration options for TWEEN.js animations.
  47984. * Used by `<a-animation>`.
  47985. */
  47986. var TWEEN = _dereq_('tween.js');
  47987. var DIRECTIONS = {
  47988. alternate: 'alternate',
  47989. alternateReverse: 'alternate-reverse',
  47990. normal: 'normal',
  47991. reverse: 'reverse'
  47992. };
  47993. var EASING_FUNCTIONS = {
  47994. 'linear': TWEEN.Easing.Linear.None,
  47995. 'ease': TWEEN.Easing.Cubic.InOut,
  47996. 'ease-in': TWEEN.Easing.Cubic.In,
  47997. 'ease-out': TWEEN.Easing.Cubic.Out,
  47998. 'ease-in-out': TWEEN.Easing.Cubic.InOut,
  47999. 'ease-cubic': TWEEN.Easing.Cubic.In,
  48000. 'ease-in-cubic': TWEEN.Easing.Cubic.In,
  48001. 'ease-out-cubic': TWEEN.Easing.Cubic.Out,
  48002. 'ease-in-out-cubic': TWEEN.Easing.Cubic.InOut,
  48003. 'ease-quad': TWEEN.Easing.Quadratic.InOut,
  48004. 'ease-in-quad': TWEEN.Easing.Quadratic.In,
  48005. 'ease-out-quad': TWEEN.Easing.Quadratic.Out,
  48006. 'ease-in-out-quad': TWEEN.Easing.Quadratic.InOut,
  48007. 'ease-quart': TWEEN.Easing.Quartic.InOut,
  48008. 'ease-in-quart': TWEEN.Easing.Quartic.In,
  48009. 'ease-out-quart': TWEEN.Easing.Quartic.Out,
  48010. 'ease-in-out-quart': TWEEN.Easing.Quartic.InOut,
  48011. 'ease-quint': TWEEN.Easing.Quintic.InOut,
  48012. 'ease-in-quint': TWEEN.Easing.Quintic.In,
  48013. 'ease-out-quint': TWEEN.Easing.Quintic.Out,
  48014. 'ease-in-out-quint': TWEEN.Easing.Quintic.InOut,
  48015. 'ease-sine': TWEEN.Easing.Sinusoidal.InOut,
  48016. 'ease-in-sine': TWEEN.Easing.Sinusoidal.In,
  48017. 'ease-out-sine': TWEEN.Easing.Sinusoidal.Out,
  48018. 'ease-in-out-sine': TWEEN.Easing.Sinusoidal.InOut,
  48019. 'ease-expo': TWEEN.Easing.Exponential.InOut,
  48020. 'ease-in-expo': TWEEN.Easing.Exponential.In,
  48021. 'ease-out-expo': TWEEN.Easing.Exponential.Out,
  48022. 'ease-in-out-expo': TWEEN.Easing.Exponential.InOut,
  48023. 'ease-circ': TWEEN.Easing.Circular.InOut,
  48024. 'ease-in-circ': TWEEN.Easing.Circular.In,
  48025. 'ease-out-circ': TWEEN.Easing.Circular.Out,
  48026. 'ease-in-out-circ': TWEEN.Easing.Circular.InOut,
  48027. 'ease-elastic': TWEEN.Easing.Elastic.InOut,
  48028. 'ease-in-elastic': TWEEN.Easing.Elastic.In,
  48029. 'ease-out-elastic': TWEEN.Easing.Elastic.Out,
  48030. 'ease-in-out-elastic': TWEEN.Easing.Elastic.InOut,
  48031. 'ease-back': TWEEN.Easing.Back.InOut,
  48032. 'ease-in-back': TWEEN.Easing.Back.In,
  48033. 'ease-out-back': TWEEN.Easing.Back.Out,
  48034. 'ease-in-out-back': TWEEN.Easing.Back.InOut,
  48035. 'ease-bounce': TWEEN.Easing.Bounce.InOut,
  48036. 'ease-in-bounce': TWEEN.Easing.Bounce.In,
  48037. 'ease-out-bounce': TWEEN.Easing.Bounce.Out,
  48038. 'ease-in-out-bounce': TWEEN.Easing.Bounce.InOut
  48039. };
  48040. var FILLS = {
  48041. backwards: 'backwards',
  48042. both: 'both',
  48043. forwards: 'forwards',
  48044. none: 'none'
  48045. };
  48046. var REPEATS = {
  48047. indefinite: 'indefinite'
  48048. };
  48049. var DEFAULTS = {
  48050. attribute: 'rotation',
  48051. begin: '',
  48052. end: '',
  48053. delay: 0,
  48054. dur: 1000,
  48055. easing: 'ease',
  48056. direction: DIRECTIONS.normal,
  48057. fill: FILLS.forwards,
  48058. from: undefined,
  48059. repeat: 0,
  48060. to: undefined
  48061. };
  48062. module.exports.defaults = DEFAULTS;
  48063. module.exports.directions = DIRECTIONS;
  48064. module.exports.easingFunctions = EASING_FUNCTIONS;
  48065. module.exports.fills = FILLS;
  48066. module.exports.repeats = REPEATS;
  48067. },{"tween.js":48}],93:[function(_dereq_,module,exports){
  48068. module.exports = {
  48069. AFRAME_INJECTED: 'aframe-injected',
  48070. DEFAULT_CAMERA_HEIGHT: 1.6,
  48071. DEFAULT_HANDEDNESS: 'right',
  48072. animation: _dereq_('./animation'),
  48073. keyboardevent: _dereq_('./keyboardevent')
  48074. };
  48075. },{"./animation":92,"./keyboardevent":94}],94:[function(_dereq_,module,exports){
  48076. module.exports = {
  48077. // Tiny KeyboardEvent.code polyfill.
  48078. KEYCODE_TO_CODE: {
  48079. '38': 'ArrowUp',
  48080. '37': 'ArrowLeft',
  48081. '40': 'ArrowDown',
  48082. '39': 'ArrowRight',
  48083. '87': 'KeyW',
  48084. '65': 'KeyA',
  48085. '83': 'KeyS',
  48086. '68': 'KeyD'
  48087. }
  48088. };
  48089. },{}],95:[function(_dereq_,module,exports){
  48090. var ANode = _dereq_('./a-node');
  48091. var animationConstants = _dereq_('../constants/animation');
  48092. var coordinates = _dereq_('../utils/').coordinates;
  48093. var parseProperty = _dereq_('./schema').parseProperty;
  48094. var registerElement = _dereq_('./a-register-element').registerElement;
  48095. var TWEEN = _dereq_('tween.js');
  48096. var THREE = _dereq_('../lib/three');
  48097. var utils = _dereq_('../utils/');
  48098. var bind = utils.bind;
  48099. var getComponentProperty = utils.entity.getComponentProperty;
  48100. var DEFAULTS = animationConstants.defaults;
  48101. var DIRECTIONS = animationConstants.directions;
  48102. var EASING_FUNCTIONS = animationConstants.easingFunctions;
  48103. var FILLS = animationConstants.fills;
  48104. var REPEATS = animationConstants.repeats;
  48105. var isCoordinates = coordinates.isCoordinates;
  48106. /**
  48107. * Animation element that applies Tween animation to parent element (entity).
  48108. * Takes after the Web Animations spec.
  48109. *
  48110. * @member {number} count - Decrementing counter for how many cycles of animations left to
  48111. * run.
  48112. * @member {Element} el - Entity which the animation is modifying.
  48113. * @member initialValue - Value before animation started. Used to restore state.
  48114. * @member {bool} isRunning - Whether animation is currently running.
  48115. * @member {function} partialSetAttribute -
  48116. * setAttribute function that is agnostic to whether we are setting an attribute value
  48117. * or a component property value. The el and the attribute names are bundled with
  48118. * the function.
  48119. * @member {object} tween - tween.js object.
  48120. */
  48121. module.exports.AAnimation = registerElement('a-animation', {
  48122. prototype: Object.create(ANode.prototype, {
  48123. createdCallback: {
  48124. value: function () {
  48125. this.bindMethods();
  48126. this.isRunning = false;
  48127. this.partialSetAttribute = function () { /* no-op */ };
  48128. this.tween = null;
  48129. }
  48130. },
  48131. attachedCallback: {
  48132. value: function () {
  48133. this.el = this.parentNode;
  48134. this.handleMixinUpdate();
  48135. this.update();
  48136. this.load();
  48137. }
  48138. },
  48139. attributeChangedCallback: {
  48140. value: function (attr, oldVal, newVal) {
  48141. if (!this.hasLoaded || !this.isRunning) { return; }
  48142. this.stop();
  48143. this.handleMixinUpdate();
  48144. this.update();
  48145. }
  48146. },
  48147. detachedCallback: {
  48148. value: function () {
  48149. if (!this.isRunning) { return; }
  48150. this.stop();
  48151. }
  48152. },
  48153. /**
  48154. * Builds a Tween object to handle animations.
  48155. * Uses tween.js's from, to, delay, easing, repeat, onUpdate, and onComplete.
  48156. * Note: tween.js takes objects for its `from` and `to` values.
  48157. *
  48158. * @returns {object}
  48159. */
  48160. getTween: {
  48161. value: function () {
  48162. var self = this;
  48163. var data = self.data;
  48164. var el = self.el;
  48165. var animationValues;
  48166. var attribute = data.attribute;
  48167. var delay = parseInt(data.delay, 10);
  48168. var currentValue = getComponentProperty(el, attribute);
  48169. var direction = self.getDirection(data.direction);
  48170. var easing = EASING_FUNCTIONS[data.easing];
  48171. var fill = data.fill;
  48172. var from;
  48173. var repeat = data.repeat === REPEATS.indefinite ? Infinity : 0;
  48174. var to;
  48175. var toTemp;
  48176. var yoyo = false;
  48177. animationValues = getAnimationValues(el, attribute, data.from || self.initialValue, data.to, currentValue);
  48178. from = animationValues.from;
  48179. to = animationValues.to;
  48180. self.partialSetAttribute = animationValues.partialSetAttribute;
  48181. if (self.count === undefined) {
  48182. self.count = repeat === Infinity ? 0 : parseInt(data.repeat, 10);
  48183. }
  48184. if (isNaN(delay)) { delay = 0; }
  48185. // Store initial state.
  48186. self.initialValue = self.initialValue || cloneValue(currentValue);
  48187. // Handle indefinite + forwards + alternate yoyo edge-case (#405).
  48188. if (repeat === Infinity && fill === FILLS.forwards &&
  48189. [DIRECTIONS.alternate,
  48190. DIRECTIONS.alternateReverse].indexOf(data.direction) !== -1) {
  48191. yoyo = true;
  48192. }
  48193. // If reversing, swap from and to.
  48194. if (direction === DIRECTIONS.reverse) {
  48195. toTemp = to;
  48196. to = cloneValue(from);
  48197. from = cloneValue(toTemp);
  48198. }
  48199. // If fill is backwards or both, start animation at the specified from.
  48200. if ([FILLS.backwards, FILLS.both].indexOf(fill) !== -1) {
  48201. self.partialSetAttribute(from);
  48202. }
  48203. // Create Tween.
  48204. return new TWEEN.Tween(cloneValue(from))
  48205. .to(to, data.dur)
  48206. .delay(delay)
  48207. .easing(easing)
  48208. .repeat(repeat)
  48209. .yoyo(yoyo)
  48210. .onUpdate(function () {
  48211. self.partialSetAttribute(this);
  48212. })
  48213. .onComplete(bind(self.onCompleted, self));
  48214. }
  48215. },
  48216. /**
  48217. * Animation parameters changed. Stop current animation, get a new one, and start it.
  48218. */
  48219. update: {
  48220. value: function () {
  48221. var data = this.data;
  48222. // Terminology warning if infinite used instead of indefinite
  48223. if (data.repeat === 'infinite') {
  48224. console.warn("Using 'infinite' as 'repeat' value is invalid. Use 'indefinite' instead.");
  48225. }
  48226. // Deprecation warning for begin when used as a delay.
  48227. if (data.begin !== '' && !isNaN(data.begin)) {
  48228. console.warn("Using 'begin' to specify a delay is deprecated. Use 'delay' instead.");
  48229. data.delay = data.begin;
  48230. data.begin = '';
  48231. }
  48232. var begin = data.begin;
  48233. var end = data.end;
  48234. // Cancel previous event listeners
  48235. if (this.evt) { this.removeEventListeners(this.evt); }
  48236. // Store new event name.
  48237. this.evt = {begin: begin, end: end};
  48238. // Add new event listeners
  48239. this.addEventListeners(this.evt);
  48240. // If `begin` is not defined, start the animation right away.
  48241. if (begin === '') {
  48242. this.stop();
  48243. this.start();
  48244. }
  48245. },
  48246. writable: window.debug
  48247. },
  48248. /**
  48249. * Callback for when a cycle of an animation is complete. Handles when to completely
  48250. * finish the animation.
  48251. *
  48252. * If `repeat` is set to a value, this method is called after each repeat. Repeats are
  48253. * handled by ending the current animation and creating a new one with `count` updated.
  48254. * Note that this method is *not* called if repeat is set to `indefinite`.
  48255. */
  48256. onCompleted: {
  48257. value: function () {
  48258. var data = this.data;
  48259. this.isRunning = false;
  48260. if ([FILLS.backwards, FILLS.none].indexOf(data.fill) !== -1) {
  48261. this.partialSetAttribute(this.initialValue);
  48262. }
  48263. if (this.count === 0) {
  48264. this.count = undefined;
  48265. this.emit('animationend');
  48266. return;
  48267. }
  48268. this.isRunning = false;
  48269. this.count--;
  48270. this.start();
  48271. }
  48272. },
  48273. start: {
  48274. value: function () {
  48275. var self = this;
  48276. // Postpone animation start until the entity has loaded
  48277. if (!this.el.hasLoaded) {
  48278. this.el.addEventListener('loaded', function () { self.start(); });
  48279. return;
  48280. }
  48281. if (this.isRunning || !this.el.isPlaying) { return; }
  48282. this.tween = this.getTween();
  48283. this.isRunning = true;
  48284. this.tween.start();
  48285. this.emit('animationstart');
  48286. },
  48287. writable: true
  48288. },
  48289. stop: {
  48290. value: function () {
  48291. var tween = this.tween;
  48292. if (!tween) { return; }
  48293. tween.stop();
  48294. this.isRunning = false;
  48295. if ([FILLS.backwards, FILLS.none].indexOf(this.data.fill) !== -1) {
  48296. this.partialSetAttribute(this.initialValue);
  48297. }
  48298. this.emit('animationstop');
  48299. },
  48300. writable: true
  48301. },
  48302. /**
  48303. * Handle alternating directions. Given the current direction, calculate the next one,
  48304. * and store the current one.
  48305. *
  48306. * @param {string} direction
  48307. * @returns {string} Direction that the next individual cycle of the animation will go
  48308. * towards.
  48309. */
  48310. getDirection: {
  48311. value: function (direction) {
  48312. if (direction === DIRECTIONS.alternate) {
  48313. this.prevDirection =
  48314. this.prevDirection === DIRECTIONS.normal ? DIRECTIONS.reverse : DIRECTIONS.normal;
  48315. return this.prevDirection;
  48316. }
  48317. if (direction === DIRECTIONS.alternateReverse) {
  48318. this.prevDirection =
  48319. this.prevDirection === DIRECTIONS.reverse ? DIRECTIONS.normal : DIRECTIONS.reverse;
  48320. return this.prevDirection;
  48321. }
  48322. return direction;
  48323. }
  48324. },
  48325. /**
  48326. * Preemptive binding to attach/detach event listeners (see `update`).
  48327. */
  48328. bindMethods: {
  48329. value: function () {
  48330. this.start = bind(this.start, this);
  48331. this.stop = bind(this.stop, this);
  48332. this.onStateAdded = bind(this.onStateAdded, this);
  48333. this.onStateRemoved = bind(this.onStateRemoved, this);
  48334. }
  48335. },
  48336. addEventListeners: {
  48337. value: function (evts) {
  48338. var el = this.el;
  48339. var self = this;
  48340. utils.splitString(evts.begin).forEach(function (evt) {
  48341. el.addEventListener(evt, self.start);
  48342. });
  48343. utils.splitString(evts.end).forEach(function (evt) {
  48344. el.addEventListener(evt, self.stop);
  48345. });
  48346. // If "begin" is an event name, wait. If it is not defined, start.
  48347. if (evts.begin === '') { el.addEventListener('play', this.start); }
  48348. el.addEventListener('pause', this.stop);
  48349. el.addEventListener('stateadded', this.onStateAdded);
  48350. el.addEventListener('stateremoved', this.onStateRemoved);
  48351. }
  48352. },
  48353. removeEventListeners: {
  48354. value: function (evts) {
  48355. var el = this.el;
  48356. var start = this.start;
  48357. var stop = this.stop;
  48358. utils.splitString(evts.begin).forEach(function (evt) {
  48359. el.removeEventListener(evt, start);
  48360. });
  48361. utils.splitString(evts.end).forEach(function (evt) {
  48362. el.removeEventListener(evt, stop);
  48363. });
  48364. el.removeEventListener('stateadded', this.onStateAdded);
  48365. el.removeEventListener('stateremoved', this.onStateRemoved);
  48366. }
  48367. },
  48368. onStateAdded: {
  48369. value: function (evt) {
  48370. if (evt.detail.state === this.data.begin) { this.start(); }
  48371. },
  48372. writable: true
  48373. },
  48374. onStateRemoved: {
  48375. value: function (evt) {
  48376. if (evt.detail.state === this.data.begin) { this.stop(); }
  48377. },
  48378. writable: true
  48379. },
  48380. /**
  48381. * Applies animation data from a mixin element.
  48382. * Works the same as component mixins but reimplemented because animations
  48383. * aren't components.
  48384. */
  48385. handleMixinUpdate: {
  48386. value: function () {
  48387. var data = {};
  48388. var elData;
  48389. var mixinData;
  48390. var mixinEl;
  48391. // Get mixin data.
  48392. mixinEl = document.querySelector('#' + this.getAttribute('mixin'));
  48393. mixinData = mixinEl ? utils.getElData(mixinEl, DEFAULTS) : {};
  48394. elData = utils.getElData(this, DEFAULTS);
  48395. utils.extend(data, DEFAULTS, mixinData, elData);
  48396. this.data = data;
  48397. }
  48398. }
  48399. })
  48400. });
  48401. function cloneValue (val) {
  48402. return utils.extend({}, val);
  48403. }
  48404. /**
  48405. * Deduces different animation values based on whether we are:
  48406. * - animating an inner attribute of a component.
  48407. * - animating a coordinate component.
  48408. * - animating a boolean.
  48409. * - animating a number.
  48410. *
  48411. * @param {Element} el
  48412. * @param {string} attribute - Tells what to animate based on whether it is dot-separated.
  48413. * @param {string} dataFrom - Data `from` value.
  48414. * @param {string} dataTo - Data `to` value.
  48415. * @param currentValue
  48416. * @returns {object}
  48417. * Object with keys [from, to, partialSetAttribute].
  48418. * `from` and `to`
  48419. * Objects where key is attribute being animated and value is value.
  48420. * `partialSetAttribute`
  48421. * Closured-function that tells tween how to update the component.
  48422. */
  48423. function getAnimationValues (el, attribute, dataFrom, dataTo, currentValue) {
  48424. var attributeSplit = attribute.split('.');
  48425. var schema;
  48426. var component;
  48427. var componentPropName;
  48428. var componentName;
  48429. var from = {};
  48430. var partialSetAttribute;
  48431. var to = {};
  48432. if (attributeSplit.length === 2) {
  48433. if (isColor()) {
  48434. getForColorComponent();
  48435. } else {
  48436. getForComponentAttribute();
  48437. }
  48438. } else if (dataTo && isCoordinates(dataTo)) {
  48439. getForCoordinateComponent();
  48440. } else if (['true', 'false'].indexOf(dataTo) !== -1) {
  48441. getForBoolean();
  48442. } else if (isNaN(dataTo)) {
  48443. getForColorComponent();
  48444. } else {
  48445. getForNumber();
  48446. }
  48447. return {
  48448. from: from,
  48449. partialSetAttribute: partialSetAttribute,
  48450. to: to
  48451. };
  48452. /**
  48453. * Match the schema type to color
  48454. * @return {bool} if the schema is of type color
  48455. */
  48456. function isColor () {
  48457. var componentName = attributeSplit[0];
  48458. var propertyName = attributeSplit[1];
  48459. var component = el.components[componentName];
  48460. var schema = component && component.schema;
  48461. return schema && schema[propertyName] && schema[propertyName].type === 'color';
  48462. }
  48463. /**
  48464. * Animating a component that has multiple attributes (e.g., geometry.width).
  48465. */
  48466. function getForComponentAttribute () {
  48467. componentName = attributeSplit[0];
  48468. componentPropName = attributeSplit[1];
  48469. component = el.components[componentName];
  48470. if (!component) {
  48471. el.setAttribute(componentName, '');
  48472. component = el.components[componentName];
  48473. }
  48474. schema = component.schema;
  48475. if (dataFrom === undefined) { // dataFrom can be 0.
  48476. from[attribute] = getComponentProperty(el, attribute);
  48477. } else {
  48478. from[attribute] = dataFrom;
  48479. }
  48480. from[attribute] = parseProperty(from[attribute], schema[componentPropName]);
  48481. to[attribute] = parseProperty(dataTo, schema[componentPropName]);
  48482. partialSetAttribute = function (value) {
  48483. if (!(attribute in value)) { return; }
  48484. el.setAttribute(componentName, componentPropName, value[attribute]);
  48485. };
  48486. }
  48487. /**
  48488. * Animating a component that is an XYZ coordinate (e.g., position).
  48489. * Will be tweening {x, y, z} all at once.
  48490. */
  48491. function getForCoordinateComponent () {
  48492. from = dataFrom ? coordinates.parse(dataFrom) : currentValue;
  48493. to = coordinates.parse(dataTo);
  48494. partialSetAttribute = function (value) {
  48495. el.setAttribute(attribute, value);
  48496. };
  48497. }
  48498. /**
  48499. * Animation a boolean (e.g., visible).
  48500. * Have to convert from boolean to an integer (0 is false, > 0 is true) for tween.
  48501. */
  48502. function getForBoolean () {
  48503. if (dataFrom === undefined) {
  48504. from[attribute] = false;
  48505. } else {
  48506. from[attribute] = strToBool(dataFrom);
  48507. }
  48508. from[attribute] = boolToNum(from[attribute]);
  48509. to[attribute] = boolToNum(strToBool(dataTo));
  48510. partialSetAttribute = function (value) {
  48511. el.setAttribute(attribute, !!value[attribute]);
  48512. };
  48513. }
  48514. /**
  48515. * Animating a color component
  48516. * Will convert a hex value to a THREE.Color
  48517. * Then converts to hex for the setAttribute
  48518. */
  48519. function getForColorComponent () {
  48520. from = new THREE.Color(dataFrom);
  48521. to = new THREE.Color(dataTo);
  48522. partialSetAttribute = function (value) {
  48523. if (attributeSplit.length > 1) {
  48524. el.setAttribute(attributeSplit[0], attributeSplit[1], rgbVectorToHex(value));
  48525. }
  48526. el.setAttribute(attribute, rgbVectorToHex(value));
  48527. };
  48528. }
  48529. /**
  48530. * Animating a numbered attribute (e.g., opacity).
  48531. */
  48532. function getForNumber () {
  48533. if (dataFrom === undefined) { // dataFrom can be 0.
  48534. from[attribute] = parseFloat(el.getAttribute(attribute));
  48535. } else {
  48536. from[attribute] = parseFloat(dataFrom);
  48537. }
  48538. to[attribute] = parseFloat(dataTo);
  48539. partialSetAttribute = function (value) {
  48540. el.setAttribute(attribute, value[attribute]);
  48541. };
  48542. }
  48543. }
  48544. module.exports.getAnimationValues = getAnimationValues;
  48545. /**
  48546. * Converts string to bool.
  48547. *
  48548. * @param {string} str - `true` or `false`.
  48549. * @returns {bool}
  48550. */
  48551. function strToBool (str) {
  48552. if (str === 'true') { return true; }
  48553. return false;
  48554. }
  48555. /**
  48556. * Converts boolean to number.
  48557. *
  48558. * @param {bool}
  48559. * @returns {number}
  48560. */
  48561. function boolToNum (bool) {
  48562. return bool ? 1 : 0;
  48563. }
  48564. /**
  48565. * Converts a number 0-255 to hex
  48566. * @param {number} color number 0 - 255
  48567. * @returns {string} hex value of number bassed
  48568. */
  48569. function componentToHex (color) {
  48570. var hex = color.toString(16);
  48571. return hex.length === 1 ? '0' + hex : hex;
  48572. }
  48573. /**
  48574. * Clamps a number to 0-1
  48575. * Then converts that number to 0-255
  48576. * @param {number} color number 0 - 1
  48577. * @returns {number} color number 0 - 255
  48578. */
  48579. function convertToIntegerColor (color) {
  48580. return Math.floor(Math.min(Math.abs(color), 1) * 255);
  48581. }
  48582. /**
  48583. * Converts a rgb object into a hex string
  48584. * @param {object} color { r: 1, g: 1, b: 1 }
  48585. * @returns {string} hex value #ffffff
  48586. */
  48587. function rgbVectorToHex (color) {
  48588. return '#' + ['r', 'g', 'b'].map(function (prop) {
  48589. return componentToHex(convertToIntegerColor(color[prop]));
  48590. }).join('');
  48591. }
  48592. },{"../constants/animation":92,"../lib/three":149,"../utils/":172,"./a-node":100,"./a-register-element":101,"./schema":110,"tween.js":48}],96:[function(_dereq_,module,exports){
  48593. var ANode = _dereq_('./a-node');
  48594. var bind = _dereq_('../utils/bind');
  48595. var debug = _dereq_('../utils/debug');
  48596. var registerElement = _dereq_('./a-register-element').registerElement;
  48597. var THREE = _dereq_('../lib/three');
  48598. var fileLoader = new THREE.FileLoader();
  48599. var warn = debug('core:a-assets:warn');
  48600. /**
  48601. * Asset management system. Handles blocking on asset loading.
  48602. */
  48603. module.exports = registerElement('a-assets', {
  48604. prototype: Object.create(ANode.prototype, {
  48605. createdCallback: {
  48606. value: function () {
  48607. this.isAssets = true;
  48608. this.fileLoader = fileLoader;
  48609. this.timeout = null;
  48610. }
  48611. },
  48612. attachedCallback: {
  48613. value: function () {
  48614. var self = this;
  48615. var i;
  48616. var loaded = [];
  48617. var mediaEl;
  48618. var mediaEls;
  48619. var imgEl;
  48620. var imgEls;
  48621. var timeout;
  48622. if (!this.parentNode.isScene) {
  48623. throw new Error('<a-assets> must be a child of a <a-scene>.');
  48624. }
  48625. // Wait for <img>s.
  48626. imgEls = this.querySelectorAll('img');
  48627. for (i = 0; i < imgEls.length; i++) {
  48628. imgEl = fixUpMediaElement(imgEls[i]);
  48629. loaded.push(new Promise(function (resolve, reject) {
  48630. // Set in cache because we won't be needing to call three.js loader if we have.
  48631. // a loaded media element.
  48632. THREE.Cache.files[imgEls[i].getAttribute('src')] = imgEl;
  48633. imgEl.onload = resolve;
  48634. imgEl.onerror = reject;
  48635. }));
  48636. }
  48637. // Wait for <audio>s and <video>s.
  48638. mediaEls = this.querySelectorAll('audio, video');
  48639. for (i = 0; i < mediaEls.length; i++) {
  48640. mediaEl = fixUpMediaElement(mediaEls[i]);
  48641. loaded.push(mediaElementLoaded(mediaEl));
  48642. }
  48643. // Trigger loaded for scene to start rendering.
  48644. Promise.all(loaded).then(bind(this.load, this));
  48645. // Timeout to start loading anyways.
  48646. timeout = parseInt(this.getAttribute('timeout'), 10) || 3000;
  48647. this.timeout = setTimeout(function () {
  48648. if (self.hasLoaded) { return; }
  48649. warn('Asset loading timed out in ', timeout, 'ms');
  48650. self.emit('timeout');
  48651. self.load();
  48652. }, timeout);
  48653. }
  48654. },
  48655. detachedCallback: {
  48656. value: function () {
  48657. if (this.timeout) { clearTimeout(this.timeout); }
  48658. }
  48659. },
  48660. load: {
  48661. value: function () {
  48662. ANode.prototype.load.call(this, null, function waitOnFilter (el) {
  48663. return el.isAssetItem && el.hasAttribute('src');
  48664. });
  48665. }
  48666. }
  48667. })
  48668. });
  48669. /**
  48670. * Preload using XHRLoader for any type of asset.
  48671. */
  48672. registerElement('a-asset-item', {
  48673. prototype: Object.create(ANode.prototype, {
  48674. createdCallback: {
  48675. value: function () {
  48676. this.data = null;
  48677. this.isAssetItem = true;
  48678. }
  48679. },
  48680. attachedCallback: {
  48681. value: function () {
  48682. var self = this;
  48683. var src = this.getAttribute('src');
  48684. fileLoader.setResponseType(
  48685. this.getAttribute('response-type') || inferResponseType(src));
  48686. fileLoader.load(src, function handleOnLoad (response) {
  48687. self.data = response;
  48688. /*
  48689. Workaround for a Chrome bug. If another XHR is sent to the same url before the
  48690. previous one closes, the second request never finishes.
  48691. setTimeout finishes the first request and lets the logic triggered by load open
  48692. subsequent requests.
  48693. setTimeout can be removed once the fix for the bug below ships:
  48694. 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
  48695. */
  48696. setTimeout(function load () { ANode.prototype.load.call(self); });
  48697. }, function handleOnProgress (xhr) {
  48698. self.emit('progress', {
  48699. loadedBytes: xhr.loaded,
  48700. totalBytes: xhr.total,
  48701. xhr: xhr
  48702. });
  48703. }, function handleOnError (xhr) {
  48704. self.emit('error', {xhr: xhr});
  48705. });
  48706. }
  48707. }
  48708. })
  48709. });
  48710. /**
  48711. * Create a Promise that resolves once the media element has finished buffering.
  48712. *
  48713. * @param {Element} el - HTMLMediaElement.
  48714. * @returns {Promise}
  48715. */
  48716. function mediaElementLoaded (el) {
  48717. if (!el.hasAttribute('autoplay') && el.getAttribute('preload') !== 'auto') {
  48718. return;
  48719. }
  48720. // If media specifies autoplay or preload, wait until media is completely buffered.
  48721. return new Promise(function (resolve, reject) {
  48722. if (el.readyState === 4) { return resolve(); } // Already loaded.
  48723. if (el.error) { return reject(); } // Error.
  48724. el.addEventListener('loadeddata', checkProgress, false);
  48725. el.addEventListener('progress', checkProgress, false);
  48726. el.addEventListener('error', reject, false);
  48727. function checkProgress () {
  48728. // Add up the seconds buffered.
  48729. var secondsBuffered = 0;
  48730. for (var i = 0; i < el.buffered.length; i++) {
  48731. secondsBuffered += el.buffered.end(i) - el.buffered.start(i);
  48732. }
  48733. // Compare seconds buffered to media duration.
  48734. if (secondsBuffered >= el.duration) {
  48735. // Set in cache because we won't be needing to call three.js loader if we have.
  48736. // a loaded media element.
  48737. THREE.Cache.files[el.getAttribute('src')] = el;
  48738. resolve();
  48739. }
  48740. }
  48741. });
  48742. }
  48743. /**
  48744. * Automatically add attributes to media elements where convenient.
  48745. * crossorigin, playsinline.
  48746. */
  48747. function fixUpMediaElement (mediaEl) {
  48748. // Cross-origin.
  48749. var newMediaEl = setCrossOrigin(mediaEl);
  48750. // Plays inline for mobile.
  48751. if (newMediaEl.tagName && newMediaEl.tagName.toLowerCase() === 'video') {
  48752. newMediaEl.setAttribute('playsinline', '');
  48753. newMediaEl.setAttribute('webkit-playsinline', '');
  48754. }
  48755. if (newMediaEl !== mediaEl) {
  48756. mediaEl.parentNode.appendChild(newMediaEl);
  48757. mediaEl.parentNode.removeChild(mediaEl);
  48758. }
  48759. return newMediaEl;
  48760. }
  48761. /**
  48762. * Automatically set `crossorigin` if not defined on the media element.
  48763. * If it is not defined, we must create and re-append a new media element <img> and
  48764. * have the browser re-request it with `crossorigin` set.
  48765. *
  48766. * @param {Element} Media element (e.g., <img>, <audio>, <video>).
  48767. * @returns {Element} Media element to be used to listen to for loaded events.
  48768. */
  48769. function setCrossOrigin (mediaEl) {
  48770. var newMediaEl;
  48771. var src;
  48772. // Already has crossorigin set.
  48773. if (mediaEl.hasAttribute('crossorigin')) { return mediaEl; }
  48774. src = mediaEl.getAttribute('src');
  48775. if (src !== null) {
  48776. // Does not have protocol.
  48777. if (src.indexOf('://') === -1) { return mediaEl; }
  48778. // Determine if cross origin is actually needed.
  48779. if (extractDomain(src) === window.location.host) { return mediaEl; }
  48780. }
  48781. warn('Cross-origin element (e.g., <img>) was requested without `crossorigin` set. ' +
  48782. 'A-Frame will re-request the asset with `crossorigin` attribute set. ' +
  48783. 'Please set `crossorigin` on the element (e.g., <img crossorigin="anonymous">)', src);
  48784. mediaEl.crossOrigin = 'anonymous';
  48785. newMediaEl = mediaEl.cloneNode(true);
  48786. return newMediaEl;
  48787. }
  48788. /**
  48789. * Extract domain out of URL.
  48790. *
  48791. * @param {string} url
  48792. * @returns {string}
  48793. */
  48794. function extractDomain (url) {
  48795. // Find and remove protocol (e.g., http, ftp, etc.) to get domain.
  48796. var domain = url.indexOf('://') > -1 ? url.split('/')[2] : url.split('/')[0];
  48797. // Find and remove port number.
  48798. return domain.split(':')[0];
  48799. }
  48800. /**
  48801. * Infer response-type attribute from src.
  48802. * Default is text(default XMLHttpRequest.responseType)
  48803. * but we use arraybuffer for .gltf and .glb files
  48804. * because of THREE.GLTFLoader specification.
  48805. *
  48806. * @param {string} src
  48807. * @returns {string}
  48808. */
  48809. function inferResponseType (src) {
  48810. var dotLastIndex = src.lastIndexOf('.');
  48811. if (dotLastIndex >= 0) {
  48812. var extension = src.slice(dotLastIndex, src.length);
  48813. if (extension === '.gltf' || extension === '.glb') {
  48814. return 'arraybuffer';
  48815. }
  48816. }
  48817. return 'text';
  48818. }
  48819. module.exports.inferResponseType = inferResponseType;
  48820. },{"../lib/three":149,"../utils/bind":166,"../utils/debug":168,"./a-node":100,"./a-register-element":101}],97:[function(_dereq_,module,exports){
  48821. /* global HTMLElement */
  48822. var debug = _dereq_('../utils/debug');
  48823. var registerElement = _dereq_('./a-register-element').registerElement;
  48824. var warn = debug('core:cubemap:warn');
  48825. /**
  48826. * Cubemap element that handles validation and exposes list of URLs.
  48827. * Does not listen to updates.
  48828. */
  48829. module.exports = registerElement('a-cubemap', {
  48830. prototype: Object.create(HTMLElement.prototype, {
  48831. /**
  48832. * Calculates this.srcs.
  48833. */
  48834. attachedCallback: {
  48835. value: function () {
  48836. this.srcs = this.validate();
  48837. },
  48838. writable: window.debug
  48839. },
  48840. /**
  48841. * Checks for exactly six elements with [src].
  48842. * Does not check explicitly for <img>s in case user does not want
  48843. * prefetching.
  48844. *
  48845. * @returns {Array|null} - six URLs if valid, else null.
  48846. */
  48847. validate: {
  48848. value: function () {
  48849. var elements = this.querySelectorAll('[src]');
  48850. var i;
  48851. var srcs = [];
  48852. if (elements.length === 6) {
  48853. for (i = 0; i < elements.length; i++) {
  48854. srcs.push(elements[i].getAttribute('src'));
  48855. }
  48856. return srcs;
  48857. }
  48858. // Else if there are not six elements, throw a warning.
  48859. warn(
  48860. '<a-cubemap> did not contain exactly six elements each with a ' +
  48861. '`src` attribute.');
  48862. },
  48863. writable: window.debug
  48864. }
  48865. })
  48866. });
  48867. },{"../utils/debug":168,"./a-register-element":101}],98:[function(_dereq_,module,exports){
  48868. /* global HTMLElement */
  48869. var ANode = _dereq_('./a-node');
  48870. var COMPONENTS = _dereq_('./component').components;
  48871. var registerElement = _dereq_('./a-register-element').registerElement;
  48872. var THREE = _dereq_('../lib/three');
  48873. var utils = _dereq_('../utils/');
  48874. var AEntity;
  48875. var bind = utils.bind;
  48876. var debug = utils.debug('core:a-entity:debug');
  48877. var warn = utils.debug('core:a-entity:warn');
  48878. var MULTIPLE_COMPONENT_DELIMITER = '__';
  48879. /**
  48880. * Entity is a container object that components are plugged into to comprise everything in
  48881. * the scene. In A-Frame, they inherently have position, rotation, and scale.
  48882. *
  48883. * To be able to take components, the scene element inherits from the entity definition.
  48884. *
  48885. * @member {object} components - entity's currently initialized components.
  48886. * @member {object} object3D - three.js object.
  48887. * @member {array} states
  48888. * @member {boolean} isPlaying - false if dynamic behavior of the entity is paused.
  48889. */
  48890. var proto = Object.create(ANode.prototype, {
  48891. defaultComponents: {
  48892. value: {
  48893. position: '',
  48894. rotation: '',
  48895. scale: '',
  48896. visible: ''
  48897. }
  48898. },
  48899. createdCallback: {
  48900. value: function () {
  48901. this.components = {};
  48902. // to avoid double initializations and infinite loops
  48903. this.initializingComponents = {};
  48904. this.isEntity = true;
  48905. this.isPlaying = false;
  48906. this.object3D = new THREE.Group();
  48907. this.object3D.el = this;
  48908. this.object3DMap = {};
  48909. this.parentEl = null;
  48910. this.states = [];
  48911. }
  48912. },
  48913. /**
  48914. * Handle changes coming from the browser DOM inspector.
  48915. */
  48916. attributeChangedCallback: {
  48917. value: function (attr, oldVal, newVal) {
  48918. var component = this.components[attr];
  48919. // If the empty string is passed by the component initialization
  48920. // logic we ignore the component update.
  48921. if (component && component.justInitialized && newVal === '') {
  48922. delete component.justInitialized;
  48923. return;
  48924. }
  48925. // When a component is removed after calling el.removeAttribute('material')
  48926. if (!component && newVal === null) { return; }
  48927. this.setEntityAttribute(attr, oldVal, newVal);
  48928. }
  48929. },
  48930. /**
  48931. * Add to parent, load, play.
  48932. */
  48933. attachedCallback: {
  48934. value: function () {
  48935. var assetsEl; // Asset management system element.
  48936. var sceneEl = this.sceneEl;
  48937. var self = this; // Component.
  48938. this.addToParent();
  48939. // Don't .load() scene on attachedCallback.
  48940. if (this.isScene) { return; }
  48941. // Gracefully not error when outside of <a-scene> (e.g., tests).
  48942. if (!sceneEl) {
  48943. this.load();
  48944. return;
  48945. }
  48946. // Wait for asset management system to finish before loading.
  48947. assetsEl = sceneEl.querySelector('a-assets');
  48948. if (assetsEl && !assetsEl.hasLoaded) {
  48949. assetsEl.addEventListener('loaded', function () { self.load(); });
  48950. return;
  48951. }
  48952. this.load();
  48953. }
  48954. },
  48955. /**
  48956. * Tell parent to remove this element's object3D from its object3D.
  48957. * Do not call on scene element because that will cause a call to document.body.remove().
  48958. */
  48959. detachedCallback: {
  48960. value: function () {
  48961. if (!this.parentEl) { return; }
  48962. // Remove components.
  48963. Object.keys(this.components).forEach(bind(this.removeComponent, this));
  48964. if (this.isScene) { return; }
  48965. this.removeFromParent();
  48966. ANode.prototype.detachedCallback.call(this);
  48967. }
  48968. },
  48969. /**
  48970. * Apply mixin to component.
  48971. */
  48972. handleMixinUpdate: {
  48973. value: function (attrName) {
  48974. if (!attrName) {
  48975. this.updateComponents();
  48976. return;
  48977. }
  48978. this.updateComponent(attrName, this.getDOMAttribute(attrName));
  48979. }
  48980. },
  48981. mapStateMixins: {
  48982. value: function (state, op) {
  48983. var mixins = this.getAttribute('mixin');
  48984. var mixinIds;
  48985. if (!mixins) { return; }
  48986. mixinIds = mixins.split(' ');
  48987. mixinIds.forEach(function (id) {
  48988. var mixinId = id + '-' + state;
  48989. op(mixinId);
  48990. });
  48991. this.updateComponents();
  48992. }
  48993. },
  48994. /**
  48995. * Handle update of mixin states (e.g., `box-hovered` where `box` is the mixin ID and
  48996. * `hovered` is the entity state.
  48997. */
  48998. updateStateMixins: {
  48999. value: function (newMixins, oldMixins) {
  49000. var diff;
  49001. var newMixinsIds = newMixins.split(' ');
  49002. var oldMixinsIds = (oldMixins || '') ? oldMixins.split(' ') : [];
  49003. var self = this;
  49004. // List of mixins that might have been removed on update.
  49005. diff = oldMixinsIds.filter(function (i) { return newMixinsIds.indexOf(i) < 0; });
  49006. // Remove removed mixins.
  49007. diff.forEach(function (mixinId) {
  49008. // State Mixins
  49009. var stateMixinsEls = document.querySelectorAll('[id^=' + mixinId + '-]');
  49010. Array.prototype.forEach.call(stateMixinsEls, function (el) {
  49011. self.unregisterMixin(el.id);
  49012. });
  49013. });
  49014. // Add new mixins.
  49015. this.states.forEach(function (state) {
  49016. newMixinsIds.forEach(function (id) {
  49017. var mixinId = id + '-' + state;
  49018. self.registerMixin(mixinId);
  49019. });
  49020. });
  49021. }
  49022. },
  49023. getObject3D: {
  49024. value: function (type) {
  49025. return this.object3DMap[type];
  49026. }
  49027. },
  49028. /**
  49029. * Set a THREE.Object3D into the map.
  49030. *
  49031. * @param {string} type - Developer-set name of the type of object, will be unique per type.
  49032. * @param {object} obj - A THREE.Object3D.
  49033. */
  49034. setObject3D: {
  49035. value: function (type, obj) {
  49036. var oldObj;
  49037. var self = this;
  49038. if (!(obj instanceof THREE.Object3D)) {
  49039. throw new Error(
  49040. '`Entity.setObject3D` was called with an object that was not an instance of ' +
  49041. 'THREE.Object3D.'
  49042. );
  49043. }
  49044. // Remove existing object of the type.
  49045. oldObj = this.getObject3D(type);
  49046. if (oldObj) { this.object3D.remove(oldObj); }
  49047. // Set references to A-Frame entity.
  49048. obj.el = this;
  49049. if (obj.children.length) {
  49050. obj.traverse(function bindEl (child) {
  49051. child.el = self;
  49052. });
  49053. }
  49054. // Add.
  49055. this.object3D.add(obj);
  49056. this.object3DMap[type] = obj;
  49057. this.emit('object3dset', {object: obj, type: type});
  49058. }
  49059. },
  49060. /**
  49061. * Remove object from scene and entity object3D map.
  49062. */
  49063. removeObject3D: {
  49064. value: function (type) {
  49065. var obj = this.getObject3D(type);
  49066. if (!obj) {
  49067. warn('Tried to remove `Object3D` of type:', type, 'which was not defined.');
  49068. return;
  49069. }
  49070. this.object3D.remove(obj);
  49071. delete this.object3DMap[type];
  49072. this.emit('object3dremove', {type: type});
  49073. }
  49074. },
  49075. /**
  49076. * Gets or creates an object3D of a given type.
  49077. *
  49078. * @param {string} type - Type of the object3D.
  49079. * @param {string} Constructor - Constructor to use to create the object3D if needed.
  49080. * @returns {object}
  49081. */
  49082. getOrCreateObject3D: {
  49083. value: function (type, Constructor) {
  49084. var object3D = this.getObject3D(type);
  49085. if (!object3D && Constructor) {
  49086. object3D = new Constructor();
  49087. this.setObject3D(type, object3D);
  49088. }
  49089. return object3D;
  49090. }
  49091. },
  49092. /**
  49093. * Add child entity.
  49094. *
  49095. * @param {Element} el - Child entity.
  49096. */
  49097. add: {
  49098. value: function (el) {
  49099. if (!el.object3D) {
  49100. throw new Error("Trying to add an element that doesn't have an `object3D`");
  49101. }
  49102. this.object3D.add(el.object3D);
  49103. this.emit('child-attached', { el: el });
  49104. }
  49105. },
  49106. /**
  49107. * Tell parentNode to add this entity to itself.
  49108. */
  49109. addToParent: {
  49110. value: function () {
  49111. var parentNode = this.parentEl = this.parentNode;
  49112. // `!parentNode` check primarily for unit tests.
  49113. if (!parentNode || !parentNode.add || this.attachedToParent) { return; }
  49114. parentNode.add(this);
  49115. this.attachedToParent = true; // To prevent multiple attachments to same parent.
  49116. }
  49117. },
  49118. /**
  49119. * Tell parentNode to remove this entity from itself.
  49120. */
  49121. removeFromParent: {
  49122. value: function () {
  49123. var parentEl = this.parentEl;
  49124. this.parentEl.remove(this);
  49125. this.attachedToParent = false;
  49126. this.parentEl = this.parentNode = null;
  49127. parentEl.emit('child-detached', {el: this});
  49128. }
  49129. },
  49130. load: {
  49131. value: function () {
  49132. var self = this;
  49133. if (this.hasLoaded || !this.parentEl) { return; }
  49134. ANode.prototype.load.call(this, function entityLoadCallback () {
  49135. // Check if entity was detached while it was waiting to load.
  49136. if (!self.parentEl) { return; }
  49137. self.updateComponents();
  49138. if (self.isScene || self.parentEl.isPlaying) { self.play(); }
  49139. });
  49140. },
  49141. writable: window.debug
  49142. },
  49143. /**
  49144. * Remove child entity.
  49145. *
  49146. * @param {Element} el - Child entity.
  49147. */
  49148. remove: {
  49149. value: function (el) {
  49150. this.object3D.remove(el.object3D);
  49151. }
  49152. },
  49153. /**
  49154. * @returns {array} Direct children that are entities.
  49155. */
  49156. getChildEntities: {
  49157. value: function () {
  49158. var children = this.children;
  49159. var childEntities = [];
  49160. for (var i = 0; i < children.length; i++) {
  49161. var child = children[i];
  49162. if (child instanceof AEntity) {
  49163. childEntities.push(child);
  49164. }
  49165. }
  49166. return childEntities;
  49167. }
  49168. },
  49169. /**
  49170. * Initialize component.
  49171. *
  49172. * @param {string} attrName - Attribute name asociated to the component.
  49173. * @param {object} data - Component data
  49174. * @param {boolean} isDependency - True if the component is a dependency.
  49175. */
  49176. initComponent: {
  49177. value: function (attrName, data, isDependency) {
  49178. var component;
  49179. var componentInfo = attrName.split(MULTIPLE_COMPONENT_DELIMITER);
  49180. var componentId = componentInfo[1];
  49181. var componentName = componentInfo[0];
  49182. var isComponentDefined = checkComponentDefined(this, attrName) || data !== undefined;
  49183. // Not a registered component.
  49184. if (!COMPONENTS[componentName]) { return; }
  49185. // Component is not a dependency and is undefined.
  49186. // If a component is a dependency, then it is okay to have no data.
  49187. if (!isComponentDefined && !isDependency) { return; }
  49188. // Component already initialized.
  49189. if (attrName in this.components) { return; }
  49190. // Initialize dependencies first
  49191. this.initComponentDependencies(componentName);
  49192. // If component name has an id we check component type multiplic
  49193. if (componentId && !COMPONENTS[componentName].multiple) {
  49194. throw new Error('Trying to initialize multiple ' +
  49195. 'components of type `' + componentName +
  49196. '`. There can only be one component of this type per entity.');
  49197. }
  49198. component = new COMPONENTS[componentName].Component(this, data, componentId);
  49199. if (this.isPlaying) { component.play(); }
  49200. // Components are reflected in the DOM as attributes but the state is not shown
  49201. // hence we set the attribute to empty string.
  49202. // The flag justInitialized is for attributeChangedCallback to not overwrite
  49203. // the component with the empty string.
  49204. if (!this.hasAttribute(attrName)) {
  49205. component.justInitialized = true;
  49206. HTMLElement.prototype.setAttribute.call(this, attrName, '');
  49207. }
  49208. debug('Component initialized: %s', attrName);
  49209. },
  49210. writable: window.debug
  49211. },
  49212. /**
  49213. * Initialize dependencies of a component.
  49214. *
  49215. * @param {string} name - Root component name.
  49216. */
  49217. initComponentDependencies: {
  49218. value: function (name) {
  49219. var self = this;
  49220. var component = COMPONENTS[name];
  49221. var dependencies;
  49222. // Not a component.
  49223. if (!component) { return; }
  49224. // No dependencies.
  49225. dependencies = COMPONENTS[name].dependencies;
  49226. if (!dependencies) { return; }
  49227. // Initialize dependencies.
  49228. dependencies.forEach(function initializeDependency (componentName) {
  49229. // Call getAttribute to initialize the data from the DOM.
  49230. self.initComponent(
  49231. componentName,
  49232. HTMLElement.prototype.getAttribute.call(self, componentName) || undefined,
  49233. true
  49234. );
  49235. });
  49236. }
  49237. },
  49238. removeComponent: {
  49239. value: function (name) {
  49240. var component;
  49241. var isDefault;
  49242. var isMixedIn;
  49243. // Don't remove default or mixed-in components.
  49244. isDefault = name in this.defaultComponents;
  49245. isMixedIn = isComponentMixedIn(name, this.mixinEls);
  49246. if (isDefault || isMixedIn) { return; }
  49247. component = this.components[name];
  49248. component.pause();
  49249. component.remove();
  49250. delete this.components[name];
  49251. this.emit('componentremoved', {
  49252. id: component.id,
  49253. name: name
  49254. });
  49255. }
  49256. },
  49257. /**
  49258. * Initialize or update all components.
  49259. * Build data using initial components, defined attributes, mixins, and defaults.
  49260. * Update default components before the rest.
  49261. *
  49262. * @member {function} getExtraComponents - Can be implemented to include component data
  49263. * from other sources (e.g., implemented by primitives).
  49264. */
  49265. updateComponents: {
  49266. value: function () {
  49267. var componentsToUpdate = {};
  49268. var extraComponents = {};
  49269. var i;
  49270. var self = this;
  49271. if (!this.hasLoaded) { return; }
  49272. // Gather mixin-defined components.
  49273. getMixedInComponents(this).forEach(addComponent);
  49274. // Gather from extra initial component data if defined (e.g., primitives).
  49275. if (this.getExtraComponents) {
  49276. extraComponents = this.getExtraComponents();
  49277. Object.keys(extraComponents).forEach(addComponent);
  49278. }
  49279. // Gather entity-defined components.
  49280. for (i = 0; i < this.attributes.length; ++i) {
  49281. addComponent(this.attributes[i].name);
  49282. }
  49283. // Initialze or update default components first.
  49284. Object.keys(this.defaultComponents).forEach(doUpdateComponent);
  49285. // Initialize or update rest of components.
  49286. Object.keys(componentsToUpdate).forEach(doUpdateComponent);
  49287. /**
  49288. * Add component to the list to initialize or update.
  49289. */
  49290. function addComponent (componentName) {
  49291. var name = componentName.split(MULTIPLE_COMPONENT_DELIMITER)[0];
  49292. if (!COMPONENTS[name]) { return; }
  49293. componentsToUpdate[componentName] = true;
  49294. }
  49295. /**
  49296. * Get component data and initialize or update component.
  49297. */
  49298. function doUpdateComponent (name) {
  49299. // Build defined component data.
  49300. var data = mergeComponentData(self.getDOMAttribute(name), extraComponents[name]);
  49301. delete componentsToUpdate[name];
  49302. self.updateComponent(name, data);
  49303. }
  49304. },
  49305. writable: window.debug
  49306. },
  49307. /**
  49308. * Initialize, update, or remove a single component.
  49309. *
  49310. * When initializing, we set the component on `this.components`.
  49311. *
  49312. * @param {string} attr - Component name.
  49313. * @param {object} attrValue - The value of the DOM attribute.
  49314. * @param {bollean} clobber - if the new attrValue will ccompletely replace the previous properties
  49315. */
  49316. updateComponent: {
  49317. value: function (attr, attrValue, clobber) {
  49318. var component = this.components[attr];
  49319. var isDefault = attr in this.defaultComponents;
  49320. if (component) {
  49321. if (attrValue === null && !isDefault) {
  49322. this.removeComponent(attr);
  49323. return;
  49324. }
  49325. // Component already initialized. Update component.
  49326. component.updateProperties(attrValue, clobber);
  49327. return;
  49328. }
  49329. // Component not yet initialized. Initialize component.
  49330. this.initComponent(attr, attrValue, false);
  49331. }
  49332. },
  49333. /**
  49334. * Updates one property of the component
  49335. *
  49336. * @param {string} name - Component name
  49337. * @param {string} property - Component property name
  49338. * @param {any} propertyValue - New property value
  49339. */
  49340. updateComponentProperty: {
  49341. value: function (name, property, propertyValue) {
  49342. var component = this.components[name];
  49343. // Cached attribute value
  49344. var attrValue = component && component.attrValue;
  49345. // Copy cached value
  49346. var componentObj = attrValue ? utils.extend({}, attrValue) : {};
  49347. componentObj[property] = propertyValue;
  49348. this.updateComponent(name, componentObj);
  49349. }
  49350. },
  49351. /**
  49352. * If `attr` is a component name, detach the component from the entity.
  49353. *
  49354. * If `propertyName` is given, reset the component property value to its default.
  49355. *
  49356. * @param {string} attr - Attribute name, which could also be a component name.
  49357. * @param {string} propertyName - Component prop name, if resetting an individual prop.
  49358. */
  49359. removeAttribute: {
  49360. value: function (attr, propertyName) {
  49361. var component = this.components[attr];
  49362. // Remove component.
  49363. if (component && propertyName === undefined) {
  49364. this.setEntityAttribute(attr, undefined, null);
  49365. // Do not remove the component from the DOM if default component.
  49366. if (this.components[attr]) { return; }
  49367. }
  49368. // Reset component property value.
  49369. if (component && propertyName !== undefined) {
  49370. component.resetProperty(propertyName);
  49371. return;
  49372. }
  49373. // Remove mixins.
  49374. if (attr === 'mixin') {
  49375. this.mixinUpdate('');
  49376. }
  49377. HTMLElement.prototype.removeAttribute.call(this, attr);
  49378. }
  49379. },
  49380. /**
  49381. * Start dynamic behavior associated with entity such as dynamic components and animations.
  49382. * Tell all children entities to also play.
  49383. */
  49384. play: {
  49385. value: function () {
  49386. var components = this.components;
  49387. var componentKeys = Object.keys(components);
  49388. // Already playing.
  49389. if (this.isPlaying || !this.hasLoaded) { return; }
  49390. this.isPlaying = true;
  49391. // Wake up all components.
  49392. componentKeys.forEach(function playComponent (key) {
  49393. components[key].play();
  49394. });
  49395. // Tell all child entities to play.
  49396. this.getChildEntities().forEach(function play (entity) {
  49397. entity.play();
  49398. });
  49399. this.emit('play');
  49400. },
  49401. writable: true
  49402. },
  49403. /**
  49404. * Pause dynamic behavior associated with entity such as dynamic components and animations.
  49405. * Tell all children entities to also pause.
  49406. */
  49407. pause: {
  49408. value: function () {
  49409. var components = this.components;
  49410. var componentKeys = Object.keys(components);
  49411. if (!this.isPlaying) { return; }
  49412. this.isPlaying = false;
  49413. // Sleep all components.
  49414. componentKeys.forEach(function pauseComponent (key) {
  49415. components[key].pause();
  49416. });
  49417. // Tell all child entities to pause.
  49418. this.getChildEntities().forEach(function pause (obj) {
  49419. obj.pause();
  49420. });
  49421. this.emit('pause');
  49422. },
  49423. writable: true
  49424. },
  49425. /**
  49426. * Deals with updates on entity-specific attributes (i.e., components and mixins).
  49427. *
  49428. * @param {string} attr
  49429. * @param {string} oldVal
  49430. * @param {string|object} newVal
  49431. */
  49432. setEntityAttribute: {
  49433. value: function (attr, oldVal, newVal) {
  49434. if (COMPONENTS[attr] || this.components[attr]) {
  49435. this.updateComponent(attr, newVal);
  49436. return;
  49437. }
  49438. if (attr === 'mixin') {
  49439. this.mixinUpdate(newVal, oldVal);
  49440. return;
  49441. }
  49442. }
  49443. },
  49444. mixinUpdate: {
  49445. value: function (newMixins, oldMixins) {
  49446. oldMixins = oldMixins || this.getAttribute('mixin');
  49447. this.updateMixins(newMixins, oldMixins);
  49448. this.updateStateMixins(newMixins, oldMixins);
  49449. this.updateComponents();
  49450. }
  49451. },
  49452. /**
  49453. * setAttribute can:
  49454. *
  49455. * 1. Set a single property of a multi-property component.
  49456. * 2. Set multiple properties of a multi-property component.
  49457. * 3. Replace properties of a multi-property component.
  49458. * 4. Set a value for a single-property component, mixin, or normal HTML attribute.
  49459. *
  49460. * @param {string} attrName - Component or attribute name.
  49461. * @param {string|object} arg1 - Can be a property name or object of properties.
  49462. * @param {string|bool} arg2 - Can be a value, or boolean indicating whether to update or
  49463. * replace.
  49464. */
  49465. setAttribute: {
  49466. value: function (attrName, arg1, arg2) {
  49467. var arg1Type = typeof arg1;
  49468. var clobber;
  49469. var componentName;
  49470. var isDebugMode;
  49471. var pos = attrName.indexOf(MULTIPLE_COMPONENT_DELIMITER);
  49472. componentName = pos > 0 ? attrName.substring(0, pos) : attrName;
  49473. // Determine which type of setAttribute to call based on the types of the arguments.
  49474. if (COMPONENTS[componentName]) {
  49475. if (arg1Type === 'string' && typeof arg2 !== 'undefined') {
  49476. singlePropertyUpdate(this, attrName, arg1, arg2);
  49477. } else {
  49478. clobber = arg1Type !== 'object' || (arg1Type === 'object' && arg2 === true);
  49479. this.updateComponent(attrName, arg1, clobber);
  49480. }
  49481. // In debug mode, write component data up to the DOM.
  49482. isDebugMode = this.sceneEl && this.sceneEl.getAttribute('debug');
  49483. if (isDebugMode) { this.components[attrName].flushToDOM(); }
  49484. return;
  49485. } else {
  49486. normalSetAttribute(this, attrName, arg1);
  49487. }
  49488. /**
  49489. * Just update one of the component properties.
  49490. * >> setAttribute('foo', 'bar', 'baz')
  49491. */
  49492. function singlePropertyUpdate (el, componentName, propName, propertyValue) {
  49493. el.updateComponentProperty(componentName, propName, propertyValue);
  49494. }
  49495. /**
  49496. * Just update one of the component properties.
  49497. * >> setAttribute('id', 'myEntity')
  49498. */
  49499. function normalSetAttribute (el, attrName, value) {
  49500. ANode.prototype.setAttribute.call(el, attrName, value);
  49501. if (attrName === 'mixin') { el.mixinUpdate(value); }
  49502. }
  49503. },
  49504. writable: window.debug
  49505. },
  49506. /**
  49507. * Reflect component data in the DOM (as seen from the browser DOM Inspector).
  49508. *
  49509. * @param {bool} recursive - Also flushToDOM on the children.
  49510. **/
  49511. flushToDOM: {
  49512. value: function (recursive) {
  49513. var components = this.components;
  49514. var defaultComponents = this.defaultComponents;
  49515. var child;
  49516. var children = this.children;
  49517. var i;
  49518. // Flush entity's components to DOM.
  49519. Object.keys(components).forEach(function flushComponent (componentName) {
  49520. components[componentName].flushToDOM(componentName in defaultComponents);
  49521. });
  49522. // Recurse.
  49523. if (!recursive) { return; }
  49524. for (i = 0; i < children.length; ++i) {
  49525. child = children[i];
  49526. if (!child.flushToDOM) { continue; }
  49527. child.flushToDOM(recursive);
  49528. }
  49529. }
  49530. },
  49531. /**
  49532. * If `attr` is a component, returns ALL component data including applied mixins and
  49533. * defaults.
  49534. *
  49535. * If `attr` is not a component, fall back to HTML getAttribute.
  49536. *
  49537. * @param {string} attr
  49538. * @returns {object|string} Object if component, else string.
  49539. */
  49540. getAttribute: {
  49541. value: function (attr) {
  49542. // If component, return component data.
  49543. var component = this.components[attr];
  49544. if (component) { return component.data; }
  49545. return HTMLElement.prototype.getAttribute.call(this, attr);
  49546. },
  49547. writable: window.debug
  49548. },
  49549. /**
  49550. * `getAttribute` used to be `getDOMAttribute` and `getComputedAttribute` used to be
  49551. * what `getAttribute` is now. Now legacy code.
  49552. *
  49553. * @param {string} attr
  49554. * @returns {object|string} Object if component, else string.
  49555. */
  49556. getComputedAttribute: {
  49557. value: function (attr) {
  49558. warn('`getComputedAttribute` is deprecated. Use `getAttribute` instead.');
  49559. return this.getAttribute(attr);
  49560. }
  49561. },
  49562. /**
  49563. * If `attr` is a component, returns JUST the component data defined on the entity.
  49564. * Like a partial version of `getComputedAttribute` as returned component data
  49565. * does not include applied mixins or defaults.
  49566. *
  49567. * If `attr` is not a component, fall back to HTML getAttribute.
  49568. *
  49569. * @param {string} attr
  49570. * @returns {object|string} Object if component, else string.
  49571. */
  49572. getDOMAttribute: {
  49573. value: function (attr) {
  49574. // If cached value exists, return partial component data.
  49575. var component = this.components[attr];
  49576. if (component) { return component.attrValue; }
  49577. return HTMLElement.prototype.getAttribute.call(this, attr);
  49578. },
  49579. writable: window.debug
  49580. },
  49581. addState: {
  49582. value: function (state) {
  49583. if (this.is(state)) { return; }
  49584. this.states.push(state);
  49585. this.mapStateMixins(state, bind(this.registerMixin, this));
  49586. this.emit('stateadded', {state: state});
  49587. }
  49588. },
  49589. removeState: {
  49590. value: function (state) {
  49591. var stateIndex = this.states.indexOf(state);
  49592. if (stateIndex === -1) { return; }
  49593. this.states.splice(stateIndex, 1);
  49594. this.mapStateMixins(state, bind(this.unregisterMixin, this));
  49595. this.emit('stateremoved', {state: state});
  49596. }
  49597. },
  49598. /**
  49599. * Checks if the element is in a given state. e.g. el.is('alive');
  49600. * @type {string} state - Name of the state we want to check
  49601. */
  49602. is: {
  49603. value: function (state) {
  49604. return this.states.indexOf(state) !== -1;
  49605. }
  49606. }
  49607. });
  49608. /**
  49609. * Check if a component is *defined* for an entity, including defaults and mixins.
  49610. * Does not check whether the component has been *initialized* for an entity.
  49611. *
  49612. * @param {string} el - Entity.
  49613. * @param {string} name - Component name.
  49614. * @returns {boolean}
  49615. */
  49616. function checkComponentDefined (el, name) {
  49617. // Check if default components contain the component.
  49618. if (el.defaultComponents[name] !== undefined) { return true; }
  49619. // Check if element contains the component.
  49620. if (el.components[name] && el.components[name].attrValue) { return true; }
  49621. return isComponentMixedIn(name, el.mixinEls);
  49622. }
  49623. function getMixedInComponents (entityEl) {
  49624. var components = [];
  49625. entityEl.mixinEls.forEach(function getMixedComponents (mixinEl) {
  49626. Object.keys(mixinEl.componentCache).forEach(addComponent);
  49627. function addComponent (key) {
  49628. components.push(key);
  49629. }
  49630. });
  49631. return components;
  49632. }
  49633. /**
  49634. * Check if any mixins contains a component.
  49635. *
  49636. * @param {string} name - Component name.
  49637. * @param {array} mixinEls - Array of <a-mixin>s.
  49638. */
  49639. function isComponentMixedIn (name, mixinEls) {
  49640. var i;
  49641. var inMixin = false;
  49642. for (i = 0; i < mixinEls.length; ++i) {
  49643. inMixin = mixinEls[i].hasAttribute(name);
  49644. if (inMixin) { break; }
  49645. }
  49646. return inMixin;
  49647. }
  49648. /**
  49649. * Given entity defined value, merge in extra data if necessary.
  49650. * Handle both single and multi-property components.
  49651. *
  49652. * @param {string} attrValue - Entity data.
  49653. * @param extraData - Entity data from another source to merge in.
  49654. */
  49655. function mergeComponentData (attrValue, extraData) {
  49656. // Extra data not defined, just return attrValue.
  49657. if (!extraData) { return attrValue; }
  49658. // Merge multi-property data.
  49659. if (extraData.constructor === Object) {
  49660. return utils.extend(extraData, utils.styleParser.parse(attrValue || {}));
  49661. }
  49662. // Return data, precendence to the defined value.
  49663. return attrValue || extraData;
  49664. }
  49665. AEntity = registerElement('a-entity', {
  49666. prototype: proto
  49667. });
  49668. module.exports = AEntity;
  49669. },{"../lib/three":149,"../utils/":172,"./a-node":100,"./a-register-element":101,"./component":102}],99:[function(_dereq_,module,exports){
  49670. /* global HTMLElement */
  49671. var ANode = _dereq_('./a-node');
  49672. var registerElement = _dereq_('./a-register-element').registerElement;
  49673. var components = _dereq_('./component').components;
  49674. var MULTIPLE_COMPONENT_DELIMITER = '__';
  49675. /**
  49676. * @member {object} componentCache - Cache of pre-parsed values. An object where the keys
  49677. * are component names and the values are already parsed by the component.
  49678. */
  49679. module.exports = registerElement('a-mixin', {
  49680. prototype: Object.create(ANode.prototype, {
  49681. createdCallback: {
  49682. value: function () {
  49683. this.componentCache = {};
  49684. this.id = this.getAttribute('id');
  49685. }
  49686. },
  49687. attributeChangedCallback: {
  49688. value: function (attr, oldVal, newVal) {
  49689. this.cacheAttribute(attr, newVal);
  49690. }
  49691. },
  49692. attachedCallback: {
  49693. value: function () {
  49694. this.sceneEl = this.closestScene();
  49695. this.cacheAttributes();
  49696. this.updateEntities();
  49697. this.load();
  49698. }
  49699. },
  49700. /**
  49701. * setAttribute that parses and caches component values.
  49702. */
  49703. setAttribute: {
  49704. value: function (attr, value) {
  49705. this.cacheAttribute(attr, value);
  49706. HTMLElement.prototype.setAttribute.call(this, attr, value);
  49707. }
  49708. },
  49709. /**
  49710. * If `attr` is a component, then parse the value using the schema and store it.
  49711. */
  49712. cacheAttribute: {
  49713. value: function (attr, value) {
  49714. var componentName = attr.split(MULTIPLE_COMPONENT_DELIMITER)[0];
  49715. var component = components[componentName];
  49716. if (!component) { return; }
  49717. if (value === undefined) {
  49718. value = HTMLElement.prototype.getAttribute.call(this, attr);
  49719. }
  49720. this.componentCache[attr] = component.parseAttrValueForCache(value);
  49721. }
  49722. },
  49723. /**
  49724. * If `attr` is a component, then grab pre-parsed value from the cache.
  49725. * Else do a normal getAttribute.
  49726. */
  49727. getAttribute: {
  49728. value: function (attr) {
  49729. return this.componentCache[attr] ||
  49730. HTMLElement.prototype.getAttribute.call(this, attr);
  49731. }
  49732. },
  49733. /**
  49734. * Parse and cache every component defined on the mixin.
  49735. */
  49736. cacheAttributes: {
  49737. value: function () {
  49738. var attributes = this.attributes;
  49739. var attrName;
  49740. var i;
  49741. for (i = 0; i < attributes.length; i++) {
  49742. attrName = attributes[i].name;
  49743. this.cacheAttribute(attrName);
  49744. }
  49745. }
  49746. },
  49747. /**
  49748. * For entities that already have been loaded by the time the mixin was attached, tell
  49749. * those entities to register the mixin and refresh their component data.
  49750. */
  49751. updateEntities: {
  49752. value: function () {
  49753. if (!this.sceneEl) { return; }
  49754. var entities = this.sceneEl.querySelectorAll('[mixin~=' + this.id + ']');
  49755. for (var i = 0; i < entities.length; i++) {
  49756. var entity = entities[i];
  49757. if (!entity.hasLoaded) { continue; }
  49758. entity.registerMixin(this.id);
  49759. Object.keys(this.componentCache).forEach(function updateComponent (componentName) {
  49760. entity.updateComponent(componentName);
  49761. });
  49762. }
  49763. }
  49764. }
  49765. })
  49766. });
  49767. },{"./a-node":100,"./a-register-element":101,"./component":102}],100:[function(_dereq_,module,exports){
  49768. /* global HTMLElement, MutationObserver */
  49769. var registerElement = _dereq_('./a-register-element').registerElement;
  49770. var utils = _dereq_('../utils/');
  49771. var bind = utils.bind;
  49772. var warn = utils.debug('core:a-node:warn');
  49773. /**
  49774. * Base class for A-Frame that manages loading of objects.
  49775. *
  49776. * Nodes can be modified using mixins.
  49777. * Nodes emit a `loaded` event when they and their children have initialized.
  49778. */
  49779. module.exports = registerElement('a-node', {
  49780. prototype: Object.create(HTMLElement.prototype, {
  49781. createdCallback: {
  49782. value: function () {
  49783. this.hasLoaded = false;
  49784. this.isNode = true;
  49785. this.mixinEls = [];
  49786. this.mixinObservers = {};
  49787. },
  49788. writable: window.debug
  49789. },
  49790. attachedCallback: {
  49791. value: function () {
  49792. var mixins;
  49793. this.sceneEl = this.closestScene();
  49794. if (!this.sceneEl) {
  49795. warn('You are attempting to attach <' + this.tagName + '> outside of an A-Frame ' +
  49796. 'scene. Append this element to `<a-scene>` instead.');
  49797. }
  49798. this.hasLoaded = false;
  49799. this.emit('nodeready', {}, false);
  49800. mixins = this.getAttribute('mixin');
  49801. if (mixins) { this.updateMixins(mixins); }
  49802. },
  49803. writable: window.debug
  49804. },
  49805. attributeChangedCallback: {
  49806. value: function (attr, oldVal, newVal) {
  49807. if (attr === 'mixin') { this.updateMixins(newVal, oldVal); }
  49808. }
  49809. },
  49810. /**
  49811. * Returns the first scene by traversing up the tree starting from and
  49812. * including receiver element.
  49813. */
  49814. closestScene: {
  49815. value: function closest () {
  49816. var element = this;
  49817. while (element) {
  49818. if (element.isScene) { break; }
  49819. element = element.parentElement;
  49820. }
  49821. return element;
  49822. }
  49823. },
  49824. /**
  49825. * Returns first element matching a selector by traversing up the tree starting
  49826. * from and including receiver element.
  49827. *
  49828. * @param {string} selector - Selector of element to find.
  49829. */
  49830. closest: {
  49831. value: function closest (selector) {
  49832. var matches = this.matches || this.mozMatchesSelector ||
  49833. this.msMatchesSelector || this.oMatchesSelector || this.webkitMatchesSelector;
  49834. var element = this;
  49835. while (element) {
  49836. if (matches.call(element, selector)) { break; }
  49837. element = element.parentElement;
  49838. }
  49839. return element;
  49840. }
  49841. },
  49842. detachedCallback: {
  49843. value: function () {
  49844. this.hasLoaded = false;
  49845. }
  49846. },
  49847. /**
  49848. * Wait for children to load, if any.
  49849. * Then emit `loaded` event and set `hasLoaded`.
  49850. */
  49851. load: {
  49852. value: function (cb, childFilter) {
  49853. var children;
  49854. var childrenLoaded;
  49855. var self = this;
  49856. if (this.hasLoaded) { return; }
  49857. // Default to waiting for all nodes.
  49858. childFilter = childFilter || function (el) { return el.isNode; };
  49859. // Wait for children to load (if any), then load.
  49860. children = this.getChildren();
  49861. childrenLoaded = children.filter(childFilter).map(function (child) {
  49862. return new Promise(function waitForLoaded (resolve) {
  49863. if (child.hasLoaded) { return resolve(); }
  49864. child.addEventListener('loaded', resolve);
  49865. });
  49866. });
  49867. Promise.all(childrenLoaded).then(function emitLoaded () {
  49868. self.hasLoaded = true;
  49869. if (cb) { cb(); }
  49870. self.emit('loaded', {}, false);
  49871. });
  49872. },
  49873. writable: true
  49874. },
  49875. getChildren: {
  49876. value: function () {
  49877. return Array.prototype.slice.call(this.children, 0);
  49878. }
  49879. },
  49880. /**
  49881. * Remove old mixins and mixin listeners.
  49882. * Add new mixins and mixin listeners.
  49883. */
  49884. updateMixins: {
  49885. value: function (newMixins, oldMixins) {
  49886. var newMixinIds = newMixins ? newMixins.trim().split(/\s+/) : [];
  49887. var oldMixinIds = oldMixins ? oldMixins.trim().split(/\s+/) : [];
  49888. // Unregister old mixins.
  49889. oldMixinIds.filter(function (i) {
  49890. return newMixinIds.indexOf(i) < 0;
  49891. }).forEach(bind(this.unregisterMixin, this));
  49892. // Register new mixins.
  49893. this.mixinEls = [];
  49894. newMixinIds.forEach(bind(this.registerMixin, this));
  49895. }
  49896. },
  49897. registerMixin: {
  49898. value: function (mixinId) {
  49899. if (!this.sceneEl) { return; }
  49900. var mixinEl = this.sceneEl.querySelector('a-mixin#' + mixinId);
  49901. if (!mixinEl) { return; }
  49902. this.attachMixinListener(mixinEl);
  49903. this.mixinEls.push(mixinEl);
  49904. }
  49905. },
  49906. setAttribute: {
  49907. value: function (attr, newValue) {
  49908. if (attr === 'mixin') { this.updateMixins(newValue); }
  49909. HTMLElement.prototype.setAttribute.call(this, attr, newValue);
  49910. }
  49911. },
  49912. unregisterMixin: {
  49913. value: function (mixinId) {
  49914. var mixinEls = this.mixinEls;
  49915. var mixinEl;
  49916. var i;
  49917. for (i = 0; i < mixinEls.length; ++i) {
  49918. mixinEl = mixinEls[i];
  49919. if (mixinId === mixinEl.id) {
  49920. mixinEls.splice(i, 1);
  49921. break;
  49922. }
  49923. }
  49924. this.removeMixinListener(mixinId);
  49925. }
  49926. },
  49927. removeMixinListener: {
  49928. value: function (mixinId) {
  49929. var observer = this.mixinObservers[mixinId];
  49930. if (!observer) { return; }
  49931. observer.disconnect();
  49932. this.mixinObservers[mixinId] = null;
  49933. }
  49934. },
  49935. attachMixinListener: {
  49936. value: function (mixinEl) {
  49937. var self = this;
  49938. var mixinId = mixinEl.id;
  49939. var currentObserver = this.mixinObservers[mixinId];
  49940. if (!mixinEl) { return; }
  49941. if (currentObserver) { return; }
  49942. var observer = new MutationObserver(function (mutations) {
  49943. var attr = mutations[0].attributeName;
  49944. self.handleMixinUpdate(attr);
  49945. });
  49946. var config = { attributes: true };
  49947. observer.observe(mixinEl, config);
  49948. this.mixinObservers[mixinId] = observer;
  49949. }
  49950. },
  49951. handleMixinUpdate: {
  49952. value: function () { /* no-op */ }
  49953. },
  49954. /**
  49955. * Emits a DOM event.
  49956. *
  49957. * @param {String} name
  49958. * Name of event (use a space-delimited string for multiple events).
  49959. * @param {Object=} [detail={}]
  49960. * Custom data to pass as `detail` to the event.
  49961. * @param {Boolean=} [bubbles=true]
  49962. * Whether the event should bubble.
  49963. * @param {Object=} [extraData]
  49964. * Extra data to pass to the event, if any.
  49965. */
  49966. emit: {
  49967. value: function (name, detail, bubbles, extraData) {
  49968. var self = this;
  49969. detail = detail || {};
  49970. if (bubbles === undefined) { bubbles = true; }
  49971. var data = { bubbles: !!bubbles, detail: detail };
  49972. if (extraData) { utils.extend(data, extraData); }
  49973. return name.split(' ').map(function (eventName) {
  49974. return utils.fireEvent(self, eventName, data);
  49975. });
  49976. },
  49977. writable: window.debug
  49978. },
  49979. /**
  49980. * Returns a closure that emits a DOM event.
  49981. *
  49982. * @param {String} name
  49983. * Name of event (use a space-delimited string for multiple events).
  49984. * @param {Object} detail
  49985. * Custom data (optional) to pass as `detail` if the event is to
  49986. * be a `CustomEvent`.
  49987. * @param {Boolean} bubbles
  49988. * Whether the event should be bubble.
  49989. */
  49990. emitter: {
  49991. value: function (name, detail, bubbles) {
  49992. var self = this;
  49993. return function () {
  49994. self.emit(name, detail, bubbles);
  49995. };
  49996. }
  49997. }
  49998. })
  49999. });
  50000. },{"../utils/":172,"./a-register-element":101}],101:[function(_dereq_,module,exports){
  50001. /*
  50002. ------------------------------------------------------------
  50003. ------------- WARNING WARNING WARNING WARNING --------------
  50004. ------------------------------------------------------------
  50005. This module wraps registerElement to deal with components that inherit from
  50006. `ANode` and `AEntity`. It's a pass through in any other case.
  50007. It wraps some of the prototype methods of the created element to make sure
  50008. that the corresponding functions in the base prototypes (`AEntity` and `ANode`)
  50009. are also invoked. The method in the base prototype is always called before the one
  50010. in the derived prototype.
  50011. */
  50012. // Polyfill `document.registerElement`.
  50013. _dereq_('document-register-element');
  50014. var ANode; // Must declare before AEntity. Initialized at the bottom.
  50015. var AEntity;
  50016. var knownTags = module.exports.knownTags = {};
  50017. function addTagName (tagName) {
  50018. knownTags[tagName.toLowerCase()] = true;
  50019. }
  50020. /**
  50021. * Return whether the element type is one of our known registered ones.
  50022. *
  50023. * @param {string} node - The name of the tag to register.
  50024. * @returns {boolean} Whether the tag name matches that of our registered custom elements.
  50025. */
  50026. module.exports.isNode = function (node) {
  50027. return node.tagName.toLowerCase() in knownTags || node.isNode;
  50028. };
  50029. /**
  50030. * @param {string} tagName - The name of the tag to register.
  50031. * @param {object} obj - The prototype of the new element.
  50032. * @returns {object} The prototype of the new element.
  50033. */
  50034. module.exports.registerElement = function (tagName, obj) {
  50035. var proto = Object.getPrototypeOf(obj.prototype);
  50036. var newObj = obj;
  50037. var isANode = ANode && proto === ANode.prototype;
  50038. var isAEntity = AEntity && proto === AEntity.prototype;
  50039. if (isANode || isAEntity) { addTagName(tagName); }
  50040. // Wrap if element inherits from `ANode`.
  50041. if (isANode) {
  50042. newObj = wrapANodeMethods(obj.prototype);
  50043. newObj = {prototype: Object.create(proto, newObj)};
  50044. }
  50045. // Wrap if element inherits from `AEntity`.
  50046. if (isAEntity) {
  50047. newObj = wrapAEntityMethods(obj.prototype);
  50048. newObj = {prototype: Object.create(proto, newObj)};
  50049. }
  50050. return document.registerElement(tagName, newObj);
  50051. };
  50052. /**
  50053. * Wrap some obj methods to call those on `ANode` base prototype.
  50054. *
  50055. * @param {object} obj - Object that contains the methods that will be wrapped.
  50056. * @return {object} An object with the same properties as the input parameter but
  50057. * with some of methods wrapped.
  50058. */
  50059. function wrapANodeMethods (obj) {
  50060. var newObj = {};
  50061. var ANodeMethods = [
  50062. 'attachedCallback',
  50063. 'attributeChangedCallback',
  50064. 'createdCallback'
  50065. ];
  50066. wrapMethods(newObj, ANodeMethods, obj, ANode.prototype);
  50067. copyProperties(obj, newObj);
  50068. return newObj;
  50069. }
  50070. /**
  50071. * This wraps some of the obj methods to call those on `AEntity` base prototype.
  50072. *
  50073. * @param {object} obj - The objects that contains the methods that will be wrapped.
  50074. * @return {object} - An object with the same properties as the input parameter but
  50075. * with some of methods wrapped.
  50076. */
  50077. function wrapAEntityMethods (obj) {
  50078. var newObj = {};
  50079. var ANodeMethods = [
  50080. 'attachedCallback',
  50081. 'attributeChangedCallback',
  50082. 'createdCallback'
  50083. ];
  50084. var AEntityMethods = [
  50085. 'attachedCallback',
  50086. 'attributeChangedCallback',
  50087. 'createdCallback',
  50088. 'detachedCallback'
  50089. ];
  50090. wrapMethods(newObj, ANodeMethods, obj, ANode.prototype);
  50091. wrapMethods(newObj, AEntityMethods, obj, AEntity.prototype);
  50092. // Copies the remaining properties into the new object.
  50093. copyProperties(obj, newObj);
  50094. return newObj;
  50095. }
  50096. /**
  50097. * Wrap a list a methods to ensure that those in the base prototype are called
  50098. * before the derived one.
  50099. *
  50100. * @param {object} targetObj - Object that will contain the wrapped methods.
  50101. * @param {array} methodList - List of methods from the derivedObj that will be wrapped.
  50102. * @param {object} derivedObject - Object that inherits from the baseObj.
  50103. * @param {object} baseObj - Object that derivedObj inherits from.
  50104. */
  50105. function wrapMethods (targetObj, methodList, derivedObj, baseObj) {
  50106. methodList.forEach(function (methodName) {
  50107. wrapMethod(targetObj, methodName, derivedObj, baseObj);
  50108. });
  50109. }
  50110. module.exports.wrapMethods = wrapMethods;
  50111. /**
  50112. * Wrap one method to ensure that the one in the base prototype is called before
  50113. * the one in the derived one.
  50114. *
  50115. * @param {object} obj - Object that will contain the wrapped method.
  50116. * @param {string} methodName - The name of the method that will be wrapped.
  50117. * @param {object} derivedObject - Object that inherits from the baseObj.
  50118. * @param {object} baseObj - Object that derivedObj inherits from.
  50119. */
  50120. function wrapMethod (obj, methodName, derivedObj, baseObj) {
  50121. var derivedMethod = derivedObj[methodName];
  50122. var baseMethod = baseObj[methodName];
  50123. // Derived prototype does not define method, no need to wrap.
  50124. if (!derivedMethod || !baseMethod) { return; }
  50125. // Derived prototype doesn't override the one in the base one, no need to wrap.
  50126. if (derivedMethod === baseMethod) { return; }
  50127. // Wrap to ensure the base method is called before the one in the derived prototype.
  50128. obj[methodName] = {
  50129. value: function wrappedMethod () {
  50130. baseMethod.apply(this, arguments);
  50131. return derivedMethod.apply(this, arguments);
  50132. },
  50133. writable: window.debug
  50134. };
  50135. }
  50136. /**
  50137. * It copies the properties from source to destination object if they don't
  50138. * exist already.
  50139. *
  50140. * @param {object} source - The object where properties are copied from.
  50141. * @param {type} destination - The object where properties are copied to.
  50142. */
  50143. function copyProperties (source, destination) {
  50144. var props = Object.getOwnPropertyNames(source);
  50145. props.forEach(function (prop) {
  50146. var desc;
  50147. if (!destination[prop]) {
  50148. desc = Object.getOwnPropertyDescriptor(source, prop);
  50149. destination[prop] = {value: source[prop], writable: desc.writable};
  50150. }
  50151. });
  50152. }
  50153. ANode = _dereq_('./a-node');
  50154. AEntity = _dereq_('./a-entity');
  50155. },{"./a-entity":98,"./a-node":100,"document-register-element":10}],102:[function(_dereq_,module,exports){
  50156. /* global HTMLElement, Node */
  50157. var schema = _dereq_('./schema');
  50158. var scenes = _dereq_('./scene/scenes');
  50159. var systems = _dereq_('./system');
  50160. var utils = _dereq_('../utils/');
  50161. var components = module.exports.components = {}; // Keep track of registered components.
  50162. var parseProperties = schema.parseProperties;
  50163. var parseProperty = schema.parseProperty;
  50164. var processSchema = schema.process;
  50165. var isSingleProp = schema.isSingleProperty;
  50166. var stringifyProperties = schema.stringifyProperties;
  50167. var stringifyProperty = schema.stringifyProperty;
  50168. var styleParser = utils.styleParser;
  50169. var warn = utils.debug('core:component:warn');
  50170. var aframeScript = document.currentScript;
  50171. var upperCaseRegExp = new RegExp('[A-Z]+');
  50172. /**
  50173. * Component class definition.
  50174. *
  50175. * Components configure appearance, modify behavior, or add functionality to
  50176. * entities. The behavior and appearance of an entity can be changed at runtime
  50177. * by adding, removing, or updating components. Entities do not share instances
  50178. * of components.
  50179. *
  50180. * @member {object} el - Reference to the entity element.
  50181. * @member {string} attrValue - Value of the corresponding HTML attribute.
  50182. * @member {object} data - Component data populated by parsing the
  50183. * mapped attribute of the component plus applying defaults and mixins.
  50184. */
  50185. var Component = module.exports.Component = function (el, attrValue, id) {
  50186. //var self = this;
  50187. this.el = el;
  50188. this.id = id;
  50189. this.attrName = this.name + (id ? '__' + id : '');
  50190. this.el.components[this.attrName] = this;
  50191. // Last value passed to updateProperties.
  50192. this.previousAttrValue = undefined;
  50193. this.updateProperties(attrValue);
  50194. // this.throttledEmitComponentChanged = utils.throttle(function emitComponentChange (oldData) {
  50195. // el.emit('componentchanged', {
  50196. // id: self.id,
  50197. // name: self.name,
  50198. // newData: self.data,
  50199. // oldData: oldData
  50200. // }, false);
  50201. // }, 200);
  50202. };
  50203. Component.prototype = {
  50204. /**
  50205. * Contains the type schema and defaults for the data values.
  50206. * Data is coerced into the types of the values of the defaults.
  50207. */
  50208. schema: {},
  50209. /**
  50210. * Init handler. Similar to attachedCallback.
  50211. * Called during component initialization and is only run once.
  50212. * Components can use this to set initial state.
  50213. */
  50214. init: function () { /* no-op */ },
  50215. /**
  50216. * Update handler. Similar to attributeChangedCallback.
  50217. * Called whenever component's data changes.
  50218. * Also called on component initialization when the component receives initial data.
  50219. *
  50220. * @param {object} prevData - Previous attributes of the component.
  50221. */
  50222. update: function (prevData) { /* no-op */ },
  50223. updateSchema: undefined,
  50224. /**
  50225. * Tick handler.
  50226. * Called on each tick of the scene render loop.
  50227. * Affected by play and pause.
  50228. *
  50229. * @param {number} time - Scene tick time.
  50230. * @param {number} timeDelta - Difference in current render time and previous render time.
  50231. */
  50232. tick: undefined,
  50233. /**
  50234. * Tock handler.
  50235. * Called on each tock of the scene render loop.
  50236. * Affected by play and pause.
  50237. *
  50238. * @param {number} time - Scene tick time.
  50239. * @param {number} timeDelta - Difference in current render time and previous render time.
  50240. */
  50241. tock: undefined,
  50242. /**
  50243. * Called to start any dynamic behavior (e.g., animation, AI, events, physics).
  50244. */
  50245. play: function () { /* no-op */ },
  50246. /**
  50247. * Called to stop any dynamic behavior (e.g., animation, AI, events, physics).
  50248. */
  50249. pause: function () { /* no-op */ },
  50250. /**
  50251. * Remove handler. Similar to detachedCallback.
  50252. * Called whenever component is removed from the entity (i.e., removeAttribute).
  50253. * Components can use this to reset behavior on the entity.
  50254. */
  50255. remove: function () { /* no-op */ },
  50256. /**
  50257. * Parses each property based on property type.
  50258. * If component is single-property, then parses the single property value.
  50259. *
  50260. * @param {string} value - HTML attribute value.
  50261. * @param {boolean} silent - Suppress warning messages.
  50262. * @returns {object} Component data.
  50263. */
  50264. parse: function (value, silent) {
  50265. var schema = this.schema;
  50266. if (isSingleProp(schema)) { return parseProperty(value, schema); }
  50267. return parseProperties(styleParser.parse(value), schema, true, this.name, silent);
  50268. },
  50269. /**
  50270. * Stringify properties if necessary.
  50271. *
  50272. * Only called from `Entity.setAttribute` for properties whose parsers accept a non-string
  50273. * value (e.g., selector, vec3 property types).
  50274. *
  50275. * @param {object} data - Complete component data.
  50276. * @returns {string}
  50277. */
  50278. stringify: function (data) {
  50279. var schema = this.schema;
  50280. if (typeof data === 'string') { return data; }
  50281. if (isSingleProp(schema)) { return stringifyProperty(data, schema); }
  50282. data = stringifyProperties(data, schema);
  50283. return styleParser.stringify(data);
  50284. },
  50285. /**
  50286. * Returns a copy of data such that we don't expose the private this.data.
  50287. *
  50288. * @returns {object} data
  50289. */
  50290. getData: function () {
  50291. var data = this.data;
  50292. if (typeof data !== 'object') { return data; }
  50293. return utils.extend({}, data);
  50294. },
  50295. /**
  50296. * Update the cache of the pre-parsed attribute value.
  50297. *
  50298. * @param {string} value - HTML attribute value.
  50299. */
  50300. updateCachedAttrValue: function (value) {
  50301. var isSinglePropSchema = isSingleProp(this.schema);
  50302. var attrValue = this.parseAttrValueForCache(value);
  50303. if (value === undefined) { return; }
  50304. this.attrValue = extendProperties({}, attrValue, isSinglePropSchema);
  50305. },
  50306. /**
  50307. * Given an HTML attribute value parses the string
  50308. * based on the component schema. To avoid double parsings of
  50309. * strings into strings we store the original instead
  50310. * of the parsed one
  50311. *
  50312. * @param {string} value - HTML attribute value
  50313. */
  50314. parseAttrValueForCache: function (value) {
  50315. var parsedValue;
  50316. if (typeof value !== 'string') { return value; }
  50317. if (isSingleProp(this.schema)) {
  50318. parsedValue = this.schema.parse(value);
  50319. /**
  50320. * To avoid bogus double parsings. Cached values will be parsed when building
  50321. * component data. For instance when parsing a src id to its url, we want to cache
  50322. * original string and not the parsed one (#monster -> models/monster.dae)
  50323. * so when building data we parse the expected value.
  50324. */
  50325. if (typeof parsedValue === 'string') { parsedValue = value; }
  50326. } else {
  50327. // Parse using the style parser to avoid double parsing of individual properties.
  50328. parsedValue = styleParser.parse(value);
  50329. }
  50330. return parsedValue;
  50331. },
  50332. /**
  50333. * Write cached attribute data to the entity DOM element.
  50334. *
  50335. * @param {boolean} isDefault - Whether component is a default component. Always flush for
  50336. * default components.
  50337. */
  50338. flushToDOM: function (isDefault) {
  50339. var attrValue = isDefault ? this.data : this.attrValue;
  50340. if (!attrValue) { return; }
  50341. HTMLElement.prototype.setAttribute.call(this.el, this.attrName,
  50342. this.stringify(attrValue));
  50343. },
  50344. /**
  50345. * Apply new component data if data has changed.
  50346. *
  50347. * @param {string} attrValue - HTML attribute value.
  50348. * If undefined, use the cached attribute value and continue updating properties.
  50349. * @param {boolean} clobber - The previous component data is overwritten by the atrrValue
  50350. */
  50351. updateProperties: function (attrValue, clobber) {
  50352. var el = this.el;
  50353. var isSinglePropSchema;
  50354. var oldData;
  50355. var skipTypeChecking;
  50356. // Just cache the attribute if the entity has not loaded
  50357. // Components are not initialized until the entity has loaded
  50358. if (!el.hasLoaded) {
  50359. this.updateCachedAttrValue(attrValue);
  50360. return;
  50361. }
  50362. isSinglePropSchema = isSingleProp(this.schema);
  50363. // Copy old data since this.data is going to be recreated.
  50364. oldData = extendProperties({}, this.data, isSinglePropSchema);
  50365. // Disable type checking if the passed attribute is an object and has not changed.
  50366. skipTypeChecking = typeof this.previousAttrValue === 'object' &&
  50367. attrValue === this.previousAttrValue;
  50368. // Cache previously passed attribute to decide if we skip type checking.
  50369. this.previousAttrValue = attrValue;
  50370. attrValue = this.parseAttrValueForCache(attrValue);
  50371. if (this.updateSchema) { this.updateSchema(this.buildData(attrValue, false, true)); }
  50372. this.data = this.buildData(attrValue, clobber, false, skipTypeChecking);
  50373. // Cache current attrValue for future updates.
  50374. this.updateCachedAttrValue(attrValue);
  50375. if (!this.initialized) {
  50376. // Component is being already initialized.
  50377. if (el.initializingComponents[this.name]) { return; }
  50378. // Prevent infinite loop in case of init method setting same component on the entity.
  50379. el.initializingComponents[this.name] = true;
  50380. // Initialize component.
  50381. this.init();
  50382. this.initialized = true;
  50383. delete el.initializingComponents[this.name];
  50384. // Play the component if the entity is playing.
  50385. this.update(oldData);
  50386. if (el.isPlaying) { this.play(); }
  50387. el.emit('componentinitialized', {
  50388. id: this.id,
  50389. name: this.name,
  50390. data: this.getData()
  50391. }, false);
  50392. } else {
  50393. // Don't update if properties haven't changed
  50394. if (!skipTypeChecking && utils.deepEqual(oldData, this.data)) { return; }
  50395. // Update component.
  50396. this.update(oldData);
  50397. //remove the limit for now
  50398. // Limit event to fire once every 200ms.
  50399. //this.throttledEmitComponentChanged(oldData);
  50400. el.emit('componentchanged', {
  50401. id: this.id,
  50402. name: this.name,
  50403. newData: this.getData(),
  50404. oldData: oldData
  50405. }, false);
  50406. }
  50407. },
  50408. /**
  50409. * Reset value of a property to the property's default value.
  50410. * If single-prop component, reset value to component's default value.
  50411. *
  50412. * @param {string} propertyName - Name of property to reset.
  50413. */
  50414. resetProperty: function (propertyName) {
  50415. if (isSingleProp(this.schema)) {
  50416. this.attrValue = undefined;
  50417. } else {
  50418. if (!(propertyName in this.attrValue)) { return; }
  50419. delete this.attrValue[propertyName];
  50420. }
  50421. this.updateProperties(this.attrValue);
  50422. },
  50423. /**
  50424. * Extend schema of component given a partial schema.
  50425. *
  50426. * Some components might want to mutate their schema based on certain properties.
  50427. * e.g., Material component changes its schema based on `shader` to account for different
  50428. * uniforms
  50429. *
  50430. * @param {object} schemaAddon - Schema chunk that extend base schema.
  50431. */
  50432. extendSchema: function (schemaAddon) {
  50433. // Clone base schema.
  50434. var extendedSchema = utils.extend({}, components[this.name].schema);
  50435. // Extend base schema with new schema chunk.
  50436. utils.extend(extendedSchema, schemaAddon);
  50437. this.schema = processSchema(extendedSchema);
  50438. this.el.emit('schemachanged', {component: this.name});
  50439. },
  50440. /**
  50441. * Builds component data from the current state of the entity, ultimately
  50442. * updating this.data.
  50443. *
  50444. * If the component was detached completely, set data to null.
  50445. *
  50446. * Precedence:
  50447. * 1. Defaults data
  50448. * 2. Mixin data.
  50449. * 3. Attribute data.
  50450. *
  50451. * Finally coerce the data to the types of the defaults.
  50452. *
  50453. * @param {object} newData - Element new data.
  50454. * @param {boolean} clobber - The previous data is completely replaced by the new one.
  50455. * @param {boolean} silent - Suppress warning messages.
  50456. * @param {boolean} skipTypeChecking - Skip type checking and cohercion.
  50457. * @return {object} The component data
  50458. */
  50459. buildData: function (newData, clobber, silent, skipTypeChecking) {
  50460. var self = this;
  50461. var componentDefined = newData !== undefined && newData !== null;
  50462. var data;
  50463. var schema = this.schema;
  50464. var isSinglePropSchema = isSingleProp(schema);
  50465. var mixinEls = this.el.mixinEls;
  50466. var previousData;
  50467. // 1. Default values (lowest precendence).
  50468. if (isSinglePropSchema) {
  50469. data = schema.default;
  50470. } else {
  50471. // Preserve previously set properties if clobber not enabled.
  50472. previousData = !clobber && this.attrValue;
  50473. data = typeof previousData === 'object' ? utils.extend({}, previousData) : {};
  50474. Object.keys(schema).forEach(function applyDefault (key) {
  50475. var defaultValue = schema[key].default;
  50476. if (data[key]) { return; }
  50477. data[key] = defaultValue && defaultValue.constructor === Object
  50478. ? utils.extend({}, defaultValue)
  50479. : defaultValue;
  50480. });
  50481. }
  50482. // 2. Mixin values.
  50483. mixinEls.forEach(function handleMixinUpdate (mixinEl) {
  50484. var mixinData = mixinEl.getAttribute(self.attrName);
  50485. if (mixinData) {
  50486. data = extendProperties(data, mixinData, isSinglePropSchema);
  50487. }
  50488. });
  50489. // 3. Attribute values (highest precendence).
  50490. if (componentDefined) {
  50491. if (isSinglePropSchema) {
  50492. if (skipTypeChecking === true) { return newData; }
  50493. return parseProperty(newData, schema);
  50494. }
  50495. data = extendProperties(data, newData, isSinglePropSchema);
  50496. } else {
  50497. if (skipTypeChecking === true) { return data; }
  50498. // Parse and coerce using the schema.
  50499. if (isSinglePropSchema) { return parseProperty(data, schema); }
  50500. }
  50501. if (skipTypeChecking === true) { return data; }
  50502. return parseProperties(data, schema, undefined, this.name, silent);
  50503. }
  50504. };
  50505. // For testing.
  50506. if (window.debug) {
  50507. var registrationOrderWarnings = module.exports.registrationOrderWarnings = {};
  50508. }
  50509. /**
  50510. * Registers a component to A-Frame.
  50511. *
  50512. * @param {string} name - Component name.
  50513. * @param {object} definition - Component schema and lifecycle method handlers.
  50514. * @returns {object} Component.
  50515. */
  50516. module.exports.registerComponent = function (name, definition) {
  50517. var NewComponent;
  50518. var proto = {};
  50519. // Warning if component is statically registered after the scene.
  50520. if (document.currentScript && document.currentScript !== aframeScript) {
  50521. scenes.forEach(function checkPosition (sceneEl) {
  50522. // Okay to register component after the scene at runtime.
  50523. if (sceneEl.hasLoaded) { return; }
  50524. // Check that component is declared before the scene.
  50525. if (document.currentScript.compareDocumentPosition(sceneEl) ===
  50526. Node.DOCUMENT_POSITION_FOLLOWING) { return; }
  50527. warn('The component `' + name + '` was registered in a <script> tag after the scene. ' +
  50528. 'Component <script> tags in an HTML file should be declared *before* the scene ' +
  50529. 'such that the component is available to entities during scene initialization.');
  50530. // For testing.
  50531. if (window.debug) { registrationOrderWarnings[name] = true; }
  50532. });
  50533. }
  50534. if (upperCaseRegExp.test(name) === true) {
  50535. warn('The component name `' + name + '` contains uppercase characters, but ' +
  50536. 'HTML will ignore the capitalization of attribute names. ' +
  50537. 'Change the name to be lowercase: `' + name.toLowerCase() + '`');
  50538. }
  50539. if (name.indexOf('__') !== -1) {
  50540. throw new Error('The component name `' + name + '` is not allowed. ' +
  50541. 'The sequence __ (double underscore) is reserved to specify an id' +
  50542. ' for multiple components of the same type');
  50543. }
  50544. // Format definition object to prototype object.
  50545. Object.keys(definition).forEach(function (key) {
  50546. proto[key] = {
  50547. value: definition[key],
  50548. writable: true
  50549. };
  50550. });
  50551. if (components[name]) {
  50552. throw new Error('The component `' + name + '` has been already registered. ' +
  50553. 'Check that you are not loading two versions of the same component ' +
  50554. 'or two different components of the same name.');
  50555. }
  50556. NewComponent = function (el, attr, id) {
  50557. Component.call(this, el, attr, id);
  50558. };
  50559. NewComponent.prototype = Object.create(Component.prototype, proto);
  50560. NewComponent.prototype.name = name;
  50561. NewComponent.prototype.constructor = NewComponent;
  50562. NewComponent.prototype.system = systems && systems.systems[name];
  50563. NewComponent.prototype.play = wrapPlay(NewComponent.prototype.play);
  50564. NewComponent.prototype.pause = wrapPause(NewComponent.prototype.pause);
  50565. components[name] = {
  50566. Component: NewComponent,
  50567. dependencies: NewComponent.prototype.dependencies,
  50568. isSingleProp: isSingleProp(NewComponent.prototype.schema),
  50569. multiple: NewComponent.prototype.multiple,
  50570. parse: NewComponent.prototype.parse,
  50571. parseAttrValueForCache: NewComponent.prototype.parseAttrValueForCache,
  50572. schema: utils.extend(processSchema(NewComponent.prototype.schema, NewComponent.prototype.name)),
  50573. stringify: NewComponent.prototype.stringify,
  50574. type: NewComponent.prototype.type
  50575. };
  50576. return NewComponent;
  50577. };
  50578. /**
  50579. * Object extending with checking for single-property schema.
  50580. *
  50581. * @param dest - Destination object or value.
  50582. * @param source - Source object or value
  50583. * @param {boolean} isSinglePropSchema - Whether or not schema is only a single property.
  50584. * @returns Overridden object or value.
  50585. */
  50586. function extendProperties (dest, source, isSinglePropSchema) {
  50587. if (isSinglePropSchema) { return source; }
  50588. return utils.extend(dest, source);
  50589. }
  50590. /**
  50591. * Checks if a component has defined a method that needs to run every frame.
  50592. */
  50593. function hasBehavior (component) {
  50594. return component.tick || component.tock;
  50595. }
  50596. /**
  50597. * Wrapper for user defined pause method
  50598. * Pause component by removing tick behavior and calling user's pause method.
  50599. *
  50600. * @param pauseMethod {function} - user defined pause method
  50601. */
  50602. function wrapPause (pauseMethod) {
  50603. return function pause () {
  50604. var sceneEl = this.el.sceneEl;
  50605. if (!this.isPlaying) { return; }
  50606. pauseMethod.call(this);
  50607. this.isPlaying = false;
  50608. // Remove tick behavior.
  50609. if (!hasBehavior(this)) { return; }
  50610. sceneEl.removeBehavior(this);
  50611. };
  50612. }
  50613. /**
  50614. * Wrapper for user defined play method
  50615. * Play component by adding tick behavior and calling user's play method.
  50616. *
  50617. * @param playMethod {function} - user defined play method
  50618. *
  50619. */
  50620. function wrapPlay (playMethod) {
  50621. return function play () {
  50622. var sceneEl = this.el.sceneEl;
  50623. var shouldPlay = this.el.isPlaying && !this.isPlaying;
  50624. if (!this.initialized || !shouldPlay) { return; }
  50625. playMethod.call(this);
  50626. this.isPlaying = true;
  50627. // Add tick behavior.
  50628. if (!hasBehavior(this)) { return; }
  50629. sceneEl.addBehavior(this);
  50630. };
  50631. }
  50632. },{"../utils/":172,"./scene/scenes":108,"./schema":110,"./system":112}],103:[function(_dereq_,module,exports){
  50633. var schema = _dereq_('./schema');
  50634. var processSchema = schema.process;
  50635. var geometries = module.exports.geometries = {}; // Registered geometries.
  50636. var geometryNames = module.exports.geometryNames = []; // Names of registered geometries.
  50637. var THREE = _dereq_('../lib/three');
  50638. /**
  50639. * Geometry class definition.
  50640. *
  50641. * Geometries extend the geometry component API to create and register geometry types.
  50642. */
  50643. var Geometry = module.exports.Geometry = function () {};
  50644. Geometry.prototype = {
  50645. /**
  50646. * Contains the type schema and defaults for the data values.
  50647. * Data is coerced into the types of the values of the defaults.
  50648. */
  50649. schema: {},
  50650. /**
  50651. * Init handler. Similar to attachedCallback.
  50652. * Called during shader initialization and is only run once.
  50653. */
  50654. init: function (data) {
  50655. this.geometry = new THREE.Geometry();
  50656. return this.geometry;
  50657. },
  50658. /**
  50659. * Update handler. Similar to attributeChangedCallback.
  50660. * Called whenever the associated geometry data changes.
  50661. *
  50662. * @param {object} data - New geometry data.
  50663. */
  50664. update: function (data) { /* no-op */ }
  50665. };
  50666. /**
  50667. * Registers a geometry to A-Frame.
  50668. *
  50669. * @param {string} name - Geometry name.
  50670. * @param {object} definition - Geometry property and methods.
  50671. * @returns {object} Geometry.
  50672. */
  50673. module.exports.registerGeometry = function (name, definition) {
  50674. var NewGeometry;
  50675. var proto = {};
  50676. // Format definition object to prototype object.
  50677. Object.keys(definition).forEach(function expandDefinition (key) {
  50678. proto[key] = {
  50679. value: definition[key],
  50680. writable: true
  50681. };
  50682. });
  50683. if (geometries[name]) {
  50684. throw new Error('The geometry `' + name + '` has been already registered');
  50685. }
  50686. NewGeometry = function () { Geometry.call(this); };
  50687. NewGeometry.prototype = Object.create(Geometry.prototype, proto);
  50688. NewGeometry.prototype.name = name;
  50689. NewGeometry.prototype.constructor = NewGeometry;
  50690. geometries[name] = {
  50691. Geometry: NewGeometry,
  50692. schema: processSchema(NewGeometry.prototype.schema)
  50693. };
  50694. geometryNames.push(name);
  50695. return NewGeometry;
  50696. };
  50697. },{"../lib/three":149,"./schema":110}],104:[function(_dereq_,module,exports){
  50698. var coordinates = _dereq_('../utils/coordinates');
  50699. var debug = _dereq_('debug');
  50700. var error = debug('core:propertyTypes:warn');
  50701. var warn = debug('core:propertyTypes:warn');
  50702. var propertyTypes = module.exports.propertyTypes = {};
  50703. // Built-in property types.
  50704. registerPropertyType('audio', '', assetParse);
  50705. registerPropertyType('array', [], arrayParse, arrayStringify);
  50706. registerPropertyType('asset', '', assetParse);
  50707. registerPropertyType('boolean', false, boolParse);
  50708. registerPropertyType('color', '#FFF', defaultParse, defaultStringify);
  50709. registerPropertyType('int', 0, intParse);
  50710. registerPropertyType('number', 0, numberParse);
  50711. registerPropertyType('map', '', assetParse);
  50712. registerPropertyType('model', '', assetParse);
  50713. registerPropertyType('selector', '', selectorParse, selectorStringify);
  50714. registerPropertyType('selectorAll', '', selectorAllParse, selectorAllStringify);
  50715. registerPropertyType('src', '', srcParse);
  50716. registerPropertyType('string', '', defaultParse, defaultStringify);
  50717. registerPropertyType('time', 0, intParse);
  50718. registerPropertyType('vec2', {x: 0, y: 0}, vecParse, coordinates.stringify);
  50719. registerPropertyType('vec3', {x: 0, y: 0, z: 0}, vecParse, coordinates.stringify);
  50720. registerPropertyType('vec4', {x: 0, y: 0, z: 0, w: 0}, vecParse, coordinates.stringify);
  50721. /**
  50722. * Register a parser for re-use such that when someone uses `type` in the schema,
  50723. * `schema.process` will set the property `parse` and `stringify`.
  50724. *
  50725. * @param {string} type - Type name.
  50726. * @param [defaultValue=null] -
  50727. * Default value to use if component does not define default value.
  50728. * @param {function} [parse=defaultParse] - Parse string function.
  50729. * @param {function} [stringify=defaultStringify] - Stringify to DOM function.
  50730. */
  50731. function registerPropertyType (type, defaultValue, parse, stringify) {
  50732. if ('type' in propertyTypes) {
  50733. error('Property type ' + type + ' is already registered.');
  50734. return;
  50735. }
  50736. propertyTypes[type] = {
  50737. default: defaultValue,
  50738. parse: parse || defaultParse,
  50739. stringify: stringify || defaultStringify
  50740. };
  50741. }
  50742. module.exports.registerPropertyType = registerPropertyType;
  50743. function arrayParse (value) {
  50744. if (Array.isArray(value)) { return value; }
  50745. if (!value || typeof value !== 'string') { return []; }
  50746. return value.split(',').map(trim);
  50747. function trim (str) { return str.trim(); }
  50748. }
  50749. function arrayStringify (value) {
  50750. return value.join(', ');
  50751. }
  50752. /**
  50753. * For general assets.
  50754. *
  50755. * @param {string} value - Can either be `url(<value>)`, an ID selector to an asset, or
  50756. * just string.
  50757. * @returns {string} Parsed value from `url(<value>)`, src from `<someasset src>`, or
  50758. * just string.
  50759. */
  50760. function assetParse (value) {
  50761. var el;
  50762. var parsedUrl;
  50763. // If an element was provided (e.g. canvas or video), just return it.
  50764. if (typeof value !== 'string') { return value; }
  50765. // Wrapped `url()` in case of data URI.
  50766. parsedUrl = value.match(/\url\((.+)\)/);
  50767. if (parsedUrl) { return parsedUrl[1]; }
  50768. // ID.
  50769. if (value.charAt(0) === '#') {
  50770. el = document.getElementById(value.substring(1));
  50771. if (el) {
  50772. // Pass through media elements. If we have the elements, we don't have to call
  50773. // three.js loaders which would re-request the assets.
  50774. if (el.tagName === 'CANVAS' || el.tagName === 'VIDEO' || el.tagName === 'IMG') {
  50775. return el;
  50776. }
  50777. return el.getAttribute('src');
  50778. }
  50779. warn('"' + value + '" asset not found.');
  50780. return;
  50781. }
  50782. // Non-wrapped url().
  50783. return value;
  50784. }
  50785. function defaultParse (value) {
  50786. return value;
  50787. }
  50788. function defaultStringify (value) {
  50789. if (value === null) { return 'null'; }
  50790. return value.toString();
  50791. }
  50792. function boolParse (value) {
  50793. return value !== 'false' && value !== false;
  50794. }
  50795. function intParse (value) {
  50796. return parseInt(value, 10);
  50797. }
  50798. function numberParse (value) {
  50799. return parseFloat(value, 10);
  50800. }
  50801. function selectorParse (value) {
  50802. if (!value) { return null; }
  50803. if (typeof value !== 'string') { return value; }
  50804. return document.querySelector(value);
  50805. }
  50806. function selectorAllParse (value) {
  50807. if (!value) { return null; }
  50808. if (typeof value !== 'string') { return value; }
  50809. return Array.prototype.slice.call(document.querySelectorAll(value), 0);
  50810. }
  50811. function selectorStringify (value) {
  50812. if (value.getAttribute) {
  50813. return '#' + value.getAttribute('id');
  50814. }
  50815. return defaultStringify(value);
  50816. }
  50817. function selectorAllStringify (value) {
  50818. if (value instanceof Array) {
  50819. return value.map(function (element) {
  50820. return '#' + element.getAttribute('id');
  50821. }).join(', ');
  50822. }
  50823. return defaultStringify(value);
  50824. }
  50825. function srcParse (value) {
  50826. warn('`src` property type is deprecated. Use `asset` instead.');
  50827. return assetParse(value);
  50828. }
  50829. function vecParse (value) {
  50830. return coordinates.parse(value, this.default);
  50831. }
  50832. /**
  50833. * Validate the default values in a schema to match their type.
  50834. *
  50835. * @param {string} type - Property type name.
  50836. * @param defaultVal - Property type default value.
  50837. * @returns {boolean} Whether default value is accurate given the type.
  50838. */
  50839. function isValidDefaultValue (type, defaultVal) {
  50840. if (type === 'audio' && typeof defaultVal !== 'string') { return false; }
  50841. if (type === 'array' && !Array.isArray(defaultVal)) { return false; }
  50842. if (type === 'asset' && typeof defaultVal !== 'string') { return false; }
  50843. if (type === 'boolean' && typeof defaultVal !== 'boolean') { return false; }
  50844. if (type === 'color' && typeof defaultVal !== 'string') { return false; }
  50845. if (type === 'int' && typeof defaultVal !== 'number') { return false; }
  50846. if (type === 'number' && typeof defaultVal !== 'number') { return false; }
  50847. if (type === 'map' && typeof defaultVal !== 'string') { return false; }
  50848. if (type === 'model' && typeof defaultVal !== 'string') { return false; }
  50849. if (type === 'selector' && typeof defaultVal !== 'string') { return false; }
  50850. if (type === 'selectorAll' && typeof defaultVal !== 'string') { return false; }
  50851. if (type === 'src' && typeof defaultVal !== 'string') { return false; }
  50852. if (type === 'string' && typeof defaultVal !== 'string') { return false; }
  50853. if (type === 'time' && typeof defaultVal !== 'number') { return false; }
  50854. if (type === 'vec2') { return isValidDefaultCoordinate(defaultVal, 2); }
  50855. if (type === 'vec3') { return isValidDefaultCoordinate(defaultVal, 3); }
  50856. if (type === 'vec4') { return isValidDefaultCoordinate(defaultVal, 4); }
  50857. return true;
  50858. }
  50859. module.exports.isValidDefaultValue = isValidDefaultValue;
  50860. /**
  50861. * Checks if default coordinates are valid.
  50862. *
  50863. * @param possibleCoordinates
  50864. * @param {number} dimensions - 2 for 2D Vector, 3 for 3D vector.
  50865. * @returns {boolean} Whether coordinates are parsed correctly.
  50866. */
  50867. function isValidDefaultCoordinate (possibleCoordinates, dimensions) {
  50868. if (possibleCoordinates === null) { return true; }
  50869. if (typeof possibleCoordinates !== 'object') { return false; }
  50870. if (Object.keys(possibleCoordinates).length !== dimensions) {
  50871. return false;
  50872. } else {
  50873. var x = possibleCoordinates.x;
  50874. var y = possibleCoordinates.y;
  50875. var z = possibleCoordinates.z;
  50876. var w = possibleCoordinates.w;
  50877. if (typeof x !== 'number' || typeof y !== 'number') { return false; }
  50878. if (dimensions > 2 && typeof z !== 'number') { return false; }
  50879. if (dimensions > 3 && typeof w !== 'number') { return false; }
  50880. }
  50881. return true;
  50882. }
  50883. module.exports.isValidDefaultCoordinate = isValidDefaultCoordinate;
  50884. },{"../utils/coordinates":167,"debug":7}],105:[function(_dereq_,module,exports){
  50885. /* global Promise, screen */
  50886. var initMetaTags = _dereq_('./metaTags').inject;
  50887. var initWakelock = _dereq_('./wakelock');
  50888. var re = _dereq_('../a-register-element');
  50889. var scenes = _dereq_('./scenes');
  50890. var systems = _dereq_('../system').systems;
  50891. var THREE = _dereq_('../../lib/three');
  50892. var TWEEN = _dereq_('tween.js');
  50893. var utils = _dereq_('../../utils/');
  50894. // Require after.
  50895. var AEntity = _dereq_('../a-entity');
  50896. var ANode = _dereq_('../a-node');
  50897. var initPostMessageAPI = _dereq_('./postMessage');
  50898. var bind = utils.bind;
  50899. var isIOS = utils.device.isIOS();
  50900. var isMobile = utils.device.isMobile();
  50901. var registerElement = re.registerElement;
  50902. var warn = utils.debug('core:a-scene:warn');
  50903. /**
  50904. * Scene element, holds all entities.
  50905. *
  50906. * @member {number} animationFrameID
  50907. * @member {array} behaviors - Component instances that have registered themselves to be
  50908. updated on every tick.
  50909. * @member {object} camera - three.js Camera object.
  50910. * @member {object} canvas
  50911. * @member {bool} isScene - Differentiates as scene entity as opposed to other entites.
  50912. * @member {bool} isMobile - Whether browser is mobile (via UA detection).
  50913. * @member {object} object3D - Root three.js Scene object.
  50914. * @member {object} renderer
  50915. * @member {bool} renderStarted
  50916. * @member (object) effect - three.js VREffect
  50917. * @member {object} systems - Registered instantiated systems.
  50918. * @member {number} time
  50919. */
  50920. module.exports.AScene = registerElement('a-scene', {
  50921. prototype: Object.create(AEntity.prototype, {
  50922. defaultComponents: {
  50923. value: {
  50924. 'canvas': '',
  50925. 'inspector': '',
  50926. 'keyboard-shortcuts': '',
  50927. 'screenshot': '',
  50928. 'vr-mode-ui': '',
  50929. 'auto-enter-vr': ''
  50930. }
  50931. },
  50932. createdCallback: {
  50933. value: function () {
  50934. this.isIOS = isIOS;
  50935. this.isMobile = isMobile;
  50936. this.isScene = true;
  50937. this.object3D = new THREE.Scene();
  50938. this.render = bind(this.render, this);
  50939. this.systems = {};
  50940. this.time = 0;
  50941. this.init();
  50942. }
  50943. },
  50944. init: {
  50945. value: function () {
  50946. this.behaviors = { tick: [], tock: [] };
  50947. this.hasLoaded = false;
  50948. this.isPlaying = false;
  50949. this.renderTarget = null;
  50950. this.originalHTML = this.innerHTML;
  50951. this.addEventListener('render-target-loaded', function () {
  50952. this.setupRenderer();
  50953. this.resize();
  50954. });
  50955. this.addFullScreenStyles();
  50956. initPostMessageAPI(this);
  50957. },
  50958. writable: true
  50959. },
  50960. addFullScreenStyles: {
  50961. value: function () {
  50962. var htmlEl = document.documentElement;
  50963. htmlEl.classList.add('a-html');
  50964. document.body.classList.add('a-body');
  50965. this.classList.add('fullscreen');
  50966. }
  50967. },
  50968. removeFullScreenStyles: {
  50969. value: function () {
  50970. var htmlEl = document.documentElement;
  50971. htmlEl.classList.remove('a-html');
  50972. document.body.classList.remove('a-body');
  50973. this.classList.remove('fullscreen');
  50974. }
  50975. },
  50976. attachedCallback: {
  50977. value: function () {
  50978. var resize = bind(this.resize, this);
  50979. initMetaTags(this);
  50980. initWakelock(this);
  50981. this.initSystems();
  50982. window.addEventListener('load', resize);
  50983. window.addEventListener('resize', resize);
  50984. this.play();
  50985. // Add to scene index.
  50986. scenes.push(this);
  50987. },
  50988. writable: window.debug
  50989. },
  50990. initSystems: {
  50991. value: function () {
  50992. Object.keys(systems).forEach(bind(this.initSystem, this));
  50993. }
  50994. },
  50995. initSystem: {
  50996. value: function (name) {
  50997. if (this.systems[name]) { return; }
  50998. this.systems[name] = new systems[name](this);
  50999. }
  51000. },
  51001. /**
  51002. * Shuts down scene on detach.
  51003. */
  51004. detachedCallback: {
  51005. value: function () {
  51006. if (this.effect && this.effect.cancelAnimationFrame) {
  51007. this.effect.cancelAnimationFrame(this.animationFrameID);
  51008. } else {
  51009. window.cancelAnimationFrame(this.animationFrameID);
  51010. }
  51011. var sceneIndex;
  51012. this.animationFrameID = null;
  51013. // Remove from scene index.
  51014. sceneIndex = scenes.indexOf(this);
  51015. scenes.splice(sceneIndex, 1);
  51016. }
  51017. },
  51018. /**
  51019. * @param {object} behavior - Generally a component. Must implement a .update() method to
  51020. * be called on every tick.
  51021. */
  51022. addBehavior: {
  51023. value: function (behavior) {
  51024. var self = this;
  51025. var behaviors = this.behaviors;
  51026. // Check if behavior has tick and/or tock and add the behavior to the appropriate list.
  51027. Object.keys(behaviors).forEach(function (behaviorType) {
  51028. if (!behavior[behaviorType]) { return; }
  51029. var behaviorArr = self.behaviors[behaviorType];
  51030. if (behaviorArr.indexOf(behavior) === -1) {
  51031. behaviorArr.push(behavior);
  51032. }
  51033. });
  51034. }
  51035. },
  51036. /**
  51037. * For tests.
  51038. */
  51039. checkHeadsetConnected: {
  51040. value: utils.device.checkHeadsetConnected,
  51041. writable: window.debug
  51042. },
  51043. /**
  51044. * Call `requestPresent` if WebVR or WebVR polyfill.
  51045. * Call `requestFullscreen` on desktop.
  51046. * Handle events, states, fullscreen styles.
  51047. *
  51048. * @returns {Promise}
  51049. */
  51050. enterVR: {
  51051. value: function (event) {
  51052. var self = this;
  51053. // Don't enter VR if already in VR.
  51054. if (this.is('vr-mode')) { return Promise.resolve('Already in VR.'); }
  51055. if (this.checkHeadsetConnected() || this.isMobile) {
  51056. return this.effect.requestPresent().then(enterVRSuccess, enterVRFailure);
  51057. }
  51058. enterVRSuccess();
  51059. return Promise.resolve();
  51060. function enterVRSuccess () {
  51061. self.addState('vr-mode');
  51062. self.emit('enter-vr', event);
  51063. // Lock to landscape orientation on mobile.
  51064. if (self.isMobile && screen.orientation && screen.orientation.lock) {
  51065. screen.orientation.lock('landscape');
  51066. }
  51067. self.addFullScreenStyles();
  51068. // On mobile, the polyfill handles fullscreen.
  51069. // TODO: 07/16 Chromium builds break when `requestFullscreen`ing on a canvas
  51070. // that we are also `requestPresent`ing. Until then, don't fullscreen if headset
  51071. // connected.
  51072. if (!self.isMobile && !self.checkHeadsetConnected()) {
  51073. requestFullscreen(self.canvas);
  51074. }
  51075. self.resize();
  51076. }
  51077. function enterVRFailure (err) {
  51078. if (err && err.message) {
  51079. throw new Error('Failed to enter VR mode (`requestPresent`): ' + err.message);
  51080. } else {
  51081. throw new Error('Failed to enter VR mode (`requestPresent`).');
  51082. }
  51083. }
  51084. }
  51085. },
  51086. /**
  51087. * Call `exitPresent` if WebVR or WebVR polyfill.
  51088. * Handle events, states, fullscreen styles.
  51089. *
  51090. * @returns {Promise}
  51091. */
  51092. exitVR: {
  51093. value: function () {
  51094. var self = this;
  51095. // Don't exit VR if not in VR.
  51096. if (!this.is('vr-mode')) { return Promise.resolve('Not in VR.'); }
  51097. exitFullscreen();
  51098. if (this.checkHeadsetConnected() || this.isMobile) {
  51099. return this.effect.exitPresent().then(exitVRSuccess, exitVRFailure);
  51100. }
  51101. exitVRSuccess();
  51102. return Promise.resolve();
  51103. function exitVRSuccess () {
  51104. self.removeState('vr-mode');
  51105. // Lock to landscape orientation on mobile.
  51106. if (self.isMobile && screen.orientation && screen.orientation.unlock) {
  51107. screen.orientation.unlock();
  51108. }
  51109. // Exiting VR in embedded mode, no longer need fullscreen styles.
  51110. if (self.hasAttribute('embedded')) { self.removeFullScreenStyles(); }
  51111. self.resize();
  51112. if (self.isIOS) { utils.forceCanvasResizeSafariMobile(this.canvas); }
  51113. self.emit('exit-vr', {target: self});
  51114. }
  51115. function exitVRFailure (err) {
  51116. if (err && err.message) {
  51117. throw new Error('Failed to exit VR mode (`exitPresent`): ' + err.message);
  51118. } else {
  51119. throw new Error('Failed to exit VR mode (`exitPresent`).');
  51120. }
  51121. }
  51122. }
  51123. },
  51124. /**
  51125. * Wraps Entity.getAttribute to take into account for systems.
  51126. * If system exists, then return system data rather than possible component data.
  51127. */
  51128. getAttribute: {
  51129. value: function (attr) {
  51130. var system = this.systems[attr];
  51131. if (system) { return system.data; }
  51132. return AEntity.prototype.getAttribute.call(this, attr);
  51133. }
  51134. },
  51135. /**
  51136. * `getAttribute` used to be `getDOMAttribute` and `getComputedAttribute` used to be
  51137. * what `getAttribute` is now. Now legacy code.
  51138. */
  51139. getComputedAttribute: {
  51140. value: function (attr) {
  51141. warn('`getComputedAttribute` is deprecated. Use `getAttribute` instead.');
  51142. this.getAttribute(attr);
  51143. }
  51144. },
  51145. /**
  51146. * Wraps Entity.getDOMAttribute to take into account for systems.
  51147. * If system exists, then return system data rather than possible component data.
  51148. */
  51149. getDOMAttribute: {
  51150. value: function (attr) {
  51151. var system = this.systems[attr];
  51152. if (system) { return system.data; }
  51153. return AEntity.prototype.getDOMAttribute.call(this, attr);
  51154. }
  51155. },
  51156. /**
  51157. * Wrap Entity.setAttribute to take into account for systems.
  51158. * If system exists, then skip component initialization checks and do a normal
  51159. * setAttribute.
  51160. */
  51161. setAttribute: {
  51162. value: function (attr, value, componentPropValue) {
  51163. var system = this.systems[attr];
  51164. if (system) {
  51165. ANode.prototype.setAttribute.call(this, attr, value);
  51166. system.updateProperties(value);
  51167. return;
  51168. }
  51169. AEntity.prototype.setAttribute.call(this, attr, value, componentPropValue);
  51170. }
  51171. },
  51172. /**
  51173. * @param {object} behavior - Generally a component. Has registered itself to behaviors.
  51174. */
  51175. removeBehavior: {
  51176. value: function (behavior) {
  51177. var self = this;
  51178. var behaviors = this.behaviors;
  51179. // Check if behavior has tick and/or tock and remove the behavior from the appropriate array.
  51180. Object.keys(behaviors).forEach(function (behaviorType) {
  51181. if (!behavior[behaviorType]) { return; }
  51182. var behaviorArr = self.behaviors[behaviorType];
  51183. var index = behaviorArr.indexOf(behavior);
  51184. if (index !== -1) {
  51185. behaviorArr.splice(index, 1);
  51186. }
  51187. });
  51188. }
  51189. },
  51190. resize: {
  51191. value: function () {
  51192. var camera = this.camera;
  51193. var canvas = this.canvas;
  51194. var embedded = this.getAttribute('embedded') && !this.is('vr-mode');
  51195. var size;
  51196. // Possible camera or canvas not injected yet.
  51197. // ON MOBILE the webvr-polyfill relies on the fullscreen API to enter
  51198. // VR mode. The canvas is resized by VREffect following the values returned
  51199. // by getEyeParameters. We don't want to overwrite the size with the
  51200. // windows width and height.
  51201. if (!camera || !canvas || this.is('vr-mode') && isMobile) { return; }
  51202. // Update camera.
  51203. size = getCanvasSize(canvas, embedded);
  51204. camera.aspect = size.width / size.height;
  51205. camera.updateProjectionMatrix();
  51206. // Notify renderer of size change.
  51207. this.renderer.setSize(size.width, size.height);
  51208. },
  51209. writable: window.debug
  51210. },
  51211. setupRenderer: {
  51212. value: function () {
  51213. var renderer = this.renderer = new THREE.WebGLRenderer({
  51214. canvas: this.canvas,
  51215. antialias: shouldAntiAlias(this),
  51216. alpha: true
  51217. });
  51218. renderer.setPixelRatio(window.devicePixelRatio);
  51219. renderer.sortObjects = false;
  51220. this.effect = new THREE.VREffect(renderer);
  51221. this.effect.autoSubmitFrame = false;
  51222. },
  51223. writable: window.debug
  51224. },
  51225. /**
  51226. * Handler attached to elements to help scene know when to kick off.
  51227. * Scene waits for all entities to load.
  51228. */
  51229. play: {
  51230. value: function () {
  51231. var self = this;
  51232. if (this.renderStarted) {
  51233. AEntity.prototype.play.call(this);
  51234. return;
  51235. }
  51236. this.addEventListener('loaded', function () {
  51237. AEntity.prototype.play.call(this); // .play() *before* render.
  51238. // Wait for camera if necessary before rendering.
  51239. if (this.camera) {
  51240. startRender(this);
  51241. return;
  51242. }
  51243. this.addEventListener('camera-set-active', function () { startRender(this); });
  51244. function startRender (sceneEl) {
  51245. if (sceneEl.renderStarted) { return; }
  51246. sceneEl.resize();
  51247. // Kick off render loop.
  51248. if (sceneEl.renderer) {
  51249. if (window.performance) {
  51250. window.performance.mark('render-started');
  51251. }
  51252. sceneEl.clock = new THREE.Clock();
  51253. sceneEl.render();
  51254. sceneEl.renderStarted = true;
  51255. sceneEl.emit('renderstart');
  51256. }
  51257. }
  51258. });
  51259. // setTimeout to wait for all nodes to attach and run their callbacks.
  51260. setTimeout(function () {
  51261. AEntity.prototype.load.call(self);
  51262. });
  51263. }
  51264. },
  51265. /**
  51266. * Reload the scene to the original DOM content.
  51267. *
  51268. * @param {bool} doPause - Whether to reload the scene with all dynamic behavior paused.
  51269. */
  51270. reload: {
  51271. value: function (doPause) {
  51272. var self = this;
  51273. if (doPause) { this.pause(); }
  51274. this.innerHTML = this.originalHTML;
  51275. this.init();
  51276. ANode.prototype.load.call(this, play);
  51277. function play () {
  51278. if (!self.isPlaying) { return; }
  51279. AEntity.prototype.play.call(self);
  51280. }
  51281. }
  51282. },
  51283. /**
  51284. * Wrap `updateComponent` to not initialize the component if the component has a system
  51285. * (aframevr/aframe#2365).
  51286. */
  51287. updateComponent: {
  51288. value: function (componentName) {
  51289. if (componentName in systems) { return; }
  51290. AEntity.prototype.updateComponent.apply(this, arguments);
  51291. }
  51292. },
  51293. /**
  51294. * Behavior-updater meant to be called from scene render.
  51295. * Abstracted to a different function to facilitate unit testing (`scene.tick()`) without
  51296. * needing to render.
  51297. */
  51298. tick: {
  51299. value: function (time, timeDelta) {
  51300. var systems = this.systems;
  51301. // Animations.
  51302. TWEEN.update();
  51303. // Components.
  51304. this.behaviors.tick.forEach(function (component) {
  51305. if (!component.el.isPlaying) { return; }
  51306. component.tick(time, timeDelta);
  51307. });
  51308. // Systems.
  51309. Object.keys(systems).forEach(function (key) {
  51310. if (!systems[key].tick) { return; }
  51311. systems[key].tick(time, timeDelta);
  51312. });
  51313. }
  51314. },
  51315. /**
  51316. * Behavior-updater meant to be called after scene render for post processing purposes.
  51317. * Abstracted to a different function to facilitate unit testing (`scene.tock()`) without
  51318. * needing to render.
  51319. */
  51320. tock: {
  51321. value: function (time, timeDelta) {
  51322. var systems = this.systems;
  51323. // Components.
  51324. this.behaviors.tock.forEach(function (component) {
  51325. if (!component.el.isPlaying) { return; }
  51326. component.tock(time, timeDelta);
  51327. });
  51328. // Systems.
  51329. Object.keys(systems).forEach(function (key) {
  51330. if (!systems[key].tock) { return; }
  51331. systems[key].tock(time, timeDelta);
  51332. });
  51333. }
  51334. },
  51335. /**
  51336. * The render loop.
  51337. *
  51338. * Updates animations.
  51339. * Updates behaviors.
  51340. * Renders with request animation frame.
  51341. */
  51342. render: {
  51343. value: function () {
  51344. var effect = this.effect;
  51345. var delta = this.clock.getDelta() * 1000;
  51346. this.time = this.clock.elapsedTime * 1000;
  51347. if (this.isPlaying) { this.tick(this.time, delta); }
  51348. this.animationFrameID = effect.requestAnimationFrame(this.render);
  51349. effect.render(this.object3D, this.camera, this.renderTarget);
  51350. if (this.isPlaying) { this.tock(this.time, delta); }
  51351. this.effect.submitFrame();
  51352. },
  51353. writable: true
  51354. }
  51355. })
  51356. });
  51357. /**
  51358. * Return the canvas size where the scene will be rendered
  51359. * It will be always the window size except when the scene
  51360. * is embedded. The parent size will be returned in that case
  51361. *
  51362. * @param {object} canvasEl - the canvas element
  51363. * @param {boolean} embedded - Is the scene embedded?
  51364. */
  51365. function getCanvasSize (canvasEl, embedded) {
  51366. if (embedded) {
  51367. return {
  51368. height: canvasEl.parentElement.offsetHeight,
  51369. width: canvasEl.parentElement.offsetWidth
  51370. };
  51371. }
  51372. return {
  51373. height: window.innerHeight,
  51374. width: window.innerWidth
  51375. };
  51376. }
  51377. function requestFullscreen (canvas) {
  51378. var requestFullscreen =
  51379. canvas.requestFullscreen ||
  51380. canvas.webkitRequestFullscreen ||
  51381. canvas.mozRequestFullScreen || // The capitalized `S` is not a typo.
  51382. canvas.msRequestFullscreen;
  51383. requestFullscreen.apply(canvas);
  51384. }
  51385. function exitFullscreen () {
  51386. if (document.exitFullscreen) {
  51387. document.exitFullscreen();
  51388. } else if (document.mozCancelFullScreen) {
  51389. document.mozCancelFullScreen();
  51390. } else if (document.webkitExitFullscreen) {
  51391. document.webkitExitFullscreen();
  51392. }
  51393. }
  51394. /**
  51395. * Determines if renderer anti-aliasing should be enabled.
  51396. * Enabled by default if has native WebVR or is desktop.
  51397. *
  51398. * @returns {bool}
  51399. */
  51400. function shouldAntiAlias (sceneEl) {
  51401. // Explicitly set.
  51402. if (sceneEl.getAttribute('antialias') !== null) {
  51403. return sceneEl.getAttribute('antialias') === 'true';
  51404. }
  51405. // Default not AA for mobile.
  51406. return !sceneEl.isMobile;
  51407. }
  51408. module.exports.shouldAntiAlias = shouldAntiAlias; // For testing.
  51409. },{"../../lib/three":149,"../../utils/":172,"../a-entity":98,"../a-node":100,"../a-register-element":101,"../system":112,"./metaTags":106,"./postMessage":107,"./scenes":108,"./wakelock":109,"tween.js":48}],106:[function(_dereq_,module,exports){
  51410. var constants = _dereq_('../../constants/');
  51411. var extend = _dereq_('../../utils').extend;
  51412. var MOBILE_HEAD_TAGS = module.exports.MOBILE_HEAD_TAGS = [
  51413. Meta({name: 'viewport', content: 'width=device-width,initial-scale=1,maximum-scale=1,shrink-to-fit=no,user-scalable=no,minimal-ui'}),
  51414. // W3C-standardised meta tags.
  51415. Meta({name: 'mobile-web-app-capable', content: 'yes'}),
  51416. Meta({name: 'theme-color', content: 'black'})
  51417. ];
  51418. var MOBILE_IOS_HEAD_TAGS = [
  51419. // iOS-specific meta tags for fullscreen when pinning to homescreen.
  51420. Meta({name: 'apple-mobile-web-app-capable', content: 'yes'}),
  51421. Meta({name: 'apple-mobile-web-app-status-bar-style', content: 'black'}),
  51422. Link({rel: 'apple-touch-icon', href: 'https://aframe.io/images/aframe-logo-152.png'})
  51423. ];
  51424. function Meta (attrs) {
  51425. return {
  51426. tagName: 'meta',
  51427. attributes: attrs,
  51428. exists: function () { return document.querySelector('meta[name="' + attrs.name + '"]'); }
  51429. };
  51430. }
  51431. function Link (attrs) {
  51432. return {
  51433. tagName: 'link',
  51434. attributes: attrs,
  51435. exists: function () { return document.querySelector('link[rel="' + attrs.rel + '"]'); }
  51436. };
  51437. }
  51438. /**
  51439. * Injects the necessary metatags in the document for mobile support:
  51440. * 1. Prevent the user to zoom in the document.
  51441. * 2. Ensure that window.innerWidth and window.innerHeight have the correct
  51442. * values and the canvas is properly scaled.
  51443. * 3. To allow fullscreen mode when pinning a web app on the home screen on
  51444. * iOS.
  51445. * Adapted from https://www.reddit.com/r/web_design/comments/3la04p/
  51446. *
  51447. * @param {object} scene - Scene element
  51448. * @returns {Array}
  51449. */
  51450. module.exports.inject = function injectHeadTags (scene) {
  51451. var headEl = document.head;
  51452. var headScriptEl = headEl.querySelector('script');
  51453. var tag;
  51454. var headTags = [];
  51455. MOBILE_HEAD_TAGS.forEach(createAndInjectTag);
  51456. if (scene.isIOS) {
  51457. MOBILE_IOS_HEAD_TAGS.forEach(createAndInjectTag);
  51458. }
  51459. return headTags;
  51460. function createAndInjectTag (tagObj) {
  51461. if (!tagObj || tagObj.exists()) { return; }
  51462. tag = createTag(tagObj);
  51463. if (!tag) { return; }
  51464. if (headScriptEl) {
  51465. headScriptEl.parentNode.insertBefore(tag, headScriptEl);
  51466. } else {
  51467. headEl.appendChild(tag);
  51468. }
  51469. headTags.push(tag);
  51470. }
  51471. };
  51472. function createTag (tagObj) {
  51473. if (!tagObj || !tagObj.tagName) { return; }
  51474. var meta = document.createElement(tagObj.tagName);
  51475. meta.setAttribute(constants.AFRAME_INJECTED, '');
  51476. return extend(meta, tagObj.attributes);
  51477. }
  51478. },{"../../constants/":93,"../../utils":172}],107:[function(_dereq_,module,exports){
  51479. var bind = _dereq_('../../utils/bind');
  51480. var isIframed = _dereq_('../../utils/').isIframed;
  51481. /**
  51482. * Provides a post message API for scenes contained
  51483. * in an iframe.
  51484. */
  51485. module.exports = function initPostMessageAPI (scene) {
  51486. // Handles fullscreen behavior when inside an iframe.
  51487. if (!isIframed()) { return; }
  51488. // postMessage API handler
  51489. window.addEventListener('message', bind(postMessageAPIHandler, scene));
  51490. };
  51491. function postMessageAPIHandler (event) {
  51492. var scene = this;
  51493. if (!event.data) { return; }
  51494. switch (event.data.type) {
  51495. case 'vr': {
  51496. switch (event.data.data) {
  51497. case 'enter':
  51498. scene.enterVR();
  51499. break;
  51500. case 'exit':
  51501. scene.exitVR();
  51502. break;
  51503. }
  51504. }
  51505. }
  51506. }
  51507. },{"../../utils/":172,"../../utils/bind":166}],108:[function(_dereq_,module,exports){
  51508. /*
  51509. Scene index for keeping track of created scenes.
  51510. */
  51511. module.exports = [];
  51512. },{}],109:[function(_dereq_,module,exports){
  51513. var Wakelock = _dereq_('../../../vendor/wakelock/wakelock');
  51514. module.exports = function initWakelock (scene) {
  51515. if (!scene.isMobile) { return; }
  51516. var wakelock = scene.wakelock = new Wakelock();
  51517. scene.addEventListener('enter-vr', function () { wakelock.request(); });
  51518. scene.addEventListener('exit-vr', function () { wakelock.release(); });
  51519. };
  51520. },{"../../../vendor/wakelock/wakelock":182}],110:[function(_dereq_,module,exports){
  51521. var utils = _dereq_('../utils/');
  51522. var PropertyTypes = _dereq_('./propertyTypes');
  51523. var debug = utils.debug;
  51524. var isValidDefaultValue = PropertyTypes.isValidDefaultValue;
  51525. var propertyTypes = PropertyTypes.propertyTypes;
  51526. var warn = debug('core:schema:warn');
  51527. /**
  51528. * A schema is classified as a schema for a single property if:
  51529. * - `type` is defined on the schema as a string.
  51530. * - OR `default` is defined on the schema, as a reserved keyword.
  51531. * - OR schema is empty.
  51532. */
  51533. function isSingleProperty (schema) {
  51534. if ('type' in schema) {
  51535. return typeof schema.type === 'string';
  51536. }
  51537. return 'default' in schema;
  51538. }
  51539. module.exports.isSingleProperty = isSingleProperty;
  51540. /**
  51541. * Build step to schema to use `type` to inject default value, parser, and stringifier.
  51542. *
  51543. * @param {object} schema
  51544. * @param {string} componentName
  51545. * @returns {object} Schema.
  51546. */
  51547. module.exports.process = function (schema, componentName) {
  51548. // For single property schema, run processPropDefinition over the whole schema.
  51549. if (isSingleProperty(schema)) {
  51550. return processPropertyDefinition(schema, componentName);
  51551. }
  51552. // For multi-property schema, run processPropDefinition over each property definition.
  51553. Object.keys(schema).forEach(function (propName) {
  51554. schema[propName] = processPropertyDefinition(schema[propName], componentName);
  51555. });
  51556. return schema;
  51557. };
  51558. /**
  51559. * Inject default value, parser, stringifier for single property.
  51560. *
  51561. * @param {object} propDefinition
  51562. * @param {string} componentName
  51563. */
  51564. function processPropertyDefinition (propDefinition, componentName) {
  51565. var defaultVal = propDefinition.default;
  51566. var propType;
  51567. var typeName = propDefinition.type;
  51568. // Type inference.
  51569. if (!propDefinition.type) {
  51570. if (defaultVal !== undefined && ['boolean', 'number'].indexOf(typeof defaultVal) !== -1) {
  51571. // Type inference.
  51572. typeName = typeof defaultVal;
  51573. } else if (Array.isArray(defaultVal)) {
  51574. typeName = 'array';
  51575. } else {
  51576. // Fall back to string.
  51577. typeName = 'string';
  51578. }
  51579. } else if (propDefinition.type === 'bool') {
  51580. typeName = 'boolean';
  51581. } else if (propDefinition.type === 'float') {
  51582. typeName = 'number';
  51583. }
  51584. propType = propertyTypes[typeName];
  51585. if (!propType) {
  51586. warn('Unknown property type for component `' + componentName + '`: ' + typeName);
  51587. }
  51588. // Fill in parse and stringify using property types.
  51589. propDefinition.parse = propDefinition.parse || propType.parse;
  51590. propDefinition.stringify = propDefinition.stringify || propType.stringify;
  51591. // Fill in type name.
  51592. propDefinition.type = typeName;
  51593. // Check that default value exists.
  51594. if ('default' in propDefinition) {
  51595. // Check that default values are valid.
  51596. if (!isValidDefaultValue(typeName, defaultVal)) {
  51597. warn('Default value `' + defaultVal + '` does not match type `' + typeName +
  51598. '` in component `' + componentName + '`');
  51599. }
  51600. } else {
  51601. // Fill in default value.
  51602. propDefinition.default = propType.default;
  51603. }
  51604. return propDefinition;
  51605. }
  51606. module.exports.processPropertyDefinition = processPropertyDefinition;
  51607. /**
  51608. * Parse propData using schema. Use default values if not existing in propData.
  51609. *
  51610. * @param {object} propData - Unparsed properties.
  51611. * @param {object} schema - Property types definition.
  51612. * @param {boolean} getPartialData - Whether to return full component data or just the data
  51613. * with keys in `propData`.
  51614. * @param {string } componentName - Name of the component, used for the property warning.
  51615. * @param {boolean} silent - Suppress warning messages.
  51616. */
  51617. module.exports.parseProperties = function (propData, schema, getPartialData, componentName,
  51618. silent) {
  51619. var propNames = Object.keys(getPartialData ? propData : schema);
  51620. if (propData === null || typeof propData !== 'object') { return propData; }
  51621. // Validation errors.
  51622. Object.keys(propData).forEach(function (propName) {
  51623. if (!schema[propName] && !silent) {
  51624. warn('Unknown property `' + propName +
  51625. '` for component/system `' + componentName + '`.');
  51626. }
  51627. });
  51628. propNames.forEach(function parse (propName) {
  51629. var propDefinition = schema[propName];
  51630. var propValue = propData[propName];
  51631. if (!(schema[propName])) { return; }
  51632. propData[propName] = parseProperty(propValue, propDefinition);
  51633. });
  51634. return propData;
  51635. };
  51636. /**
  51637. * Deserialize a single property.
  51638. */
  51639. function parseProperty (value, propDefinition) {
  51640. // Use default value if value is falsy.
  51641. if (value === undefined || value === null || value === '') {
  51642. value = propDefinition.default;
  51643. if (Array.isArray(value)) { value = value.slice(); }
  51644. }
  51645. // Invoke property type parser.
  51646. return propDefinition.parse(value, propDefinition.default);
  51647. }
  51648. module.exports.parseProperty = parseProperty;
  51649. /**
  51650. * Serialize a group of properties.
  51651. */
  51652. module.exports.stringifyProperties = function (propData, schema) {
  51653. var stringifiedData = {};
  51654. Object.keys(propData).forEach(function (propName) {
  51655. var propDefinition = schema[propName];
  51656. var propValue = propData[propName];
  51657. var value = propValue;
  51658. if (typeof value === 'object') {
  51659. value = stringifyProperty(propValue, propDefinition);
  51660. if (!propDefinition) { warn('Unknown component property: ' + propName); }
  51661. }
  51662. stringifiedData[propName] = value;
  51663. });
  51664. return stringifiedData;
  51665. };
  51666. /**
  51667. * Serialize a single property.
  51668. */
  51669. function stringifyProperty (value, propDefinition) {
  51670. // This function stringifies but it's used in a context where
  51671. // there's always second stringification pass. By returning the original
  51672. // value when it's not an object we save one unnecessary call
  51673. // to JSON.stringify.
  51674. if (typeof value !== 'object') { return value; }
  51675. // if there's no schema for the property we use standar JSON stringify
  51676. if (!propDefinition || value === null) { return JSON.stringify(value); }
  51677. return propDefinition.stringify(value);
  51678. }
  51679. module.exports.stringifyProperty = stringifyProperty;
  51680. },{"../utils/":172,"./propertyTypes":104}],111:[function(_dereq_,module,exports){
  51681. var schema = _dereq_('./schema');
  51682. var processSchema = schema.process;
  51683. var shaders = module.exports.shaders = {}; // Keep track of registered shaders.
  51684. var shaderNames = module.exports.shaderNames = []; // Keep track of the names of registered shaders.
  51685. var THREE = _dereq_('../lib/three');
  51686. var utils = _dereq_('../utils');
  51687. // A-Frame properties to three.js uniform types.
  51688. var propertyToThreeMapping = {
  51689. array: 'v3',
  51690. color: 'v3',
  51691. int: 'i',
  51692. number: 'f',
  51693. map: 't',
  51694. time: 'f',
  51695. vec2: 'v2',
  51696. vec3: 'v3',
  51697. vec4: 'v4'
  51698. };
  51699. /**
  51700. * Shader class definition.
  51701. *
  51702. * Shaders extend the material component API so you can create your own library
  51703. * of customized materials
  51704. *
  51705. */
  51706. var Shader = module.exports.Shader = function () {};
  51707. Shader.prototype = {
  51708. /**
  51709. * Contains the type schema and defaults for the data values.
  51710. * Data is coerced into the types of the values of the defaults.
  51711. */
  51712. schema: {},
  51713. vertexShader:
  51714. 'void main() {' +
  51715. 'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);' +
  51716. '}',
  51717. fragmentShader:
  51718. 'void main() {' +
  51719. 'gl_FragColor = vec4(1.0, 0.0, 1.0, 1.0);' +
  51720. '}',
  51721. /**
  51722. * Init handler. Similar to attachedCallback.
  51723. * Called during shader initialization and is only run once.
  51724. */
  51725. init: function (data) {
  51726. this.attributes = this.initVariables(data, 'attribute');
  51727. this.uniforms = this.initVariables(data, 'uniform');
  51728. this.material = new (this.raw ? THREE.RawShaderMaterial : THREE.ShaderMaterial)({
  51729. // attributes: this.attributes,
  51730. uniforms: this.uniforms,
  51731. vertexShader: this.vertexShader,
  51732. fragmentShader: this.fragmentShader
  51733. });
  51734. return this.material;
  51735. },
  51736. initVariables: function (data, type) {
  51737. var variables = {};
  51738. var schema = this.schema;
  51739. Object.keys(schema).forEach(function processSchema (key) {
  51740. if (schema[key].is !== type) { return; }
  51741. var varType = propertyToThreeMapping[schema[key].type];
  51742. variables[key] = {
  51743. type: varType,
  51744. value: undefined // Let updateVariables handle setting these.
  51745. };
  51746. });
  51747. return variables;
  51748. },
  51749. /**
  51750. * Update handler. Similar to attributeChangedCallback.
  51751. * Called whenever the associated material data changes.
  51752. *
  51753. * @param {object} data - New material data.
  51754. */
  51755. update: function (data) {
  51756. this.updateVariables(data, 'attribute');
  51757. this.updateVariables(data, 'uniform');
  51758. },
  51759. updateVariables: function (data, type) {
  51760. var self = this;
  51761. var variables = type === 'uniform' ? this.uniforms : this.attributes;
  51762. var schema = this.schema;
  51763. Object.keys(data).forEach(function processData (key) {
  51764. var materialKey;
  51765. if (!schema[key] || schema[key].is !== type) { return; }
  51766. if (schema[key].type === 'map') {
  51767. // If data unchanged, get out early.
  51768. if (!variables[key] || variables[key].value === data[key]) { return; }
  51769. // Special handling is needed for textures.
  51770. materialKey = '_texture_' + key;
  51771. // We can't actually set the variable correctly until we've loaded the texture.
  51772. self.el.addEventListener('materialtextureloaded', function () {
  51773. variables[key].value = self.material[materialKey];
  51774. variables[key].needsUpdate = true;
  51775. });
  51776. // Kick off the texture update now that handler is added.
  51777. utils.material.updateMapMaterialFromData(materialKey, key, self, data);
  51778. return;
  51779. }
  51780. variables[key].value = self.parseValue(schema[key].type, data[key]);
  51781. variables[key].needsUpdate = true;
  51782. });
  51783. },
  51784. parseValue: function (type, value) {
  51785. var color;
  51786. switch (type) {
  51787. case 'vec2': {
  51788. return new THREE.Vector2(value.x, value.y);
  51789. }
  51790. case 'vec3': {
  51791. return new THREE.Vector3(value.x, value.y, value.z);
  51792. }
  51793. case 'vec4': {
  51794. return new THREE.Vector4(value.x, value.y, value.z, value.w);
  51795. }
  51796. case 'color': {
  51797. color = new THREE.Color(value);
  51798. return new THREE.Vector3(color.r, color.g, color.b);
  51799. }
  51800. default: {
  51801. return value;
  51802. }
  51803. }
  51804. }
  51805. };
  51806. /**
  51807. * Registers a shader to A-Frame.
  51808. *
  51809. * @param {string} name - shader name.
  51810. * @param {object} definition - shader property and methods.
  51811. * @returns {object} Shader.
  51812. */
  51813. module.exports.registerShader = function (name, definition) {
  51814. var NewShader;
  51815. var proto = {};
  51816. // Format definition object to prototype object.
  51817. Object.keys(definition).forEach(function (key) {
  51818. proto[key] = {
  51819. value: definition[key],
  51820. writable: true
  51821. };
  51822. });
  51823. if (shaders[name]) {
  51824. throw new Error('The shader ' + name + ' has been already registered');
  51825. }
  51826. NewShader = function () { Shader.call(this); };
  51827. NewShader.prototype = Object.create(Shader.prototype, proto);
  51828. NewShader.prototype.name = name;
  51829. NewShader.prototype.constructor = NewShader;
  51830. shaders[name] = {
  51831. Shader: NewShader,
  51832. schema: processSchema(NewShader.prototype.schema)
  51833. };
  51834. shaderNames.push(name);
  51835. return NewShader;
  51836. };
  51837. },{"../lib/three":149,"../utils":172,"./schema":110}],112:[function(_dereq_,module,exports){
  51838. /* global HTMLElement */
  51839. var components = _dereq_('./component');
  51840. var schema = _dereq_('./schema');
  51841. var utils = _dereq_('../utils/');
  51842. var parseProperties = schema.parseProperties;
  51843. var parseProperty = schema.parseProperty;
  51844. var processSchema = schema.process;
  51845. var isSingleProp = schema.isSingleProperty;
  51846. var styleParser = utils.styleParser;
  51847. var systems = module.exports.systems = {}; // Keep track of registered systems.
  51848. /**
  51849. * System class definition.
  51850. *
  51851. * Systems provide global scope and services to a group of instantiated components of the
  51852. * same class. They can also help abstract logic away from components such that components
  51853. * only have to worry about data.
  51854. *
  51855. * For example, a physics component that creates a physics world that oversees
  51856. * all entities with a physics or rigid body component.
  51857. *
  51858. * TODO: Have the System prototype reuse the Component prototype. Most code is copied
  51859. * and some pieces are missing from the Component facilities (e.g., attribute caching,
  51860. * setAttribute behavior).
  51861. *
  51862. * @member {string} name - Name that system is registered under.
  51863. * @member {Element} sceneEl - Handle to the scene element where system applies to.
  51864. */
  51865. var System = module.exports.System = function (sceneEl) {
  51866. var component = components && components.components[this.name];
  51867. // Set reference to scene.
  51868. this.el = sceneEl;
  51869. this.sceneEl = sceneEl;
  51870. // Set reference to matching component (if exists).
  51871. if (component) { component.Component.prototype.system = this; }
  51872. // Process system configuration.
  51873. this.buildData();
  51874. this.init();
  51875. this.update({});
  51876. };
  51877. System.prototype = {
  51878. /**
  51879. * Schema to configure system.
  51880. */
  51881. schema: {},
  51882. /**
  51883. * Init handler. Called during scene initialization and is only run once.
  51884. * Systems can use this to set initial state.
  51885. */
  51886. init: function () { /* no-op */ },
  51887. /**
  51888. * Update handler. Called during scene attribute updates.
  51889. * Systems can use this to dynamically update their state.
  51890. */
  51891. update: function (oldData) { /* no-op */ },
  51892. /**
  51893. * Build data and call update handler.
  51894. *
  51895. * @private
  51896. */
  51897. updateProperties: function (rawData) {
  51898. var oldData = this.data;
  51899. if (!Object.keys(schema).length) { return; }
  51900. this.buildData(rawData);
  51901. this.update(oldData);
  51902. },
  51903. /**
  51904. * Parse data.
  51905. */
  51906. buildData: function (rawData) {
  51907. var schema = this.schema;
  51908. if (!Object.keys(schema).length) { return; }
  51909. rawData = rawData || HTMLElement.prototype.getAttribute.call(this.sceneEl, this.name);
  51910. if (isSingleProp(schema)) {
  51911. this.data = parseProperty(rawData, schema);
  51912. } else {
  51913. this.data = parseProperties(styleParser.parse(rawData) || {}, schema);
  51914. }
  51915. },
  51916. /**
  51917. * Tick handler.
  51918. * Called on each tick of the scene render loop.
  51919. * Affected by play and pause.
  51920. *
  51921. * @param {number} time - Scene tick time.
  51922. * @param {number} timeDelta - Difference in current render time and previous render time.
  51923. */
  51924. tick: undefined,
  51925. /**
  51926. * Tock handler.
  51927. * Called on each tock of the scene render loop.
  51928. * Affected by play and pause.
  51929. *
  51930. * @param {number} time - Scene tick time.
  51931. * @param {number} timeDelta - Difference in current render time and previous render time.
  51932. */
  51933. tock: undefined,
  51934. /**
  51935. * Called to start any dynamic behavior (e.g., animation, AI, events, physics).
  51936. */
  51937. play: function () { /* no-op */ },
  51938. /**
  51939. * Called to stop any dynamic behavior (e.g., animation, AI, events, physics).
  51940. */
  51941. pause: function () { /* no-op */ }
  51942. };
  51943. /**
  51944. * Registers a system to A-Frame.
  51945. *
  51946. * @param {string} name - Component name.
  51947. * @param {object} definition - Component property and methods.
  51948. * @returns {object} Component.
  51949. */
  51950. module.exports.registerSystem = function (name, definition) {
  51951. var i;
  51952. var NewSystem;
  51953. var proto = {};
  51954. var scenes = utils.findAllScenes(document);
  51955. // Format definition object to prototype object.
  51956. Object.keys(definition).forEach(function (key) {
  51957. proto[key] = {
  51958. value: definition[key],
  51959. writable: true
  51960. };
  51961. });
  51962. if (systems[name]) {
  51963. throw new Error('The system `' + name + '` has been already registered. ' +
  51964. 'Check that you are not loading two versions of the same system ' +
  51965. 'or two different systems of the same name.');
  51966. }
  51967. NewSystem = function (sceneEl) { System.call(this, sceneEl); };
  51968. NewSystem.prototype = Object.create(System.prototype, proto);
  51969. NewSystem.prototype.name = name;
  51970. NewSystem.prototype.constructor = NewSystem;
  51971. NewSystem.prototype.schema = utils.extend(processSchema(NewSystem.prototype.schema));
  51972. systems[name] = NewSystem;
  51973. // Initialize systems for existing scenes
  51974. for (i = 0; i < scenes.length; i++) { scenes[i].initSystem(name); }
  51975. };
  51976. },{"../utils/":172,"./component":102,"./schema":110}],113:[function(_dereq_,module,exports){
  51977. _dereq_('./pivot');
  51978. },{"./pivot":114}],114:[function(_dereq_,module,exports){
  51979. var registerComponent = _dereq_('../../core/component').registerComponent;
  51980. var THREE = _dereq_('../../lib/three');
  51981. var originalPosition = new THREE.Vector3();
  51982. var originalRotation = new THREE.Vector3();
  51983. /**
  51984. * Wrap el.object3D within an outer group. Apply pivot to el.object3D as position.
  51985. */
  51986. registerComponent('pivot', {
  51987. dependencies: ['position'],
  51988. schema: {type: 'vec3'},
  51989. init: function () {
  51990. var data = this.data;
  51991. var el = this.el;
  51992. var originalParent = el.object3D.parent;
  51993. var originalGroup = el.object3D;
  51994. var outerGroup = new THREE.Group();
  51995. originalPosition.copy(originalGroup.position);
  51996. originalRotation.copy(originalGroup.rotation);
  51997. // Detach current group from parent.
  51998. originalParent.remove(originalGroup);
  51999. outerGroup.add(originalGroup);
  52000. // Set new group as the outer group.
  52001. originalParent.add(outerGroup);
  52002. // Set outer group as new object3D.
  52003. el.object3D = outerGroup;
  52004. // Apply pivot to original group.
  52005. originalGroup.position.set(-1 * data.x, -1 * data.y, -1 * data.z);
  52006. // Offset the pivot so that world position not affected.
  52007. // And restore position onto outer group.
  52008. outerGroup.position.set(data.x + originalPosition.x, data.y + originalPosition.y,
  52009. data.z + originalPosition.z);
  52010. // Transfer rotation to outer group.
  52011. outerGroup.rotation.copy(originalGroup.rotation);
  52012. originalGroup.rotation.set(0, 0, 0);
  52013. }
  52014. });
  52015. },{"../../core/component":102,"../../lib/three":149}],115:[function(_dereq_,module,exports){
  52016. /**
  52017. * Common mesh defaults, mappings, and transforms.
  52018. */
  52019. var components = _dereq_('../../core/component').components;
  52020. var shaders = _dereq_('../../core/shader').shaders;
  52021. var utils = _dereq_('../../utils/');
  52022. var materialMappings = {};
  52023. Object.keys(components.material.schema).forEach(addMapping);
  52024. Object.keys(shaders.standard.schema).forEach(addMapping);
  52025. function addMapping (prop) {
  52026. // To hyphenated.
  52027. var htmlAttrName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  52028. if (prop === 'fog') { htmlAttrName = 'material-fog'; }
  52029. if (prop === 'visible') { htmlAttrName = 'material-visible'; }
  52030. materialMappings[htmlAttrName] = 'material.' + prop;
  52031. }
  52032. module.exports = function getMeshMixin () {
  52033. return {
  52034. defaultComponents: {material: {}},
  52035. mappings: utils.extend({}, materialMappings)
  52036. };
  52037. };
  52038. },{"../../core/component":102,"../../core/shader":111,"../../utils/":172}],116:[function(_dereq_,module,exports){
  52039. _dereq_('./primitives/a-camera');
  52040. _dereq_('./primitives/a-collada-model');
  52041. _dereq_('./primitives/a-cursor');
  52042. _dereq_('./primitives/a-curvedimage');
  52043. _dereq_('./primitives/a-gltf-model');
  52044. _dereq_('./primitives/a-image');
  52045. _dereq_('./primitives/a-light');
  52046. _dereq_('./primitives/a-obj-model');
  52047. _dereq_('./primitives/a-sky');
  52048. _dereq_('./primitives/a-sound');
  52049. _dereq_('./primitives/a-text');
  52050. _dereq_('./primitives/a-video');
  52051. _dereq_('./primitives/a-videosphere');
  52052. _dereq_('./primitives/meshPrimitives');
  52053. },{"./primitives/a-camera":118,"./primitives/a-collada-model":119,"./primitives/a-cursor":120,"./primitives/a-curvedimage":121,"./primitives/a-gltf-model":122,"./primitives/a-image":123,"./primitives/a-light":124,"./primitives/a-obj-model":125,"./primitives/a-sky":126,"./primitives/a-sound":127,"./primitives/a-text":128,"./primitives/a-video":129,"./primitives/a-videosphere":130,"./primitives/meshPrimitives":131}],117:[function(_dereq_,module,exports){
  52054. var AEntity = _dereq_('../../core/a-entity');
  52055. var components = _dereq_('../../core/component').components;
  52056. var registerElement = _dereq_('../../core/a-register-element').registerElement;
  52057. var utils = _dereq_('../../utils/');
  52058. var debug = utils.debug;
  52059. var setComponentProperty = utils.entity.setComponentProperty;
  52060. var log = debug('extras:primitives:debug');
  52061. var warn = debug('extras:primitives:warn');
  52062. var primitives = module.exports.primitives = {};
  52063. module.exports.registerPrimitive = function registerPrimitive (name, definition) {
  52064. name = name.toLowerCase();
  52065. log('Registering <%s>', name);
  52066. // Deprecation warning for defaultAttributes usage.
  52067. if (definition.defaultAttributes) {
  52068. warn("The 'defaultAttributes' object is deprecated. Use 'defaultComponents' instead.");
  52069. }
  52070. var primitive = registerElement(name, {
  52071. prototype: Object.create(AEntity.prototype, {
  52072. defaultComponentsFromPrimitive: {
  52073. value: definition.defaultComponents || definition.defaultAttributes || {}
  52074. },
  52075. deprecated: {value: definition.deprecated || null},
  52076. deprecatedMappings: {value: definition.deprecatedMappings || {}},
  52077. mappings: {value: definition.mappings || {}},
  52078. createdCallback: {
  52079. value: function () {
  52080. if (definition.deprecated) { console.warn(definition.deprecated); }
  52081. this.resolveMappingCollisions();
  52082. }
  52083. },
  52084. /**
  52085. * If a mapping collides with a registered component name
  52086. * it renames the mapping to componentname-property
  52087. */
  52088. resolveMappingCollisions: {
  52089. value: function () {
  52090. var mappings = this.mappings;
  52091. var self = this;
  52092. Object.keys(mappings).forEach(function resolveCollision (key) {
  52093. var newAttribute;
  52094. if (key !== key.toLowerCase()) { warn('Mapping keys should be specified in lower case. The mapping key ' + key + ' may not be recognized'); }
  52095. if (components[key]) {
  52096. newAttribute = mappings[key].replace('.', '-');
  52097. mappings[newAttribute] = mappings[key];
  52098. delete mappings[key];
  52099. console.warn('The primitive ' + self.tagName.toLowerCase() + ' has a mapping collision. ' +
  52100. 'The attribute ' + key + ' has the same name as a registered component and' +
  52101. ' has been renamed to ' + newAttribute);
  52102. }
  52103. });
  52104. }
  52105. },
  52106. getExtraComponents: {
  52107. value: function () {
  52108. var attr;
  52109. var data;
  52110. var i;
  52111. var mapping;
  52112. var mixins;
  52113. var path;
  52114. var self = this;
  52115. // Gather component data from default components.
  52116. data = utils.clone(this.defaultComponentsFromPrimitive);
  52117. // Factor in mixins to overwrite default components.
  52118. mixins = this.getAttribute('mixin');
  52119. if (mixins) {
  52120. mixins = mixins.trim().split(' ');
  52121. mixins.forEach(function applyMixin (mixinId) {
  52122. var mixinComponents = self.sceneEl.querySelector('#' + mixinId).componentCache;
  52123. Object.keys(mixinComponents).forEach(function setComponent (name) {
  52124. data[name] = utils.extendDeep(data[name] || {}, mixinComponents[name]);
  52125. });
  52126. });
  52127. }
  52128. // Gather component data from mappings.
  52129. for (i = 0; i < this.attributes.length; i++) {
  52130. attr = this.attributes[i];
  52131. mapping = this.mappings[attr.name];
  52132. if (mapping) {
  52133. path = utils.entity.getComponentPropertyPath(mapping);
  52134. if (path.constructor === Array) {
  52135. data[path[0]][path[1]] = attr.value;
  52136. } else {
  52137. data[path] = attr.value;
  52138. }
  52139. continue;
  52140. }
  52141. }
  52142. return data;
  52143. }
  52144. },
  52145. /**
  52146. * Sync to attribute to component property whenever mapped attribute changes.
  52147. * If attribute is mapped to a component property, set the component property using
  52148. * the attribute value.
  52149. */
  52150. attributeChangedCallback: {
  52151. value: function (attr, oldVal, value) {
  52152. var componentName = this.mappings[attr];
  52153. if (attr in this.deprecatedMappings) {
  52154. console.warn(this.deprecatedMappings[attr]);
  52155. }
  52156. if (!attr || !componentName) { return; }
  52157. // Set value.
  52158. setComponentProperty(this, componentName, value);
  52159. }
  52160. }
  52161. })
  52162. });
  52163. // Store.
  52164. primitives[name] = primitive;
  52165. return primitive;
  52166. };
  52167. /**
  52168. * Add component mappings using schema.
  52169. */
  52170. function addComponentMapping (componentName, mappings) {
  52171. var schema = components[componentName].schema;
  52172. Object.keys(schema).map(function (prop) {
  52173. // Hyphenate where there is camelCase.
  52174. var attrName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  52175. // If there is a mapping collision, prefix with component name and hyphen.
  52176. if (mappings[attrName] !== undefined) { attrName = componentName + '-' + prop; }
  52177. mappings[attrName] = componentName + '.' + prop;
  52178. });
  52179. }
  52180. /**
  52181. * Helper to define a primitive, building mappings using a component schema.
  52182. */
  52183. function definePrimitive (tagName, defaultComponents, mappings) {
  52184. // If no initial mappings provided, start from empty map.
  52185. mappings = mappings || {};
  52186. // From the default components, add mapping automagically.
  52187. Object.keys(defaultComponents).map(function buildMappings (componentName) {
  52188. addComponentMapping(componentName, mappings);
  52189. });
  52190. // Register the primitive.
  52191. module.exports.registerPrimitive(tagName, utils.extendDeep({}, null, {
  52192. defaultComponents: defaultComponents,
  52193. mappings: mappings
  52194. }));
  52195. }
  52196. module.exports.definePrimitive = definePrimitive;
  52197. },{"../../core/a-entity":98,"../../core/a-register-element":101,"../../core/component":102,"../../utils/":172}],118:[function(_dereq_,module,exports){
  52198. var DEFAULT_CAMERA_HEIGHT = _dereq_('../../../constants/').DEFAULT_CAMERA_HEIGHT;
  52199. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52200. registerPrimitive('a-camera', {
  52201. defaultComponents: {
  52202. camera: {
  52203. userHeight: DEFAULT_CAMERA_HEIGHT
  52204. },
  52205. 'look-controls': {},
  52206. 'wasd-controls': {}
  52207. },
  52208. mappings: {
  52209. active: 'camera.active',
  52210. far: 'camera.far',
  52211. fov: 'camera.fov',
  52212. 'look-controls-enabled': 'look-controls.enabled',
  52213. near: 'camera.near',
  52214. 'wasd-controls-enabled': 'wasd-controls.enabled',
  52215. 'reverse-mouse-drag': 'look-controls.reverseMouseDrag',
  52216. 'user-height': 'camera.userHeight',
  52217. zoom: 'camera.zoom'
  52218. },
  52219. deprecatedMappings: {
  52220. 'cursor-color': 'a-camera[cursor-color] has been removed. Use a-cursor[color] instead.',
  52221. 'cursor-maxdistance': 'a-camera[cursor-maxdistance] has been removed. Use a-cursor[max-distance] instead.',
  52222. 'cursor-offset': 'a-camera[cursor-offset] has been removed. Use a-cursor[position] instead.',
  52223. 'cursor-opacity': 'a-camera[cursor-offset] has been removed. Use a-cursor[opacity] instead.',
  52224. 'cursor-scale': 'a-camera[cursor-scale] has been removed. Use a-cursor[scale] instead.',
  52225. 'cursor-visible': 'a-camera[cursor-visible] has been removed. Use a-cursor[visible] instead.'
  52226. }
  52227. });
  52228. },{"../../../constants/":93,"../primitives":117}],119:[function(_dereq_,module,exports){
  52229. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52230. registerPrimitive('a-collada-model', {
  52231. mappings: {
  52232. src: 'collada-model'
  52233. }
  52234. });
  52235. },{"../primitives":117}],120:[function(_dereq_,module,exports){
  52236. var getMeshMixin = _dereq_('../getMeshMixin');
  52237. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52238. var utils = _dereq_('../../../utils/');
  52239. registerPrimitive('a-cursor', utils.extendDeep({}, getMeshMixin(), {
  52240. defaultComponents: {
  52241. cursor: {},
  52242. geometry: {
  52243. primitive: 'ring',
  52244. radiusOuter: 0.016,
  52245. radiusInner: 0.01,
  52246. segmentsTheta: 64
  52247. },
  52248. material: {
  52249. color: '#000',
  52250. shader: 'flat',
  52251. opacity: 0.8
  52252. },
  52253. position: {
  52254. x: 0,
  52255. y: 0,
  52256. z: -1
  52257. },
  52258. raycaster: {
  52259. far: 1000
  52260. }
  52261. },
  52262. mappings: {
  52263. far: 'raycaster.far',
  52264. fuse: 'cursor.fuse',
  52265. interval: 'raycaster.interval',
  52266. objects: 'raycaster.objects',
  52267. 'fuse-timeout': 'cursor.fuseTimeout'
  52268. }
  52269. }));
  52270. },{"../../../utils/":172,"../getMeshMixin":115,"../primitives":117}],121:[function(_dereq_,module,exports){
  52271. var getMeshMixin = _dereq_('../getMeshMixin');
  52272. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52273. var utils = _dereq_('../../../utils/');
  52274. registerPrimitive('a-curvedimage', utils.extendDeep({}, getMeshMixin(), {
  52275. defaultComponents: {
  52276. geometry: {
  52277. height: 1,
  52278. primitive: 'cylinder',
  52279. radius: 2,
  52280. segmentsRadial: 48,
  52281. thetaLength: 270,
  52282. openEnded: true,
  52283. thetaStart: 0
  52284. },
  52285. material: {
  52286. color: '#FFF',
  52287. shader: 'flat',
  52288. side: 'double',
  52289. transparent: true,
  52290. repeat: '-1 1'
  52291. }
  52292. },
  52293. mappings: {
  52294. height: 'geometry.height',
  52295. 'open-ended': 'geometry.openEnded',
  52296. radius: 'geometry.radius',
  52297. segments: 'geometry.segmentsRadial',
  52298. start: 'geometry.thetaStart',
  52299. 'theta-length': 'geometry.thetaLength',
  52300. 'theta-start': 'geometry.thetaStart',
  52301. 'width': 'geometry.thetaLength'
  52302. }
  52303. }));
  52304. },{"../../../utils/":172,"../getMeshMixin":115,"../primitives":117}],122:[function(_dereq_,module,exports){
  52305. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52306. registerPrimitive('a-gltf-model', {
  52307. mappings: {
  52308. src: 'gltf-model'
  52309. }
  52310. });
  52311. },{"../primitives":117}],123:[function(_dereq_,module,exports){
  52312. var getMeshMixin = _dereq_('../getMeshMixin');
  52313. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52314. var utils = _dereq_('../../../utils/');
  52315. registerPrimitive('a-image', utils.extendDeep({}, getMeshMixin(), {
  52316. defaultComponents: {
  52317. geometry: {
  52318. primitive: 'plane'
  52319. },
  52320. material: {
  52321. color: '#FFF',
  52322. shader: 'flat',
  52323. side: 'double',
  52324. transparent: true
  52325. }
  52326. },
  52327. mappings: {
  52328. height: 'geometry.height',
  52329. width: 'geometry.width'
  52330. }
  52331. }));
  52332. },{"../../../utils/":172,"../getMeshMixin":115,"../primitives":117}],124:[function(_dereq_,module,exports){
  52333. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52334. registerPrimitive('a-light', {
  52335. defaultComponents: {
  52336. light: {}
  52337. },
  52338. mappings: {
  52339. angle: 'light.angle',
  52340. color: 'light.color',
  52341. 'ground-color': 'light.groundColor',
  52342. decay: 'light.decay',
  52343. distance: 'light.distance',
  52344. intensity: 'light.intensity',
  52345. penumbra: 'light.penumbra',
  52346. type: 'light.type',
  52347. target: 'light.target'
  52348. }
  52349. });
  52350. },{"../primitives":117}],125:[function(_dereq_,module,exports){
  52351. var meshMixin = _dereq_('../getMeshMixin')();
  52352. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52353. var utils = _dereq_('../../../utils/');
  52354. registerPrimitive('a-obj-model', utils.extendDeep({}, meshMixin, {
  52355. defaultComponents: {
  52356. 'obj-model': {}
  52357. },
  52358. mappings: {
  52359. src: 'obj-model.obj',
  52360. mtl: 'obj-model.mtl'
  52361. }
  52362. }));
  52363. },{"../../../utils/":172,"../getMeshMixin":115,"../primitives":117}],126:[function(_dereq_,module,exports){
  52364. var getMeshMixin = _dereq_('../getMeshMixin');
  52365. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52366. var utils = _dereq_('../../../utils/');
  52367. var meshPrimitives = _dereq_('./meshPrimitives');
  52368. registerPrimitive('a-sky', utils.extendDeep({}, getMeshMixin(), {
  52369. defaultComponents: {
  52370. geometry: {
  52371. primitive: 'sphere',
  52372. radius: 5000,
  52373. segmentsWidth: 64,
  52374. segmentsHeight: 32
  52375. },
  52376. material: {
  52377. color: '#FFF',
  52378. shader: 'flat',
  52379. npot: true
  52380. },
  52381. scale: '-1 1 1'
  52382. },
  52383. mappings: utils.extendDeep({}, meshPrimitives['a-sphere'].prototype.mappings)
  52384. }));
  52385. },{"../../../utils/":172,"../getMeshMixin":115,"../primitives":117,"./meshPrimitives":131}],127:[function(_dereq_,module,exports){
  52386. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52387. registerPrimitive('a-sound', {
  52388. defaultComponents: {
  52389. sound: {}
  52390. },
  52391. mappings: {
  52392. src: 'sound.src',
  52393. on: 'sound.on',
  52394. autoplay: 'sound.autoplay',
  52395. loop: 'sound.loop',
  52396. volume: 'sound.volume'
  52397. }
  52398. });
  52399. },{"../primitives":117}],128:[function(_dereq_,module,exports){
  52400. // <a-text> using `definePrimitive` helper.
  52401. var definePrimitive = _dereq_('../primitives').definePrimitive;
  52402. definePrimitive('a-text', {text: {anchor: 'align', width: 5}});
  52403. },{"../primitives":117}],129:[function(_dereq_,module,exports){
  52404. var getMeshMixin = _dereq_('../getMeshMixin');
  52405. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52406. var utils = _dereq_('../../../utils/');
  52407. registerPrimitive('a-video', utils.extendDeep({}, getMeshMixin(), {
  52408. defaultComponents: {
  52409. geometry: {
  52410. primitive: 'plane'
  52411. },
  52412. material: {
  52413. color: '#FFF',
  52414. shader: 'flat',
  52415. side: 'double',
  52416. transparent: true
  52417. }
  52418. },
  52419. mappings: {
  52420. height: 'geometry.height',
  52421. width: 'geometry.width'
  52422. }
  52423. }));
  52424. },{"../../../utils/":172,"../getMeshMixin":115,"../primitives":117}],130:[function(_dereq_,module,exports){
  52425. var getMeshMixin = _dereq_('../getMeshMixin');
  52426. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52427. var utils = _dereq_('../../../utils/');
  52428. registerPrimitive('a-videosphere', utils.extendDeep({}, getMeshMixin(), {
  52429. defaultComponents: {
  52430. geometry: {
  52431. primitive: 'sphere',
  52432. radius: 5000,
  52433. segmentsWidth: 64,
  52434. segmentsHeight: 32
  52435. },
  52436. material: {
  52437. color: '#FFF',
  52438. shader: 'flat',
  52439. npot: true
  52440. },
  52441. scale: '-1 1 1'
  52442. },
  52443. mappings: {
  52444. radius: 'geometry.radius',
  52445. 'segments-height': 'geometry.segmentsHeight',
  52446. 'segments-width': 'geometry.segmentsWidth'
  52447. }
  52448. }));
  52449. },{"../../../utils/":172,"../getMeshMixin":115,"../primitives":117}],131:[function(_dereq_,module,exports){
  52450. /**
  52451. * Automated mesh primitive registration.
  52452. */
  52453. var getMeshMixin = _dereq_('../getMeshMixin');
  52454. var geometries = _dereq_('../../../core/geometry').geometries;
  52455. var geometryNames = _dereq_('../../../core/geometry').geometryNames;
  52456. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52457. var utils = _dereq_('../../../utils/');
  52458. // For testing.
  52459. var meshPrimitives = module.exports = {};
  52460. // Generate primitive for each geometry type.
  52461. geometryNames.forEach(function registerMeshPrimitive (geometryName) {
  52462. var geometry = geometries[geometryName];
  52463. var geometryHyphened = unCamelCase(geometryName);
  52464. // Generate mappings.
  52465. var mappings = {};
  52466. Object.keys(geometry.schema).forEach(function createMapping (property) {
  52467. mappings[unCamelCase(property)] = 'geometry.' + property;
  52468. });
  52469. // Register.
  52470. var tagName = 'a-' + geometryHyphened;
  52471. var primitive = registerPrimitive(tagName, utils.extendDeep({}, getMeshMixin(), {
  52472. defaultComponents: {geometry: {primitive: geometryName}},
  52473. mappings: mappings
  52474. }));
  52475. meshPrimitives[tagName] = primitive;
  52476. });
  52477. /**
  52478. * camelCase to hyphened-string.
  52479. */
  52480. function unCamelCase (str) {
  52481. return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  52482. }
  52483. },{"../../../core/geometry":103,"../../../utils/":172,"../getMeshMixin":115,"../primitives":117}],132:[function(_dereq_,module,exports){
  52484. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52485. var THREE = _dereq_('../lib/three');
  52486. registerGeometry('box', {
  52487. schema: {
  52488. depth: {default: 1, min: 0},
  52489. height: {default: 1, min: 0},
  52490. width: {default: 1, min: 0},
  52491. segmentsHeight: {default: 1, min: 1, max: 20, type: 'int'},
  52492. segmentsWidth: {default: 1, min: 1, max: 20, type: 'int'},
  52493. segmentsDepth: {default: 1, min: 1, max: 20, type: 'int'}
  52494. },
  52495. init: function (data) {
  52496. this.geometry = new THREE.BoxGeometry(data.width, data.height, data.depth);
  52497. }
  52498. });
  52499. },{"../core/geometry":103,"../lib/three":149}],133:[function(_dereq_,module,exports){
  52500. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52501. var THREE = _dereq_('../lib/three');
  52502. var degToRad = THREE.Math.degToRad;
  52503. registerGeometry('circle', {
  52504. schema: {
  52505. radius: {default: 1, min: 0},
  52506. segments: {default: 32, min: 3, type: 'int'},
  52507. thetaLength: {default: 360, min: 0},
  52508. thetaStart: {default: 0}
  52509. },
  52510. init: function (data) {
  52511. this.geometry = new THREE.CircleGeometry(
  52512. data.radius, data.segments, degToRad(data.thetaStart), degToRad(data.thetaLength));
  52513. }
  52514. });
  52515. },{"../core/geometry":103,"../lib/three":149}],134:[function(_dereq_,module,exports){
  52516. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52517. var THREE = _dereq_('../lib/three');
  52518. var degToRad = THREE.Math.degToRad;
  52519. registerGeometry('cone', {
  52520. schema: {
  52521. height: {default: 1, min: 0},
  52522. openEnded: {default: false},
  52523. radiusBottom: {default: 1, min: 0},
  52524. radiusTop: {default: 0.01, min: 0},
  52525. segmentsHeight: {default: 18, min: 1, type: 'int'},
  52526. segmentsRadial: {default: 36, min: 3, type: 'int'},
  52527. thetaLength: {default: 360, min: 0},
  52528. thetaStart: {default: 0}
  52529. },
  52530. init: function (data) {
  52531. this.geometry = new THREE.CylinderGeometry(
  52532. data.radiusTop, data.radiusBottom, data.height, data.segmentsRadial,
  52533. data.segmentsHeight, data.openEnded, degToRad(data.thetaStart),
  52534. degToRad(data.thetaLength));
  52535. }
  52536. });
  52537. },{"../core/geometry":103,"../lib/three":149}],135:[function(_dereq_,module,exports){
  52538. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52539. var THREE = _dereq_('../lib/three');
  52540. var degToRad = THREE.Math.degToRad;
  52541. registerGeometry('cylinder', {
  52542. schema: {
  52543. height: {default: 1, min: 0},
  52544. openEnded: {default: false},
  52545. radius: {default: 1, min: 0},
  52546. segmentsHeight: {default: 18, min: 1, type: 'int'},
  52547. segmentsRadial: {default: 36, min: 3, type: 'int'},
  52548. thetaLength: {default: 360, min: 0},
  52549. thetaStart: {default: 0}
  52550. },
  52551. init: function (data) {
  52552. this.geometry = new THREE.CylinderGeometry(
  52553. data.radius, data.radius, data.height, data.segmentsRadial, data.segmentsHeight,
  52554. data.openEnded, degToRad(data.thetaStart), degToRad(data.thetaLength));
  52555. }
  52556. });
  52557. },{"../core/geometry":103,"../lib/three":149}],136:[function(_dereq_,module,exports){
  52558. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52559. var THREE = _dereq_('../lib/three');
  52560. registerGeometry('dodecahedron', {
  52561. schema: {
  52562. detail: {default: 0, min: 0, max: 5, type: 'int'},
  52563. radius: {default: 1, min: 0}
  52564. },
  52565. init: function (data) {
  52566. this.geometry = new THREE.DodecahedronGeometry(data.radius, data.detail);
  52567. }
  52568. });
  52569. },{"../core/geometry":103,"../lib/three":149}],137:[function(_dereq_,module,exports){
  52570. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52571. var THREE = _dereq_('../lib/three');
  52572. registerGeometry('icosahedron', {
  52573. schema: {
  52574. detail: {default: 0, min: 0, max: 5, type: 'int'},
  52575. radius: {default: 1, min: 0}
  52576. },
  52577. init: function (data) {
  52578. this.geometry = new THREE.IcosahedronGeometry(data.radius, data.detail);
  52579. }
  52580. });
  52581. },{"../core/geometry":103,"../lib/three":149}],138:[function(_dereq_,module,exports){
  52582. _dereq_('./box.js');
  52583. _dereq_('./circle.js');
  52584. _dereq_('./cone.js');
  52585. _dereq_('./cylinder.js');
  52586. _dereq_('./dodecahedron.js');
  52587. _dereq_('./icosahedron.js');
  52588. _dereq_('./octahedron.js');
  52589. _dereq_('./plane.js');
  52590. _dereq_('./ring.js');
  52591. _dereq_('./sphere.js');
  52592. _dereq_('./tetrahedron.js');
  52593. _dereq_('./torus.js');
  52594. _dereq_('./torusKnot.js');
  52595. _dereq_('./triangle.js');
  52596. },{"./box.js":132,"./circle.js":133,"./cone.js":134,"./cylinder.js":135,"./dodecahedron.js":136,"./icosahedron.js":137,"./octahedron.js":139,"./plane.js":140,"./ring.js":141,"./sphere.js":142,"./tetrahedron.js":143,"./torus.js":144,"./torusKnot.js":145,"./triangle.js":146}],139:[function(_dereq_,module,exports){
  52597. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52598. var THREE = _dereq_('../lib/three');
  52599. registerGeometry('octahedron', {
  52600. schema: {
  52601. detail: {default: 0, min: 0, max: 5, type: 'int'},
  52602. radius: {default: 1, min: 0}
  52603. },
  52604. init: function (data) {
  52605. this.geometry = new THREE.OctahedronGeometry(data.radius, data.detail);
  52606. }
  52607. });
  52608. },{"../core/geometry":103,"../lib/three":149}],140:[function(_dereq_,module,exports){
  52609. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52610. var THREE = _dereq_('../lib/three');
  52611. registerGeometry('plane', {
  52612. schema: {
  52613. height: {default: 1, min: 0},
  52614. width: {default: 1, min: 0},
  52615. segmentsHeight: {default: 1, min: 1, max: 20, type: 'int'},
  52616. segmentsWidth: {default: 1, min: 1, max: 20, type: 'int'}
  52617. },
  52618. init: function (data) {
  52619. this.geometry = new THREE.PlaneGeometry(data.width, data.height, data.segmentsWidth, data.segmentsHeight);
  52620. }
  52621. });
  52622. },{"../core/geometry":103,"../lib/three":149}],141:[function(_dereq_,module,exports){
  52623. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52624. var THREE = _dereq_('../lib/three');
  52625. var degToRad = THREE.Math.degToRad;
  52626. registerGeometry('ring', {
  52627. schema: {
  52628. radiusInner: {default: 0.8, min: 0},
  52629. radiusOuter: {default: 1.2, min: 0},
  52630. segmentsPhi: {default: 10, min: 1, type: 'int'},
  52631. segmentsTheta: {default: 32, min: 3, type: 'int'},
  52632. thetaLength: {default: 360, min: 0},
  52633. thetaStart: {default: 0}
  52634. },
  52635. init: function (data) {
  52636. this.geometry = new THREE.RingGeometry(
  52637. data.radiusInner, data.radiusOuter, data.segmentsTheta, data.segmentsPhi,
  52638. degToRad(data.thetaStart), degToRad(data.thetaLength));
  52639. }
  52640. });
  52641. },{"../core/geometry":103,"../lib/three":149}],142:[function(_dereq_,module,exports){
  52642. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52643. var THREE = _dereq_('../lib/three');
  52644. var degToRad = THREE.Math.degToRad;
  52645. registerGeometry('sphere', {
  52646. schema: {
  52647. radius: {default: 1, min: 0},
  52648. phiLength: {default: 360},
  52649. phiStart: {default: 0, min: 0},
  52650. thetaLength: {default: 180, min: 0},
  52651. thetaStart: {default: 0},
  52652. segmentsHeight: {default: 18, min: 2, type: 'int'},
  52653. segmentsWidth: {default: 36, min: 3, type: 'int'}
  52654. },
  52655. init: function (data) {
  52656. this.geometry = new THREE.SphereGeometry(
  52657. data.radius, data.segmentsWidth, data.segmentsHeight, degToRad(data.phiStart),
  52658. degToRad(data.phiLength), degToRad(data.thetaStart), degToRad(data.thetaLength));
  52659. }
  52660. });
  52661. },{"../core/geometry":103,"../lib/three":149}],143:[function(_dereq_,module,exports){
  52662. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52663. var THREE = _dereq_('../lib/three');
  52664. registerGeometry('tetrahedron', {
  52665. schema: {
  52666. detail: {default: 0, min: 0, max: 5, type: 'int'},
  52667. radius: {default: 1, min: 0}
  52668. },
  52669. init: function (data) {
  52670. this.geometry = new THREE.TetrahedronGeometry(data.radius, data.detail);
  52671. }
  52672. });
  52673. },{"../core/geometry":103,"../lib/three":149}],144:[function(_dereq_,module,exports){
  52674. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52675. var THREE = _dereq_('../lib/three');
  52676. var degToRad = THREE.Math.degToRad;
  52677. registerGeometry('torus', {
  52678. schema: {
  52679. arc: {default: 360},
  52680. radius: {default: 1, min: 0},
  52681. radiusTubular: {default: 0.2, min: 0},
  52682. segmentsRadial: {default: 36, min: 2, type: 'int'},
  52683. segmentsTubular: {default: 32, min: 3, type: 'int'}
  52684. },
  52685. init: function (data) {
  52686. this.geometry = new THREE.TorusGeometry(
  52687. data.radius, data.radiusTubular * 2, data.segmentsRadial, data.segmentsTubular,
  52688. degToRad(data.arc));
  52689. }
  52690. });
  52691. },{"../core/geometry":103,"../lib/three":149}],145:[function(_dereq_,module,exports){
  52692. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52693. var THREE = _dereq_('../lib/three');
  52694. registerGeometry('torusKnot', {
  52695. schema: {
  52696. p: {default: 2, min: 1},
  52697. q: {default: 3, min: 1},
  52698. radius: {default: 1, min: 0},
  52699. radiusTubular: {default: 0.2, min: 0},
  52700. segmentsRadial: {default: 8, min: 3, type: 'int'},
  52701. segmentsTubular: {default: 100, min: 3, type: 'int'}
  52702. },
  52703. init: function (data) {
  52704. this.geometry = new THREE.TorusKnotGeometry(
  52705. data.radius, data.radiusTubular * 2, data.segmentsTubular, data.segmentsRadial,
  52706. data.p, data.q);
  52707. }
  52708. });
  52709. },{"../core/geometry":103,"../lib/three":149}],146:[function(_dereq_,module,exports){
  52710. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52711. var THREE = _dereq_('../lib/three');
  52712. var quaternion = new THREE.Quaternion();
  52713. var rotateVector = new THREE.Vector3(0, 0, 1);
  52714. var uvMinVector = new THREE.Vector2();
  52715. var uvMaxVector = new THREE.Vector2();
  52716. var uvScaleVector = new THREE.Vector2();
  52717. registerGeometry('triangle', {
  52718. schema: {
  52719. vertexA: {type: 'vec3', default: {x: 0, y: 0.5, z: 0}},
  52720. vertexB: {type: 'vec3', default: {x: -0.5, y: -0.5, z: 0}},
  52721. vertexC: {type: 'vec3', default: {x: 0.5, y: -0.5, z: 0}}
  52722. },
  52723. init: function (data) {
  52724. var geometry;
  52725. var normal;
  52726. var triangle;
  52727. var uvA;
  52728. var uvB;
  52729. var uvC;
  52730. triangle = new THREE.Triangle();
  52731. triangle.a.set(data.vertexA.x, data.vertexA.y, data.vertexA.z);
  52732. triangle.b.set(data.vertexB.x, data.vertexB.y, data.vertexB.z);
  52733. triangle.c.set(data.vertexC.x, data.vertexC.y, data.vertexC.z);
  52734. normal = triangle.normal();
  52735. // Rotate the 3D triangle to be parallel to XY plane.
  52736. quaternion.setFromUnitVectors(normal, rotateVector);
  52737. uvA = triangle.a.clone().applyQuaternion(quaternion);
  52738. uvB = triangle.b.clone().applyQuaternion(quaternion);
  52739. uvC = triangle.c.clone().applyQuaternion(quaternion);
  52740. // Compute UVs.
  52741. // Normalize x/y values of UV so they are within 0 to 1.
  52742. uvMinVector.set(Math.min(uvA.x, uvB.x, uvC.x), Math.min(uvA.y, uvB.y, uvC.y));
  52743. uvMaxVector.set(Math.max(uvA.x, uvB.x, uvC.x), Math.max(uvA.y, uvB.y, uvC.y));
  52744. uvScaleVector.set(0, 0).subVectors(uvMaxVector, uvMinVector);
  52745. uvA = new THREE.Vector2().subVectors(uvA, uvMinVector).divide(uvScaleVector);
  52746. uvB = new THREE.Vector2().subVectors(uvB, uvMinVector).divide(uvScaleVector);
  52747. uvC = new THREE.Vector2().subVectors(uvC, uvMinVector).divide(uvScaleVector);
  52748. geometry = this.geometry = new THREE.Geometry();
  52749. geometry.vertices.push(triangle.a);
  52750. geometry.vertices.push(triangle.b);
  52751. geometry.vertices.push(triangle.c);
  52752. geometry.faces.push(new THREE.Face3(0, 1, 2, normal));
  52753. geometry.faceVertexUvs[0] = [[uvA, uvB, uvC]];
  52754. }
  52755. });
  52756. },{"../core/geometry":103,"../lib/three":149}],147:[function(_dereq_,module,exports){
  52757. var utils = _dereq_('./utils/');
  52758. var debug = utils.debug;
  52759. var error = debug('A-Frame:error');
  52760. var warn = debug('A-Frame:warn');
  52761. if (document.currentScript && document.currentScript.parentNode !== document.head &&
  52762. !window.debug) {
  52763. warn('Put the A-Frame <script> tag in the <head> of the HTML *before* the scene to ' +
  52764. 'ensure everything for A-Frame is properly registered before they are used from ' +
  52765. 'HTML.');
  52766. }
  52767. // Error if not using a server.
  52768. if (window.location.protocol === 'file:') {
  52769. error(
  52770. 'This HTML file is currently being served via the file:// protocol. ' +
  52771. 'Assets, textures, and models WILL NOT WORK due to cross-origin policy! ' +
  52772. 'Please use a local or hosted server: ' +
  52773. 'https://aframe.io/docs/0.5.0/introduction/getting-started.html#using-a-local-server.');
  52774. }
  52775. // Polyfill `Promise`.
  52776. window.Promise = window.Promise || _dereq_('promise-polyfill');
  52777. // Check before the polyfill runs.
  52778. window.hasNativeWebVRImplementation = !!navigator.getVRDisplays || !!navigator.getVRDevices;
  52779. window.WebVRConfig = window.WebVRConfig || {
  52780. BUFFER_SCALE: 1,
  52781. CARDBOARD_UI_DISABLED: true,
  52782. ROTATE_INSTRUCTIONS_DISABLED: true,
  52783. TOUCH_PANNER_DISABLED: true,
  52784. MOUSE_KEYBOARD_CONTROLS_DISABLED: true
  52785. };
  52786. // Workaround for iOS Safari canvas sizing issues in stereo (webvr-polyfill/issues/102).
  52787. // Only for iOS on versions older than 10.
  52788. if (utils.device.isIOSOlderThan10(navigator.userAgent)) {
  52789. window.WebVRConfig.BUFFER_SCALE = 1 / window.devicePixelRatio;
  52790. }
  52791. // WebVR polyfill
  52792. _dereq_('webvr-polyfill');
  52793. _dereq_('present'); // Polyfill `performance.now()`.
  52794. // CSS.
  52795. if (utils.device.isBrowserEnvironment) {
  52796. _dereq_('./style/aframe.css');
  52797. _dereq_('./style/rStats.css');
  52798. }
  52799. // Required before `AEntity` so that all components are registered.
  52800. var AScene = _dereq_('./core/scene/a-scene').AScene;
  52801. var components = _dereq_('./core/component').components;
  52802. var registerComponent = _dereq_('./core/component').registerComponent;
  52803. var registerGeometry = _dereq_('./core/geometry').registerGeometry;
  52804. var registerPrimitive = _dereq_('./extras/primitives/primitives').registerPrimitive;
  52805. var registerShader = _dereq_('./core/shader').registerShader;
  52806. var registerSystem = _dereq_('./core/system').registerSystem;
  52807. var shaders = _dereq_('./core/shader').shaders;
  52808. var systems = _dereq_('./core/system').systems;
  52809. // Exports THREE to window so three.js can be used without alteration.
  52810. var THREE = window.THREE = _dereq_('./lib/three');
  52811. var TWEEN = window.TWEEN = _dereq_('tween.js');
  52812. var pkg = _dereq_('../package');
  52813. _dereq_('./components/index'); // Register standard components.
  52814. _dereq_('./geometries/index'); // Register standard geometries.
  52815. _dereq_('./shaders/index'); // Register standard shaders.
  52816. _dereq_('./systems/index'); // Register standard systems.
  52817. var ANode = _dereq_('./core/a-node');
  52818. var AEntity = _dereq_('./core/a-entity'); // Depends on ANode and core components.
  52819. _dereq_('./core/a-animation');
  52820. _dereq_('./core/a-assets');
  52821. _dereq_('./core/a-cubemap');
  52822. _dereq_('./core/a-mixin');
  52823. // Extras.
  52824. _dereq_('./extras/components/');
  52825. _dereq_('./extras/primitives/');
  52826. console.log('A-Frame Version: 0.5.0 (Date 01-06-2017, Commit #e6b5935)');
  52827. console.log('three Version:', pkg.dependencies['three']);
  52828. console.log('WebVR Polyfill Version:', pkg.dependencies['webvr-polyfill']);
  52829. module.exports = window.AFRAME = {
  52830. AComponent: _dereq_('./core/component').Component,
  52831. AEntity: AEntity,
  52832. ANode: ANode,
  52833. AScene: AScene,
  52834. components: components,
  52835. geometries: _dereq_('./core/geometry').geometries,
  52836. registerComponent: registerComponent,
  52837. registerElement: _dereq_('./core/a-register-element').registerElement,
  52838. registerGeometry: registerGeometry,
  52839. registerPrimitive: registerPrimitive,
  52840. registerShader: registerShader,
  52841. registerSystem: registerSystem,
  52842. primitives: {
  52843. getMeshMixin: _dereq_('./extras/primitives/getMeshMixin'),
  52844. primitives: _dereq_('./extras/primitives/primitives').primitives
  52845. },
  52846. scenes: _dereq_('./core/scene/scenes'),
  52847. schema: _dereq_('./core/schema'),
  52848. shaders: shaders,
  52849. systems: systems,
  52850. THREE: THREE,
  52851. TWEEN: TWEEN,
  52852. utils: utils,
  52853. version: pkg.version
  52854. };
  52855. },{"../package":54,"./components/index":64,"./core/a-animation":95,"./core/a-assets":96,"./core/a-cubemap":97,"./core/a-entity":98,"./core/a-mixin":99,"./core/a-node":100,"./core/a-register-element":101,"./core/component":102,"./core/geometry":103,"./core/scene/a-scene":105,"./core/scene/scenes":108,"./core/schema":110,"./core/shader":111,"./core/system":112,"./extras/components/":113,"./extras/primitives/":116,"./extras/primitives/getMeshMixin":115,"./extras/primitives/primitives":117,"./geometries/index":138,"./lib/three":149,"./shaders/index":151,"./style/aframe.css":156,"./style/rStats.css":157,"./systems/index":161,"./utils/":172,"present":32,"promise-polyfill":34,"tween.js":48,"webvr-polyfill":49}],148:[function(_dereq_,module,exports){
  52856. window.aframeStats = function (scene) {
  52857. var _rS = null;
  52858. var _scene = scene;
  52859. var _values = {
  52860. te: {
  52861. caption: 'Entities'
  52862. },
  52863. lt: {
  52864. caption: 'Load Time'
  52865. }
  52866. };
  52867. var _groups = [ {
  52868. caption: 'A-Frame',
  52869. values: [ 'te', 'lt' ]
  52870. } ];
  52871. function _update () {
  52872. _rS('te').set(getEntityCount());
  52873. if (window.performance.getEntriesByName) {
  52874. _rS('lt').set(window.performance.getEntriesByName('render-started')[0].startTime.toFixed(0));
  52875. }
  52876. }
  52877. function getEntityCount () {
  52878. var elements = _scene.querySelectorAll('*');
  52879. Array.prototype.slice.call(elements).filter(function (el) {
  52880. return el.isEntity;
  52881. });
  52882. return elements.length;
  52883. }
  52884. function _start () {}
  52885. function _end () {}
  52886. function _attach (r) {
  52887. _rS = r;
  52888. }
  52889. return {
  52890. update: _update,
  52891. start: _start,
  52892. end: _end,
  52893. attach: _attach,
  52894. values: _values,
  52895. groups: _groups,
  52896. fractions: []
  52897. };
  52898. };
  52899. if (typeof module === 'object') {
  52900. module.exports = {
  52901. aframeStats: window.aframeStats
  52902. };
  52903. }
  52904. },{}],149:[function(_dereq_,module,exports){
  52905. (function (global){
  52906. var THREE = global.THREE = _dereq_('three');
  52907. // Allow cross-origin images to be loaded.
  52908. // This should not be on `THREE.Loader` nor `THREE.ImageUtils`.
  52909. // Must be on `THREE.TextureLoader`.
  52910. if (THREE.TextureLoader) {
  52911. THREE.TextureLoader.prototype.crossOrigin = 'anonymous';
  52912. }
  52913. // This is for images loaded from the model loaders.
  52914. if (THREE.ImageLoader) {
  52915. THREE.ImageLoader.prototype.crossOrigin = 'anonymous';
  52916. }
  52917. // In-memory caching for XHRs (for images, audio files, textures, etc.).
  52918. if (THREE.Cache) {
  52919. THREE.Cache.enabled = true;
  52920. }
  52921. // TODO: Eventually include these only if they are needed by a component.
  52922. _dereq_('three/examples/js/loaders/GLTFLoader'); // THREE.GLTFLoader
  52923. _dereq_('three/examples/js/loaders/OBJLoader'); // THREE.OBJLoader
  52924. _dereq_('three/examples/js/loaders/MTLLoader'); // THREE.MTLLoader
  52925. _dereq_('three/examples/js/BlendCharacter'); // THREE.BlendCharacter
  52926. _dereq_('three/examples/js/loaders/ColladaLoader'); // THREE.ColladaLoader
  52927. _dereq_('../../vendor/VRControls'); // THREE.VRControls
  52928. _dereq_('../../vendor/VREffect'); // THREE.VREffect
  52929. THREE.ColladaLoader.prototype.crossOrigin = 'anonymous';
  52930. THREE.GLTFLoader.prototype.crossOrigin = 'anonymous';
  52931. THREE.MTLLoader.prototype.crossOrigin = 'anonymous';
  52932. THREE.OBJLoader.prototype.crossOrigin = 'anonymous';
  52933. module.exports = THREE;
  52934. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  52935. },{"../../vendor/VRControls":177,"../../vendor/VREffect":178,"three":41,"three/examples/js/BlendCharacter":42,"three/examples/js/loaders/ColladaLoader":43,"three/examples/js/loaders/GLTFLoader":44,"three/examples/js/loaders/MTLLoader":45,"three/examples/js/loaders/OBJLoader":46}],150:[function(_dereq_,module,exports){
  52936. var registerShader = _dereq_('../core/shader').registerShader;
  52937. var THREE = _dereq_('../lib/three');
  52938. var utils = _dereq_('../utils/');
  52939. /**
  52940. * Flat shader using THREE.MeshBasicMaterial.
  52941. */
  52942. module.exports.Shader = registerShader('flat', {
  52943. schema: {
  52944. color: {type: 'color'},
  52945. fog: {default: true},
  52946. height: {default: 256},
  52947. offset: {type: 'vec2', default: {x: 0, y: 0}},
  52948. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  52949. src: {type: 'map'},
  52950. width: {default: 512},
  52951. wireframe: {default: false},
  52952. wireframeLinewidth: {default: 2}
  52953. },
  52954. /**
  52955. * Initializes the shader.
  52956. * Adds a reference from the scene to this entity as the camera.
  52957. */
  52958. init: function (data) {
  52959. this.textureSrc = null;
  52960. this.material = new THREE.MeshBasicMaterial(getMaterialData(data));
  52961. utils.material.updateMap(this, data);
  52962. },
  52963. update: function (data) {
  52964. this.updateMaterial(data);
  52965. utils.material.updateMap(this, data);
  52966. },
  52967. /**
  52968. * Updating existing material.
  52969. *
  52970. * @param {object} data - Material component data.
  52971. */
  52972. updateMaterial: function (data) {
  52973. var material = this.material;
  52974. data = getMaterialData(data);
  52975. Object.keys(data).forEach(function (key) {
  52976. material[key] = data[key];
  52977. });
  52978. }
  52979. });
  52980. /**
  52981. * Builds and normalize material data, normalizing stuff along the way.
  52982. *
  52983. * @param {object} data - Material data.
  52984. * @returns {object} data - Processed material data.
  52985. */
  52986. function getMaterialData (data) {
  52987. return {
  52988. fog: data.fog,
  52989. color: new THREE.Color(data.color),
  52990. wireframe: data.wireframe,
  52991. wireframeLinewidth: data.wireframeLinewidth
  52992. };
  52993. }
  52994. },{"../core/shader":111,"../lib/three":149,"../utils/":172}],151:[function(_dereq_,module,exports){
  52995. _dereq_('./flat');
  52996. _dereq_('./standard');
  52997. _dereq_('./sdf');
  52998. _dereq_('./msdf');
  52999. _dereq_('./ios10hls');
  53000. },{"./flat":150,"./ios10hls":152,"./msdf":153,"./sdf":154,"./standard":155}],152:[function(_dereq_,module,exports){
  53001. var registerShader = _dereq_('../core/shader').registerShader;
  53002. /**
  53003. * Custom shader for iOS 10 HTTP Live Streaming (HLS).
  53004. * For more information on HLS, see https://datatracker.ietf.org/doc/draft-pantos-http-live-streaming/
  53005. */
  53006. module.exports.Shader = registerShader('ios10hls', {
  53007. schema: {
  53008. src: {type: 'map', is: 'uniform'},
  53009. opacity: {type: 'number', is: 'uniform', default: 1}
  53010. },
  53011. vertexShader: [
  53012. 'varying vec2 vUV;',
  53013. 'void main(void) {',
  53014. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  53015. ' vUV = uv;',
  53016. '}'
  53017. ].join('\n'),
  53018. fragmentShader: [
  53019. 'uniform sampler2D src;',
  53020. 'uniform float opacity;',
  53021. 'varying vec2 vUV;',
  53022. 'void main() {',
  53023. ' vec2 offset = vec2(0, 0);',
  53024. ' vec2 repeat = vec2(1, 1);',
  53025. ' vec4 color = texture2D(src, vec2(vUV.x / repeat.x + offset.x, (1.0 - vUV.y) / repeat.y + offset.y)).bgra;',
  53026. ' gl_FragColor = vec4(color.rgb, opacity);',
  53027. '}'
  53028. ].join('\n')
  53029. });
  53030. },{"../core/shader":111}],153:[function(_dereq_,module,exports){
  53031. var registerShader = _dereq_('../core/shader').registerShader;
  53032. /**
  53033. * Multi-channel signed distance field.
  53034. * Used by text component.
  53035. */
  53036. module.exports.Shader = registerShader('msdf', {
  53037. schema: {
  53038. alphaTest: {type: 'number', is: 'uniform', default: 0.5},
  53039. color: {type: 'color', is: 'uniform', default: 'white'},
  53040. map: {type: 'map', is: 'uniform'},
  53041. opacity: {type: 'number', is: 'uniform', default: 1.0}
  53042. },
  53043. raw: true,
  53044. vertexShader: [
  53045. 'attribute vec2 uv;',
  53046. 'attribute vec3 position;',
  53047. 'uniform mat4 projectionMatrix;',
  53048. 'uniform mat4 modelViewMatrix;',
  53049. 'varying vec2 vUV;',
  53050. 'void main(void) {',
  53051. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  53052. ' vUV = uv;',
  53053. '}'
  53054. ].join('\n'),
  53055. fragmentShader: [
  53056. '#ifdef GL_OES_standard_derivatives',
  53057. '#extension GL_OES_standard_derivatives: enable',
  53058. '#endif',
  53059. 'precision highp float;',
  53060. // FIXME: Experimentally determined constants.
  53061. '#define BIG_ENOUGH 0.001',
  53062. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  53063. '#define ALL_SMOOTH 0.4',
  53064. '#define ALL_ROUGH 0.02',
  53065. '#define DISCARD_ALPHA (alphaTest / (2.2 - 1.2 * ratio))',
  53066. 'uniform sampler2D map;',
  53067. 'uniform vec3 color;',
  53068. 'uniform float opacity;',
  53069. 'uniform float alphaTest;',
  53070. 'varying vec2 vUV;',
  53071. 'float median(float r, float g, float b) {',
  53072. ' return max(min(r, g), min(max(r, g), b));',
  53073. '}',
  53074. 'void main() {',
  53075. ' vec3 sample = 1.0 - texture2D(map, vUV).rgb;',
  53076. ' float sigDist = median(sample.r, sample.g, sample.b) - 0.5;',
  53077. ' float alpha = clamp(sigDist/fwidth(sigDist) + 0.5, 0.0, 1.0);',
  53078. ' float dscale = 0.353505;',
  53079. ' vec2 duv = dscale * (dFdx(vUV) + dFdy(vUV));',
  53080. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  53081. // When texel is too small, blend raw alpha value rather than supersampling.
  53082. // FIXME: Experimentally determined constant.
  53083. ' if (isBigEnough > BIG_ENOUGH) {',
  53084. ' float ratio = BIG_ENOUGH / isBigEnough;',
  53085. ' alpha = ratio * alpha + (1.0 - ratio) * (sigDist + 0.5);',
  53086. ' }',
  53087. // When texel is big enough, do standard alpha test.
  53088. // FIXME: Experimentally determined constant.
  53089. // Looks much better if we *don't* do this, but do we get Z fighting?
  53090. ' if (isBigEnough <= BIG_ENOUGH && alpha < alphaTest) { discard; return; }',
  53091. // Else, do modified alpha test.
  53092. // FIXME: Experimentally determined constant.
  53093. ' if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  53094. ' gl_FragColor = vec4(color.xyz, alpha * opacity);',
  53095. '}'
  53096. ].join('\n')
  53097. });
  53098. },{"../core/shader":111}],154:[function(_dereq_,module,exports){
  53099. var registerShader = _dereq_('../core/shader').registerShader;
  53100. /**
  53101. * Signed distance field.
  53102. * Used by text component.
  53103. */
  53104. module.exports.Shader = registerShader('sdf', {
  53105. schema: {
  53106. alphaTest: {type: 'number', is: 'uniform', default: 0.5},
  53107. color: {type: 'color', is: 'uniform', default: 'white'},
  53108. map: {type: 'map', is: 'uniform'},
  53109. opacity: {type: 'number', is: 'uniform', default: 1.0}
  53110. },
  53111. raw: true,
  53112. vertexShader: [
  53113. 'attribute vec2 uv;',
  53114. 'attribute vec3 position;',
  53115. 'uniform mat4 projectionMatrix;',
  53116. 'uniform mat4 modelViewMatrix;',
  53117. 'varying vec2 vUV;',
  53118. 'void main(void) {',
  53119. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  53120. ' vUV = uv;',
  53121. '}'
  53122. ].join('\n'),
  53123. fragmentShader: [
  53124. '#ifdef GL_OES_standard_derivatives',
  53125. '#extension GL_OES_standard_derivatives: enable',
  53126. '#endif',
  53127. 'precision highp float;',
  53128. // FIXME: experimentally determined constants
  53129. '#define BIG_ENOUGH 0.001',
  53130. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  53131. '#define ALL_SMOOTH 0.4',
  53132. '#define ALL_ROUGH 0.02',
  53133. '#define DISCARD_ALPHA (alphaTest / (2.2 - 1.2 * ratio))',
  53134. 'uniform sampler2D map;',
  53135. 'uniform vec3 color;',
  53136. 'uniform float opacity;',
  53137. 'uniform float alphaTest;',
  53138. 'varying vec2 vUV;',
  53139. '#ifdef GL_OES_standard_derivatives',
  53140. 'float contour(float width, float value) {',
  53141. ' return smoothstep(0.5 - value, 0.5 + value, width);',
  53142. '}',
  53143. '#else',
  53144. 'float aastep(float value, float afwidth) {',
  53145. ' return smoothstep(0.5 - afwidth, 0.5 + afwidth, value);',
  53146. '}',
  53147. '#endif',
  53148. 'void main() {',
  53149. '#ifdef GL_OES_standard_derivatives',
  53150. // when we have derivatives and can get texel size etc., that allows supersampling etc.
  53151. ' vec2 uv = vUV;',
  53152. ' vec4 texColor = texture2D(map, uv);',
  53153. ' float dist = texColor.a;',
  53154. ' float width = fwidth(dist);',
  53155. ' float alpha = contour(dist, width);',
  53156. ' float dscale = 0.353505;',
  53157. ' vec2 duv = dscale * (dFdx(uv) + dFdy(uv));',
  53158. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  53159. // when texel is too small, blend raw alpha value rather than supersampling etc.
  53160. // FIXME: experimentally determined constant
  53161. ' if (isBigEnough > BIG_ENOUGH) {',
  53162. ' float ratio = BIG_ENOUGH / isBigEnough;',
  53163. ' alpha = ratio * alpha + (1.0 - ratio) * dist;',
  53164. ' }',
  53165. // otherwise do weighted supersampling
  53166. // FIXME: why this weighting?
  53167. ' else if (isBigEnough <= BIG_ENOUGH) {',
  53168. ' vec4 box = vec4 (uv - duv, uv + duv);',
  53169. ' alpha = (alpha + 0.5 * (',
  53170. ' contour(texture2D(map, box.xy).a, width)',
  53171. ' + contour(texture2D(map, box.zw).a, width)',
  53172. ' + contour(texture2D(map, box.xw).a, width)',
  53173. ' + contour(texture2D(map, box.zy).a, width)',
  53174. ' )) / 3.0;',
  53175. ' }',
  53176. // when texel is big enough, do standard alpha test
  53177. // FIXME: experimentally determined constant
  53178. // looks much better if we DON'T do this, but do we get Z fighting etc.?
  53179. ' if (isBigEnough <= BIG_ENOUGH && alpha < alphaTest) { discard; return; }',
  53180. // else do modified alpha test
  53181. // FIXME: experimentally determined constant
  53182. ' if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  53183. '#else',
  53184. ' vec4 texColor = texture2D(map, vUV);',
  53185. ' float value = texColor.a;',
  53186. // when we don't have derivatives, use approximations
  53187. // FIXME: if we understood font pixel dimensions, this could probably be improved
  53188. ' float afwidth = (1.0 / 32.0) * (1.4142135623730951 / (2.0 * gl_FragCoord.w));',
  53189. ' float alpha = aastep(value, afwidth);',
  53190. // use gl_FragCoord.w to guess when we should blend
  53191. // FIXME: if we understood font pixel dimensions, this could probably be improved
  53192. ' 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);',
  53193. ' if (alpha < alphaTest) { if (ratio >= 1.0) { discard; return; } alpha = 0.0; }',
  53194. ' alpha = alpha * ratio + (1.0 - ratio) * value;',
  53195. ' if (ratio < 1.0)',
  53196. ' if (alpha <= DISCARD_ALPHA) { discard; return; }',
  53197. '#endif',
  53198. ' gl_FragColor = vec4(color, opacity * alpha);',
  53199. '}'
  53200. ].join('\n')
  53201. });
  53202. },{"../core/shader":111}],155:[function(_dereq_,module,exports){
  53203. var registerShader = _dereq_('../core/shader').registerShader;
  53204. var THREE = _dereq_('../lib/three');
  53205. var utils = _dereq_('../utils/');
  53206. var CubeLoader = new THREE.CubeTextureLoader();
  53207. var texturePromises = {};
  53208. /**
  53209. * Standard (physically-based) shader using THREE.MeshStandardMaterial.
  53210. */
  53211. module.exports.Shader = registerShader('standard', {
  53212. schema: {
  53213. ambientOcclusionMap: {type: 'map'},
  53214. ambientOcclusionMapIntensity: {default: 1},
  53215. ambientOcclusionTextureOffset: {type: 'vec2'},
  53216. ambientOcclusionTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  53217. color: {type: 'color'},
  53218. displacementMap: {type: 'map'},
  53219. displacementScale: {default: 1},
  53220. displacementBias: {default: 0.5},
  53221. displacementTextureOffset: {type: 'vec2'},
  53222. displacementTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  53223. envMap: {default: ''},
  53224. fog: {default: true},
  53225. height: {default: 256},
  53226. metalness: {default: 0.0, min: 0.0, max: 1.0},
  53227. normalMap: {type: 'map'},
  53228. normalScale: {type: 'vec2', default: {x: 1, y: 1}},
  53229. normalTextureOffset: {type: 'vec2'},
  53230. normalTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  53231. offset: {type: 'vec2', default: {x: 0, y: 0}},
  53232. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  53233. roughness: {default: 0.5, min: 0.0, max: 1.0},
  53234. sphericalEnvMap: {type: 'map'},
  53235. src: {type: 'map'},
  53236. width: {default: 512},
  53237. wireframe: {default: false},
  53238. wireframeLinewidth: {default: 2}
  53239. },
  53240. /**
  53241. * Initializes the shader.
  53242. * Adds a reference from the scene to this entity as the camera.
  53243. */
  53244. init: function (data) {
  53245. this.material = new THREE.MeshStandardMaterial(getMaterialData(data));
  53246. utils.material.updateMap(this, data);
  53247. if (data.normalMap) { utils.material.updateDistortionMap('normal', this, data); }
  53248. if (data.displacementMap) { utils.material.updateDistortionMap('displacement', this, data); }
  53249. if (data.ambientOcclusionMap) { utils.material.updateDistortionMap('ambientOcclusion', this, data); }
  53250. this.updateEnvMap(data);
  53251. },
  53252. update: function (data) {
  53253. this.updateMaterial(data);
  53254. utils.material.updateMap(this, data);
  53255. if (data.normalMap) { utils.material.updateDistortionMap('normal', this, data); }
  53256. if (data.displacementMap) { utils.material.updateDistortionMap('displacement', this, data); }
  53257. if (data.ambientOcclusionMap) { utils.material.updateDistortionMap('ambientOcclusion', this, data); }
  53258. this.updateEnvMap(data);
  53259. },
  53260. /**
  53261. * Updating existing material.
  53262. *
  53263. * @param {object} data - Material component data.
  53264. * @returns {object} Material.
  53265. */
  53266. updateMaterial: function (data) {
  53267. var material = this.material;
  53268. data = getMaterialData(data);
  53269. Object.keys(data).forEach(function (key) {
  53270. material[key] = data[key];
  53271. });
  53272. },
  53273. /**
  53274. * Handle environment cubemap. Textures are cached in texturePromises.
  53275. */
  53276. updateEnvMap: function (data) {
  53277. var self = this;
  53278. var material = this.material;
  53279. var envMap = data.envMap;
  53280. var sphericalEnvMap = data.sphericalEnvMap;
  53281. // No envMap defined or already loading.
  53282. if ((!envMap && !sphericalEnvMap) || this.isLoadingEnvMap) {
  53283. material.envMap = null;
  53284. material.needsUpdate = true;
  53285. return;
  53286. }
  53287. this.isLoadingEnvMap = true;
  53288. // if a spherical env map is defined then use it.
  53289. if (sphericalEnvMap) {
  53290. this.el.sceneEl.systems.material.loadTexture(sphericalEnvMap, {src: sphericalEnvMap}, function textureLoaded (texture) {
  53291. self.isLoadingEnvMap = false;
  53292. texture.mapping = THREE.SphericalReflectionMapping;
  53293. material.envMap = texture;
  53294. utils.material.handleTextureEvents(self.el, texture);
  53295. material.needsUpdate = true;
  53296. });
  53297. return;
  53298. }
  53299. // Another material is already loading this texture. Wait on promise.
  53300. if (texturePromises[envMap]) {
  53301. texturePromises[envMap].then(function (cube) {
  53302. self.isLoadingEnvMap = false;
  53303. material.envMap = cube;
  53304. utils.material.handleTextureEvents(self.el, cube);
  53305. material.needsUpdate = true;
  53306. });
  53307. return;
  53308. }
  53309. // Material is first to load this texture. Load and resolve texture.
  53310. texturePromises[envMap] = new Promise(function (resolve) {
  53311. utils.srcLoader.validateCubemapSrc(envMap, function loadEnvMap (urls) {
  53312. CubeLoader.load(urls, function (cube) {
  53313. // Texture loaded.
  53314. self.isLoadingEnvMap = false;
  53315. material.envMap = cube;
  53316. utils.material.handleTextureEvents(self.el, cube);
  53317. resolve(cube);
  53318. });
  53319. });
  53320. });
  53321. }
  53322. });
  53323. /**
  53324. * Builds and normalize material data, normalizing stuff along the way.
  53325. *
  53326. * @param {object} data - Material data.
  53327. * @returns {object} data - Processed material data.
  53328. */
  53329. function getMaterialData (data) {
  53330. var newData = {
  53331. color: new THREE.Color(data.color),
  53332. fog: data.fog,
  53333. metalness: data.metalness,
  53334. roughness: data.roughness,
  53335. wireframe: data.wireframe,
  53336. wireframeLinewidth: data.wireframeLinewidth
  53337. };
  53338. if (data.normalMap) { newData.normalScale = data.normalScale; }
  53339. if (data.ambientOcclusionMap) { newData.aoMapIntensity = data.ambientOcclusionMapIntensity; }
  53340. if (data.displacementMap) {
  53341. newData.displacementScale = data.displacementScale;
  53342. newData.displacementBias = data.displacementBias;
  53343. }
  53344. return newData;
  53345. }
  53346. },{"../core/shader":111,"../lib/three":149,"../utils/":172}],156:[function(_dereq_,module,exports){
  53347. 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;
  53348. },{"browserify-css":4}],157:[function(_dereq_,module,exports){
  53349. 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;
  53350. },{"browserify-css":4}],158:[function(_dereq_,module,exports){
  53351. var bind = _dereq_('../utils/bind');
  53352. var constants = _dereq_('../constants/');
  53353. var registerSystem = _dereq_('../core/system').registerSystem;
  53354. var DEFAULT_CAMERA_ATTR = 'data-aframe-default-camera';
  53355. /**
  53356. * Camera system. Manages which camera is active among multiple cameras in scene.
  53357. *
  53358. * @member {object} activeCameraEl - Active camera entity.
  53359. */
  53360. module.exports.System = registerSystem('camera', {
  53361. init: function () {
  53362. this.activeCameraEl = null;
  53363. // Wait for all entities to fully load before checking for existence of camera.
  53364. // Since entities wait for <a-assets> to load, any cameras attaching to the scene
  53365. // will do so asynchronously.
  53366. this.sceneEl.addEventListener('loaded', bind(this.setupDefaultCamera, this));
  53367. },
  53368. /**
  53369. * Create a default camera if user has not added one during the initial scene traversal.
  53370. *
  53371. * Default camera offset height is at average eye level (~1.6m).
  53372. */
  53373. setupDefaultCamera: function () {
  53374. var sceneEl = this.sceneEl;
  53375. var defaultCameraEl;
  53376. // Camera already defined.
  53377. if (sceneEl.camera) {
  53378. sceneEl.emit('camera-ready', {cameraEl: sceneEl.camera.el});
  53379. return;
  53380. }
  53381. // Set up default camera.
  53382. defaultCameraEl = document.createElement('a-entity');
  53383. defaultCameraEl.setAttribute('position', '0 0 0');
  53384. defaultCameraEl.setAttribute(DEFAULT_CAMERA_ATTR, '');
  53385. defaultCameraEl.setAttribute('camera', {active: true, userHeight: constants.DEFAULT_CAMERA_HEIGHT});
  53386. defaultCameraEl.setAttribute('wasd-controls', '');
  53387. defaultCameraEl.setAttribute('look-controls', '');
  53388. defaultCameraEl.setAttribute(constants.AFRAME_INJECTED, '');
  53389. sceneEl.appendChild(defaultCameraEl);
  53390. sceneEl.addEventListener('enter-vr', this.removeDefaultOffset);
  53391. sceneEl.addEventListener('exit-vr', this.addDefaultOffset);
  53392. sceneEl.emit('camera-ready', {cameraEl: defaultCameraEl});
  53393. },
  53394. /**
  53395. * Set a different active camera.
  53396. * When we choose a (sort of) random scene camera as the replacement, set its `active` to
  53397. * true. The camera component will call `setActiveCamera` and handle passing the torch to
  53398. * the new camera.
  53399. */
  53400. disableActiveCamera: function () {
  53401. var cameraEls = this.sceneEl.querySelectorAll('[camera]');
  53402. var newActiveCameraEl = cameraEls[cameraEls.length - 1];
  53403. newActiveCameraEl.setAttribute('camera', 'active', true);
  53404. },
  53405. /**
  53406. * Set active camera to be used by renderer.
  53407. * Removes the default camera (if present).
  53408. * Disables all other cameras in the scene.
  53409. *
  53410. * @param {Element} newCameraEl - Entity with camera component.
  53411. */
  53412. setActiveCamera: function (newCameraEl) {
  53413. var cameraEl;
  53414. var cameraEls;
  53415. var i;
  53416. var newCamera;
  53417. var previousCamera = this.activeCameraEl;
  53418. var sceneEl = this.sceneEl;
  53419. // Same camera.
  53420. newCamera = newCameraEl.getObject3D('camera');
  53421. if (!newCamera || newCameraEl === this.activeCameraEl) { return; }
  53422. // Grab the default camera.
  53423. var defaultCameraWrapper = sceneEl.querySelector('[' + DEFAULT_CAMERA_ATTR + ']');
  53424. var defaultCameraEl = defaultCameraWrapper &&
  53425. defaultCameraWrapper.querySelector('[camera]');
  53426. // Remove default camera if new camera is not the default camera.
  53427. if (newCameraEl !== defaultCameraEl) { removeDefaultCamera(sceneEl); }
  53428. // Make new camera active.
  53429. this.activeCameraEl = newCameraEl;
  53430. this.activeCameraEl.play();
  53431. sceneEl.camera = newCamera;
  53432. // Disable current camera
  53433. if (previousCamera) {
  53434. previousCamera.setAttribute('camera', 'active', false);
  53435. }
  53436. // Disable other cameras in the scene
  53437. cameraEls = sceneEl.querySelectorAll('[camera]');
  53438. for (i = 0; i < cameraEls.length; i++) {
  53439. cameraEl = cameraEls[i];
  53440. if (newCameraEl === cameraEl) { continue; }
  53441. cameraEl.setAttribute('camera', 'active', false);
  53442. cameraEl.pause();
  53443. }
  53444. sceneEl.emit('camera-set-active', {cameraEl: newCameraEl});
  53445. }
  53446. });
  53447. /**
  53448. * Remove injected default camera from scene, if present.
  53449. *
  53450. * @param {Element} sceneEl
  53451. */
  53452. function removeDefaultCamera (sceneEl) {
  53453. var defaultCamera;
  53454. var camera = sceneEl.camera;
  53455. if (!camera) { return; }
  53456. // Remove default camera if present.
  53457. defaultCamera = sceneEl.querySelector('[' + DEFAULT_CAMERA_ATTR + ']');
  53458. if (!defaultCamera) { return; }
  53459. sceneEl.removeChild(defaultCamera);
  53460. }
  53461. },{"../constants/":93,"../core/system":112,"../utils/bind":166}],159:[function(_dereq_,module,exports){
  53462. var geometries = _dereq_('../core/geometry').geometries;
  53463. var registerSystem = _dereq_('../core/system').registerSystem;
  53464. var THREE = _dereq_('../lib/three');
  53465. /**
  53466. * System for geometry component.
  53467. * Handle geometry caching.
  53468. *
  53469. * @member {object} cache - Mapping of stringified component data to THREE.Geometry objects.
  53470. * @member {object} cacheCount - Keep track of number of entities using a geometry to
  53471. * know whether to dispose on removal.
  53472. */
  53473. module.exports.System = registerSystem('geometry', {
  53474. init: function () {
  53475. this.cache = {};
  53476. this.cacheCount = {};
  53477. },
  53478. /**
  53479. * Reset cache. Mainly for testing.
  53480. */
  53481. clearCache: function () {
  53482. this.cache = {};
  53483. this.cacheCount = {};
  53484. },
  53485. /**
  53486. * Attempt to retrieve from cache.
  53487. *
  53488. * @returns {Object|null} A geometry if it exists, else null.
  53489. */
  53490. getOrCreateGeometry: function (data) {
  53491. var cache = this.cache;
  53492. var cachedGeometry;
  53493. var hash;
  53494. // Skip all caching logic.
  53495. if (data.skipCache || data.mergeTo) { return createGeometry(data); }
  53496. // Try to retrieve from cache first.
  53497. hash = this.hash(data);
  53498. cachedGeometry = cache[hash];
  53499. incrementCacheCount(this.cacheCount, hash);
  53500. if (cachedGeometry) { return cachedGeometry; }
  53501. // Create geometry.
  53502. cachedGeometry = createGeometry(data);
  53503. // Cache and return geometry.
  53504. cache[hash] = cachedGeometry;
  53505. return cachedGeometry;
  53506. },
  53507. /**
  53508. * Let system know that an entity is no longer using a geometry.
  53509. */
  53510. unuseGeometry: function (data) {
  53511. var cache = this.cache;
  53512. var cacheCount = this.cacheCount;
  53513. var geometry;
  53514. var hash;
  53515. if (data.skipCache || data.mergeTo) { return; }
  53516. hash = this.hash(data);
  53517. if (!cache[hash]) { return; }
  53518. decrementCacheCount(cacheCount, hash);
  53519. // Another entity is still using this geometry. No need to do anything.
  53520. if (cacheCount[hash] > 0) { return; }
  53521. // No more entities are using this geometry. Dispose.
  53522. geometry = cache[hash];
  53523. geometry.dispose();
  53524. delete cache[hash];
  53525. delete cacheCount[hash];
  53526. },
  53527. /**
  53528. * Use JSON.stringify to turn component data into hash.
  53529. * Should be deterministic within a single browser engine.
  53530. * If not, then look into json-stable-stringify.
  53531. */
  53532. hash: function (data) {
  53533. return JSON.stringify(data);
  53534. }
  53535. });
  53536. /**
  53537. * Create geometry using component data.
  53538. *
  53539. * @param {object} data - Component data.
  53540. * @returns {object} Geometry.
  53541. */
  53542. function createGeometry (data) {
  53543. var geometryType = data.primitive;
  53544. var GeometryClass = geometries[geometryType] && geometries[geometryType].Geometry;
  53545. var geometryInstance = new GeometryClass();
  53546. if (!GeometryClass) { throw new Error('Unknown geometry `' + geometryType + '`'); }
  53547. geometryInstance.init(data);
  53548. return toBufferGeometry(geometryInstance.geometry, data.buffer);
  53549. }
  53550. /**
  53551. * Decreate count of entity using a geometry.
  53552. */
  53553. function decrementCacheCount (cacheCount, hash) {
  53554. cacheCount[hash]--;
  53555. }
  53556. /**
  53557. * Increase count of entity using a geometry.
  53558. */
  53559. function incrementCacheCount (cacheCount, hash) {
  53560. cacheCount[hash] = cacheCount[hash] === undefined ? 1 : cacheCount[hash] + 1;
  53561. }
  53562. /**
  53563. * Transform geometry to BufferGeometry if `doBuffer`.
  53564. *
  53565. * @param {object} geometry
  53566. * @param {boolean} doBuffer
  53567. * @returns {object} Geometry.
  53568. */
  53569. function toBufferGeometry (geometry, doBuffer) {
  53570. var bufferGeometry;
  53571. if (!doBuffer) { return geometry; }
  53572. bufferGeometry = new THREE.BufferGeometry().fromGeometry(geometry);
  53573. bufferGeometry.metadata = {type: geometry.type, parameters: geometry.parameters || {}};
  53574. geometry.dispose(); // Dispose no longer needed non-buffer geometry.
  53575. return bufferGeometry;
  53576. }
  53577. },{"../core/geometry":103,"../core/system":112,"../lib/three":149}],160:[function(_dereq_,module,exports){
  53578. var registerSystem = _dereq_('../core/system').registerSystem;
  53579. var THREE = _dereq_('../lib/three');
  53580. /**
  53581. * glTF model system.
  53582. */
  53583. module.exports.System = registerSystem('gltf-model', {
  53584. init: function () {
  53585. this.models = [];
  53586. },
  53587. /**
  53588. * Updates shaders for all glTF models in the system.
  53589. */
  53590. tick: function () {
  53591. var sceneEl = this.sceneEl;
  53592. if (sceneEl.hasLoaded && this.models.length) {
  53593. THREE.GLTFLoader.Shaders.update(sceneEl.object3D, sceneEl.camera);
  53594. }
  53595. },
  53596. /**
  53597. * Registers a glTF asset.
  53598. * @param {object} gltf Asset containing a scene and (optional) animations and cameras.
  53599. */
  53600. registerModel: function (gltf) {
  53601. this.models.push(gltf);
  53602. },
  53603. /**
  53604. * Unregisters a glTF asset.
  53605. * @param {object} gltf Asset containing a scene and (optional) animations and cameras.
  53606. */
  53607. unregisterModel: function (gltf) {
  53608. var models = this.models;
  53609. var index = models.indexOf(gltf);
  53610. if (index >= 0) {
  53611. models.splice(index, 1);
  53612. }
  53613. }
  53614. });
  53615. },{"../core/system":112,"../lib/three":149}],161:[function(_dereq_,module,exports){
  53616. _dereq_('./camera');
  53617. _dereq_('./geometry');
  53618. _dereq_('./gltf-model');
  53619. _dereq_('./light');
  53620. _dereq_('./material');
  53621. _dereq_('./shadow');
  53622. _dereq_('./tracked-controls');
  53623. },{"./camera":158,"./geometry":159,"./gltf-model":160,"./light":162,"./material":163,"./shadow":164,"./tracked-controls":165}],162:[function(_dereq_,module,exports){
  53624. var registerSystem = _dereq_('../core/system').registerSystem;
  53625. var bind = _dereq_('../utils/bind');
  53626. var constants = _dereq_('../constants/');
  53627. var DEFAULT_LIGHT_ATTR = 'data-aframe-default-light';
  53628. /**
  53629. * Light system.
  53630. *
  53631. * Prescribes default lighting if not specified (one ambient, one directional).
  53632. * Removes default lighting from the scene when a new light is added.
  53633. *
  53634. * @param {bool} defaultLights - Whether default lighting are defined.
  53635. * @param {bool} userDefinedLights - Whether user lighting is defined.
  53636. */
  53637. module.exports.System = registerSystem('light', {
  53638. schema: {
  53639. defaultLightsEnabled: {default: true}
  53640. },
  53641. init: function () {
  53642. this.defaultLights = false;
  53643. this.userDefinedLights = false;
  53644. // Wait for all entities to fully load before checking for existence of lights.
  53645. // Since entities wait for <a-assets> to load, any lights attaching to the scene
  53646. // will do so asynchronously.
  53647. this.sceneEl.addEventListener('loaded', bind(this.setupDefaultLights, this));
  53648. },
  53649. /**
  53650. * Notify scene that light has been added and to remove the default.
  53651. *
  53652. * @param {object} el - element holding the light component.
  53653. */
  53654. registerLight: function (el) {
  53655. if (!el.hasAttribute(DEFAULT_LIGHT_ATTR)) {
  53656. // User added a light, remove default lights through DOM.
  53657. this.removeDefaultLights();
  53658. this.userDefinedLights = true;
  53659. }
  53660. },
  53661. removeDefaultLights: function () {
  53662. var defaultLights;
  53663. var sceneEl = this.sceneEl;
  53664. if (!this.defaultLights) { return; }
  53665. defaultLights = document.querySelectorAll('[' + DEFAULT_LIGHT_ATTR + ']');
  53666. for (var i = 0; i < defaultLights.length; i++) {
  53667. sceneEl.removeChild(defaultLights[i]);
  53668. }
  53669. this.defaultLights = false;
  53670. },
  53671. /**
  53672. * Prescibe default lights to the scene.
  53673. * Does so by injecting markup such that this state is not invisible.
  53674. * These lights are removed if the user adds any lights.
  53675. */
  53676. setupDefaultLights: function () {
  53677. var sceneEl = this.sceneEl;
  53678. var ambientLight;
  53679. var directionalLight;
  53680. if (this.userDefinedLights || this.defaultLights || !this.data.defaultLightsEnabled) {
  53681. return;
  53682. }
  53683. ambientLight = document.createElement('a-entity');
  53684. directionalLight = document.createElement('a-entity');
  53685. ambientLight.setAttribute('light', {color: '#BBB', type: 'ambient'});
  53686. ambientLight.setAttribute(DEFAULT_LIGHT_ATTR, '');
  53687. ambientLight.setAttribute(constants.AFRAME_INJECTED, '');
  53688. sceneEl.appendChild(ambientLight);
  53689. directionalLight.setAttribute('light', {color: '#FFF', intensity: 0.6});
  53690. directionalLight.setAttribute('position', {x: -0.5, y: 1, z: 1});
  53691. directionalLight.setAttribute(DEFAULT_LIGHT_ATTR, '');
  53692. directionalLight.setAttribute(constants.AFRAME_INJECTED, '');
  53693. sceneEl.appendChild(directionalLight);
  53694. this.defaultLights = true;
  53695. }
  53696. });
  53697. },{"../constants/":93,"../core/system":112,"../utils/bind":166}],163:[function(_dereq_,module,exports){
  53698. var registerSystem = _dereq_('../core/system').registerSystem;
  53699. var THREE = _dereq_('../lib/three');
  53700. var utils = _dereq_('../utils/');
  53701. var isHLS = _dereq_('../utils/material').isHLS;
  53702. var bind = utils.bind;
  53703. var debug = utils.debug;
  53704. var error = debug('components:texture:error');
  53705. var TextureLoader = new THREE.TextureLoader();
  53706. var warn = debug('components:texture:warn');
  53707. TextureLoader.setCrossOrigin('anonymous');
  53708. /**
  53709. * System for material component.
  53710. * Handle material registration, updates (for fog), and texture caching.
  53711. *
  53712. * @member {object} materials - Registered materials.
  53713. * @member {object} textureCounts - Number of times each texture is used. Tracked
  53714. * separately from textureCache, because the cache (1) is populated in
  53715. * multiple places, and (2) may be cleared at any time.
  53716. * @member {object} textureCache - Texture cache for:
  53717. * - Images: textureCache has mapping of src -> repeat -> cached three.js texture.
  53718. * - Videos: textureCache has mapping of videoElement -> cached three.js texture.
  53719. */
  53720. module.exports.System = registerSystem('material', {
  53721. init: function () {
  53722. this.materials = {};
  53723. this.textureCounts = {};
  53724. this.textureCache = {};
  53725. this.sceneEl.addEventListener(
  53726. 'materialtextureloaded',
  53727. bind(this.onMaterialTextureLoaded, this)
  53728. );
  53729. },
  53730. clearTextureCache: function () {
  53731. this.textureCache = {};
  53732. },
  53733. /**
  53734. * Determine whether `src` is a image or video. Then try to load the asset, then call back.
  53735. *
  53736. * @param {string, or element} src - Texture URL or element.
  53737. * @param {string} data - Relevant texture data used for caching.
  53738. * @param {function} cb - Callback to pass texture to.
  53739. */
  53740. loadTexture: function (src, data, cb) {
  53741. var self = this;
  53742. // Canvas.
  53743. if (src.tagName === 'CANVAS') {
  53744. this.loadCanvas(src, data, cb);
  53745. return;
  53746. }
  53747. // Video element.
  53748. if (src.tagName === 'VIDEO') {
  53749. if (!src.hasAttribute('src') && !src.hasAttribute('srcObject')) {
  53750. warn('Video element was defined without `src` nor `srcObject` attributes.');
  53751. }
  53752. this.loadVideo(src, data, cb);
  53753. return;
  53754. }
  53755. utils.srcLoader.validateSrc(src, loadImageCb, loadVideoCb);
  53756. function loadImageCb (src) { self.loadImage(src, data, cb); }
  53757. function loadVideoCb (src) { self.loadVideo(src, data, cb); }
  53758. },
  53759. /**
  53760. * High-level function for loading image textures (THREE.Texture).
  53761. *
  53762. * @param {Element|string} src - Texture source.
  53763. * @param {object} data - Texture data.
  53764. * @param {function} cb - Callback to pass texture to.
  53765. */
  53766. loadImage: function (src, data, handleImageTextureLoaded) {
  53767. var hash = this.hash(data);
  53768. var textureCache = this.textureCache;
  53769. // Texture already being loaded or already loaded. Wait on promise.
  53770. if (textureCache[hash]) {
  53771. textureCache[hash].then(handleImageTextureLoaded);
  53772. return;
  53773. }
  53774. // Texture not yet being loaded. Start loading it.
  53775. textureCache[hash] = loadImageTexture(src, data);
  53776. textureCache[hash].then(handleImageTextureLoaded);
  53777. },
  53778. /**
  53779. * High-level function for loading canvas textures (THREE.Texture).
  53780. *
  53781. * @param {Element|string} src - Texture source.
  53782. * @param {object} data - Texture data.
  53783. * @param {function} cb - Callback to pass texture to.
  53784. */
  53785. loadCanvas: function (src, data, cb) {
  53786. // Hack readyState and HAVE_CURRENT_DATA on canvas to work with THREE.VideoTexture
  53787. src.readyState = 2;
  53788. src.HAVE_CURRENT_DATA = 2;
  53789. this.loadVideo(src, data, cb);
  53790. },
  53791. /**
  53792. * Load video texture (THREE.VideoTexture).
  53793. * Which is just an image texture that RAFs + needsUpdate.
  53794. * Note that creating a video texture is synchronous unlike loading an image texture.
  53795. * Made asynchronous to be consistent with image textures.
  53796. *
  53797. * @param {Element|string} src - Texture source.
  53798. * @param {object} data - Texture data.
  53799. * @param {function} cb - Callback to pass texture to.
  53800. */
  53801. loadVideo: function (src, data, cb) {
  53802. var hash;
  53803. var texture;
  53804. var textureCache = this.textureCache;
  53805. var videoEl;
  53806. var videoTextureResult;
  53807. function handleVideoTextureLoaded (result) {
  53808. result.texture.needsUpdate = true;
  53809. cb(result.texture, result.videoEl);
  53810. }
  53811. // Video element provided.
  53812. if (typeof src !== 'string') {
  53813. // Check cache before creating texture.
  53814. videoEl = src;
  53815. hash = this.hashVideo(data, videoEl);
  53816. if (textureCache[hash]) {
  53817. textureCache[hash].then(handleVideoTextureLoaded);
  53818. return;
  53819. }
  53820. // If not in cache, fix up the attributes then start to create the texture.
  53821. fixVideoAttributes(videoEl);
  53822. }
  53823. // Only URL provided. Use video element to create texture.
  53824. videoEl = videoEl || createVideoEl(src, data.width, data.height);
  53825. // Generated video element already cached. Use that.
  53826. hash = this.hashVideo(data, videoEl);
  53827. if (textureCache[hash]) {
  53828. textureCache[hash].then(handleVideoTextureLoaded);
  53829. return;
  53830. }
  53831. // Create new video texture.
  53832. texture = new THREE.VideoTexture(videoEl);
  53833. texture.minFilter = THREE.LinearFilter;
  53834. setTextureProperties(texture, data);
  53835. // If iOS and video is HLS, do some hacks.
  53836. if (this.sceneEl.isIOS &&
  53837. isHLS(videoEl.src || videoEl.getAttribute('src'),
  53838. videoEl.type || videoEl.getAttribute('type'))) {
  53839. // Actually BGRA. Tell shader to correct later.
  53840. texture.format = THREE.RGBAFormat;
  53841. texture.needsCorrectionBGRA = true;
  53842. // Apparently needed for HLS. Tell shader to correct later.
  53843. texture.flipY = false;
  53844. texture.needsCorrectionFlipY = true;
  53845. }
  53846. // Cache as promise to be consistent with image texture caching.
  53847. videoTextureResult = {texture: texture, videoEl: videoEl};
  53848. textureCache[hash] = Promise.resolve(videoTextureResult);
  53849. handleVideoTextureLoaded(videoTextureResult);
  53850. },
  53851. /**
  53852. * Create a hash of the material properties for texture cache key.
  53853. */
  53854. hash: function (data) {
  53855. if (data.src.tagName) {
  53856. // Since `data.src` can be an element, parse out the string if necessary for the hash.
  53857. data = utils.extendDeep({}, data);
  53858. data.src = data.src.getAttribute('src');
  53859. }
  53860. return JSON.stringify(data);
  53861. },
  53862. hashVideo: function (data, videoEl) {
  53863. return calculateVideoCacheHash(data, videoEl);
  53864. },
  53865. /**
  53866. * Keep track of material in case an update trigger is needed (e.g., fog).
  53867. *
  53868. * @param {object} material
  53869. */
  53870. registerMaterial: function (material) {
  53871. this.materials[material.uuid] = material;
  53872. },
  53873. /**
  53874. * Stop tracking material, and dispose of any textures not being used by
  53875. * another material component.
  53876. *
  53877. * @param {object} material
  53878. */
  53879. unregisterMaterial: function (material) {
  53880. delete this.materials[material.uuid];
  53881. // If any textures on this material are no longer in use, dispose of them.
  53882. var textureCounts = this.textureCounts;
  53883. Object.keys(material)
  53884. .filter(function (propName) {
  53885. return material[propName] && material[propName].isTexture;
  53886. })
  53887. .forEach(function (mapName) {
  53888. textureCounts[material[mapName].uuid]--;
  53889. if (textureCounts[material[mapName].uuid] <= 0) {
  53890. material[mapName].dispose();
  53891. }
  53892. });
  53893. },
  53894. /**
  53895. * Trigger update to all registered materials.
  53896. */
  53897. updateMaterials: function (material) {
  53898. var materials = this.materials;
  53899. Object.keys(materials).forEach(function (uuid) {
  53900. materials[uuid].needsUpdate = true;
  53901. });
  53902. },
  53903. /**
  53904. * Track textures used by material components, so that they can be safely
  53905. * disposed when no longer in use. Textures must be registered here, and not
  53906. * through registerMaterial(), because textures may not be attached at the
  53907. * time the material is registered.
  53908. *
  53909. * @param {Event} e
  53910. */
  53911. onMaterialTextureLoaded: function (e) {
  53912. if (!this.textureCounts[e.detail.texture.uuid]) {
  53913. this.textureCounts[e.detail.texture.uuid] = 0;
  53914. }
  53915. this.textureCounts[e.detail.texture.uuid]++;
  53916. }
  53917. });
  53918. /**
  53919. * Calculates consistent hash from a video element using its attributes.
  53920. * If the video element has an ID, use that.
  53921. * Else build a hash that looks like `src:myvideo.mp4;height:200;width:400;`.
  53922. *
  53923. * @param data {object} - Texture data such as repeat.
  53924. * @param videoEl {Element} - Video element.
  53925. * @returns {string}
  53926. */
  53927. function calculateVideoCacheHash (data, videoEl) {
  53928. var i;
  53929. var id = videoEl.getAttribute('id');
  53930. var hash;
  53931. var videoAttributes;
  53932. if (id) { return id; }
  53933. // Calculate hash using sorted video attributes.
  53934. hash = '';
  53935. videoAttributes = data || {};
  53936. for (i = 0; i < videoEl.attributes.length; i++) {
  53937. videoAttributes[videoEl.attributes[i].name] = videoEl.attributes[i].value;
  53938. }
  53939. Object.keys(videoAttributes).sort().forEach(function (name) {
  53940. hash += name + ':' + videoAttributes[name] + ';';
  53941. });
  53942. return hash;
  53943. }
  53944. /**
  53945. * Load image texture.
  53946. *
  53947. * @private
  53948. * @param {string|object} src - An <img> element or url to an image file.
  53949. * @param {object} data - Data to set texture properties like `repeat`.
  53950. * @returns {Promise} Resolves once texture is loaded.
  53951. */
  53952. function loadImageTexture (src, data) {
  53953. return new Promise(doLoadImageTexture);
  53954. function doLoadImageTexture (resolve, reject) {
  53955. var isEl = typeof src !== 'string';
  53956. function resolveTexture (texture) {
  53957. setTextureProperties(texture, data);
  53958. texture.needsUpdate = true;
  53959. resolve(texture);
  53960. }
  53961. // Create texture from an element.
  53962. if (isEl) {
  53963. resolveTexture(new THREE.Texture(src));
  53964. return;
  53965. }
  53966. // Request and load texture from src string. THREE will create underlying element.
  53967. // Use THREE.TextureLoader (src, onLoad, onProgress, onError) to load texture.
  53968. TextureLoader.load(
  53969. src,
  53970. resolveTexture,
  53971. function () { /* no-op */ },
  53972. function (xhr) {
  53973. error('`$s` could not be fetched (Error code: %s; Response: %s)', xhr.status,
  53974. xhr.statusText);
  53975. }
  53976. );
  53977. }
  53978. }
  53979. /**
  53980. * Set texture properties such as repeat and offset.
  53981. *
  53982. * @param {object} data - With keys like `repeat`.
  53983. */
  53984. function setTextureProperties (texture, data) {
  53985. var offset = data.offset || {x: 0, y: 0};
  53986. var repeat = data.repeat || {x: 1, y: 1};
  53987. var npot = data.npot || false;
  53988. // To support NPOT textures, wrap must be ClampToEdge (not Repeat),
  53989. // and filters must not use mipmaps (i.e. Nearest or Linear).
  53990. if (npot) {
  53991. texture.wrapS = THREE.ClampToEdgeWrapping;
  53992. texture.wrapT = THREE.ClampToEdgeWrapping;
  53993. texture.magFilter = THREE.LinearFilter;
  53994. texture.minFilter = THREE.LinearFilter;
  53995. }
  53996. // Don't bother setting repeat if it is 1/1. Power-of-two is required to repeat.
  53997. if (repeat.x !== 1 || repeat.y !== 1) {
  53998. texture.wrapS = THREE.RepeatWrapping;
  53999. texture.wrapT = THREE.RepeatWrapping;
  54000. texture.repeat.set(repeat.x, repeat.y);
  54001. }
  54002. // Don't bother setting offset if it is 0/0.
  54003. if (offset.x !== 0 || offset.y !== 0) {
  54004. texture.offset.set(offset.x, offset.y);
  54005. }
  54006. }
  54007. /**
  54008. * Create video element to be used as a texture.
  54009. *
  54010. * @param {string} src - Url to a video file.
  54011. * @param {number} width - Width of the video.
  54012. * @param {number} height - Height of the video.
  54013. * @returns {Element} Video element.
  54014. */
  54015. function createVideoEl (src, width, height) {
  54016. var videoEl = document.createElement('video');
  54017. videoEl.width = width;
  54018. videoEl.height = height;
  54019. // Support inline videos for iOS webviews.
  54020. videoEl.setAttribute('playsinline', '');
  54021. videoEl.setAttribute('webkit-playsinline', '');
  54022. videoEl.autoplay = true;
  54023. videoEl.loop = true;
  54024. videoEl.crossOrigin = 'anonymous';
  54025. videoEl.addEventListener('error', function () {
  54026. warn('`$s` is not a valid video', src);
  54027. }, true);
  54028. videoEl.src = src;
  54029. return videoEl;
  54030. }
  54031. /**
  54032. * Fixes a video element's attributes to prevent developers from accidentally passing the
  54033. * wrong attribute values to commonly misused video attributes.
  54034. *
  54035. * <video> does not treat `autoplay`, `controls`, `crossorigin`, `loop`, and `preload` as
  54036. * as booleans. Existence of those attributes will mean truthy.
  54037. *
  54038. * For example, translates <video loop="false"> to <video>.
  54039. *
  54040. * @see https://developer.mozilla.org/docs/Web/HTML/Element/video#Attributes
  54041. * @param {Element} videoEl - Video element.
  54042. * @returns {Element} Video element with the correct properties updated.
  54043. */
  54044. function fixVideoAttributes (videoEl) {
  54045. videoEl.autoplay = videoEl.hasAttribute('autoplay') && videoEl.getAttribute('autoplay') !== 'false';
  54046. videoEl.controls = videoEl.hasAttribute('controls') && videoEl.getAttribute('controls') !== 'false';
  54047. if (videoEl.getAttribute('loop') === 'false') {
  54048. videoEl.removeAttribute('loop');
  54049. }
  54050. if (videoEl.getAttribute('preload') === 'false') {
  54051. videoEl.preload = 'none';
  54052. }
  54053. videoEl.crossOrigin = videoEl.crossOrigin || 'anonymous';
  54054. // To support inline videos in iOS webviews.
  54055. videoEl.setAttribute('playsinline', '');
  54056. videoEl.setAttribute('webkit-playsinline', '');
  54057. return videoEl;
  54058. }
  54059. },{"../core/system":112,"../lib/three":149,"../utils/":172,"../utils/material":173}],164:[function(_dereq_,module,exports){
  54060. var registerSystem = _dereq_('../core/system').registerSystem;
  54061. var bind = _dereq_('../utils/bind');
  54062. var THREE = _dereq_('../lib/three');
  54063. var SHADOW_MAP_TYPE_MAP = {
  54064. basic: THREE.BasicShadowMap,
  54065. pcf: THREE.PCFShadowMap,
  54066. pcfsoft: THREE.PCFSoftShadowMap
  54067. };
  54068. /**
  54069. * Shadow system.
  54070. *
  54071. * Enabled automatically when one or more shadow components are added to the scene, the system sets
  54072. * options on the WebGLRenderer for configuring shadow appearance.
  54073. */
  54074. module.exports.System = registerSystem('shadow', {
  54075. schema: {
  54076. type: {default: 'pcf', oneOf: ['basic', 'pcf', 'pcfsoft']},
  54077. renderReverseSided: {default: true},
  54078. renderSingleSided: {default: true}
  54079. },
  54080. init: function () {
  54081. var sceneEl = this.sceneEl;
  54082. var data = this.data;
  54083. this.shadowMapEnabled = false;
  54084. sceneEl.addEventListener('render-target-loaded', bind(function () {
  54085. // Renderer is not initialized in most tests.
  54086. if (!sceneEl.renderer) { return; }
  54087. sceneEl.renderer.shadowMap.type = SHADOW_MAP_TYPE_MAP[data.type];
  54088. sceneEl.renderer.shadowMap.renderReverseSided = data.renderReverseSided;
  54089. sceneEl.renderer.shadowMap.renderSingleSided = data.renderSingleSided;
  54090. this.setShadowMapEnabled(this.shadowMapEnabled);
  54091. }, this));
  54092. },
  54093. /**
  54094. * Enables/disables the renderer shadow map.
  54095. * @param {boolean} enabled
  54096. */
  54097. setShadowMapEnabled: function (enabled) {
  54098. var renderer = this.sceneEl.renderer;
  54099. this.shadowMapEnabled = enabled;
  54100. if (renderer) {
  54101. renderer.shadowMap.enabled = enabled;
  54102. }
  54103. }
  54104. });
  54105. },{"../core/system":112,"../lib/three":149,"../utils/bind":166}],165:[function(_dereq_,module,exports){
  54106. var registerSystem = _dereq_('../core/system').registerSystem;
  54107. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  54108. var utils = _dereq_('../utils');
  54109. /**
  54110. * Tracked controls system.
  54111. * It maintains a list with the available tracked controllers
  54112. */
  54113. module.exports.System = registerSystem('tracked-controls', {
  54114. init: function () {
  54115. var self = this;
  54116. this.controllers = [];
  54117. this.lastControllersUpdate = 0;
  54118. // Throttle the (renamed) tick handler to minimum 10ms interval.
  54119. this.tick = utils.throttle(this.throttledTick, 10, this);
  54120. if (!navigator.getVRDisplays) { return; }
  54121. this.sceneEl.addEventListener('enter-vr', function () {
  54122. navigator.getVRDisplays().then(function (displays) {
  54123. if (displays.length) { self.vrDisplay = displays[0]; }
  54124. });
  54125. });
  54126. },
  54127. updateControllerList: function () {
  54128. var controllers = this.controllers = [];
  54129. var gamepads = trackedControlsUtils.getGamepadsByPrefix('');
  54130. for (var i = 0; i < gamepads.length; i++) {
  54131. var gamepad = gamepads[i];
  54132. if (gamepad && gamepad.pose) { controllers.push(gamepad); }
  54133. }
  54134. },
  54135. /**
  54136. * Update controller list every 10 miliseconds.
  54137. */
  54138. throttledTick: function () {
  54139. this.updateControllerList();
  54140. this.sceneEl.emit('controllersupdated', { controllers: this.controllers });
  54141. }
  54142. });
  54143. },{"../core/system":112,"../utils":172,"../utils/tracked-controls":176}],166:[function(_dereq_,module,exports){
  54144. /**
  54145. * Faster version of Function.prototype.bind
  54146. * @param {Function} fn - Function to wrap.
  54147. * @param {Object} ctx - What to bind as context.
  54148. * @param {...*} arguments - Arguments to pass through.
  54149. */
  54150. module.exports = function bind (fn, ctx/* , arg1, arg2 */) {
  54151. return (function (prependedArgs) {
  54152. return function bound () {
  54153. // Concat the bound function arguments with those passed to original bind
  54154. var args = prependedArgs.concat(Array.prototype.slice.call(arguments, 0));
  54155. return fn.apply(ctx, args);
  54156. };
  54157. })(Array.prototype.slice.call(arguments, 2));
  54158. };
  54159. },{}],167:[function(_dereq_,module,exports){
  54160. /* global THREE */
  54161. var extend = _dereq_('object-assign');
  54162. // Coordinate string regex. Handles negative, positive, and decimals.
  54163. var regex = /^\s*((-?\d*\.{0,1}\d+(e-?\d+)?)\s+){2,3}(-?\d*\.{0,1}\d+(e-?\d+)?)\s*$/;
  54164. module.exports.regex = regex;
  54165. /**
  54166. * Parses coordinates from an "x y z" string.
  54167. * Example: "3 10 -5" to {x: 3, y: 10, z: -5}.
  54168. *
  54169. * @param {string} val - An "x y z" string.
  54170. * @param {string} defaults - fallback value.
  54171. * @returns {object} An object with keys [x, y, z].
  54172. */
  54173. function parse (value, defaultVec) {
  54174. var coordinate;
  54175. var vec = {};
  54176. if (value && typeof value === 'object') {
  54177. return vecParseFloat({
  54178. x: value.x !== undefined ? value.x : (defaultVec && defaultVec.x),
  54179. y: value.y !== undefined ? value.y : (defaultVec && defaultVec.y),
  54180. z: value.z !== undefined ? value.z : (defaultVec && defaultVec.z),
  54181. w: value.w !== undefined ? value.w : (defaultVec && defaultVec.w)
  54182. });
  54183. }
  54184. if (typeof value !== 'string' || value === null) {
  54185. return typeof defaultVec === 'object' ? extend({}, defaultVec) : defaultVec;
  54186. }
  54187. coordinate = value.trim().replace(/\s+/g, ' ').split(' ');
  54188. vec.x = coordinate[0] || defaultVec && defaultVec.x;
  54189. vec.y = coordinate[1] || defaultVec && defaultVec.y;
  54190. vec.z = coordinate[2] || defaultVec && defaultVec.z;
  54191. vec.w = coordinate[3] || defaultVec && defaultVec.w;
  54192. return vecParseFloat(vec);
  54193. }
  54194. module.exports.parse = parse;
  54195. /**
  54196. * Stringifies coordinates from an object with keys [x y z].
  54197. * Example: {x: 3, y: 10, z: -5} to "3 10 -5".
  54198. *
  54199. * @param {object|string} data - An object with keys [x y z].
  54200. * @returns {string} An "x y z" string.
  54201. */
  54202. function stringify (data) {
  54203. if (typeof data !== 'object') { return data; }
  54204. return [data.x, data.y, data.z, data.w].join(' ').trim();
  54205. }
  54206. module.exports.stringify = stringify;
  54207. /**
  54208. * @returns {bool}
  54209. */
  54210. module.exports.isCoordinates = function (value) {
  54211. return regex.test(value);
  54212. };
  54213. function vecParseFloat (vec) {
  54214. Object.keys(vec).forEach(function (key) {
  54215. if (vec[key] === undefined) {
  54216. delete vec[key];
  54217. return;
  54218. }
  54219. vec[key] = parseFloat(vec[key], 10);
  54220. });
  54221. return vec;
  54222. }
  54223. /**
  54224. * Converts {x, y, z} object to three.js Vector3.
  54225. */
  54226. module.exports.toVector3 = function (vec3) {
  54227. return new THREE.Vector3(vec3.x, vec3.y, vec3.z);
  54228. };
  54229. },{"object-assign":25}],168:[function(_dereq_,module,exports){
  54230. (function (process){
  54231. var debugLib = _dereq_('debug');
  54232. var extend = _dereq_('object-assign');
  54233. var settings = {
  54234. colors: {
  54235. debug: 'gray',
  54236. error: 'red',
  54237. info: 'gray',
  54238. warn: 'orange'
  54239. }
  54240. };
  54241. /**
  54242. * Monkeypatches `debug` so we can colorize error/warning messages.
  54243. *
  54244. * (See issue: https://github.com/visionmedia/debug/issues/137)
  54245. */
  54246. var debug = function (namespace) {
  54247. var d = debugLib(namespace);
  54248. d.color = getDebugNamespaceColor(namespace);
  54249. return d;
  54250. };
  54251. extend(debug, debugLib);
  54252. /**
  54253. * Returns the type of the namespace (e.g., `error`, `warn`).
  54254. *
  54255. * @param {String} namespace
  54256. * The debug logger's namespace (e.g., `components:geometry:warn`).
  54257. * @returns {String} The type of the namespace (e.g., `warn`).
  54258. * @api private
  54259. */
  54260. function getDebugNamespaceType (namespace) {
  54261. var chunks = namespace.split(':');
  54262. return chunks[chunks.length - 1]; // Return the last one
  54263. }
  54264. /**
  54265. * Returns the color of the namespace (e.g., `orange`).
  54266. *
  54267. * @param {String} namespace
  54268. * The debug logger's namespace (e.g., `components:geometry:warn`).
  54269. * @returns {String} The color of the namespace (e.g., `orange`).
  54270. * @api private
  54271. */
  54272. function getDebugNamespaceColor (namespace) {
  54273. var type = getDebugNamespaceType(namespace);
  54274. var color = settings.colors && settings.colors[type];
  54275. return color || null;
  54276. }
  54277. /**
  54278. * Returns `localStorage` if possible.
  54279. *
  54280. * This is necessary because Safari throws when a user disables
  54281. * cookies or `localStorage` and you attempt to access it.
  54282. *
  54283. * @returns {localStorage}
  54284. * @api private
  54285. */
  54286. function storage () {
  54287. try {
  54288. return window.localStorage;
  54289. } catch (e) {
  54290. }
  54291. }
  54292. /**
  54293. * To enable console logging, type this in the Console of your Dev Tools:
  54294. *
  54295. * localStorage.logs = 1
  54296. *
  54297. * To disable console logging:
  54298. *
  54299. * localStorage.logs = 0
  54300. *
  54301. */
  54302. var ls = storage();
  54303. if (ls && (parseInt(ls.logs, 10) || ls.logs === 'true')) {
  54304. debug.enable('*');
  54305. } else {
  54306. debug.enable('*:error,*:info,*:warn');
  54307. }
  54308. if (process.browser) { window.logs = debug; }
  54309. module.exports = debug;
  54310. }).call(this,_dereq_('_process'))
  54311. },{"_process":33,"debug":7,"object-assign":25}],169:[function(_dereq_,module,exports){
  54312. (function (process){
  54313. var THREE = _dereq_('../lib/three');
  54314. var dolly = new THREE.Object3D();
  54315. var controls = new THREE.VRControls(dolly);
  54316. /**
  54317. * Determine if a headset is connected by checking if the orientation is available.
  54318. */
  54319. function checkHeadsetConnected () {
  54320. var orientation;
  54321. var vrDisplay = controls.getVRDisplay();
  54322. // If `isConnected` is available, just use that.
  54323. if (vrDisplay && 'isConnected' in vrDisplay) { return vrDisplay.isConnected; }
  54324. controls.update();
  54325. orientation = dolly.quaternion;
  54326. if (orientation._x !== 0 || orientation._y !== 0 || orientation._z !== 0) {
  54327. return true;
  54328. }
  54329. return false;
  54330. }
  54331. module.exports.checkHeadsetConnected = checkHeadsetConnected;
  54332. /**
  54333. * Check for positional tracking.
  54334. */
  54335. function checkHasPositionalTracking () {
  54336. var vrDisplay = controls.getVRDisplay();
  54337. if (isMobile() || isGearVR()) { return false; }
  54338. return vrDisplay && vrDisplay.capabilities.hasPosition;
  54339. }
  54340. module.exports.checkHasPositionalTracking = checkHasPositionalTracking;
  54341. /**
  54342. * Checks if browser is mobile.
  54343. * @return {Boolean} True if mobile browser detected.
  54344. */
  54345. var isMobile = (function () {
  54346. var _isMobile = false;
  54347. (function (a) {
  54348. // eslint-disable-next-line no-useless-escape
  54349. 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))) {
  54350. _isMobile = true;
  54351. }
  54352. if (isIOS() || isTablet()) {
  54353. _isMobile = true;
  54354. }
  54355. if (isGearVR()) {
  54356. _isMobile = false;
  54357. }
  54358. })(navigator.userAgent || navigator.vendor || window.opera);
  54359. return function () { return _isMobile; };
  54360. })();
  54361. module.exports.isMobile = isMobile;
  54362. /**
  54363. * Detect tablet devices.
  54364. * @param {string} mockUserAgent - Allow passing a mock user agent for testing.
  54365. */
  54366. function isTablet (mockUserAgent) {
  54367. var userAgent = mockUserAgent || navigator.userAgent;
  54368. return /ipad|Nexus (7|9)|xoom|sch-i800|playbook|tablet|kindle/i.test(userAgent);
  54369. }
  54370. module.exports.isTablet = isTablet;
  54371. function isIOS () {
  54372. return /iPad|iPhone|iPod/.test(navigator.platform);
  54373. }
  54374. module.exports.isIOS = isIOS;
  54375. function isGearVR () {
  54376. return /SamsungBrowser.+Mobile VR/i.test(navigator.userAgent);
  54377. }
  54378. module.exports.isGearVR = isGearVR;
  54379. /**
  54380. * Checks mobile device orientation.
  54381. * @return {Boolean} True if landscape orientation.
  54382. */
  54383. module.exports.isLandscape = function () {
  54384. return window.orientation === 90 || window.orientation === -90;
  54385. };
  54386. /**
  54387. * Check if device is iOS and older than version 10.
  54388. */
  54389. module.exports.isIOSOlderThan10 = function (userAgent) {
  54390. return /(iphone|ipod|ipad).*os.(7|8|9)/i.test(userAgent);
  54391. };
  54392. /**
  54393. * Check if running in a browser or spoofed browser (bundler).
  54394. * We need to check a node api that isn't mocked on either side.
  54395. * `require` and `module.exports` are mocked in browser by bundlers.
  54396. * `window` is mocked in node.
  54397. * `process` is also mocked by browserify, but has custom properties.
  54398. */
  54399. module.exports.isBrowserEnvironment = !!(!process || process.browser);
  54400. /**
  54401. * Check if running in node on the server.
  54402. */
  54403. module.exports.isNodeEnvironment = !module.exports.isBrowserEnvironment;
  54404. }).call(this,_dereq_('_process'))
  54405. },{"../lib/three":149,"_process":33}],170:[function(_dereq_,module,exports){
  54406. /**
  54407. * Split a delimited component property string (e.g., `material.color`) to an object
  54408. * containing `component` name and `property` name. If there is no delimiter, just return the
  54409. * string back.
  54410. */
  54411. module.exports.getComponentPropertyPath = function (str, delimiter) {
  54412. delimiter = delimiter || '.';
  54413. if (str.indexOf(delimiter) === -1) { return str; }
  54414. return str.split(delimiter);
  54415. };
  54416. /**
  54417. * Get component property using encoded component name + component property name with a
  54418. * delimiter.
  54419. */
  54420. module.exports.getComponentProperty = function (el, name, delimiter) {
  54421. var splitName;
  54422. delimiter = delimiter || '.';
  54423. if (name.indexOf(delimiter) !== -1) {
  54424. splitName = name.split(delimiter);
  54425. return el.getAttribute(splitName[0])[splitName[1]];
  54426. }
  54427. return el.getAttribute(name);
  54428. };
  54429. /**
  54430. * Set component property using encoded component name + component property name with a
  54431. * delimiter.
  54432. */
  54433. module.exports.setComponentProperty = function (el, name, value, delimiter) {
  54434. var data = {};
  54435. var splitName;
  54436. delimiter = delimiter || '.';
  54437. if (name.indexOf(delimiter) !== -1) {
  54438. splitName = name.split(delimiter);
  54439. data[splitName[1]] = value;
  54440. el.setAttribute(splitName[0], data);
  54441. return;
  54442. }
  54443. el.setAttribute(name, value);
  54444. };
  54445. },{}],171:[function(_dereq_,module,exports){
  54446. module.exports = function forceCanvasResizeSafariMobile (canvasEl) {
  54447. var width = canvasEl.style.width;
  54448. var height = canvasEl.style.height;
  54449. // Taken from webvr-polyfill (https://github.com/borismus/webvr-polyfill/blob/85f657cd502ec9417bf26b87c3cb2afa6a70e079/src/util.js#L200)
  54450. // iOS only workaround for https://bugs.webkit.org/show_bug.cgi?id=152556
  54451. // By changing the size 1 pixel and restoring the previous value
  54452. // we trigger a size recalculation cycle.
  54453. canvasEl.style.width = (parseInt(width, 10) + 1) + 'px';
  54454. canvasEl.style.height = (parseInt(height, 10) + 1) + 'px';
  54455. setTimeout(function () {
  54456. canvasEl.style.width = width;
  54457. canvasEl.style.height = height;
  54458. }, 200);
  54459. };
  54460. },{}],172:[function(_dereq_,module,exports){
  54461. /* global CustomEvent, location */
  54462. /* Centralized place to reference utilities since utils is exposed to the user. */
  54463. var debug = _dereq_('./debug');
  54464. var deepAssign = _dereq_('deep-assign');
  54465. var device = _dereq_('./device');
  54466. var objectAssign = _dereq_('object-assign');
  54467. var warn = debug('utils:warn');
  54468. module.exports.bind = _dereq_('./bind');
  54469. module.exports.coordinates = _dereq_('./coordinates');
  54470. module.exports.debug = debug;
  54471. module.exports.device = device;
  54472. module.exports.entity = _dereq_('./entity');
  54473. module.exports.forceCanvasResizeSafariMobile = _dereq_('./forceCanvasResizeSafariMobile');
  54474. module.exports.material = _dereq_('./material');
  54475. module.exports.styleParser = _dereq_('./styleParser');
  54476. module.exports.trackedControls = _dereq_('./tracked-controls');
  54477. module.exports.checkHeadsetConnected = function () {
  54478. warn('`utils.checkHeadsetConnected` has moved to `utils.device.checkHeadsetConnected`');
  54479. return device.checkHeadsetConnected(arguments);
  54480. };
  54481. module.exports.isGearVR = function () {
  54482. warn('`utils.isGearVR` has moved to `utils.device.isGearVR`');
  54483. return device.isGearVR(arguments);
  54484. };
  54485. module.exports.isIOS = function () {
  54486. warn('`utils.isIOS` has moved to `utils.device.isIOS`');
  54487. return device.isIOS(arguments);
  54488. };
  54489. module.exports.isMobile = function () {
  54490. warn('`utils.isMobile has moved to `utils.device.isMobile`');
  54491. return device.isMobile(arguments);
  54492. };
  54493. /**
  54494. * Returns throttle function that gets called at most once every interval.
  54495. *
  54496. * @param {function} functionToThrottle
  54497. * @param {number} minimumInterval - Minimal interval between calls (milliseconds).
  54498. * @param {object} optionalContext - If given, bind function to throttle to this context.
  54499. * @returns {function} Throttled function.
  54500. */
  54501. module.exports.throttle = function (functionToThrottle, minimumInterval, optionalContext) {
  54502. var lastTime;
  54503. if (optionalContext) {
  54504. functionToThrottle = module.exports.bind(functionToThrottle, optionalContext);
  54505. }
  54506. return function () {
  54507. var time = Date.now();
  54508. var sinceLastTime = typeof lastTime === 'undefined' ? minimumInterval : time - lastTime;
  54509. if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) {
  54510. lastTime = time;
  54511. functionToThrottle.apply(null, arguments);
  54512. }
  54513. };
  54514. };
  54515. /**
  54516. * Returns throttle function that gets called at most once every interval.
  54517. * Uses the time/timeDelta timestamps provided by the global render loop for better perf.
  54518. *
  54519. * @param {function} functionToThrottle
  54520. * @param {number} minimumInterval - Minimal interval between calls (milliseconds).
  54521. * @param {object} optionalContext - If given, bind function to throttle to this context.
  54522. * @returns {function} Throttled function.
  54523. */
  54524. module.exports.throttleTick = function (functionToThrottle, minimumInterval, optionalContext) {
  54525. var lastTime;
  54526. if (optionalContext) {
  54527. functionToThrottle = module.exports.bind(functionToThrottle, optionalContext);
  54528. }
  54529. return function (time, delta) {
  54530. var sinceLastTime = typeof lastTime === 'undefined' ? delta : time - lastTime;
  54531. if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) {
  54532. lastTime = time;
  54533. functionToThrottle(time, sinceLastTime);
  54534. }
  54535. };
  54536. };
  54537. /**
  54538. * Fires a custom DOM event.
  54539. *
  54540. * @param {Element} el Element on which to fire the event.
  54541. * @param {String} name Name of the event.
  54542. * @param {Object=} [data={bubbles: true, {detail: <el>}}]
  54543. * Data to pass as `customEventInit` to the event.
  54544. */
  54545. module.exports.fireEvent = function (el, name, data) {
  54546. data = data || {};
  54547. data.detail = data.detail || {};
  54548. data.detail.target = data.detail.target || el;
  54549. var evt = new CustomEvent(name, data);
  54550. el.dispatchEvent(evt);
  54551. };
  54552. /**
  54553. * Mix the properties of source object(s) into a destination object.
  54554. *
  54555. * @param {object} dest - The object to which properties will be copied.
  54556. * @param {...object} source - The object(s) from which properties will be copied.
  54557. */
  54558. module.exports.extend = objectAssign;
  54559. module.exports.extendDeep = deepAssign;
  54560. module.exports.clone = function (obj) {
  54561. return JSON.parse(JSON.stringify(obj));
  54562. };
  54563. /**
  54564. * Checks if two values are equal.
  54565. * Includes objects and arrays and nested objects and arrays.
  54566. * Try to keep this function performant as it will be called often to see if a component
  54567. * should be updated.
  54568. *
  54569. * @param {object} a - First object.
  54570. * @param {object} b - Second object.
  54571. * @returns {boolean} Whether two objects are deeply equal.
  54572. */
  54573. function deepEqual (a, b) {
  54574. var i;
  54575. var keysA;
  54576. var keysB;
  54577. var valA;
  54578. var valB;
  54579. // If not objects or arrays, compare as values.
  54580. if (a === null || b === null ||
  54581. !(a && b && (a.constructor === Object && b.constructor === Object) ||
  54582. (a.constructor === Array && b.constructor === Array))) {
  54583. return a === b;
  54584. }
  54585. // Different number of keys, not equal.
  54586. keysA = Object.keys(a);
  54587. keysB = Object.keys(b);
  54588. if (keysA.length !== keysB.length) { return false; }
  54589. // Return `false` at the first sign of inequality.
  54590. for (i = 0; i < keysA.length; ++i) {
  54591. valA = a[keysA[i]];
  54592. valB = b[keysA[i]];
  54593. // Check nested array and object.
  54594. if ((typeof valA === 'object' || typeof valB === 'object') ||
  54595. (Array.isArray(valA) && Array.isArray(valB))) {
  54596. if (valA === valB) { continue; }
  54597. if (!deepEqual(valA, valB)) { return false; }
  54598. } else if (valA !== valB) {
  54599. return false;
  54600. }
  54601. }
  54602. return true;
  54603. }
  54604. module.exports.deepEqual = deepEqual;
  54605. /**
  54606. * Computes the difference between two objects.
  54607. *
  54608. * @param {object} a - First object to compare (e.g., oldData).
  54609. * @param {object} b - Second object to compare (e.g., newData).
  54610. * @returns {object}
  54611. * Difference object where set of keys note which values were not equal, and values are
  54612. * `b`'s values.
  54613. */
  54614. module.exports.diff = function (a, b) {
  54615. var diff = {};
  54616. var keys = Object.keys(a);
  54617. Object.keys(b).forEach(function collectKeys (bKey) {
  54618. if (keys.indexOf(bKey) === -1) {
  54619. keys.push(bKey);
  54620. }
  54621. });
  54622. keys.forEach(function doDiff (key) {
  54623. var aVal = a[key];
  54624. var bVal = b[key];
  54625. var isComparingObjects = aVal && bVal &&
  54626. aVal.constructor === Object && bVal.constructor === Object;
  54627. if ((isComparingObjects && !deepEqual(aVal, bVal)) ||
  54628. (!isComparingObjects && aVal !== bVal)) {
  54629. diff[key] = bVal;
  54630. }
  54631. });
  54632. return diff;
  54633. };
  54634. /**
  54635. * Returns whether we should capture this keyboard event for keyboard shortcuts.
  54636. * @param {Event} event Event object.
  54637. * @returns {Boolean} Whether the key event should be captured.
  54638. */
  54639. module.exports.shouldCaptureKeyEvent = function (event) {
  54640. if (event.metaKey) { return false; }
  54641. return document.activeElement === document.body;
  54642. };
  54643. /**
  54644. * Splits a string into an array based on a delimiter.
  54645. *
  54646. * @param {string=} [str=''] Source string
  54647. * @param {string=} [delimiter=' '] Delimiter to use
  54648. * @returns {array} Array of delimited strings
  54649. */
  54650. module.exports.splitString = function (str, delimiter) {
  54651. if (typeof delimiter === 'undefined') { delimiter = ' '; }
  54652. // First collapse the whitespace (or whatever the delimiter is).
  54653. var regex = new RegExp(delimiter, 'g');
  54654. str = (str || '').replace(regex, delimiter);
  54655. // Then split.
  54656. return str.split(delimiter);
  54657. };
  54658. /**
  54659. * Extracts data from the element given an object that contains expected keys.
  54660. *
  54661. * @param {Element} Source element.
  54662. * @param {Object} [defaults={}] Object of default key-value pairs.
  54663. * @returns {Object}
  54664. */
  54665. module.exports.getElData = function (el, defaults) {
  54666. defaults = defaults || {};
  54667. var data = {};
  54668. Object.keys(defaults).forEach(copyAttribute);
  54669. function copyAttribute (key) {
  54670. if (el.hasAttribute(key)) {
  54671. data[key] = el.getAttribute(key);
  54672. }
  54673. }
  54674. return data;
  54675. };
  54676. /**
  54677. * Retrieves querystring value.
  54678. * @param {String} name Name of querystring key.
  54679. * @return {String} Value
  54680. */
  54681. module.exports.getUrlParameter = function (name) {
  54682. // eslint-disable-next-line no-useless-escape
  54683. name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
  54684. var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
  54685. var results = regex.exec(location.search);
  54686. return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
  54687. };
  54688. /**
  54689. * Detects whether context is within iframe.
  54690. */
  54691. module.exports.isIframed = function () {
  54692. return window.top !== window.self;
  54693. };
  54694. /**
  54695. * Finds all elements under the element that have the isScene
  54696. * property set to true
  54697. */
  54698. module.exports.findAllScenes = function (el) {
  54699. var matchingElements = [];
  54700. var allElements = el.getElementsByTagName('*');
  54701. for (var i = 0, n = allElements.length; i < n; i++) {
  54702. if (allElements[i].isScene) {
  54703. // Element exists with isScene set.
  54704. matchingElements.push(allElements[i]);
  54705. }
  54706. }
  54707. return matchingElements;
  54708. };
  54709. // Must be at bottom to avoid circular dependency.
  54710. module.exports.srcLoader = _dereq_('./src-loader');
  54711. },{"./bind":166,"./coordinates":167,"./debug":168,"./device":169,"./entity":170,"./forceCanvasResizeSafariMobile":171,"./material":173,"./src-loader":174,"./styleParser":175,"./tracked-controls":176,"deep-assign":9,"object-assign":25}],173:[function(_dereq_,module,exports){
  54712. var THREE = _dereq_('../lib/three');
  54713. var HLS_MIMETYPES = ['application/x-mpegurl', 'application/vnd.apple.mpegurl'];
  54714. /**
  54715. * Update `material` texture property (usually but not always `map`)
  54716. * from `data` property (usually but not always `src`)
  54717. *
  54718. * @param {object} shader - A-Frame shader instance.
  54719. * @param {object} data
  54720. */
  54721. module.exports.updateMapMaterialFromData = function (materialName, dataName, shader, data) {
  54722. var el = shader.el;
  54723. var material = shader.material;
  54724. var src = data[dataName];
  54725. // Because a single material / shader may have multiple textures,
  54726. // we need to remember the source value for this data property
  54727. // to avoid redundant operations which can be expensive otherwise
  54728. // (e.g. video texture loads).
  54729. if (!shader.materialSrcs) { shader.materialSrcs = {}; }
  54730. if (!src) {
  54731. // Forget the prior material src.
  54732. delete shader.materialSrcs[materialName];
  54733. // Remove the texture.
  54734. setMap(null);
  54735. return;
  54736. }
  54737. // Don't process if material src hasn't changed.
  54738. if (src === shader.materialSrcs[materialName]) { return; }
  54739. // Remember the new src for this texture (there may be multiple).
  54740. shader.materialSrcs[materialName] = src;
  54741. // If the new material src is already a texture, just use it.
  54742. if (src instanceof THREE.Texture) { setMap(src); } else {
  54743. // Load texture for the new material src.
  54744. // (And check if we should still use it once available in callback.)
  54745. el.sceneEl.systems.material.loadTexture(src,
  54746. {src: src, repeat: data.repeat, offset: data.offset, npot: data.npot},
  54747. checkSetMap);
  54748. }
  54749. function checkSetMap (texture) {
  54750. // If the source has been changed, don't use loaded texture.
  54751. if (shader.materialSrcs[materialName] !== src) { return; }
  54752. setMap(texture);
  54753. }
  54754. function setMap (texture) {
  54755. material[materialName] = texture;
  54756. material.needsUpdate = true;
  54757. handleTextureEvents(el, texture);
  54758. }
  54759. };
  54760. /**
  54761. * Update `material.map` given `data.src`. For standard and flat shaders.
  54762. *
  54763. * @param {object} shader - A-Frame shader instance.
  54764. * @param {object} data
  54765. */
  54766. module.exports.updateMap = function (shader, data) {
  54767. return module.exports.updateMapMaterialFromData('map', 'src', shader, data);
  54768. };
  54769. /**
  54770. * Updates the material's maps which give the illusion of extra geometry.
  54771. *
  54772. * @param {string} longType - The friendly name of the map from the component e.g. ambientOcclusionMap becomes aoMap in THREE.js
  54773. * @param {object} shader - A-Frame shader instance
  54774. * @param {object} data
  54775. */
  54776. module.exports.updateDistortionMap = function (longType, shader, data) {
  54777. var shortType = longType;
  54778. if (longType === 'ambientOcclusion') { shortType = 'ao'; }
  54779. var el = shader.el;
  54780. var material = shader.material;
  54781. var src = data[longType + 'Map'];
  54782. var info = {};
  54783. info.src = src;
  54784. // Pass through the repeat and offset to be handled by the material loader.
  54785. info.offset = data[longType + 'TextureOffset'];
  54786. info.repeat = data[longType + 'TextureRepeat'];
  54787. info.wrap = data[longType + 'TextureWrap'];
  54788. if (src) {
  54789. if (src === shader[longType + 'TextureSrc']) { return; }
  54790. // Texture added or changed.
  54791. shader[longType + 'TextureSrc'] = src;
  54792. el.sceneEl.systems.material.loadTexture(src, info, setMap);
  54793. return;
  54794. }
  54795. // Texture removed.
  54796. if (!material.map) { return; }
  54797. setMap(null);
  54798. function setMap (texture) {
  54799. material[shortType + 'Map'] = texture;
  54800. material.needsUpdate = true;
  54801. handleTextureEvents(el, texture);
  54802. }
  54803. };
  54804. /**
  54805. * Emit event on entities on texture-related events.
  54806. *
  54807. * @param {Element} el - Entity.
  54808. * @param {object} texture - three.js Texture.
  54809. */
  54810. function handleTextureEvents (el, texture) {
  54811. if (!texture) { return; }
  54812. el.emit('materialtextureloaded', {src: texture.image, texture: texture});
  54813. // Video events.
  54814. if (!texture.image || texture.image.tagName !== 'VIDEO') { return; }
  54815. texture.image.addEventListener('loadeddata', function emitVideoTextureLoadedDataAll () {
  54816. // Check to see if we need to use iOS 10 HLS shader.
  54817. // Only override the shader if it is stock shader that we know doesn't correct.
  54818. if (!el.components || !el.components.material) { return; }
  54819. if (texture.needsCorrectionBGRA && texture.needsCorrectionFlipY &&
  54820. ['standard', 'flat'].indexOf(el.components.material.data.shader) !== -1) {
  54821. el.setAttribute('material', 'shader', 'ios10hls');
  54822. }
  54823. el.emit('materialvideoloadeddata', {src: texture.image, texture: texture});
  54824. });
  54825. texture.image.addEventListener('ended', function emitVideoTextureEndedAll () {
  54826. // Works for non-looping videos only.
  54827. el.emit('materialvideoended', {src: texture.image, texture: texture});
  54828. });
  54829. }
  54830. module.exports.handleTextureEvents = handleTextureEvents;
  54831. /**
  54832. * Given video element src and type, guess whether stream is HLS.
  54833. *
  54834. * @param {string} src - src from video element (generally URL to content).
  54835. * @param {string} type - type from video element (generally MIME type if present).
  54836. */
  54837. module.exports.isHLS = function (src, type) {
  54838. if (type && HLS_MIMETYPES.includes(type.toLowerCase())) { return true; }
  54839. if (src && src.toLowerCase().indexOf('.m3u8') > 0) { return true; }
  54840. return false;
  54841. };
  54842. },{"../lib/three":149}],174:[function(_dereq_,module,exports){
  54843. /* global Image */
  54844. var debug = _dereq_('./debug');
  54845. var warn = debug('utils:src-loader:warn');
  54846. /**
  54847. * Validate a texture, either as a selector or as a URL.
  54848. * Detects whether `src` is pointing to an image or video and invokes the appropriate
  54849. * callback.
  54850. *
  54851. * `src` will be passed into the callback
  54852. *
  54853. * @params {string|Element} src - URL or media element.
  54854. * @params {function} isImageCb - callback if texture is an image.
  54855. * @params {function} isVideoCb - callback if texture is a video.
  54856. */
  54857. function validateSrc (src, isImageCb, isVideoCb) {
  54858. checkIsImage(src, function isAnImageUrl (isImage) {
  54859. if (isImage) {
  54860. isImageCb(src);
  54861. return;
  54862. }
  54863. isVideoCb(src);
  54864. });
  54865. }
  54866. /**
  54867. * Validates six images as a cubemap, either as selector or comma-separated
  54868. * URLs.
  54869. *
  54870. * @param {string} src - A selector or comma-separated image URLs. Image URLs
  54871. must be wrapped by `url()`.
  54872. * @param {string} src - A selector or comma-separated image URLs. Image URLs
  54873. must be wrapped by `url()`.
  54874. */
  54875. function validateCubemapSrc (src, cb) {
  54876. var aCubemap;
  54877. var cubemapSrcRegex = '';
  54878. var i;
  54879. var urls;
  54880. var validatedUrls = [];
  54881. for (i = 0; i < 5; i++) {
  54882. cubemapSrcRegex += '(url\\((?:[^\\)]+)\\),\\s*)';
  54883. }
  54884. cubemapSrcRegex += '(url\\((?:[^\\)]+)\\)\\s*)';
  54885. urls = src.match(new RegExp(cubemapSrcRegex));
  54886. // `src` is a comma-separated list of URLs.
  54887. // In this case, re-use validateSrc for each side of the cube.
  54888. function isImageCb (url) {
  54889. validatedUrls.push(url);
  54890. if (validatedUrls.length === 6) {
  54891. cb(validatedUrls);
  54892. }
  54893. }
  54894. if (urls) {
  54895. for (i = 1; i < 7; i++) {
  54896. validateSrc(parseUrl(urls[i]), isImageCb);
  54897. }
  54898. return;
  54899. }
  54900. // `src` is a query selector to <a-cubemap> containing six $([src])s.
  54901. aCubemap = validateAndGetQuerySelector(src);
  54902. if (!aCubemap) { return; }
  54903. if (aCubemap.tagName === 'A-CUBEMAP' && aCubemap.srcs) {
  54904. return cb(aCubemap.srcs);
  54905. }
  54906. // Else if aCubeMap is not a <a-cubemap>.
  54907. warn('Selector "%s" does not point to <a-cubemap>', src);
  54908. }
  54909. /**
  54910. * Parses src from `url(src)`.
  54911. * @param {string} src - String to parse.
  54912. * @return {string} The parsed src, if parseable.
  54913. */
  54914. function parseUrl (src) {
  54915. var parsedSrc = src.match(/\url\((.+)\)/);
  54916. if (!parsedSrc) { return; }
  54917. return parsedSrc[1];
  54918. }
  54919. /**
  54920. * Call back whether `src` is an image.
  54921. *
  54922. * @param {string|Element} src - URL or element that will be tested.
  54923. * @param {function} onResult - Callback with whether `src` is an image.
  54924. */
  54925. function checkIsImage (src, onResult) {
  54926. if (src.tagName) {
  54927. onResult(src.tagName === 'IMG');
  54928. return;
  54929. }
  54930. var tester = new Image();
  54931. tester.addEventListener('load', onLoad);
  54932. function onLoad () { onResult(true); }
  54933. tester.addEventListener('error', onError);
  54934. function onError () { onResult(false); }
  54935. tester.src = src;
  54936. }
  54937. /**
  54938. * Query and validate a query selector,
  54939. *
  54940. * @param {string} selector - DOM selector.
  54941. * @return {object|null|undefined} Selected DOM element if exists.
  54942. null if query yields no results.
  54943. undefined if `selector` is not a valid selector.
  54944. */
  54945. function validateAndGetQuerySelector (selector) {
  54946. try {
  54947. var el = document.querySelector(selector);
  54948. if (!el) {
  54949. warn('No element was found matching the selector: "%s"', selector);
  54950. }
  54951. return el;
  54952. } catch (e) { // Capture exception if it's not a valid selector.
  54953. warn('"%s" is not a valid selector', selector);
  54954. return undefined;
  54955. }
  54956. }
  54957. module.exports = {
  54958. parseUrl: parseUrl,
  54959. validateSrc: validateSrc,
  54960. validateCubemapSrc: validateCubemapSrc
  54961. };
  54962. },{"./debug":168}],175:[function(_dereq_,module,exports){
  54963. /* Utils for parsing style-like strings (e.g., "primitive: box; width: 5; height: 4.5"). */
  54964. var styleParser = _dereq_('style-attr');
  54965. /**
  54966. * Deserializes style-like string into an object of properties.
  54967. *
  54968. * @param {string} value - HTML attribute value.
  54969. * @returns {object} Property data.
  54970. */
  54971. module.exports.parse = function (value) {
  54972. var parsedData;
  54973. if (typeof value !== 'string') { return value; }
  54974. parsedData = styleParser.parse(value);
  54975. // The style parser returns an object { "" : "test"} when fed a string
  54976. if (parsedData['']) { return value; }
  54977. return transformKeysToCamelCase(parsedData);
  54978. };
  54979. /**
  54980. * Serialize an object of properties into a style-like string.
  54981. *
  54982. * @param {object} data - Property data.
  54983. * @returns {string}
  54984. */
  54985. module.exports.stringify = function (data) {
  54986. if (typeof data === 'string') { return data; }
  54987. return styleParser.stringify(data);
  54988. };
  54989. /**
  54990. * Converts string from hyphen to camelCase.
  54991. *
  54992. * @param {string} str - String to camelCase.
  54993. * @return {string} CamelCased string.
  54994. */
  54995. function toCamelCase (str) {
  54996. return str.replace(/-([a-z])/g, camelCase);
  54997. function camelCase (g) { return g[1].toUpperCase(); }
  54998. }
  54999. module.exports.toCamelCase = toCamelCase;
  55000. /**
  55001. * Converts object's keys from hyphens to camelCase (e.g., `max-value` to
  55002. * `maxValue`).
  55003. *
  55004. * @param {object} obj - The object to camelCase keys.
  55005. * @return {object} The object with keys camelCased.
  55006. */
  55007. function transformKeysToCamelCase (obj) {
  55008. var keys = Object.keys(obj);
  55009. var camelCaseObj = {};
  55010. keys.forEach(function (key) {
  55011. var camelCaseKey = toCamelCase(key);
  55012. camelCaseObj[camelCaseKey] = obj[key];
  55013. });
  55014. return camelCaseObj;
  55015. }
  55016. module.exports.transformKeysToCamelCase = transformKeysToCamelCase;
  55017. },{"style-attr":36}],176:[function(_dereq_,module,exports){
  55018. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  55019. var AXIS_LABELS = ['x', 'y', 'z', 'w'];
  55020. /**
  55021. * Return enumerated gamepads matching id prefix.
  55022. *
  55023. * @param {object} idPrefix - prefix to match in gamepad id, if any.
  55024. */
  55025. module.exports.getGamepadsByPrefix = function (idPrefix) {
  55026. var gamepadsList = [];
  55027. var gamepad;
  55028. var gamepads = navigator.getGamepads && navigator.getGamepads();
  55029. if (!gamepads) { return gamepadsList; }
  55030. for (var i = 0; i < gamepads.length; ++i) {
  55031. gamepad = gamepads[i];
  55032. // need to check that gamepad is valid, since browsers may return array of null values
  55033. if (gamepad) {
  55034. if (!idPrefix || gamepad.id.indexOf(idPrefix) === 0) {
  55035. gamepadsList.push(gamepad);
  55036. }
  55037. }
  55038. }
  55039. return gamepadsList;
  55040. };
  55041. /**
  55042. * Check if the controller match the parameters and inject the tracked-controls component
  55043. * and add eventlistener, otherwise it will just remove the listener.
  55044. * It will also generate a controllerconnected or controllerdisconnected.
  55045. *
  55046. * @param {object} component - the tracked controls component.
  55047. * @param {object} idPrefix - prefix to match in gamepad id, if any.
  55048. * @param {object} queryObject - map of values to match (hand; index among controllers with idPrefix)
  55049. */
  55050. module.exports.checkControllerPresentAndSetup = function (component, idPrefix, queryObject) {
  55051. var el = component.el;
  55052. var isPresent = isControllerPresent(component, idPrefix, queryObject);
  55053. // Nothing changed, no need to do anything.
  55054. if (isPresent === component.controllerPresent) { return isPresent; }
  55055. component.controllerPresent = isPresent;
  55056. // Update controller presence.
  55057. if (isPresent) {
  55058. component.injectTrackedControls();
  55059. component.addEventListeners();
  55060. el.emit('controllerconnected', {name: component.name, component: component});
  55061. } else {
  55062. component.removeEventListeners();
  55063. el.emit('controllerdisconnected', {name: component.name, component: component});
  55064. }
  55065. };
  55066. /**
  55067. * Enumerate controllers (as built by system tick, e.g. that have pose) and check if they match parameters.
  55068. *
  55069. * @param {object} component - the tracked controls component.
  55070. * @param {object} idPrefix - prefix to match in gamepad id, if any.
  55071. * @param {object} queryObject - map of values to match (hand; index among controllers with idPrefix)
  55072. */
  55073. function isControllerPresent (component, idPrefix, queryObject) {
  55074. var isPresent = false;
  55075. var index = 0;
  55076. var gamepad;
  55077. var isPrefixMatch;
  55078. var gamepads;
  55079. var sceneEl = component.el.sceneEl;
  55080. var trackedControlsSystem = sceneEl && sceneEl.systems['tracked-controls'];
  55081. if (!trackedControlsSystem) { return isPresent; }
  55082. gamepads = trackedControlsSystem.controllers;
  55083. if (!gamepads || gamepads.length === 0) {
  55084. trackedControlsSystem.updateControllerList();
  55085. gamepads = trackedControlsSystem.controllers;
  55086. }
  55087. if (!gamepads) { return isPresent; }
  55088. for (var i = 0; i < gamepads.length; ++i) {
  55089. gamepad = gamepads[i];
  55090. isPrefixMatch = (!idPrefix || idPrefix === '' || gamepad.id.indexOf(idPrefix) === 0);
  55091. isPresent = isPrefixMatch;
  55092. if (isPresent && queryObject.hand) {
  55093. isPresent = (gamepad.hand || DEFAULT_HANDEDNESS) === queryObject.hand;
  55094. }
  55095. if (isPresent && queryObject.index) {
  55096. isPresent = index === queryObject.index; // need to use count of gamepads with idPrefix
  55097. }
  55098. if (isPresent) { break; }
  55099. if (isPrefixMatch) { index++; } // update count of gamepads with idPrefix
  55100. }
  55101. return isPresent;
  55102. }
  55103. module.exports.isControllerPresent = isControllerPresent;
  55104. /**
  55105. * Emit specific moved event(s) if axes changed, based on original axismoved event.
  55106. *
  55107. * @param {object} self - the component in use (e.g. oculus-touch-controls, vive-controls...)
  55108. * @param {array} axesMapping - the axes mapping to process
  55109. * @param {object} evt - the event to process
  55110. */
  55111. module.exports.emitIfAxesChanged = function (self, axesMapping, evt) {
  55112. Object.keys(axesMapping).forEach(function (key) {
  55113. var axes = axesMapping[key];
  55114. var changed = evt.detail.changed;
  55115. // If no changed axes given at all, or at least one changed value is true in the array,
  55116. if (axes.reduce(function (b, axis) { return b || changed[axis]; }, !changed)) {
  55117. // An axis has changed, so emit the specific moved event, detailing axis values.
  55118. var detail = {};
  55119. axes.forEach(function (axis) { detail[AXIS_LABELS[axis]] = evt.detail.axis[axis]; });
  55120. self.el.emit(key + 'moved', detail);
  55121. // If we updated the model based on axis values, that call would go here.
  55122. }
  55123. });
  55124. };
  55125. },{"../constants":93}],177:[function(_dereq_,module,exports){
  55126. /**
  55127. * @author dmarcos / https://github.com/dmarcos
  55128. * @author mrdoob / http://mrdoob.com
  55129. */
  55130. THREE.VRControls = function ( object, onError ) {
  55131. var scope = this;
  55132. var vrDisplay, vrDisplays;
  55133. var standingMatrix = new THREE.Matrix4();
  55134. var frameData = null;
  55135. if ( 'VRFrameData' in window ) {
  55136. frameData = new window.VRFrameData();
  55137. }
  55138. function gotVRDisplays( displays ) {
  55139. vrDisplays = displays;
  55140. if ( displays.length > 0 ) {
  55141. vrDisplay = displays[ 0 ];
  55142. } else {
  55143. if ( onError ) onError( 'VR input not available.' );
  55144. }
  55145. }
  55146. if ( navigator.getVRDisplays ) {
  55147. navigator.getVRDisplays().then( gotVRDisplays ).catch ( function () {
  55148. console.warn( 'THREE.VRControls: Unable to get VR Displays' );
  55149. } );
  55150. }
  55151. // the Rift SDK returns the position in meters
  55152. // this scale factor allows the user to define how meters
  55153. // are converted to scene units.
  55154. this.scale = 1;
  55155. // If true will use "standing space" coordinate system where y=0 is the
  55156. // floor and x=0, z=0 is the center of the room.
  55157. this.standing = false;
  55158. // Distance from the users eyes to the floor in meters. Used when
  55159. // standing=true but the VRDisplay doesn't provide stageParameters.
  55160. this.userHeight = 1.6;
  55161. this.getVRDisplay = function () {
  55162. return vrDisplay;
  55163. };
  55164. this.setVRDisplay = function ( value ) {
  55165. vrDisplay = value;
  55166. };
  55167. this.getVRDisplays = function () {
  55168. console.warn( 'THREE.VRControls: getVRDisplays() is being deprecated.' );
  55169. return vrDisplays;
  55170. };
  55171. this.getStandingMatrix = function () {
  55172. return standingMatrix;
  55173. };
  55174. this.update = function () {
  55175. if ( vrDisplay ) {
  55176. var pose;
  55177. if ( vrDisplay.getFrameData ) {
  55178. vrDisplay.getFrameData( frameData );
  55179. pose = frameData.pose;
  55180. } else if ( vrDisplay.getPose ) {
  55181. pose = vrDisplay.getPose();
  55182. }
  55183. if ( pose.orientation !== null ) {
  55184. object.quaternion.fromArray( pose.orientation );
  55185. }
  55186. if ( pose.position !== null ) {
  55187. object.position.fromArray( pose.position );
  55188. } else {
  55189. object.position.set( 0, 0, 0 );
  55190. }
  55191. if ( this.standing ) {
  55192. if ( vrDisplay.stageParameters ) {
  55193. object.updateMatrix();
  55194. standingMatrix.fromArray( vrDisplay.stageParameters.sittingToStandingTransform );
  55195. object.applyMatrix( standingMatrix );
  55196. } else {
  55197. object.position.setY( object.position.y + this.userHeight );
  55198. }
  55199. }
  55200. object.position.multiplyScalar( scope.scale );
  55201. }
  55202. };
  55203. this.resetPose = function () {
  55204. if ( vrDisplay ) {
  55205. vrDisplay.resetPose();
  55206. }
  55207. };
  55208. this.resetSensor = function () {
  55209. console.warn( 'THREE.VRControls: .resetSensor() is now .resetPose().' );
  55210. this.resetPose();
  55211. };
  55212. this.zeroSensor = function () {
  55213. console.warn( 'THREE.VRControls: .zeroSensor() is now .resetPose().' );
  55214. this.resetPose();
  55215. };
  55216. this.dispose = function () {
  55217. vrDisplay = null;
  55218. };
  55219. };
  55220. },{}],178:[function(_dereq_,module,exports){
  55221. /**
  55222. * @author dmarcos / https://github.com/dmarcos
  55223. * @author mrdoob / http://mrdoob.com
  55224. *
  55225. * WebVR Spec: http://mozvr.github.io/webvr-spec/webvr.html
  55226. *
  55227. * Firefox: http://mozvr.com/downloads/
  55228. * Chromium: https://webvr.info/get-chrome
  55229. *
  55230. */
  55231. THREE.VREffect = function( renderer, onError ) {
  55232. var vrDisplay, vrDisplays;
  55233. var eyeTranslationL = new THREE.Vector3();
  55234. var eyeTranslationR = new THREE.Vector3();
  55235. var renderRectL, renderRectR;
  55236. var frameData = null;
  55237. if ( 'VRFrameData' in window ) {
  55238. frameData = new window.VRFrameData();
  55239. }
  55240. function gotVRDisplays( displays ) {
  55241. vrDisplays = displays;
  55242. if ( displays.length > 0 ) {
  55243. vrDisplay = displays[ 0 ];
  55244. } else {
  55245. if ( onError ) onError( 'HMD not available' );
  55246. }
  55247. }
  55248. if ( navigator.getVRDisplays ) {
  55249. navigator.getVRDisplays().then( gotVRDisplays ).catch( function() {
  55250. console.warn( 'THREE.VREffect: Unable to get VR Displays' );
  55251. } );
  55252. }
  55253. //
  55254. this.isPresenting = false;
  55255. var scope = this;
  55256. var rendererSize = renderer.getSize();
  55257. var rendererUpdateStyle = false;
  55258. var rendererPixelRatio = renderer.getPixelRatio();
  55259. this.getVRDisplay = function() {
  55260. return vrDisplay;
  55261. };
  55262. this.setVRDisplay = function( value ) {
  55263. vrDisplay = value;
  55264. };
  55265. this.getVRDisplays = function() {
  55266. console.warn( 'THREE.VREffect: getVRDisplays() is being deprecated.' );
  55267. return vrDisplays;
  55268. };
  55269. this.setSize = function( width, height, updateStyle ) {
  55270. rendererSize = { width: width, height: height };
  55271. rendererUpdateStyle = updateStyle;
  55272. if ( scope.isPresenting ) {
  55273. var eyeParamsL = vrDisplay.getEyeParameters( 'left' );
  55274. renderer.setPixelRatio( 1 );
  55275. renderer.setSize( eyeParamsL.renderWidth * 2, eyeParamsL.renderHeight, false );
  55276. } else {
  55277. renderer.setPixelRatio( rendererPixelRatio );
  55278. renderer.setSize( width, height, updateStyle );
  55279. }
  55280. };
  55281. // VR presentation
  55282. var canvas = renderer.domElement;
  55283. var defaultLeftBounds = [ 0.0, 0.0, 0.5, 1.0 ];
  55284. var defaultRightBounds = [ 0.5, 0.0, 0.5, 1.0 ];
  55285. function onVRDisplayPresentChange() {
  55286. var wasPresenting = scope.isPresenting;
  55287. scope.isPresenting = vrDisplay !== undefined && vrDisplay.isPresenting;
  55288. if ( scope.isPresenting ) {
  55289. var eyeParamsL = vrDisplay.getEyeParameters( 'left' );
  55290. var eyeWidth = eyeParamsL.renderWidth;
  55291. var eyeHeight = eyeParamsL.renderHeight;
  55292. if ( ! wasPresenting ) {
  55293. rendererPixelRatio = renderer.getPixelRatio();
  55294. rendererSize = renderer.getSize();
  55295. renderer.setPixelRatio( 1 );
  55296. renderer.setSize( eyeWidth * 2, eyeHeight, false );
  55297. }
  55298. } else if ( wasPresenting ) {
  55299. renderer.setPixelRatio( rendererPixelRatio );
  55300. renderer.setSize( rendererSize.width, rendererSize.height, rendererUpdateStyle );
  55301. }
  55302. }
  55303. window.addEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange, false );
  55304. this.setFullScreen = function( boolean ) {
  55305. return new Promise( function( resolve, reject ) {
  55306. if ( vrDisplay === undefined ) {
  55307. reject( new Error( 'No VR hardware found.' ) );
  55308. return;
  55309. }
  55310. if ( scope.isPresenting === boolean ) {
  55311. resolve();
  55312. return;
  55313. }
  55314. if ( boolean ) {
  55315. resolve( vrDisplay.requestPresent( [ { source: canvas } ] ) );
  55316. } else {
  55317. resolve( vrDisplay.exitPresent() );
  55318. }
  55319. } );
  55320. };
  55321. this.requestPresent = function() {
  55322. return this.setFullScreen( true );
  55323. };
  55324. this.exitPresent = function() {
  55325. return this.setFullScreen( false );
  55326. };
  55327. this.requestAnimationFrame = function( f ) {
  55328. if ( vrDisplay !== undefined ) {
  55329. return vrDisplay.requestAnimationFrame( f );
  55330. } else {
  55331. return window.requestAnimationFrame( f );
  55332. }
  55333. };
  55334. this.cancelAnimationFrame = function( h ) {
  55335. if ( vrDisplay !== undefined ) {
  55336. vrDisplay.cancelAnimationFrame( h );
  55337. } else {
  55338. window.cancelAnimationFrame( h );
  55339. }
  55340. };
  55341. this.submitFrame = function() {
  55342. if ( vrDisplay !== undefined && scope.isPresenting ) {
  55343. vrDisplay.submitFrame();
  55344. }
  55345. };
  55346. this.autoSubmitFrame = true;
  55347. // render
  55348. var cameraL = new THREE.PerspectiveCamera();
  55349. cameraL.layers.enable( 1 );
  55350. var cameraR = new THREE.PerspectiveCamera();
  55351. cameraR.layers.enable( 2 );
  55352. this.render = function( scene, camera, renderTarget, forceClear ) {
  55353. if ( vrDisplay && scope.isPresenting ) {
  55354. var autoUpdate = scene.autoUpdate;
  55355. if ( autoUpdate ) {
  55356. scene.updateMatrixWorld();
  55357. scene.autoUpdate = false;
  55358. }
  55359. var eyeParamsL = vrDisplay.getEyeParameters( 'left' );
  55360. var eyeParamsR = vrDisplay.getEyeParameters( 'right' );
  55361. eyeTranslationL.fromArray( eyeParamsL.offset );
  55362. eyeTranslationR.fromArray( eyeParamsR.offset );
  55363. if ( Array.isArray( scene ) ) {
  55364. console.warn( 'THREE.VREffect.render() no longer supports arrays. Use object.layers instead.' );
  55365. scene = scene[ 0 ];
  55366. }
  55367. // When rendering we don't care what the recommended size is, only what the actual size
  55368. // of the backbuffer is.
  55369. var size = renderer.getSize();
  55370. var layers = vrDisplay.getLayers();
  55371. var leftBounds;
  55372. var rightBounds;
  55373. if ( layers.length ) {
  55374. var layer = layers[ 0 ];
  55375. leftBounds = layer.leftBounds !== null && layer.leftBounds.length === 4 ? layer.leftBounds : defaultLeftBounds;
  55376. rightBounds = layer.rightBounds !== null && layer.rightBounds.length === 4 ? layer.rightBounds : defaultRightBounds;
  55377. } else {
  55378. leftBounds = defaultLeftBounds;
  55379. rightBounds = defaultRightBounds;
  55380. }
  55381. renderRectL = {
  55382. x: Math.round( size.width * leftBounds[ 0 ] ),
  55383. y: Math.round( size.height * leftBounds[ 1 ] ),
  55384. width: Math.round( size.width * leftBounds[ 2 ] ),
  55385. height: Math.round( size.height * leftBounds[ 3 ] )
  55386. };
  55387. renderRectR = {
  55388. x: Math.round( size.width * rightBounds[ 0 ] ),
  55389. y: Math.round( size.height * rightBounds[ 1 ] ),
  55390. width: Math.round( size.width * rightBounds[ 2 ] ),
  55391. height: Math.round( size.height * rightBounds[ 3 ] )
  55392. };
  55393. if ( renderTarget ) {
  55394. renderer.setRenderTarget( renderTarget );
  55395. renderTarget.scissorTest = true;
  55396. } else {
  55397. renderer.setRenderTarget( null );
  55398. renderer.setScissorTest( true );
  55399. }
  55400. if ( renderer.autoClear || forceClear ) renderer.clear();
  55401. if ( camera.parent === null ) camera.updateMatrixWorld();
  55402. camera.matrixWorld.decompose( cameraL.position, cameraL.quaternion, cameraL.scale );
  55403. cameraR.position.copy(cameraL.position);
  55404. cameraR.quaternion.copy(cameraL.quaternion);
  55405. cameraR.scale.copy(cameraL.scale);
  55406. cameraL.translateOnAxis( eyeTranslationL, cameraL.scale.x );
  55407. cameraR.translateOnAxis( eyeTranslationR, cameraR.scale.x );
  55408. if ( vrDisplay.getFrameData ) {
  55409. vrDisplay.depthNear = camera.near;
  55410. vrDisplay.depthFar = camera.far;
  55411. vrDisplay.getFrameData( frameData );
  55412. cameraL.projectionMatrix.elements = frameData.leftProjectionMatrix;
  55413. cameraR.projectionMatrix.elements = frameData.rightProjectionMatrix;
  55414. } else {
  55415. cameraL.projectionMatrix = fovToProjection( eyeParamsL.fieldOfView, true, camera.near, camera.far );
  55416. cameraR.projectionMatrix = fovToProjection( eyeParamsR.fieldOfView, true, camera.near, camera.far );
  55417. }
  55418. // render left eye
  55419. if ( renderTarget ) {
  55420. renderTarget.viewport.set( renderRectL.x, renderRectL.y, renderRectL.width, renderRectL.height );
  55421. renderTarget.scissor.set( renderRectL.x, renderRectL.y, renderRectL.width, renderRectL.height );
  55422. } else {
  55423. renderer.setViewport( renderRectL.x, renderRectL.y, renderRectL.width, renderRectL.height );
  55424. renderer.setScissor( renderRectL.x, renderRectL.y, renderRectL.width, renderRectL.height );
  55425. }
  55426. renderer.render( scene, cameraL, renderTarget, forceClear );
  55427. // render right eye
  55428. if ( renderTarget ) {
  55429. renderTarget.viewport.set( renderRectR.x, renderRectR.y, renderRectR.width, renderRectR.height );
  55430. renderTarget.scissor.set( renderRectR.x, renderRectR.y, renderRectR.width, renderRectR.height );
  55431. } else {
  55432. renderer.setViewport( renderRectR.x, renderRectR.y, renderRectR.width, renderRectR.height );
  55433. renderer.setScissor( renderRectR.x, renderRectR.y, renderRectR.width, renderRectR.height );
  55434. }
  55435. renderer.render( scene, cameraR, renderTarget, forceClear );
  55436. if ( renderTarget ) {
  55437. renderTarget.viewport.set( 0, 0, size.width, size.height );
  55438. renderTarget.scissor.set( 0, 0, size.width, size.height );
  55439. renderTarget.scissorTest = false;
  55440. renderer.setRenderTarget( null );
  55441. } else {
  55442. renderer.setViewport( 0, 0, size.width, size.height );
  55443. renderer.setScissorTest( false );
  55444. }
  55445. if ( autoUpdate ) {
  55446. scene.autoUpdate = true;
  55447. }
  55448. if ( scope.autoSubmitFrame ) {
  55449. scope.submitFrame();
  55450. }
  55451. return;
  55452. }
  55453. // Regular render mode if not HMD
  55454. renderer.render( scene, camera, renderTarget, forceClear );
  55455. };
  55456. this.dispose = function() {
  55457. window.removeEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange, false );
  55458. };
  55459. //
  55460. function fovToNDCScaleOffset( fov ) {
  55461. var pxscale = 2.0 / ( fov.leftTan + fov.rightTan );
  55462. var pxoffset = ( fov.leftTan - fov.rightTan ) * pxscale * 0.5;
  55463. var pyscale = 2.0 / ( fov.upTan + fov.downTan );
  55464. var pyoffset = ( fov.upTan - fov.downTan ) * pyscale * 0.5;
  55465. return { scale: [ pxscale, pyscale ], offset: [ pxoffset, pyoffset ] };
  55466. }
  55467. function fovPortToProjection( fov, rightHanded, zNear, zFar ) {
  55468. rightHanded = rightHanded === undefined ? true : rightHanded;
  55469. zNear = zNear === undefined ? 0.01 : zNear;
  55470. zFar = zFar === undefined ? 10000.0 : zFar;
  55471. var handednessScale = rightHanded ? - 1.0 : 1.0;
  55472. // start with an identity matrix
  55473. var mobj = new THREE.Matrix4();
  55474. var m = mobj.elements;
  55475. // and with scale/offset info for normalized device coords
  55476. var scaleAndOffset = fovToNDCScaleOffset( fov );
  55477. // X result, map clip edges to [-w,+w]
  55478. m[ 0 * 4 + 0 ] = scaleAndOffset.scale[ 0 ];
  55479. m[ 0 * 4 + 1 ] = 0.0;
  55480. m[ 0 * 4 + 2 ] = scaleAndOffset.offset[ 0 ] * handednessScale;
  55481. m[ 0 * 4 + 3 ] = 0.0;
  55482. // Y result, map clip edges to [-w,+w]
  55483. // Y offset is negated because this proj matrix transforms from world coords with Y=up,
  55484. // but the NDC scaling has Y=down (thanks D3D?)
  55485. m[ 1 * 4 + 0 ] = 0.0;
  55486. m[ 1 * 4 + 1 ] = scaleAndOffset.scale[ 1 ];
  55487. m[ 1 * 4 + 2 ] = - scaleAndOffset.offset[ 1 ] * handednessScale;
  55488. m[ 1 * 4 + 3 ] = 0.0;
  55489. // Z result (up to the app)
  55490. m[ 2 * 4 + 0 ] = 0.0;
  55491. m[ 2 * 4 + 1 ] = 0.0;
  55492. m[ 2 * 4 + 2 ] = zFar / ( zNear - zFar ) * - handednessScale;
  55493. m[ 2 * 4 + 3 ] = ( zFar * zNear ) / ( zNear - zFar );
  55494. // W result (= Z in)
  55495. m[ 3 * 4 + 0 ] = 0.0;
  55496. m[ 3 * 4 + 1 ] = 0.0;
  55497. m[ 3 * 4 + 2 ] = handednessScale;
  55498. m[ 3 * 4 + 3 ] = 0.0;
  55499. mobj.transpose();
  55500. return mobj;
  55501. }
  55502. function fovToProjection( fov, rightHanded, zNear, zFar ) {
  55503. var DEG2RAD = Math.PI / 180.0;
  55504. var fovPort = {
  55505. upTan: Math.tan( fov.upDegrees * DEG2RAD ),
  55506. downTan: Math.tan( fov.downDegrees * DEG2RAD ),
  55507. leftTan: Math.tan( fov.leftDegrees * DEG2RAD ),
  55508. rightTan: Math.tan( fov.rightDegrees * DEG2RAD )
  55509. };
  55510. return fovPortToProjection( fovPort, rightHanded, zNear, zFar );
  55511. }
  55512. };
  55513. },{}],179:[function(_dereq_,module,exports){
  55514. window.glStats = function () {
  55515. var _rS = null;
  55516. var _totalDrawArraysCalls = 0,
  55517. _totalDrawElementsCalls = 0,
  55518. _totalUseProgramCalls = 0,
  55519. _totalFaces = 0,
  55520. _totalVertices = 0,
  55521. _totalPoints = 0,
  55522. _totalBindTexures = 0;
  55523. function _h ( f, c ) {
  55524. return function () {
  55525. c.apply( this, arguments );
  55526. f.apply( this, arguments );
  55527. };
  55528. }
  55529. WebGLRenderingContext.prototype.drawArrays = _h( WebGLRenderingContext.prototype.drawArrays, function () {
  55530. _totalDrawArraysCalls++;
  55531. if ( arguments[ 0 ] == this.POINTS ) _totalPoints += arguments[ 2 ];
  55532. else _totalVertices += arguments[ 2 ];
  55533. } );
  55534. WebGLRenderingContext.prototype.drawElements = _h( WebGLRenderingContext.prototype.drawElements, function () {
  55535. _totalDrawElementsCalls++;
  55536. _totalFaces += arguments[ 1 ] / 3;
  55537. _totalVertices += arguments[ 1 ];
  55538. } );
  55539. WebGLRenderingContext.prototype.useProgram = _h( WebGLRenderingContext.prototype.useProgram, function () {
  55540. _totalUseProgramCalls++;
  55541. } );
  55542. WebGLRenderingContext.prototype.bindTexture = _h( WebGLRenderingContext.prototype.bindTexture, function () {
  55543. _totalBindTexures++;
  55544. } );
  55545. var _values = {
  55546. allcalls: {
  55547. over: 3000,
  55548. caption: 'Calls (hook)'
  55549. },
  55550. drawelements: {
  55551. caption: 'drawElements (hook)'
  55552. },
  55553. drawarrays: {
  55554. caption: 'drawArrays (hook)'
  55555. }
  55556. };
  55557. var _groups = [ {
  55558. caption: 'WebGL',
  55559. values: [ 'allcalls', 'drawelements', 'drawarrays', 'useprogram', 'bindtexture', 'glfaces', 'glvertices', 'glpoints' ]
  55560. } ];
  55561. var _fractions = [ {
  55562. base: 'allcalls',
  55563. steps: [ 'drawelements', 'drawarrays' ]
  55564. } ];
  55565. function _update () {
  55566. _rS( 'allcalls' ).set( _totalDrawArraysCalls + _totalDrawElementsCalls );
  55567. _rS( 'drawElements' ).set( _totalDrawElementsCalls );
  55568. _rS( 'drawArrays' ).set( _totalDrawArraysCalls );
  55569. _rS( 'bindTexture' ).set( _totalBindTexures );
  55570. _rS( 'useProgram' ).set( _totalUseProgramCalls );
  55571. _rS( 'glfaces' ).set( _totalFaces );
  55572. _rS( 'glvertices' ).set( _totalVertices );
  55573. _rS( 'glpoints' ).set( _totalPoints );
  55574. }
  55575. function _start () {
  55576. _totalDrawArraysCalls = 0;
  55577. _totalDrawElementsCalls = 0;
  55578. _totalUseProgramCalls = 0;
  55579. _totalFaces = 0;
  55580. _totalVertices = 0;
  55581. _totalPoints = 0;
  55582. _totalBindTexures = 0;
  55583. }
  55584. function _end () {}
  55585. function _attach ( r ) {
  55586. _rS = r;
  55587. }
  55588. return {
  55589. update: _update,
  55590. start: _start,
  55591. end: _end,
  55592. attach: _attach,
  55593. values: _values,
  55594. groups: _groups,
  55595. fractions: _fractions
  55596. };
  55597. };
  55598. window.threeStats = function ( renderer ) {
  55599. var _rS = null;
  55600. var _values = {
  55601. 'renderer.info.memory.geometries': {
  55602. caption: 'Geometries'
  55603. },
  55604. 'renderer.info.memory.textures': {
  55605. caption: 'Textures'
  55606. },
  55607. 'renderer.info.programs': {
  55608. caption: 'Programs'
  55609. },
  55610. 'renderer.info.render.calls': {
  55611. caption: 'Calls'
  55612. },
  55613. 'renderer.info.render.faces': {
  55614. caption: 'Faces',
  55615. over: 1000
  55616. },
  55617. 'renderer.info.render.points': {
  55618. caption: 'Points'
  55619. },
  55620. 'renderer.info.render.vertices': {
  55621. caption: 'Vertices'
  55622. }
  55623. };
  55624. var _groups = [ {
  55625. caption: 'Three.js - Memory',
  55626. values: [ 'renderer.info.memory.geometries', 'renderer.info.programs', 'renderer.info.memory.textures' ]
  55627. }, {
  55628. caption: 'Three.js - Render',
  55629. values: [ 'renderer.info.render.calls', 'renderer.info.render.faces', 'renderer.info.render.points', 'renderer.info.render.vertices' ]
  55630. } ];
  55631. var _fractions = [];
  55632. function _update () {
  55633. _rS( 'renderer.info.memory.geometries' ).set( renderer.info.memory.geometries );
  55634. _rS( 'renderer.info.programs' ).set( renderer.info.programs.length );
  55635. _rS( 'renderer.info.memory.textures' ).set( renderer.info.memory.textures );
  55636. _rS( 'renderer.info.render.calls' ).set( renderer.info.render.calls );
  55637. _rS( 'renderer.info.render.faces' ).set( renderer.info.render.faces );
  55638. _rS( 'renderer.info.render.points' ).set( renderer.info.render.points );
  55639. _rS( 'renderer.info.render.vertices' ).set( renderer.info.render.vertices );
  55640. }
  55641. function _start () {}
  55642. function _end () {}
  55643. function _attach ( r ) {
  55644. _rS = r;
  55645. }
  55646. return {
  55647. update: _update,
  55648. start: _start,
  55649. end: _end,
  55650. attach: _attach,
  55651. values: _values,
  55652. groups: _groups,
  55653. fractions: _fractions
  55654. };
  55655. };
  55656. /*
  55657. * From https://github.com/paulirish/memory-stats.js
  55658. */
  55659. window.BrowserStats = function () {
  55660. var _rS = null;
  55661. var _usedJSHeapSize = 0,
  55662. _totalJSHeapSize = 0;
  55663. if ( window.performance && !performance.memory ) {
  55664. performance.memory = {
  55665. usedJSHeapSize: 0,
  55666. totalJSHeapSize: 0
  55667. };
  55668. }
  55669. if ( performance.memory.totalJSHeapSize === 0 ) {
  55670. console.warn( 'totalJSHeapSize === 0... performance.memory is only available in Chrome .' );
  55671. }
  55672. var _values = {
  55673. memory: {
  55674. caption: 'Used Memory',
  55675. average: true,
  55676. avgMs: 1000,
  55677. over: 22
  55678. },
  55679. total: {
  55680. caption: 'Total Memory'
  55681. }
  55682. };
  55683. var _groups = [ {
  55684. caption: 'Browser',
  55685. values: [ 'memory', 'total' ]
  55686. } ];
  55687. var _fractions = [ {
  55688. base: 'total',
  55689. steps: [ 'memory' ]
  55690. } ];
  55691. var log1024 = Math.log( 1024 );
  55692. function _size ( v ) {
  55693. var precision = 100; //Math.pow(10, 2);
  55694. var i = Math.floor( Math.log( v ) / log1024 );
  55695. return Math.round( v * precision / Math.pow( 1024, i ) ) / precision; // + ' ' + sizes[i];
  55696. }
  55697. function _update () {
  55698. _usedJSHeapSize = _size( performance.memory.usedJSHeapSize );
  55699. _totalJSHeapSize = _size( performance.memory.totalJSHeapSize );
  55700. _rS( 'memory' ).set( _usedJSHeapSize );
  55701. _rS( 'total' ).set( _totalJSHeapSize );
  55702. }
  55703. function _start () {
  55704. _usedJSHeapSize = 0;
  55705. }
  55706. function _end () {}
  55707. function _attach ( r ) {
  55708. _rS = r;
  55709. }
  55710. return {
  55711. update: _update,
  55712. start: _start,
  55713. end: _end,
  55714. attach: _attach,
  55715. values: _values,
  55716. groups: _groups,
  55717. fractions: _fractions
  55718. };
  55719. };
  55720. if (typeof module === 'object') {
  55721. module.exports = {
  55722. glStats: window.glStats,
  55723. threeStats: window.threeStats,
  55724. BrowserStats: window.BrowserStats
  55725. };
  55726. }
  55727. },{}],180:[function(_dereq_,module,exports){
  55728. // performance.now() polyfill from https://gist.github.com/paulirish/5438650
  55729. 'use strict';
  55730. ( function () {
  55731. if ( 'performance' in window == false ) {
  55732. window.performance = {};
  55733. }
  55734. var performance = window.performance;
  55735. if ( 'now' in performance == false ) {
  55736. var nowOffset = Date.now();
  55737. if ( performance.timing && performance.timing.navigationStart ) {
  55738. nowOffset = performance.timing.navigationStart;
  55739. }
  55740. performance.now = function now () {
  55741. return Date.now() - nowOffset;
  55742. };
  55743. }
  55744. if( !performance.mark ) {
  55745. performance.mark = function(){}
  55746. }
  55747. if( !performance.measure ) {
  55748. performance.measure = function(){}
  55749. }
  55750. } )();
  55751. window.rStats = function rStats ( settings ) {
  55752. function iterateKeys ( array, callback ) {
  55753. var keys = Object.keys( array );
  55754. for ( var j = 0, l = keys.length; j < l; j++ ) {
  55755. callback( keys[ j ] );
  55756. }
  55757. }
  55758. function importCSS ( url ) {
  55759. var element = document.createElement( 'link' );
  55760. element.href = url;
  55761. element.rel = 'stylesheet';
  55762. element.type = 'text/css';
  55763. document.getElementsByTagName( 'head' )[ 0 ].appendChild( element );
  55764. }
  55765. var _settings = settings || {};
  55766. var _colours = _settings.colours || [ '#850700', '#c74900', '#fcb300', '#284280', '#4c7c0c' ];
  55767. var _cssFont = 'https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700,300';
  55768. var _cssRStats = ( _settings.CSSPath ? _settings.CSSPath : '' ) + 'rStats.css';
  55769. var _css = _settings.css || [ _cssFont, _cssRStats ];
  55770. _css.forEach(function (uri) {
  55771. importCSS( uri );
  55772. });
  55773. if ( !_settings.values ) _settings.values = {};
  55774. var _base, _div, _elHeight = 10, _elWidth = 200;
  55775. var _perfCounters = {};
  55776. function Graph ( _dom, _id, _defArg ) {
  55777. var _def = _defArg || {};
  55778. var _canvas = document.createElement( 'canvas' ),
  55779. _ctx = _canvas.getContext( '2d' ),
  55780. _max = 0,
  55781. _current = 0;
  55782. var c = _def.color ? _def.color : '#666666';
  55783. var _dotCanvas = document.createElement( 'canvas' ),
  55784. _dotCtx = _dotCanvas.getContext( '2d' );
  55785. _dotCanvas.width = 1;
  55786. _dotCanvas.height = 2 * _elHeight;
  55787. _dotCtx.fillStyle = '#444444';
  55788. _dotCtx.fillRect( 0, 0, 1, 2 * _elHeight );
  55789. _dotCtx.fillStyle = c;
  55790. _dotCtx.fillRect( 0, _elHeight, 1, _elHeight );
  55791. _dotCtx.fillStyle = '#ffffff';
  55792. _dotCtx.globalAlpha = 0.5;
  55793. _dotCtx.fillRect( 0, _elHeight, 1, 1 );
  55794. _dotCtx.globalAlpha = 1;
  55795. var _alarmCanvas = document.createElement( 'canvas' ),
  55796. _alarmCtx = _alarmCanvas.getContext( '2d' );
  55797. _alarmCanvas.width = 1;
  55798. _alarmCanvas.height = 2 * _elHeight;
  55799. _alarmCtx.fillStyle = '#444444';
  55800. _alarmCtx.fillRect( 0, 0, 1, 2 * _elHeight );
  55801. _alarmCtx.fillStyle = '#b70000';
  55802. _alarmCtx.fillRect( 0, _elHeight, 1, _elHeight );
  55803. _alarmCtx.globalAlpha = 0.5;
  55804. _alarmCtx.fillStyle = '#ffffff';
  55805. _alarmCtx.fillRect( 0, _elHeight, 1, 1 );
  55806. _alarmCtx.globalAlpha = 1;
  55807. function _init () {
  55808. _canvas.width = _elWidth;
  55809. _canvas.height = _elHeight;
  55810. _canvas.style.width = _canvas.width + 'px';
  55811. _canvas.style.height = _canvas.height + 'px';
  55812. _canvas.className = 'rs-canvas';
  55813. _dom.appendChild( _canvas );
  55814. _ctx.fillStyle = '#444444';
  55815. _ctx.fillRect( 0, 0, _canvas.width, _canvas.height );
  55816. }
  55817. function _draw ( v, alarm ) {
  55818. _current += ( v - _current ) * 0.1;
  55819. _max *= 0.99;
  55820. if ( _current > _max ) _max = _current;
  55821. _ctx.drawImage( _canvas, 1, 0, _canvas.width - 1, _canvas.height, 0, 0, _canvas.width - 1, _canvas.height );
  55822. if ( alarm ) {
  55823. _ctx.drawImage( _alarmCanvas, _canvas.width - 1, _canvas.height - _current * _canvas.height / _max - _elHeight );
  55824. } else {
  55825. _ctx.drawImage( _dotCanvas, _canvas.width - 1, _canvas.height - _current * _canvas.height / _max - _elHeight );
  55826. }
  55827. }
  55828. _init();
  55829. return {
  55830. draw: _draw
  55831. };
  55832. }
  55833. function StackGraph ( _dom, _num ) {
  55834. var _canvas = document.createElement( 'canvas' ),
  55835. _ctx = _canvas.getContext( '2d' );
  55836. function _init () {
  55837. _canvas.width = _elWidth;
  55838. _canvas.height = _elHeight * _num;
  55839. _canvas.style.width = _canvas.width + 'px';
  55840. _canvas.style.height = _canvas.height + 'px';
  55841. _canvas.className = 'rs-canvas';
  55842. _dom.appendChild( _canvas );
  55843. _ctx.fillStyle = '#444444';
  55844. _ctx.fillRect( 0, 0, _canvas.width, _canvas.height );
  55845. }
  55846. function _draw ( v ) {
  55847. _ctx.drawImage( _canvas, 1, 0, _canvas.width - 1, _canvas.height, 0, 0, _canvas.width - 1, _canvas.height );
  55848. var th = 0;
  55849. iterateKeys( v, function ( j ) {
  55850. var h = v[ j ] * _canvas.height;
  55851. _ctx.fillStyle = _colours[ j ];
  55852. _ctx.fillRect( _canvas.width - 1, th, 1, h );
  55853. th += h;
  55854. } );
  55855. }
  55856. _init();
  55857. return {
  55858. draw: _draw
  55859. };
  55860. }
  55861. function PerfCounter ( id, group ) {
  55862. var _id = id,
  55863. _time,
  55864. _value = 0,
  55865. _total = 0,
  55866. _averageValue = 0,
  55867. _accumValue = 0,
  55868. _accumStart = performance.now(),
  55869. _accumSamples = 0,
  55870. _dom = document.createElement( 'div' ),
  55871. _spanId = document.createElement( 'span' ),
  55872. _spanValue = document.createElement( 'div' ),
  55873. _spanValueText = document.createTextNode( '' ),
  55874. _def = _settings ? _settings.values[ _id.toLowerCase() ] : null,
  55875. _graph = new Graph( _dom, _id, _def ),
  55876. _started = false;
  55877. _spanId.className = 'rs-counter-id';
  55878. _spanId.textContent = ( _def && _def.caption ) ? _def.caption : _id;
  55879. _spanValue.className = 'rs-counter-value';
  55880. _spanValue.appendChild( _spanValueText );
  55881. _dom.appendChild( _spanId );
  55882. _dom.appendChild( _spanValue );
  55883. if ( group ) group.div.appendChild( _dom );
  55884. else _div.appendChild( _dom );
  55885. _time = performance.now();
  55886. function _average ( v ) {
  55887. if ( _def && _def.average ) {
  55888. _accumValue += v;
  55889. _accumSamples++;
  55890. var t = performance.now();
  55891. if ( t - _accumStart >= ( _def.avgMs || 1000 ) ) {
  55892. _averageValue = _accumValue / _accumSamples;
  55893. _accumValue = 0;
  55894. _accumStart = t;
  55895. _accumSamples = 0;
  55896. }
  55897. }
  55898. }
  55899. function _start () {
  55900. _time = performance.now();
  55901. if( _settings.userTimingAPI ) performance.mark( _id + '-start' );
  55902. _started = true;
  55903. }
  55904. function _end () {
  55905. _value = performance.now() - _time;
  55906. if( _settings.userTimingAPI ) {
  55907. performance.mark( _id + '-end' );
  55908. if( _started ) {
  55909. performance.measure( _id, _id + '-start', _id + '-end' );
  55910. }
  55911. }
  55912. _average( _value );
  55913. }
  55914. function _tick () {
  55915. _end();
  55916. _start();
  55917. }
  55918. function _draw () {
  55919. var v = ( _def && _def.average ) ? _averageValue : _value;
  55920. _spanValueText.nodeValue = Math.round( v * 100 ) / 100;
  55921. var a = ( _def && ( ( _def.below && _value < _def.below ) || ( _def.over && _value > _def.over ) ) );
  55922. _graph.draw( _value, a );
  55923. _dom.className = a ? 'rs-counter-base alarm' : 'rs-counter-base';
  55924. }
  55925. function _frame () {
  55926. var t = performance.now();
  55927. var e = t - _time;
  55928. _total++;
  55929. if ( e > 1000 ) {
  55930. if ( _def && _def.interpolate === false ) {
  55931. _value = _total;
  55932. } else {
  55933. _value = _total * 1000 / e;
  55934. }
  55935. _total = 0;
  55936. _time = t;
  55937. _average( _value );
  55938. }
  55939. }
  55940. function _set ( v ) {
  55941. _value = v;
  55942. _average( _value );
  55943. }
  55944. return {
  55945. set: _set,
  55946. start: _start,
  55947. tick: _tick,
  55948. end: _end,
  55949. frame: _frame,
  55950. value: function () {
  55951. return _value;
  55952. },
  55953. draw: _draw
  55954. };
  55955. }
  55956. function sample () {
  55957. var _value = 0;
  55958. function _set ( v ) {
  55959. _value = v;
  55960. }
  55961. return {
  55962. set: _set,
  55963. value: function () {
  55964. return _value;
  55965. }
  55966. };
  55967. }
  55968. function _perf ( idArg ) {
  55969. var id = idArg.toLowerCase();
  55970. if ( id === undefined ) id = 'default';
  55971. if ( _perfCounters[ id ] ) return _perfCounters[ id ];
  55972. var group = null;
  55973. if ( _settings && _settings.groups ) {
  55974. iterateKeys( _settings.groups, function ( j ) {
  55975. var g = _settings.groups[ parseInt( j, 10 ) ];
  55976. if ( !group && g.values.indexOf( id.toLowerCase() ) !== -1 ) {
  55977. group = g;
  55978. }
  55979. } );
  55980. }
  55981. var p = new PerfCounter( id, group );
  55982. _perfCounters[ id ] = p;
  55983. return p;
  55984. }
  55985. function _init () {
  55986. if ( _settings.plugins ) {
  55987. if ( !_settings.values ) _settings.values = {};
  55988. if ( !_settings.groups ) _settings.groups = [];
  55989. if ( !_settings.fractions ) _settings.fractions = [];
  55990. for ( var j = 0; j < _settings.plugins.length; j++ ) {
  55991. _settings.plugins[ j ].attach( _perf );
  55992. iterateKeys( _settings.plugins[ j ].values, function ( k ) {
  55993. _settings.values[ k ] = _settings.plugins[ j ].values[ k ];
  55994. } );
  55995. _settings.groups = _settings.groups.concat( _settings.plugins[ j ].groups );
  55996. _settings.fractions = _settings.fractions.concat( _settings.plugins[ j ].fractions );
  55997. }
  55998. } else {
  55999. _settings.plugins = {};
  56000. }
  56001. _base = document.createElement( 'div' );
  56002. _base.className = 'rs-base';
  56003. _div = document.createElement( 'div' );
  56004. _div.className = 'rs-container';
  56005. _div.style.height = 'auto';
  56006. _base.appendChild( _div );
  56007. document.body.appendChild( _base );
  56008. if ( !_settings ) return;
  56009. if ( _settings.groups ) {
  56010. iterateKeys( _settings.groups, function ( j ) {
  56011. var g = _settings.groups[ parseInt( j, 10 ) ];
  56012. var div = document.createElement( 'div' );
  56013. div.className = 'rs-group';
  56014. g.div = div;
  56015. var h1 = document.createElement( 'h1' );
  56016. h1.textContent = g.caption;
  56017. h1.addEventListener( 'click', function ( e ) {
  56018. this.classList.toggle( 'hidden' );
  56019. e.preventDefault();
  56020. }.bind( div ) );
  56021. _div.appendChild( h1 );
  56022. _div.appendChild( div );
  56023. } );
  56024. }
  56025. if ( _settings.fractions ) {
  56026. iterateKeys( _settings.fractions, function ( j ) {
  56027. var f = _settings.fractions[ parseInt( j, 10 ) ];
  56028. var div = document.createElement( 'div' );
  56029. div.className = 'rs-fraction';
  56030. var legend = document.createElement( 'div' );
  56031. legend.className = 'rs-legend';
  56032. var h = 0;
  56033. iterateKeys( _settings.fractions[ j ].steps, function ( k ) {
  56034. var p = document.createElement( 'p' );
  56035. p.textContent = _settings.fractions[ j ].steps[ k ];
  56036. p.style.color = _colours[ h ];
  56037. legend.appendChild( p );
  56038. h++;
  56039. } );
  56040. div.appendChild( legend );
  56041. div.style.height = h * _elHeight + 'px';
  56042. f.div = div;
  56043. var graph = new StackGraph( div, h );
  56044. f.graph = graph;
  56045. _div.appendChild( div );
  56046. } );
  56047. }
  56048. }
  56049. function _update () {
  56050. iterateKeys( _settings.plugins, function ( j ) {
  56051. _settings.plugins[ j ].update();
  56052. } );
  56053. iterateKeys( _perfCounters, function ( j ) {
  56054. _perfCounters[ j ].draw();
  56055. } );
  56056. if ( _settings && _settings.fractions ) {
  56057. iterateKeys( _settings.fractions, function ( j ) {
  56058. var f = _settings.fractions[ parseInt( j, 10 ) ];
  56059. var v = [];
  56060. var base = _perfCounters[ f.base.toLowerCase() ];
  56061. if ( base ) {
  56062. base = base.value();
  56063. iterateKeys( _settings.fractions[ j ].steps, function ( k ) {
  56064. var s = _settings.fractions[ j ].steps[ parseInt( k, 10 ) ].toLowerCase();
  56065. var val = _perfCounters[ s ];
  56066. if ( val ) {
  56067. v.push( val.value() / base );
  56068. }
  56069. } );
  56070. }
  56071. f.graph.draw( v );
  56072. } );
  56073. }
  56074. /*if( _height != _div.clientHeight ) {
  56075. _height = _div.clientHeight;
  56076. _base.style.height = _height + 2 * _elHeight + 'px';
  56077. console.log( _base.clientHeight );
  56078. }*/
  56079. }
  56080. _init();
  56081. return function ( id ) {
  56082. if ( id ) return _perf( id );
  56083. return {
  56084. element: _base,
  56085. update: _update
  56086. };
  56087. };
  56088. }
  56089. if (typeof module === 'object') {
  56090. module.exports = window.rStats;
  56091. }
  56092. },{}],181:[function(_dereq_,module,exports){
  56093. /*
  56094. * Copyright 2015 Google Inc. All Rights Reserved.
  56095. * Licensed under the Apache License, Version 2.0 (the "License");
  56096. * you may not use this file except in compliance with the License.
  56097. * You may obtain a copy of the License at
  56098. *
  56099. * http://www.apache.org/licenses/LICENSE-2.0
  56100. *
  56101. * Unless required by applicable law or agreed to in writing, software
  56102. * distributed under the License is distributed on an "AS IS" BASIS,
  56103. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  56104. * See the License for the specific language governing permissions and
  56105. * limitations under the License.
  56106. */
  56107. var Util = {};
  56108. Util.base64 = function(mimeType, base64) {
  56109. return 'data:' + mimeType + ';base64,' + base64;
  56110. };
  56111. Util.isMobile = function() {
  56112. var check = false;
  56113. (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);
  56114. return check;
  56115. };
  56116. Util.isIOS = function() {
  56117. return /(iPad|iPhone|iPod)/g.test(navigator.userAgent);
  56118. };
  56119. Util.isIFrame = function() {
  56120. try {
  56121. return window.self !== window.top;
  56122. } catch (e) {
  56123. return true;
  56124. }
  56125. };
  56126. Util.appendQueryParameter = function(url, key, value) {
  56127. // Determine delimiter based on if the URL already GET parameters in it.
  56128. var delimiter = (url.indexOf('?') < 0 ? '?' : '&');
  56129. url += delimiter + key + '=' + value;
  56130. return url;
  56131. };
  56132. // From http://goo.gl/4WX3tg
  56133. Util.getQueryParameter = function(name) {
  56134. name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  56135. var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
  56136. results = regex.exec(location.search);
  56137. return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  56138. };
  56139. Util.isLandscapeMode = function() {
  56140. return (window.orientation == 90 || window.orientation == -90);
  56141. };
  56142. module.exports = Util;
  56143. },{}],182:[function(_dereq_,module,exports){
  56144. /*
  56145. * Copyright 2015 Google Inc. All Rights Reserved.
  56146. * Licensed under the Apache License, Version 2.0 (the "License");
  56147. * you may not use this file except in compliance with the License.
  56148. * You may obtain a copy of the License at
  56149. *
  56150. * http://www.apache.org/licenses/LICENSE-2.0
  56151. *
  56152. * Unless required by applicable law or agreed to in writing, software
  56153. * distributed under the License is distributed on an "AS IS" BASIS,
  56154. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  56155. * See the License for the specific language governing permissions and
  56156. * limitations under the License.
  56157. */
  56158. var Util = _dereq_('./util.js');
  56159. /**
  56160. * Android and iOS compatible wakelock implementation.
  56161. *
  56162. * Refactored thanks to dkovalev@.
  56163. */
  56164. function AndroidWakeLock() {
  56165. var video = document.createElement('video');
  56166. video.addEventListener('ended', function() {
  56167. video.play();
  56168. });
  56169. this.request = function() {
  56170. if (video.paused) {
  56171. // Base64 version of videos_src/no-sleep-60s.webm.
  56172. video.src = Util.base64('video/webm', 'GkXfowEAAAAAAAAfQoaBAUL3gQFC8oEEQvOBCEKChHdlYm1Ch4ECQoWBAhhTgGcBAAAAAAAH4xFNm3RALE27i1OrhBVJqWZTrIHfTbuMU6uEFlSua1OsggEwTbuMU6uEHFO7a1OsggfG7AEAAAAAAACkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmAQAAAAAAAEUq17GDD0JATYCNTGF2ZjU2LjQwLjEwMVdBjUxhdmY1Ni40MC4xMDFzpJAGSJTMbsLpDt/ySkipgX1fRImIQO1MAAAAAAAWVK5rAQAAAAAAADuuAQAAAAAAADLXgQFzxYEBnIEAIrWcg3VuZIaFVl9WUDmDgQEj44OEO5rKAOABAAAAAAAABrCBsLqBkB9DtnUBAAAAAAAAo+eBAKOmgQAAgKJJg0IAAV4BHsAHBIODCoAACmH2MAAAZxgz4dPSTFi5JACjloED6ACmAECSnABMQAADYAAAWi0quoCjloEH0ACmAECSnABNwAADYAAAWi0quoCjloELuACmAECSnABNgAADYAAAWi0quoCjloEPoACmAECSnABNYAADYAAAWi0quoCjloETiACmAECSnABNIAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTnghdwo5aBAAAApgBAkpwATOAAA2AAAFotKrqAo5aBA+gApgBAkpwATMAAA2AAAFotKrqAo5aBB9AApgBAkpwATIAAA2AAAFotKrqAo5aBC7gApgBAkpwATEAAA2AAAFotKrqAo5aBD6AApgDAkpwAQ2AAA2AAAFotKrqAo5aBE4gApgBAkpwATCAAA2AAAFotKrqAH0O2dQEAAAAAAACU54Iu4KOWgQAAAKYAQJKcAEvAAANgAABaLSq6gKOWgQPoAKYAQJKcAEtgAANgAABaLSq6gKOWgQfQAKYAQJKcAEsAAANgAABaLSq6gKOWgQu4AKYAQJKcAEqAAANgAABaLSq6gKOWgQ+gAKYAQJKcAEogAANgAABaLSq6gKOWgROIAKYAQJKcAEnAAANgAABaLSq6gB9DtnUBAAAAAAAAlOeCRlCjloEAAACmAECSnABJgAADYAAAWi0quoCjloED6ACmAECSnABJIAADYAAAWi0quoCjloEH0ACmAMCSnABDYAADYAAAWi0quoCjloELuACmAECSnABI4AADYAAAWi0quoCjloEPoACmAECSnABIoAADYAAAWi0quoCjloETiACmAECSnABIYAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTngl3Ao5aBAAAApgBAkpwASCAAA2AAAFotKrqAo5aBA+gApgBAkpwASAAAA2AAAFotKrqAo5aBB9AApgBAkpwAR8AAA2AAAFotKrqAo5aBC7gApgBAkpwAR4AAA2AAAFotKrqAo5aBD6AApgBAkpwAR2AAA2AAAFotKrqAo5aBE4gApgBAkpwARyAAA2AAAFotKrqAH0O2dQEAAAAAAACU54J1MKOWgQAAAKYAwJKcAENgAANgAABaLSq6gKOWgQPoAKYAQJKcAEbgAANgAABaLSq6gKOWgQfQAKYAQJKcAEagAANgAABaLSq6gKOWgQu4AKYAQJKcAEaAAANgAABaLSq6gKOWgQ+gAKYAQJKcAEZAAANgAABaLSq6gKOWgROIAKYAQJKcAEYAAANgAABaLSq6gB9DtnUBAAAAAAAAlOeCjKCjloEAAACmAECSnABF4AADYAAAWi0quoCjloED6ACmAECSnABFwAADYAAAWi0quoCjloEH0ACmAECSnABFoAADYAAAWi0quoCjloELuACmAECSnABFgAADYAAAWi0quoCjloEPoACmAMCSnABDYAADYAAAWi0quoCjloETiACmAECSnABFYAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTngqQQo5aBAAAApgBAkpwARUAAA2AAAFotKrqAo5aBA+gApgBAkpwARSAAA2AAAFotKrqAo5aBB9AApgBAkpwARQAAA2AAAFotKrqAo5aBC7gApgBAkpwARQAAA2AAAFotKrqAo5aBD6AApgBAkpwAROAAA2AAAFotKrqAo5aBE4gApgBAkpwARMAAA2AAAFotKrqAH0O2dQEAAAAAAACU54K7gKOWgQAAAKYAQJKcAESgAANgAABaLSq6gKOWgQPoAKYAQJKcAESAAANgAABaLSq6gKOWgQfQAKYAwJKcAENgAANgAABaLSq6gKOWgQu4AKYAQJKcAERgAANgAABaLSq6gKOWgQ+gAKYAQJKcAERAAANgAABaLSq6gKOWgROIAKYAQJKcAEQgAANgAABaLSq6gB9DtnUBAAAAAAAAlOeC0vCjloEAAACmAECSnABEIAADYAAAWi0quoCjloED6ACmAECSnABEAAADYAAAWi0quoCjloEH0ACmAECSnABD4AADYAAAWi0quoCjloELuACmAECSnABDwAADYAAAWi0quoCjloEPoACmAECSnABDoAADYAAAWi0quoCjloETiACmAECSnABDgAADYAAAWi0quoAcU7trAQAAAAAAABG7j7OBALeK94EB8YIBd/CBAw==');
  56173. video.play();
  56174. }
  56175. };
  56176. this.release = function() {
  56177. video.pause();
  56178. video.src = '';
  56179. };
  56180. }
  56181. function iOSWakeLock() {
  56182. var timer = null;
  56183. this.request = function() {
  56184. if (!timer) {
  56185. timer = setInterval(function() {
  56186. window.location = window.location;
  56187. setTimeout(window.stop, 0);
  56188. }, 30000);
  56189. }
  56190. }
  56191. this.release = function() {
  56192. if (timer) {
  56193. clearInterval(timer);
  56194. timer = null;
  56195. }
  56196. }
  56197. }
  56198. function getWakeLock() {
  56199. var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  56200. if (userAgent.match(/iPhone/i) || userAgent.match(/iPod/i)) {
  56201. return iOSWakeLock;
  56202. } else {
  56203. return AndroidWakeLock;
  56204. }
  56205. }
  56206. module.exports = getWakeLock();
  56207. },{"./util.js":181}]},{},[147])(147)
  56208. });
  56209. //# sourceMappingURL=aframe-master.js.map