aframe-master.js 2.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.AFRAME = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
  2. (function (process){
  3. /**
  4. * Tween.js - Licensed under the MIT license
  5. * https://github.com/tweenjs/tween.js
  6. * ----------------------------------------------
  7. *
  8. * See https://github.com/tweenjs/tween.js/graphs/contributors for the full list of contributors.
  9. * Thank you all, you're awesome!
  10. */
  11. var TWEEN = TWEEN || (function () {
  12. var _tweens = [];
  13. return {
  14. getAll: function () {
  15. return _tweens;
  16. },
  17. removeAll: function () {
  18. _tweens = [];
  19. },
  20. add: function (tween) {
  21. _tweens.push(tween);
  22. },
  23. remove: function (tween) {
  24. var i = _tweens.indexOf(tween);
  25. if (i !== -1) {
  26. _tweens.splice(i, 1);
  27. }
  28. },
  29. update: function (time, preserve) {
  30. if (_tweens.length === 0) {
  31. return false;
  32. }
  33. var i = 0;
  34. time = time !== undefined ? time : TWEEN.now();
  35. while (i < _tweens.length) {
  36. if (_tweens[i].update(time) || preserve) {
  37. i++;
  38. } else {
  39. _tweens.splice(i, 1);
  40. }
  41. }
  42. return true;
  43. }
  44. };
  45. })();
  46. // Include a performance.now polyfill.
  47. // In node.js, use process.hrtime.
  48. if (typeof (window) === 'undefined' && typeof (process) !== 'undefined') {
  49. TWEEN.now = function () {
  50. var time = process.hrtime();
  51. // Convert [seconds, nanoseconds] to milliseconds.
  52. return time[0] * 1000 + time[1] / 1000000;
  53. };
  54. }
  55. // In a browser, use window.performance.now if it is available.
  56. else if (typeof (window) !== 'undefined' &&
  57. window.performance !== undefined &&
  58. window.performance.now !== undefined) {
  59. // This must be bound, because directly assigning this function
  60. // leads to an invocation exception in Chrome.
  61. TWEEN.now = window.performance.now.bind(window.performance);
  62. }
  63. // Use Date.now if it is available.
  64. else if (Date.now !== undefined) {
  65. TWEEN.now = Date.now;
  66. }
  67. // Otherwise, use 'new Date().getTime()'.
  68. else {
  69. TWEEN.now = function () {
  70. return new Date().getTime();
  71. };
  72. }
  73. TWEEN.Tween = function (object) {
  74. var _object = object;
  75. var _valuesStart = {};
  76. var _valuesEnd = {};
  77. var _valuesStartRepeat = {};
  78. var _duration = 1000;
  79. var _repeat = 0;
  80. var _repeatDelayTime;
  81. var _yoyo = false;
  82. var _isPlaying = false;
  83. var _reversed = false;
  84. var _delayTime = 0;
  85. var _startTime = null;
  86. var _easingFunction = TWEEN.Easing.Linear.None;
  87. var _interpolationFunction = TWEEN.Interpolation.Linear;
  88. var _chainedTweens = [];
  89. var _onStartCallback = null;
  90. var _onStartCallbackFired = false;
  91. var _onUpdateCallback = null;
  92. var _onCompleteCallback = null;
  93. var _onStopCallback = null;
  94. this.to = function (properties, duration) {
  95. _valuesEnd = properties;
  96. if (duration !== undefined) {
  97. _duration = duration;
  98. }
  99. return this;
  100. };
  101. this.start = function (time) {
  102. TWEEN.add(this);
  103. _isPlaying = true;
  104. _onStartCallbackFired = false;
  105. _startTime = time !== undefined ? time : TWEEN.now();
  106. _startTime += _delayTime;
  107. for (var property in _valuesEnd) {
  108. // Check if an Array was provided as property value
  109. if (_valuesEnd[property] instanceof Array) {
  110. if (_valuesEnd[property].length === 0) {
  111. continue;
  112. }
  113. // Create a local copy of the Array with the start value at the front
  114. _valuesEnd[property] = [_object[property]].concat(_valuesEnd[property]);
  115. }
  116. // If `to()` specifies a property that doesn't exist in the source object,
  117. // we should not set that property in the object
  118. if (_object[property] === undefined) {
  119. continue;
  120. }
  121. // Save the starting value.
  122. _valuesStart[property] = _object[property];
  123. if ((_valuesStart[property] instanceof Array) === false) {
  124. _valuesStart[property] *= 1.0; // Ensures we're using numbers, not strings
  125. }
  126. _valuesStartRepeat[property] = _valuesStart[property] || 0;
  127. }
  128. return this;
  129. };
  130. this.stop = function () {
  131. if (!_isPlaying) {
  132. return this;
  133. }
  134. TWEEN.remove(this);
  135. _isPlaying = false;
  136. if (_onStopCallback !== null) {
  137. _onStopCallback.call(_object, _object);
  138. }
  139. this.stopChainedTweens();
  140. return this;
  141. };
  142. this.end = function () {
  143. this.update(_startTime + _duration);
  144. return this;
  145. };
  146. this.stopChainedTweens = function () {
  147. for (var i = 0, numChainedTweens = _chainedTweens.length; i < numChainedTweens; i++) {
  148. _chainedTweens[i].stop();
  149. }
  150. };
  151. this.delay = function (amount) {
  152. _delayTime = amount;
  153. return this;
  154. };
  155. this.repeat = function (times) {
  156. _repeat = times;
  157. return this;
  158. };
  159. this.repeatDelay = function (amount) {
  160. _repeatDelayTime = amount;
  161. return this;
  162. };
  163. this.yoyo = function (yoyo) {
  164. _yoyo = yoyo;
  165. return this;
  166. };
  167. this.easing = function (easing) {
  168. _easingFunction = easing;
  169. return this;
  170. };
  171. this.interpolation = function (interpolation) {
  172. _interpolationFunction = interpolation;
  173. return this;
  174. };
  175. this.chain = function () {
  176. _chainedTweens = arguments;
  177. return this;
  178. };
  179. this.onStart = function (callback) {
  180. _onStartCallback = callback;
  181. return this;
  182. };
  183. this.onUpdate = function (callback) {
  184. _onUpdateCallback = callback;
  185. return this;
  186. };
  187. this.onComplete = function (callback) {
  188. _onCompleteCallback = callback;
  189. return this;
  190. };
  191. this.onStop = function (callback) {
  192. _onStopCallback = callback;
  193. return this;
  194. };
  195. this.update = function (time) {
  196. var property;
  197. var elapsed;
  198. var value;
  199. if (time < _startTime) {
  200. return true;
  201. }
  202. if (_onStartCallbackFired === false) {
  203. if (_onStartCallback !== null) {
  204. _onStartCallback.call(_object, _object);
  205. }
  206. _onStartCallbackFired = true;
  207. }
  208. elapsed = (time - _startTime) / _duration;
  209. elapsed = elapsed > 1 ? 1 : elapsed;
  210. value = _easingFunction(elapsed);
  211. for (property in _valuesEnd) {
  212. // Don't update properties that do not exist in the source object
  213. if (_valuesStart[property] === undefined) {
  214. continue;
  215. }
  216. var start = _valuesStart[property] || 0;
  217. var end = _valuesEnd[property];
  218. if (end instanceof Array) {
  219. _object[property] = _interpolationFunction(end, value);
  220. } else {
  221. // Parses relative end values with start as base (e.g.: +10, -3)
  222. if (typeof (end) === 'string') {
  223. if (end.charAt(0) === '+' || end.charAt(0) === '-') {
  224. end = start + parseFloat(end);
  225. } else {
  226. end = parseFloat(end);
  227. }
  228. }
  229. // Protect against non numeric properties.
  230. if (typeof (end) === 'number') {
  231. _object[property] = start + (end - start) * value;
  232. }
  233. }
  234. }
  235. if (_onUpdateCallback !== null) {
  236. _onUpdateCallback.call(_object, value);
  237. }
  238. if (elapsed === 1) {
  239. if (_repeat > 0) {
  240. if (isFinite(_repeat)) {
  241. _repeat--;
  242. }
  243. // Reassign starting values, restart by making startTime = now
  244. for (property in _valuesStartRepeat) {
  245. if (typeof (_valuesEnd[property]) === 'string') {
  246. _valuesStartRepeat[property] = _valuesStartRepeat[property] + parseFloat(_valuesEnd[property]);
  247. }
  248. if (_yoyo) {
  249. var tmp = _valuesStartRepeat[property];
  250. _valuesStartRepeat[property] = _valuesEnd[property];
  251. _valuesEnd[property] = tmp;
  252. }
  253. _valuesStart[property] = _valuesStartRepeat[property];
  254. }
  255. if (_yoyo) {
  256. _reversed = !_reversed;
  257. }
  258. if (_repeatDelayTime !== undefined) {
  259. _startTime = time + _repeatDelayTime;
  260. } else {
  261. _startTime = time + _delayTime;
  262. }
  263. return true;
  264. } else {
  265. if (_onCompleteCallback !== null) {
  266. _onCompleteCallback.call(_object, _object);
  267. }
  268. for (var i = 0, numChainedTweens = _chainedTweens.length; i < numChainedTweens; i++) {
  269. // Make the chained tweens start exactly at the time they should,
  270. // even if the `update()` method was called way past the duration of the tween
  271. _chainedTweens[i].start(_startTime + _duration);
  272. }
  273. return false;
  274. }
  275. }
  276. return true;
  277. };
  278. };
  279. TWEEN.Easing = {
  280. Linear: {
  281. None: function (k) {
  282. return k;
  283. }
  284. },
  285. Quadratic: {
  286. In: function (k) {
  287. return k * k;
  288. },
  289. Out: function (k) {
  290. return k * (2 - k);
  291. },
  292. InOut: function (k) {
  293. if ((k *= 2) < 1) {
  294. return 0.5 * k * k;
  295. }
  296. return - 0.5 * (--k * (k - 2) - 1);
  297. }
  298. },
  299. Cubic: {
  300. In: function (k) {
  301. return k * k * k;
  302. },
  303. Out: function (k) {
  304. return --k * k * k + 1;
  305. },
  306. InOut: function (k) {
  307. if ((k *= 2) < 1) {
  308. return 0.5 * k * k * k;
  309. }
  310. return 0.5 * ((k -= 2) * k * k + 2);
  311. }
  312. },
  313. Quartic: {
  314. In: function (k) {
  315. return k * k * k * k;
  316. },
  317. Out: function (k) {
  318. return 1 - (--k * k * k * k);
  319. },
  320. InOut: function (k) {
  321. if ((k *= 2) < 1) {
  322. return 0.5 * k * k * k * k;
  323. }
  324. return - 0.5 * ((k -= 2) * k * k * k - 2);
  325. }
  326. },
  327. Quintic: {
  328. In: function (k) {
  329. return k * k * k * k * k;
  330. },
  331. Out: function (k) {
  332. return --k * k * k * k * k + 1;
  333. },
  334. InOut: function (k) {
  335. if ((k *= 2) < 1) {
  336. return 0.5 * k * k * k * k * k;
  337. }
  338. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  339. }
  340. },
  341. Sinusoidal: {
  342. In: function (k) {
  343. return 1 - Math.cos(k * Math.PI / 2);
  344. },
  345. Out: function (k) {
  346. return Math.sin(k * Math.PI / 2);
  347. },
  348. InOut: function (k) {
  349. return 0.5 * (1 - Math.cos(Math.PI * k));
  350. }
  351. },
  352. Exponential: {
  353. In: function (k) {
  354. return k === 0 ? 0 : Math.pow(1024, k - 1);
  355. },
  356. Out: function (k) {
  357. return k === 1 ? 1 : 1 - Math.pow(2, - 10 * k);
  358. },
  359. InOut: function (k) {
  360. if (k === 0) {
  361. return 0;
  362. }
  363. if (k === 1) {
  364. return 1;
  365. }
  366. if ((k *= 2) < 1) {
  367. return 0.5 * Math.pow(1024, k - 1);
  368. }
  369. return 0.5 * (- Math.pow(2, - 10 * (k - 1)) + 2);
  370. }
  371. },
  372. Circular: {
  373. In: function (k) {
  374. return 1 - Math.sqrt(1 - k * k);
  375. },
  376. Out: function (k) {
  377. return Math.sqrt(1 - (--k * k));
  378. },
  379. InOut: function (k) {
  380. if ((k *= 2) < 1) {
  381. return - 0.5 * (Math.sqrt(1 - k * k) - 1);
  382. }
  383. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  384. }
  385. },
  386. Elastic: {
  387. In: function (k) {
  388. if (k === 0) {
  389. return 0;
  390. }
  391. if (k === 1) {
  392. return 1;
  393. }
  394. return -Math.pow(2, 10 * (k - 1)) * Math.sin((k - 1.1) * 5 * Math.PI);
  395. },
  396. Out: function (k) {
  397. if (k === 0) {
  398. return 0;
  399. }
  400. if (k === 1) {
  401. return 1;
  402. }
  403. return Math.pow(2, -10 * k) * Math.sin((k - 0.1) * 5 * Math.PI) + 1;
  404. },
  405. InOut: function (k) {
  406. if (k === 0) {
  407. return 0;
  408. }
  409. if (k === 1) {
  410. return 1;
  411. }
  412. k *= 2;
  413. if (k < 1) {
  414. return -0.5 * Math.pow(2, 10 * (k - 1)) * Math.sin((k - 1.1) * 5 * Math.PI);
  415. }
  416. return 0.5 * Math.pow(2, -10 * (k - 1)) * Math.sin((k - 1.1) * 5 * Math.PI) + 1;
  417. }
  418. },
  419. Back: {
  420. In: function (k) {
  421. var s = 1.70158;
  422. return k * k * ((s + 1) * k - s);
  423. },
  424. Out: function (k) {
  425. var s = 1.70158;
  426. return --k * k * ((s + 1) * k + s) + 1;
  427. },
  428. InOut: function (k) {
  429. var s = 1.70158 * 1.525;
  430. if ((k *= 2) < 1) {
  431. return 0.5 * (k * k * ((s + 1) * k - s));
  432. }
  433. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  434. }
  435. },
  436. Bounce: {
  437. In: function (k) {
  438. return 1 - TWEEN.Easing.Bounce.Out(1 - k);
  439. },
  440. Out: function (k) {
  441. if (k < (1 / 2.75)) {
  442. return 7.5625 * k * k;
  443. } else if (k < (2 / 2.75)) {
  444. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  445. } else if (k < (2.5 / 2.75)) {
  446. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  447. } else {
  448. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  449. }
  450. },
  451. InOut: function (k) {
  452. if (k < 0.5) {
  453. return TWEEN.Easing.Bounce.In(k * 2) * 0.5;
  454. }
  455. return TWEEN.Easing.Bounce.Out(k * 2 - 1) * 0.5 + 0.5;
  456. }
  457. }
  458. };
  459. TWEEN.Interpolation = {
  460. Linear: function (v, k) {
  461. var m = v.length - 1;
  462. var f = m * k;
  463. var i = Math.floor(f);
  464. var fn = TWEEN.Interpolation.Utils.Linear;
  465. if (k < 0) {
  466. return fn(v[0], v[1], f);
  467. }
  468. if (k > 1) {
  469. return fn(v[m], v[m - 1], m - f);
  470. }
  471. return fn(v[i], v[i + 1 > m ? m : i + 1], f - i);
  472. },
  473. Bezier: function (v, k) {
  474. var b = 0;
  475. var n = v.length - 1;
  476. var pw = Math.pow;
  477. var bn = TWEEN.Interpolation.Utils.Bernstein;
  478. for (var i = 0; i <= n; i++) {
  479. b += pw(1 - k, n - i) * pw(k, i) * v[i] * bn(n, i);
  480. }
  481. return b;
  482. },
  483. CatmullRom: function (v, k) {
  484. var m = v.length - 1;
  485. var f = m * k;
  486. var i = Math.floor(f);
  487. var fn = TWEEN.Interpolation.Utils.CatmullRom;
  488. if (v[0] === v[m]) {
  489. if (k < 0) {
  490. i = Math.floor(f = m * (1 + k));
  491. }
  492. return fn(v[(i - 1 + m) % m], v[i], v[(i + 1) % m], v[(i + 2) % m], f - i);
  493. } else {
  494. if (k < 0) {
  495. return v[0] - (fn(v[0], v[0], v[1], v[1], -f) - v[0]);
  496. }
  497. if (k > 1) {
  498. return v[m] - (fn(v[m], v[m], v[m - 1], v[m - 1], f - m) - v[m]);
  499. }
  500. return fn(v[i ? i - 1 : 0], v[i], v[m < i + 1 ? m : i + 1], v[m < i + 2 ? m : i + 2], f - i);
  501. }
  502. },
  503. Utils: {
  504. Linear: function (p0, p1, t) {
  505. return (p1 - p0) * t + p0;
  506. },
  507. Bernstein: function (n, i) {
  508. var fc = TWEEN.Interpolation.Utils.Factorial;
  509. return fc(n) / fc(i) / fc(n - i);
  510. },
  511. Factorial: (function () {
  512. var a = [1];
  513. return function (n) {
  514. var s = 1;
  515. if (a[n]) {
  516. return a[n];
  517. }
  518. for (var i = n; i > 1; i--) {
  519. s *= i;
  520. }
  521. a[n] = s;
  522. return s;
  523. };
  524. })(),
  525. CatmullRom: function (p0, p1, p2, p3, t) {
  526. var v0 = (p2 - p0) * 0.5;
  527. var v1 = (p3 - p1) * 0.5;
  528. var t2 = t * t;
  529. var t3 = t * t2;
  530. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (- 3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  531. }
  532. }
  533. };
  534. // UMD (Universal Module Definition)
  535. (function (root) {
  536. if (typeof define === 'function' && define.amd) {
  537. // AMD
  538. define([], function () {
  539. return TWEEN;
  540. });
  541. } else if (typeof module !== 'undefined' && typeof exports === 'object') {
  542. // Node.js
  543. module.exports = TWEEN;
  544. } else if (root !== undefined) {
  545. // Global variable
  546. root.TWEEN = TWEEN;
  547. }
  548. })(this);
  549. }).call(this,_dereq_('_process'))
  550. },{"_process":34}],2:[function(_dereq_,module,exports){
  551. var str = Object.prototype.toString
  552. module.exports = anArray
  553. function anArray(arr) {
  554. return (
  555. arr.BYTES_PER_ELEMENT
  556. && str.call(arr.buffer) === '[object ArrayBuffer]'
  557. || Array.isArray(arr)
  558. )
  559. }
  560. },{}],3:[function(_dereq_,module,exports){
  561. module.exports = function numtype(num, def) {
  562. return typeof num === 'number'
  563. ? num
  564. : (typeof def === 'number' ? def : 0)
  565. }
  566. },{}],4:[function(_dereq_,module,exports){
  567. 'use strict'
  568. exports.byteLength = byteLength
  569. exports.toByteArray = toByteArray
  570. exports.fromByteArray = fromByteArray
  571. var lookup = []
  572. var revLookup = []
  573. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  574. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  575. for (var i = 0, len = code.length; i < len; ++i) {
  576. lookup[i] = code[i]
  577. revLookup[code.charCodeAt(i)] = i
  578. }
  579. revLookup['-'.charCodeAt(0)] = 62
  580. revLookup['_'.charCodeAt(0)] = 63
  581. function placeHoldersCount (b64) {
  582. var len = b64.length
  583. if (len % 4 > 0) {
  584. throw new Error('Invalid string. Length must be a multiple of 4')
  585. }
  586. // the number of equal signs (place holders)
  587. // if there are two placeholders, than the two characters before it
  588. // represent one byte
  589. // if there is only one, then the three characters before it represent 2 bytes
  590. // this is just a cheap hack to not do indexOf twice
  591. return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
  592. }
  593. function byteLength (b64) {
  594. // base64 is 4/3 + up to two characters of the original data
  595. return b64.length * 3 / 4 - placeHoldersCount(b64)
  596. }
  597. function toByteArray (b64) {
  598. var i, j, l, tmp, placeHolders, arr
  599. var len = b64.length
  600. placeHolders = placeHoldersCount(b64)
  601. arr = new Arr(len * 3 / 4 - placeHolders)
  602. // if there are placeholders, only get up to the last complete 4 chars
  603. l = placeHolders > 0 ? len - 4 : len
  604. var L = 0
  605. for (i = 0, j = 0; i < l; i += 4, j += 3) {
  606. tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
  607. arr[L++] = (tmp >> 16) & 0xFF
  608. arr[L++] = (tmp >> 8) & 0xFF
  609. arr[L++] = tmp & 0xFF
  610. }
  611. if (placeHolders === 2) {
  612. tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
  613. arr[L++] = tmp & 0xFF
  614. } else if (placeHolders === 1) {
  615. tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
  616. arr[L++] = (tmp >> 8) & 0xFF
  617. arr[L++] = tmp & 0xFF
  618. }
  619. return arr
  620. }
  621. function tripletToBase64 (num) {
  622. return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
  623. }
  624. function encodeChunk (uint8, start, end) {
  625. var tmp
  626. var output = []
  627. for (var i = start; i < end; i += 3) {
  628. tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
  629. output.push(tripletToBase64(tmp))
  630. }
  631. return output.join('')
  632. }
  633. function fromByteArray (uint8) {
  634. var tmp
  635. var len = uint8.length
  636. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  637. var output = ''
  638. var parts = []
  639. var maxChunkLength = 16383 // must be multiple of 3
  640. // go through the array every three bytes, we'll deal with trailing stuff later
  641. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  642. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
  643. }
  644. // pad the end with zeros, but make sure to not forget the extra bytes
  645. if (extraBytes === 1) {
  646. tmp = uint8[len - 1]
  647. output += lookup[tmp >> 2]
  648. output += lookup[(tmp << 4) & 0x3F]
  649. output += '=='
  650. } else if (extraBytes === 2) {
  651. tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
  652. output += lookup[tmp >> 10]
  653. output += lookup[(tmp >> 4) & 0x3F]
  654. output += lookup[(tmp << 2) & 0x3F]
  655. output += '='
  656. }
  657. parts.push(output)
  658. return parts.join('')
  659. }
  660. },{}],5:[function(_dereq_,module,exports){
  661. 'use strict';
  662. // For more information about browser field, check out the browser field at https://github.com/substack/browserify-handbook#browser-field.
  663. module.exports = {
  664. // Create a <link> tag with optional data attributes
  665. createLink: function(href, attributes) {
  666. var head = document.head || document.getElementsByTagName('head')[0];
  667. var link = document.createElement('link');
  668. link.href = href;
  669. link.rel = 'stylesheet';
  670. for (var key in attributes) {
  671. if ( ! attributes.hasOwnProperty(key)) {
  672. continue;
  673. }
  674. var value = attributes[key];
  675. link.setAttribute('data-' + key, value);
  676. }
  677. head.appendChild(link);
  678. },
  679. // Create a <style> tag with optional data attributes
  680. createStyle: function(cssText, attributes) {
  681. var head = document.head || document.getElementsByTagName('head')[0],
  682. style = document.createElement('style');
  683. style.type = 'text/css';
  684. for (var key in attributes) {
  685. if ( ! attributes.hasOwnProperty(key)) {
  686. continue;
  687. }
  688. var value = attributes[key];
  689. style.setAttribute('data-' + key, value);
  690. }
  691. if (style.sheet) { // for jsdom and IE9+
  692. style.innerHTML = cssText;
  693. style.sheet.cssText = cssText;
  694. head.appendChild(style);
  695. } else if (style.styleSheet) { // for IE8 and below
  696. head.appendChild(style);
  697. style.styleSheet.cssText = cssText;
  698. } else { // for Chrome, Firefox, and Safari
  699. style.appendChild(document.createTextNode(cssText));
  700. head.appendChild(style);
  701. }
  702. }
  703. };
  704. },{}],6:[function(_dereq_,module,exports){
  705. var Buffer = _dereq_('buffer').Buffer; // for use with browserify
  706. module.exports = function (a, b) {
  707. if (!Buffer.isBuffer(a)) return undefined;
  708. if (!Buffer.isBuffer(b)) return undefined;
  709. if (typeof a.equals === 'function') return a.equals(b);
  710. if (a.length !== b.length) return false;
  711. for (var i = 0; i < a.length; i++) {
  712. if (a[i] !== b[i]) return false;
  713. }
  714. return true;
  715. };
  716. },{"buffer":7}],7:[function(_dereq_,module,exports){
  717. (function (global){
  718. /*!
  719. * The buffer module from node.js, for the browser.
  720. *
  721. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  722. * @license MIT
  723. */
  724. /* eslint-disable no-proto */
  725. 'use strict'
  726. var base64 = _dereq_('base64-js')
  727. var ieee754 = _dereq_('ieee754')
  728. var isArray = _dereq_('isarray')
  729. exports.Buffer = Buffer
  730. exports.SlowBuffer = SlowBuffer
  731. exports.INSPECT_MAX_BYTES = 50
  732. /**
  733. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  734. * === true Use Uint8Array implementation (fastest)
  735. * === false Use Object implementation (most compatible, even IE6)
  736. *
  737. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  738. * Opera 11.6+, iOS 4.2+.
  739. *
  740. * Due to various browser bugs, sometimes the Object implementation will be used even
  741. * when the browser supports typed arrays.
  742. *
  743. * Note:
  744. *
  745. * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
  746. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
  747. *
  748. * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
  749. *
  750. * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
  751. * incorrect length in some situations.
  752. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
  753. * get the Object implementation, which is slower but behaves correctly.
  754. */
  755. Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
  756. ? global.TYPED_ARRAY_SUPPORT
  757. : typedArraySupport()
  758. /*
  759. * Export kMaxLength after typed array support is determined.
  760. */
  761. exports.kMaxLength = kMaxLength()
  762. function typedArraySupport () {
  763. try {
  764. var arr = new Uint8Array(1)
  765. arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
  766. return arr.foo() === 42 && // typed array instances can be augmented
  767. typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
  768. arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
  769. } catch (e) {
  770. return false
  771. }
  772. }
  773. function kMaxLength () {
  774. return Buffer.TYPED_ARRAY_SUPPORT
  775. ? 0x7fffffff
  776. : 0x3fffffff
  777. }
  778. function createBuffer (that, length) {
  779. if (kMaxLength() < length) {
  780. throw new RangeError('Invalid typed array length')
  781. }
  782. if (Buffer.TYPED_ARRAY_SUPPORT) {
  783. // Return an augmented `Uint8Array` instance, for best performance
  784. that = new Uint8Array(length)
  785. that.__proto__ = Buffer.prototype
  786. } else {
  787. // Fallback: Return an object instance of the Buffer class
  788. if (that === null) {
  789. that = new Buffer(length)
  790. }
  791. that.length = length
  792. }
  793. return that
  794. }
  795. /**
  796. * The Buffer constructor returns instances of `Uint8Array` that have their
  797. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  798. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  799. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  800. * returns a single octet.
  801. *
  802. * The `Uint8Array` prototype remains unmodified.
  803. */
  804. function Buffer (arg, encodingOrOffset, length) {
  805. if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
  806. return new Buffer(arg, encodingOrOffset, length)
  807. }
  808. // Common case.
  809. if (typeof arg === 'number') {
  810. if (typeof encodingOrOffset === 'string') {
  811. throw new Error(
  812. 'If encoding is specified then the first argument must be a string'
  813. )
  814. }
  815. return allocUnsafe(this, arg)
  816. }
  817. return from(this, arg, encodingOrOffset, length)
  818. }
  819. Buffer.poolSize = 8192 // not used by this implementation
  820. // TODO: Legacy, not needed anymore. Remove in next major version.
  821. Buffer._augment = function (arr) {
  822. arr.__proto__ = Buffer.prototype
  823. return arr
  824. }
  825. function from (that, value, encodingOrOffset, length) {
  826. if (typeof value === 'number') {
  827. throw new TypeError('"value" argument must not be a number')
  828. }
  829. if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
  830. return fromArrayBuffer(that, value, encodingOrOffset, length)
  831. }
  832. if (typeof value === 'string') {
  833. return fromString(that, value, encodingOrOffset)
  834. }
  835. return fromObject(that, value)
  836. }
  837. /**
  838. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  839. * if value is a number.
  840. * Buffer.from(str[, encoding])
  841. * Buffer.from(array)
  842. * Buffer.from(buffer)
  843. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  844. **/
  845. Buffer.from = function (value, encodingOrOffset, length) {
  846. return from(null, value, encodingOrOffset, length)
  847. }
  848. if (Buffer.TYPED_ARRAY_SUPPORT) {
  849. Buffer.prototype.__proto__ = Uint8Array.prototype
  850. Buffer.__proto__ = Uint8Array
  851. if (typeof Symbol !== 'undefined' && Symbol.species &&
  852. Buffer[Symbol.species] === Buffer) {
  853. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  854. Object.defineProperty(Buffer, Symbol.species, {
  855. value: null,
  856. configurable: true
  857. })
  858. }
  859. }
  860. function assertSize (size) {
  861. if (typeof size !== 'number') {
  862. throw new TypeError('"size" argument must be a number')
  863. } else if (size < 0) {
  864. throw new RangeError('"size" argument must not be negative')
  865. }
  866. }
  867. function alloc (that, size, fill, encoding) {
  868. assertSize(size)
  869. if (size <= 0) {
  870. return createBuffer(that, size)
  871. }
  872. if (fill !== undefined) {
  873. // Only pay attention to encoding if it's a string. This
  874. // prevents accidentally sending in a number that would
  875. // be interpretted as a start offset.
  876. return typeof encoding === 'string'
  877. ? createBuffer(that, size).fill(fill, encoding)
  878. : createBuffer(that, size).fill(fill)
  879. }
  880. return createBuffer(that, size)
  881. }
  882. /**
  883. * Creates a new filled Buffer instance.
  884. * alloc(size[, fill[, encoding]])
  885. **/
  886. Buffer.alloc = function (size, fill, encoding) {
  887. return alloc(null, size, fill, encoding)
  888. }
  889. function allocUnsafe (that, size) {
  890. assertSize(size)
  891. that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
  892. if (!Buffer.TYPED_ARRAY_SUPPORT) {
  893. for (var i = 0; i < size; ++i) {
  894. that[i] = 0
  895. }
  896. }
  897. return that
  898. }
  899. /**
  900. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  901. * */
  902. Buffer.allocUnsafe = function (size) {
  903. return allocUnsafe(null, size)
  904. }
  905. /**
  906. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  907. */
  908. Buffer.allocUnsafeSlow = function (size) {
  909. return allocUnsafe(null, size)
  910. }
  911. function fromString (that, string, encoding) {
  912. if (typeof encoding !== 'string' || encoding === '') {
  913. encoding = 'utf8'
  914. }
  915. if (!Buffer.isEncoding(encoding)) {
  916. throw new TypeError('"encoding" must be a valid string encoding')
  917. }
  918. var length = byteLength(string, encoding) | 0
  919. that = createBuffer(that, length)
  920. var actual = that.write(string, encoding)
  921. if (actual !== length) {
  922. // Writing a hex string, for example, that contains invalid characters will
  923. // cause everything after the first invalid character to be ignored. (e.g.
  924. // 'abxxcd' will be treated as 'ab')
  925. that = that.slice(0, actual)
  926. }
  927. return that
  928. }
  929. function fromArrayLike (that, array) {
  930. var length = array.length < 0 ? 0 : checked(array.length) | 0
  931. that = createBuffer(that, length)
  932. for (var i = 0; i < length; i += 1) {
  933. that[i] = array[i] & 255
  934. }
  935. return that
  936. }
  937. function fromArrayBuffer (that, array, byteOffset, length) {
  938. array.byteLength // this throws if `array` is not a valid ArrayBuffer
  939. if (byteOffset < 0 || array.byteLength < byteOffset) {
  940. throw new RangeError('\'offset\' is out of bounds')
  941. }
  942. if (array.byteLength < byteOffset + (length || 0)) {
  943. throw new RangeError('\'length\' is out of bounds')
  944. }
  945. if (byteOffset === undefined && length === undefined) {
  946. array = new Uint8Array(array)
  947. } else if (length === undefined) {
  948. array = new Uint8Array(array, byteOffset)
  949. } else {
  950. array = new Uint8Array(array, byteOffset, length)
  951. }
  952. if (Buffer.TYPED_ARRAY_SUPPORT) {
  953. // Return an augmented `Uint8Array` instance, for best performance
  954. that = array
  955. that.__proto__ = Buffer.prototype
  956. } else {
  957. // Fallback: Return an object instance of the Buffer class
  958. that = fromArrayLike(that, array)
  959. }
  960. return that
  961. }
  962. function fromObject (that, obj) {
  963. if (Buffer.isBuffer(obj)) {
  964. var len = checked(obj.length) | 0
  965. that = createBuffer(that, len)
  966. if (that.length === 0) {
  967. return that
  968. }
  969. obj.copy(that, 0, 0, len)
  970. return that
  971. }
  972. if (obj) {
  973. if ((typeof ArrayBuffer !== 'undefined' &&
  974. obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
  975. if (typeof obj.length !== 'number' || isnan(obj.length)) {
  976. return createBuffer(that, 0)
  977. }
  978. return fromArrayLike(that, obj)
  979. }
  980. if (obj.type === 'Buffer' && isArray(obj.data)) {
  981. return fromArrayLike(that, obj.data)
  982. }
  983. }
  984. throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  985. }
  986. function checked (length) {
  987. // Note: cannot use `length < kMaxLength()` here because that fails when
  988. // length is NaN (which is otherwise coerced to zero.)
  989. if (length >= kMaxLength()) {
  990. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  991. 'size: 0x' + kMaxLength().toString(16) + ' bytes')
  992. }
  993. return length | 0
  994. }
  995. function SlowBuffer (length) {
  996. if (+length != length) { // eslint-disable-line eqeqeq
  997. length = 0
  998. }
  999. return Buffer.alloc(+length)
  1000. }
  1001. Buffer.isBuffer = function isBuffer (b) {
  1002. return !!(b != null && b._isBuffer)
  1003. }
  1004. Buffer.compare = function compare (a, b) {
  1005. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  1006. throw new TypeError('Arguments must be Buffers')
  1007. }
  1008. if (a === b) return 0
  1009. var x = a.length
  1010. var y = b.length
  1011. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  1012. if (a[i] !== b[i]) {
  1013. x = a[i]
  1014. y = b[i]
  1015. break
  1016. }
  1017. }
  1018. if (x < y) return -1
  1019. if (y < x) return 1
  1020. return 0
  1021. }
  1022. Buffer.isEncoding = function isEncoding (encoding) {
  1023. switch (String(encoding).toLowerCase()) {
  1024. case 'hex':
  1025. case 'utf8':
  1026. case 'utf-8':
  1027. case 'ascii':
  1028. case 'latin1':
  1029. case 'binary':
  1030. case 'base64':
  1031. case 'ucs2':
  1032. case 'ucs-2':
  1033. case 'utf16le':
  1034. case 'utf-16le':
  1035. return true
  1036. default:
  1037. return false
  1038. }
  1039. }
  1040. Buffer.concat = function concat (list, length) {
  1041. if (!isArray(list)) {
  1042. throw new TypeError('"list" argument must be an Array of Buffers')
  1043. }
  1044. if (list.length === 0) {
  1045. return Buffer.alloc(0)
  1046. }
  1047. var i
  1048. if (length === undefined) {
  1049. length = 0
  1050. for (i = 0; i < list.length; ++i) {
  1051. length += list[i].length
  1052. }
  1053. }
  1054. var buffer = Buffer.allocUnsafe(length)
  1055. var pos = 0
  1056. for (i = 0; i < list.length; ++i) {
  1057. var buf = list[i]
  1058. if (!Buffer.isBuffer(buf)) {
  1059. throw new TypeError('"list" argument must be an Array of Buffers')
  1060. }
  1061. buf.copy(buffer, pos)
  1062. pos += buf.length
  1063. }
  1064. return buffer
  1065. }
  1066. function byteLength (string, encoding) {
  1067. if (Buffer.isBuffer(string)) {
  1068. return string.length
  1069. }
  1070. if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
  1071. (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
  1072. return string.byteLength
  1073. }
  1074. if (typeof string !== 'string') {
  1075. string = '' + string
  1076. }
  1077. var len = string.length
  1078. if (len === 0) return 0
  1079. // Use a for loop to avoid recursion
  1080. var loweredCase = false
  1081. for (;;) {
  1082. switch (encoding) {
  1083. case 'ascii':
  1084. case 'latin1':
  1085. case 'binary':
  1086. return len
  1087. case 'utf8':
  1088. case 'utf-8':
  1089. case undefined:
  1090. return utf8ToBytes(string).length
  1091. case 'ucs2':
  1092. case 'ucs-2':
  1093. case 'utf16le':
  1094. case 'utf-16le':
  1095. return len * 2
  1096. case 'hex':
  1097. return len >>> 1
  1098. case 'base64':
  1099. return base64ToBytes(string).length
  1100. default:
  1101. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  1102. encoding = ('' + encoding).toLowerCase()
  1103. loweredCase = true
  1104. }
  1105. }
  1106. }
  1107. Buffer.byteLength = byteLength
  1108. function slowToString (encoding, start, end) {
  1109. var loweredCase = false
  1110. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  1111. // property of a typed array.
  1112. // This behaves neither like String nor Uint8Array in that we set start/end
  1113. // to their upper/lower bounds if the value passed is out of range.
  1114. // undefined is handled specially as per ECMA-262 6th Edition,
  1115. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  1116. if (start === undefined || start < 0) {
  1117. start = 0
  1118. }
  1119. // Return early if start > this.length. Done here to prevent potential uint32
  1120. // coercion fail below.
  1121. if (start > this.length) {
  1122. return ''
  1123. }
  1124. if (end === undefined || end > this.length) {
  1125. end = this.length
  1126. }
  1127. if (end <= 0) {
  1128. return ''
  1129. }
  1130. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  1131. end >>>= 0
  1132. start >>>= 0
  1133. if (end <= start) {
  1134. return ''
  1135. }
  1136. if (!encoding) encoding = 'utf8'
  1137. while (true) {
  1138. switch (encoding) {
  1139. case 'hex':
  1140. return hexSlice(this, start, end)
  1141. case 'utf8':
  1142. case 'utf-8':
  1143. return utf8Slice(this, start, end)
  1144. case 'ascii':
  1145. return asciiSlice(this, start, end)
  1146. case 'latin1':
  1147. case 'binary':
  1148. return latin1Slice(this, start, end)
  1149. case 'base64':
  1150. return base64Slice(this, start, end)
  1151. case 'ucs2':
  1152. case 'ucs-2':
  1153. case 'utf16le':
  1154. case 'utf-16le':
  1155. return utf16leSlice(this, start, end)
  1156. default:
  1157. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  1158. encoding = (encoding + '').toLowerCase()
  1159. loweredCase = true
  1160. }
  1161. }
  1162. }
  1163. // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
  1164. // Buffer instances.
  1165. Buffer.prototype._isBuffer = true
  1166. function swap (b, n, m) {
  1167. var i = b[n]
  1168. b[n] = b[m]
  1169. b[m] = i
  1170. }
  1171. Buffer.prototype.swap16 = function swap16 () {
  1172. var len = this.length
  1173. if (len % 2 !== 0) {
  1174. throw new RangeError('Buffer size must be a multiple of 16-bits')
  1175. }
  1176. for (var i = 0; i < len; i += 2) {
  1177. swap(this, i, i + 1)
  1178. }
  1179. return this
  1180. }
  1181. Buffer.prototype.swap32 = function swap32 () {
  1182. var len = this.length
  1183. if (len % 4 !== 0) {
  1184. throw new RangeError('Buffer size must be a multiple of 32-bits')
  1185. }
  1186. for (var i = 0; i < len; i += 4) {
  1187. swap(this, i, i + 3)
  1188. swap(this, i + 1, i + 2)
  1189. }
  1190. return this
  1191. }
  1192. Buffer.prototype.swap64 = function swap64 () {
  1193. var len = this.length
  1194. if (len % 8 !== 0) {
  1195. throw new RangeError('Buffer size must be a multiple of 64-bits')
  1196. }
  1197. for (var i = 0; i < len; i += 8) {
  1198. swap(this, i, i + 7)
  1199. swap(this, i + 1, i + 6)
  1200. swap(this, i + 2, i + 5)
  1201. swap(this, i + 3, i + 4)
  1202. }
  1203. return this
  1204. }
  1205. Buffer.prototype.toString = function toString () {
  1206. var length = this.length | 0
  1207. if (length === 0) return ''
  1208. if (arguments.length === 0) return utf8Slice(this, 0, length)
  1209. return slowToString.apply(this, arguments)
  1210. }
  1211. Buffer.prototype.equals = function equals (b) {
  1212. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  1213. if (this === b) return true
  1214. return Buffer.compare(this, b) === 0
  1215. }
  1216. Buffer.prototype.inspect = function inspect () {
  1217. var str = ''
  1218. var max = exports.INSPECT_MAX_BYTES
  1219. if (this.length > 0) {
  1220. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
  1221. if (this.length > max) str += ' ... '
  1222. }
  1223. return '<Buffer ' + str + '>'
  1224. }
  1225. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  1226. if (!Buffer.isBuffer(target)) {
  1227. throw new TypeError('Argument must be a Buffer')
  1228. }
  1229. if (start === undefined) {
  1230. start = 0
  1231. }
  1232. if (end === undefined) {
  1233. end = target ? target.length : 0
  1234. }
  1235. if (thisStart === undefined) {
  1236. thisStart = 0
  1237. }
  1238. if (thisEnd === undefined) {
  1239. thisEnd = this.length
  1240. }
  1241. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  1242. throw new RangeError('out of range index')
  1243. }
  1244. if (thisStart >= thisEnd && start >= end) {
  1245. return 0
  1246. }
  1247. if (thisStart >= thisEnd) {
  1248. return -1
  1249. }
  1250. if (start >= end) {
  1251. return 1
  1252. }
  1253. start >>>= 0
  1254. end >>>= 0
  1255. thisStart >>>= 0
  1256. thisEnd >>>= 0
  1257. if (this === target) return 0
  1258. var x = thisEnd - thisStart
  1259. var y = end - start
  1260. var len = Math.min(x, y)
  1261. var thisCopy = this.slice(thisStart, thisEnd)
  1262. var targetCopy = target.slice(start, end)
  1263. for (var i = 0; i < len; ++i) {
  1264. if (thisCopy[i] !== targetCopy[i]) {
  1265. x = thisCopy[i]
  1266. y = targetCopy[i]
  1267. break
  1268. }
  1269. }
  1270. if (x < y) return -1
  1271. if (y < x) return 1
  1272. return 0
  1273. }
  1274. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  1275. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  1276. //
  1277. // Arguments:
  1278. // - buffer - a Buffer to search
  1279. // - val - a string, Buffer, or number
  1280. // - byteOffset - an index into `buffer`; will be clamped to an int32
  1281. // - encoding - an optional encoding, relevant is val is a string
  1282. // - dir - true for indexOf, false for lastIndexOf
  1283. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  1284. // Empty buffer means no match
  1285. if (buffer.length === 0) return -1
  1286. // Normalize byteOffset
  1287. if (typeof byteOffset === 'string') {
  1288. encoding = byteOffset
  1289. byteOffset = 0
  1290. } else if (byteOffset > 0x7fffffff) {
  1291. byteOffset = 0x7fffffff
  1292. } else if (byteOffset < -0x80000000) {
  1293. byteOffset = -0x80000000
  1294. }
  1295. byteOffset = +byteOffset // Coerce to Number.
  1296. if (isNaN(byteOffset)) {
  1297. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  1298. byteOffset = dir ? 0 : (buffer.length - 1)
  1299. }
  1300. // Normalize byteOffset: negative offsets start from the end of the buffer
  1301. if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  1302. if (byteOffset >= buffer.length) {
  1303. if (dir) return -1
  1304. else byteOffset = buffer.length - 1
  1305. } else if (byteOffset < 0) {
  1306. if (dir) byteOffset = 0
  1307. else return -1
  1308. }
  1309. // Normalize val
  1310. if (typeof val === 'string') {
  1311. val = Buffer.from(val, encoding)
  1312. }
  1313. // Finally, search either indexOf (if dir is true) or lastIndexOf
  1314. if (Buffer.isBuffer(val)) {
  1315. // Special case: looking for empty string/buffer always fails
  1316. if (val.length === 0) {
  1317. return -1
  1318. }
  1319. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  1320. } else if (typeof val === 'number') {
  1321. val = val & 0xFF // Search for a byte value [0-255]
  1322. if (Buffer.TYPED_ARRAY_SUPPORT &&
  1323. typeof Uint8Array.prototype.indexOf === 'function') {
  1324. if (dir) {
  1325. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  1326. } else {
  1327. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  1328. }
  1329. }
  1330. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  1331. }
  1332. throw new TypeError('val must be string, number or Buffer')
  1333. }
  1334. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  1335. var indexSize = 1
  1336. var arrLength = arr.length
  1337. var valLength = val.length
  1338. if (encoding !== undefined) {
  1339. encoding = String(encoding).toLowerCase()
  1340. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  1341. encoding === 'utf16le' || encoding === 'utf-16le') {
  1342. if (arr.length < 2 || val.length < 2) {
  1343. return -1
  1344. }
  1345. indexSize = 2
  1346. arrLength /= 2
  1347. valLength /= 2
  1348. byteOffset /= 2
  1349. }
  1350. }
  1351. function read (buf, i) {
  1352. if (indexSize === 1) {
  1353. return buf[i]
  1354. } else {
  1355. return buf.readUInt16BE(i * indexSize)
  1356. }
  1357. }
  1358. var i
  1359. if (dir) {
  1360. var foundIndex = -1
  1361. for (i = byteOffset; i < arrLength; i++) {
  1362. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  1363. if (foundIndex === -1) foundIndex = i
  1364. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  1365. } else {
  1366. if (foundIndex !== -1) i -= i - foundIndex
  1367. foundIndex = -1
  1368. }
  1369. }
  1370. } else {
  1371. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
  1372. for (i = byteOffset; i >= 0; i--) {
  1373. var found = true
  1374. for (var j = 0; j < valLength; j++) {
  1375. if (read(arr, i + j) !== read(val, j)) {
  1376. found = false
  1377. break
  1378. }
  1379. }
  1380. if (found) return i
  1381. }
  1382. }
  1383. return -1
  1384. }
  1385. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  1386. return this.indexOf(val, byteOffset, encoding) !== -1
  1387. }
  1388. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  1389. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  1390. }
  1391. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  1392. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  1393. }
  1394. function hexWrite (buf, string, offset, length) {
  1395. offset = Number(offset) || 0
  1396. var remaining = buf.length - offset
  1397. if (!length) {
  1398. length = remaining
  1399. } else {
  1400. length = Number(length)
  1401. if (length > remaining) {
  1402. length = remaining
  1403. }
  1404. }
  1405. // must be an even number of digits
  1406. var strLen = string.length
  1407. if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
  1408. if (length > strLen / 2) {
  1409. length = strLen / 2
  1410. }
  1411. for (var i = 0; i < length; ++i) {
  1412. var parsed = parseInt(string.substr(i * 2, 2), 16)
  1413. if (isNaN(parsed)) return i
  1414. buf[offset + i] = parsed
  1415. }
  1416. return i
  1417. }
  1418. function utf8Write (buf, string, offset, length) {
  1419. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  1420. }
  1421. function asciiWrite (buf, string, offset, length) {
  1422. return blitBuffer(asciiToBytes(string), buf, offset, length)
  1423. }
  1424. function latin1Write (buf, string, offset, length) {
  1425. return asciiWrite(buf, string, offset, length)
  1426. }
  1427. function base64Write (buf, string, offset, length) {
  1428. return blitBuffer(base64ToBytes(string), buf, offset, length)
  1429. }
  1430. function ucs2Write (buf, string, offset, length) {
  1431. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  1432. }
  1433. Buffer.prototype.write = function write (string, offset, length, encoding) {
  1434. // Buffer#write(string)
  1435. if (offset === undefined) {
  1436. encoding = 'utf8'
  1437. length = this.length
  1438. offset = 0
  1439. // Buffer#write(string, encoding)
  1440. } else if (length === undefined && typeof offset === 'string') {
  1441. encoding = offset
  1442. length = this.length
  1443. offset = 0
  1444. // Buffer#write(string, offset[, length][, encoding])
  1445. } else if (isFinite(offset)) {
  1446. offset = offset | 0
  1447. if (isFinite(length)) {
  1448. length = length | 0
  1449. if (encoding === undefined) encoding = 'utf8'
  1450. } else {
  1451. encoding = length
  1452. length = undefined
  1453. }
  1454. // legacy write(string, encoding, offset, length) - remove in v0.13
  1455. } else {
  1456. throw new Error(
  1457. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  1458. )
  1459. }
  1460. var remaining = this.length - offset
  1461. if (length === undefined || length > remaining) length = remaining
  1462. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  1463. throw new RangeError('Attempt to write outside buffer bounds')
  1464. }
  1465. if (!encoding) encoding = 'utf8'
  1466. var loweredCase = false
  1467. for (;;) {
  1468. switch (encoding) {
  1469. case 'hex':
  1470. return hexWrite(this, string, offset, length)
  1471. case 'utf8':
  1472. case 'utf-8':
  1473. return utf8Write(this, string, offset, length)
  1474. case 'ascii':
  1475. return asciiWrite(this, string, offset, length)
  1476. case 'latin1':
  1477. case 'binary':
  1478. return latin1Write(this, string, offset, length)
  1479. case 'base64':
  1480. // Warning: maxLength not taken into account in base64Write
  1481. return base64Write(this, string, offset, length)
  1482. case 'ucs2':
  1483. case 'ucs-2':
  1484. case 'utf16le':
  1485. case 'utf-16le':
  1486. return ucs2Write(this, string, offset, length)
  1487. default:
  1488. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  1489. encoding = ('' + encoding).toLowerCase()
  1490. loweredCase = true
  1491. }
  1492. }
  1493. }
  1494. Buffer.prototype.toJSON = function toJSON () {
  1495. return {
  1496. type: 'Buffer',
  1497. data: Array.prototype.slice.call(this._arr || this, 0)
  1498. }
  1499. }
  1500. function base64Slice (buf, start, end) {
  1501. if (start === 0 && end === buf.length) {
  1502. return base64.fromByteArray(buf)
  1503. } else {
  1504. return base64.fromByteArray(buf.slice(start, end))
  1505. }
  1506. }
  1507. function utf8Slice (buf, start, end) {
  1508. end = Math.min(buf.length, end)
  1509. var res = []
  1510. var i = start
  1511. while (i < end) {
  1512. var firstByte = buf[i]
  1513. var codePoint = null
  1514. var bytesPerSequence = (firstByte > 0xEF) ? 4
  1515. : (firstByte > 0xDF) ? 3
  1516. : (firstByte > 0xBF) ? 2
  1517. : 1
  1518. if (i + bytesPerSequence <= end) {
  1519. var secondByte, thirdByte, fourthByte, tempCodePoint
  1520. switch (bytesPerSequence) {
  1521. case 1:
  1522. if (firstByte < 0x80) {
  1523. codePoint = firstByte
  1524. }
  1525. break
  1526. case 2:
  1527. secondByte = buf[i + 1]
  1528. if ((secondByte & 0xC0) === 0x80) {
  1529. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  1530. if (tempCodePoint > 0x7F) {
  1531. codePoint = tempCodePoint
  1532. }
  1533. }
  1534. break
  1535. case 3:
  1536. secondByte = buf[i + 1]
  1537. thirdByte = buf[i + 2]
  1538. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  1539. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  1540. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  1541. codePoint = tempCodePoint
  1542. }
  1543. }
  1544. break
  1545. case 4:
  1546. secondByte = buf[i + 1]
  1547. thirdByte = buf[i + 2]
  1548. fourthByte = buf[i + 3]
  1549. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  1550. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  1551. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  1552. codePoint = tempCodePoint
  1553. }
  1554. }
  1555. }
  1556. }
  1557. if (codePoint === null) {
  1558. // we did not generate a valid codePoint so insert a
  1559. // replacement char (U+FFFD) and advance only 1 byte
  1560. codePoint = 0xFFFD
  1561. bytesPerSequence = 1
  1562. } else if (codePoint > 0xFFFF) {
  1563. // encode to utf16 (surrogate pair dance)
  1564. codePoint -= 0x10000
  1565. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  1566. codePoint = 0xDC00 | codePoint & 0x3FF
  1567. }
  1568. res.push(codePoint)
  1569. i += bytesPerSequence
  1570. }
  1571. return decodeCodePointsArray(res)
  1572. }
  1573. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  1574. // the lowest limit is Chrome, with 0x10000 args.
  1575. // We go 1 magnitude less, for safety
  1576. var MAX_ARGUMENTS_LENGTH = 0x1000
  1577. function decodeCodePointsArray (codePoints) {
  1578. var len = codePoints.length
  1579. if (len <= MAX_ARGUMENTS_LENGTH) {
  1580. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  1581. }
  1582. // Decode in chunks to avoid "call stack size exceeded".
  1583. var res = ''
  1584. var i = 0
  1585. while (i < len) {
  1586. res += String.fromCharCode.apply(
  1587. String,
  1588. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  1589. )
  1590. }
  1591. return res
  1592. }
  1593. function asciiSlice (buf, start, end) {
  1594. var ret = ''
  1595. end = Math.min(buf.length, end)
  1596. for (var i = start; i < end; ++i) {
  1597. ret += String.fromCharCode(buf[i] & 0x7F)
  1598. }
  1599. return ret
  1600. }
  1601. function latin1Slice (buf, start, end) {
  1602. var ret = ''
  1603. end = Math.min(buf.length, end)
  1604. for (var i = start; i < end; ++i) {
  1605. ret += String.fromCharCode(buf[i])
  1606. }
  1607. return ret
  1608. }
  1609. function hexSlice (buf, start, end) {
  1610. var len = buf.length
  1611. if (!start || start < 0) start = 0
  1612. if (!end || end < 0 || end > len) end = len
  1613. var out = ''
  1614. for (var i = start; i < end; ++i) {
  1615. out += toHex(buf[i])
  1616. }
  1617. return out
  1618. }
  1619. function utf16leSlice (buf, start, end) {
  1620. var bytes = buf.slice(start, end)
  1621. var res = ''
  1622. for (var i = 0; i < bytes.length; i += 2) {
  1623. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
  1624. }
  1625. return res
  1626. }
  1627. Buffer.prototype.slice = function slice (start, end) {
  1628. var len = this.length
  1629. start = ~~start
  1630. end = end === undefined ? len : ~~end
  1631. if (start < 0) {
  1632. start += len
  1633. if (start < 0) start = 0
  1634. } else if (start > len) {
  1635. start = len
  1636. }
  1637. if (end < 0) {
  1638. end += len
  1639. if (end < 0) end = 0
  1640. } else if (end > len) {
  1641. end = len
  1642. }
  1643. if (end < start) end = start
  1644. var newBuf
  1645. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1646. newBuf = this.subarray(start, end)
  1647. newBuf.__proto__ = Buffer.prototype
  1648. } else {
  1649. var sliceLen = end - start
  1650. newBuf = new Buffer(sliceLen, undefined)
  1651. for (var i = 0; i < sliceLen; ++i) {
  1652. newBuf[i] = this[i + start]
  1653. }
  1654. }
  1655. return newBuf
  1656. }
  1657. /*
  1658. * Need to make sure that buffer isn't trying to write out of bounds.
  1659. */
  1660. function checkOffset (offset, ext, length) {
  1661. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  1662. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  1663. }
  1664. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  1665. offset = offset | 0
  1666. byteLength = byteLength | 0
  1667. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1668. var val = this[offset]
  1669. var mul = 1
  1670. var i = 0
  1671. while (++i < byteLength && (mul *= 0x100)) {
  1672. val += this[offset + i] * mul
  1673. }
  1674. return val
  1675. }
  1676. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  1677. offset = offset | 0
  1678. byteLength = byteLength | 0
  1679. if (!noAssert) {
  1680. checkOffset(offset, byteLength, this.length)
  1681. }
  1682. var val = this[offset + --byteLength]
  1683. var mul = 1
  1684. while (byteLength > 0 && (mul *= 0x100)) {
  1685. val += this[offset + --byteLength] * mul
  1686. }
  1687. return val
  1688. }
  1689. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  1690. if (!noAssert) checkOffset(offset, 1, this.length)
  1691. return this[offset]
  1692. }
  1693. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  1694. if (!noAssert) checkOffset(offset, 2, this.length)
  1695. return this[offset] | (this[offset + 1] << 8)
  1696. }
  1697. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  1698. if (!noAssert) checkOffset(offset, 2, this.length)
  1699. return (this[offset] << 8) | this[offset + 1]
  1700. }
  1701. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  1702. if (!noAssert) checkOffset(offset, 4, this.length)
  1703. return ((this[offset]) |
  1704. (this[offset + 1] << 8) |
  1705. (this[offset + 2] << 16)) +
  1706. (this[offset + 3] * 0x1000000)
  1707. }
  1708. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  1709. if (!noAssert) checkOffset(offset, 4, this.length)
  1710. return (this[offset] * 0x1000000) +
  1711. ((this[offset + 1] << 16) |
  1712. (this[offset + 2] << 8) |
  1713. this[offset + 3])
  1714. }
  1715. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  1716. offset = offset | 0
  1717. byteLength = byteLength | 0
  1718. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1719. var val = this[offset]
  1720. var mul = 1
  1721. var i = 0
  1722. while (++i < byteLength && (mul *= 0x100)) {
  1723. val += this[offset + i] * mul
  1724. }
  1725. mul *= 0x80
  1726. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1727. return val
  1728. }
  1729. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  1730. offset = offset | 0
  1731. byteLength = byteLength | 0
  1732. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1733. var i = byteLength
  1734. var mul = 1
  1735. var val = this[offset + --i]
  1736. while (i > 0 && (mul *= 0x100)) {
  1737. val += this[offset + --i] * mul
  1738. }
  1739. mul *= 0x80
  1740. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1741. return val
  1742. }
  1743. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  1744. if (!noAssert) checkOffset(offset, 1, this.length)
  1745. if (!(this[offset] & 0x80)) return (this[offset])
  1746. return ((0xff - this[offset] + 1) * -1)
  1747. }
  1748. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  1749. if (!noAssert) checkOffset(offset, 2, this.length)
  1750. var val = this[offset] | (this[offset + 1] << 8)
  1751. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1752. }
  1753. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  1754. if (!noAssert) checkOffset(offset, 2, this.length)
  1755. var val = this[offset + 1] | (this[offset] << 8)
  1756. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1757. }
  1758. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  1759. if (!noAssert) checkOffset(offset, 4, this.length)
  1760. return (this[offset]) |
  1761. (this[offset + 1] << 8) |
  1762. (this[offset + 2] << 16) |
  1763. (this[offset + 3] << 24)
  1764. }
  1765. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  1766. if (!noAssert) checkOffset(offset, 4, this.length)
  1767. return (this[offset] << 24) |
  1768. (this[offset + 1] << 16) |
  1769. (this[offset + 2] << 8) |
  1770. (this[offset + 3])
  1771. }
  1772. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  1773. if (!noAssert) checkOffset(offset, 4, this.length)
  1774. return ieee754.read(this, offset, true, 23, 4)
  1775. }
  1776. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  1777. if (!noAssert) checkOffset(offset, 4, this.length)
  1778. return ieee754.read(this, offset, false, 23, 4)
  1779. }
  1780. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  1781. if (!noAssert) checkOffset(offset, 8, this.length)
  1782. return ieee754.read(this, offset, true, 52, 8)
  1783. }
  1784. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  1785. if (!noAssert) checkOffset(offset, 8, this.length)
  1786. return ieee754.read(this, offset, false, 52, 8)
  1787. }
  1788. function checkInt (buf, value, offset, ext, max, min) {
  1789. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  1790. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  1791. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1792. }
  1793. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  1794. value = +value
  1795. offset = offset | 0
  1796. byteLength = byteLength | 0
  1797. if (!noAssert) {
  1798. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  1799. checkInt(this, value, offset, byteLength, maxBytes, 0)
  1800. }
  1801. var mul = 1
  1802. var i = 0
  1803. this[offset] = value & 0xFF
  1804. while (++i < byteLength && (mul *= 0x100)) {
  1805. this[offset + i] = (value / mul) & 0xFF
  1806. }
  1807. return offset + byteLength
  1808. }
  1809. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  1810. value = +value
  1811. offset = offset | 0
  1812. byteLength = byteLength | 0
  1813. if (!noAssert) {
  1814. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  1815. checkInt(this, value, offset, byteLength, maxBytes, 0)
  1816. }
  1817. var i = byteLength - 1
  1818. var mul = 1
  1819. this[offset + i] = value & 0xFF
  1820. while (--i >= 0 && (mul *= 0x100)) {
  1821. this[offset + i] = (value / mul) & 0xFF
  1822. }
  1823. return offset + byteLength
  1824. }
  1825. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  1826. value = +value
  1827. offset = offset | 0
  1828. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  1829. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1830. this[offset] = (value & 0xff)
  1831. return offset + 1
  1832. }
  1833. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  1834. if (value < 0) value = 0xffff + value + 1
  1835. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
  1836. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  1837. (littleEndian ? i : 1 - i) * 8
  1838. }
  1839. }
  1840. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  1841. value = +value
  1842. offset = offset | 0
  1843. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1844. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1845. this[offset] = (value & 0xff)
  1846. this[offset + 1] = (value >>> 8)
  1847. } else {
  1848. objectWriteUInt16(this, value, offset, true)
  1849. }
  1850. return offset + 2
  1851. }
  1852. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  1853. value = +value
  1854. offset = offset | 0
  1855. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1856. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1857. this[offset] = (value >>> 8)
  1858. this[offset + 1] = (value & 0xff)
  1859. } else {
  1860. objectWriteUInt16(this, value, offset, false)
  1861. }
  1862. return offset + 2
  1863. }
  1864. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  1865. if (value < 0) value = 0xffffffff + value + 1
  1866. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
  1867. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
  1868. }
  1869. }
  1870. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  1871. value = +value
  1872. offset = offset | 0
  1873. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1874. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1875. this[offset + 3] = (value >>> 24)
  1876. this[offset + 2] = (value >>> 16)
  1877. this[offset + 1] = (value >>> 8)
  1878. this[offset] = (value & 0xff)
  1879. } else {
  1880. objectWriteUInt32(this, value, offset, true)
  1881. }
  1882. return offset + 4
  1883. }
  1884. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  1885. value = +value
  1886. offset = offset | 0
  1887. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1888. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1889. this[offset] = (value >>> 24)
  1890. this[offset + 1] = (value >>> 16)
  1891. this[offset + 2] = (value >>> 8)
  1892. this[offset + 3] = (value & 0xff)
  1893. } else {
  1894. objectWriteUInt32(this, value, offset, false)
  1895. }
  1896. return offset + 4
  1897. }
  1898. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  1899. value = +value
  1900. offset = offset | 0
  1901. if (!noAssert) {
  1902. var limit = Math.pow(2, 8 * byteLength - 1)
  1903. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1904. }
  1905. var i = 0
  1906. var mul = 1
  1907. var sub = 0
  1908. this[offset] = value & 0xFF
  1909. while (++i < byteLength && (mul *= 0x100)) {
  1910. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  1911. sub = 1
  1912. }
  1913. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1914. }
  1915. return offset + byteLength
  1916. }
  1917. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  1918. value = +value
  1919. offset = offset | 0
  1920. if (!noAssert) {
  1921. var limit = Math.pow(2, 8 * byteLength - 1)
  1922. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1923. }
  1924. var i = byteLength - 1
  1925. var mul = 1
  1926. var sub = 0
  1927. this[offset + i] = value & 0xFF
  1928. while (--i >= 0 && (mul *= 0x100)) {
  1929. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  1930. sub = 1
  1931. }
  1932. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1933. }
  1934. return offset + byteLength
  1935. }
  1936. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  1937. value = +value
  1938. offset = offset | 0
  1939. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  1940. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1941. if (value < 0) value = 0xff + value + 1
  1942. this[offset] = (value & 0xff)
  1943. return offset + 1
  1944. }
  1945. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  1946. value = +value
  1947. offset = offset | 0
  1948. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1949. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1950. this[offset] = (value & 0xff)
  1951. this[offset + 1] = (value >>> 8)
  1952. } else {
  1953. objectWriteUInt16(this, value, offset, true)
  1954. }
  1955. return offset + 2
  1956. }
  1957. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  1958. value = +value
  1959. offset = offset | 0
  1960. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1961. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1962. this[offset] = (value >>> 8)
  1963. this[offset + 1] = (value & 0xff)
  1964. } else {
  1965. objectWriteUInt16(this, value, offset, false)
  1966. }
  1967. return offset + 2
  1968. }
  1969. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  1970. value = +value
  1971. offset = offset | 0
  1972. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1973. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1974. this[offset] = (value & 0xff)
  1975. this[offset + 1] = (value >>> 8)
  1976. this[offset + 2] = (value >>> 16)
  1977. this[offset + 3] = (value >>> 24)
  1978. } else {
  1979. objectWriteUInt32(this, value, offset, true)
  1980. }
  1981. return offset + 4
  1982. }
  1983. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  1984. value = +value
  1985. offset = offset | 0
  1986. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1987. if (value < 0) value = 0xffffffff + value + 1
  1988. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1989. this[offset] = (value >>> 24)
  1990. this[offset + 1] = (value >>> 16)
  1991. this[offset + 2] = (value >>> 8)
  1992. this[offset + 3] = (value & 0xff)
  1993. } else {
  1994. objectWriteUInt32(this, value, offset, false)
  1995. }
  1996. return offset + 4
  1997. }
  1998. function checkIEEE754 (buf, value, offset, ext, max, min) {
  1999. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  2000. if (offset < 0) throw new RangeError('Index out of range')
  2001. }
  2002. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  2003. if (!noAssert) {
  2004. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  2005. }
  2006. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  2007. return offset + 4
  2008. }
  2009. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  2010. return writeFloat(this, value, offset, true, noAssert)
  2011. }
  2012. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  2013. return writeFloat(this, value, offset, false, noAssert)
  2014. }
  2015. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  2016. if (!noAssert) {
  2017. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  2018. }
  2019. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  2020. return offset + 8
  2021. }
  2022. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  2023. return writeDouble(this, value, offset, true, noAssert)
  2024. }
  2025. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  2026. return writeDouble(this, value, offset, false, noAssert)
  2027. }
  2028. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  2029. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  2030. if (!start) start = 0
  2031. if (!end && end !== 0) end = this.length
  2032. if (targetStart >= target.length) targetStart = target.length
  2033. if (!targetStart) targetStart = 0
  2034. if (end > 0 && end < start) end = start
  2035. // Copy 0 bytes; we're done
  2036. if (end === start) return 0
  2037. if (target.length === 0 || this.length === 0) return 0
  2038. // Fatal error conditions
  2039. if (targetStart < 0) {
  2040. throw new RangeError('targetStart out of bounds')
  2041. }
  2042. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  2043. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  2044. // Are we oob?
  2045. if (end > this.length) end = this.length
  2046. if (target.length - targetStart < end - start) {
  2047. end = target.length - targetStart + start
  2048. }
  2049. var len = end - start
  2050. var i
  2051. if (this === target && start < targetStart && targetStart < end) {
  2052. // descending copy from end
  2053. for (i = len - 1; i >= 0; --i) {
  2054. target[i + targetStart] = this[i + start]
  2055. }
  2056. } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
  2057. // ascending copy from start
  2058. for (i = 0; i < len; ++i) {
  2059. target[i + targetStart] = this[i + start]
  2060. }
  2061. } else {
  2062. Uint8Array.prototype.set.call(
  2063. target,
  2064. this.subarray(start, start + len),
  2065. targetStart
  2066. )
  2067. }
  2068. return len
  2069. }
  2070. // Usage:
  2071. // buffer.fill(number[, offset[, end]])
  2072. // buffer.fill(buffer[, offset[, end]])
  2073. // buffer.fill(string[, offset[, end]][, encoding])
  2074. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  2075. // Handle string cases:
  2076. if (typeof val === 'string') {
  2077. if (typeof start === 'string') {
  2078. encoding = start
  2079. start = 0
  2080. end = this.length
  2081. } else if (typeof end === 'string') {
  2082. encoding = end
  2083. end = this.length
  2084. }
  2085. if (val.length === 1) {
  2086. var code = val.charCodeAt(0)
  2087. if (code < 256) {
  2088. val = code
  2089. }
  2090. }
  2091. if (encoding !== undefined && typeof encoding !== 'string') {
  2092. throw new TypeError('encoding must be a string')
  2093. }
  2094. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  2095. throw new TypeError('Unknown encoding: ' + encoding)
  2096. }
  2097. } else if (typeof val === 'number') {
  2098. val = val & 255
  2099. }
  2100. // Invalid ranges are not set to a default, so can range check early.
  2101. if (start < 0 || this.length < start || this.length < end) {
  2102. throw new RangeError('Out of range index')
  2103. }
  2104. if (end <= start) {
  2105. return this
  2106. }
  2107. start = start >>> 0
  2108. end = end === undefined ? this.length : end >>> 0
  2109. if (!val) val = 0
  2110. var i
  2111. if (typeof val === 'number') {
  2112. for (i = start; i < end; ++i) {
  2113. this[i] = val
  2114. }
  2115. } else {
  2116. var bytes = Buffer.isBuffer(val)
  2117. ? val
  2118. : utf8ToBytes(new Buffer(val, encoding).toString())
  2119. var len = bytes.length
  2120. for (i = 0; i < end - start; ++i) {
  2121. this[i + start] = bytes[i % len]
  2122. }
  2123. }
  2124. return this
  2125. }
  2126. // HELPER FUNCTIONS
  2127. // ================
  2128. var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
  2129. function base64clean (str) {
  2130. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  2131. str = stringtrim(str).replace(INVALID_BASE64_RE, '')
  2132. // Node converts strings with length < 2 to ''
  2133. if (str.length < 2) return ''
  2134. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  2135. while (str.length % 4 !== 0) {
  2136. str = str + '='
  2137. }
  2138. return str
  2139. }
  2140. function stringtrim (str) {
  2141. if (str.trim) return str.trim()
  2142. return str.replace(/^\s+|\s+$/g, '')
  2143. }
  2144. function toHex (n) {
  2145. if (n < 16) return '0' + n.toString(16)
  2146. return n.toString(16)
  2147. }
  2148. function utf8ToBytes (string, units) {
  2149. units = units || Infinity
  2150. var codePoint
  2151. var length = string.length
  2152. var leadSurrogate = null
  2153. var bytes = []
  2154. for (var i = 0; i < length; ++i) {
  2155. codePoint = string.charCodeAt(i)
  2156. // is surrogate component
  2157. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  2158. // last char was a lead
  2159. if (!leadSurrogate) {
  2160. // no lead yet
  2161. if (codePoint > 0xDBFF) {
  2162. // unexpected trail
  2163. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  2164. continue
  2165. } else if (i + 1 === length) {
  2166. // unpaired lead
  2167. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  2168. continue
  2169. }
  2170. // valid lead
  2171. leadSurrogate = codePoint
  2172. continue
  2173. }
  2174. // 2 leads in a row
  2175. if (codePoint < 0xDC00) {
  2176. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  2177. leadSurrogate = codePoint
  2178. continue
  2179. }
  2180. // valid surrogate pair
  2181. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  2182. } else if (leadSurrogate) {
  2183. // valid bmp char, but last char was a lead
  2184. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  2185. }
  2186. leadSurrogate = null
  2187. // encode utf8
  2188. if (codePoint < 0x80) {
  2189. if ((units -= 1) < 0) break
  2190. bytes.push(codePoint)
  2191. } else if (codePoint < 0x800) {
  2192. if ((units -= 2) < 0) break
  2193. bytes.push(
  2194. codePoint >> 0x6 | 0xC0,
  2195. codePoint & 0x3F | 0x80
  2196. )
  2197. } else if (codePoint < 0x10000) {
  2198. if ((units -= 3) < 0) break
  2199. bytes.push(
  2200. codePoint >> 0xC | 0xE0,
  2201. codePoint >> 0x6 & 0x3F | 0x80,
  2202. codePoint & 0x3F | 0x80
  2203. )
  2204. } else if (codePoint < 0x110000) {
  2205. if ((units -= 4) < 0) break
  2206. bytes.push(
  2207. codePoint >> 0x12 | 0xF0,
  2208. codePoint >> 0xC & 0x3F | 0x80,
  2209. codePoint >> 0x6 & 0x3F | 0x80,
  2210. codePoint & 0x3F | 0x80
  2211. )
  2212. } else {
  2213. throw new Error('Invalid code point')
  2214. }
  2215. }
  2216. return bytes
  2217. }
  2218. function asciiToBytes (str) {
  2219. var byteArray = []
  2220. for (var i = 0; i < str.length; ++i) {
  2221. // Node's code seems to be doing this and not & 0x7F..
  2222. byteArray.push(str.charCodeAt(i) & 0xFF)
  2223. }
  2224. return byteArray
  2225. }
  2226. function utf16leToBytes (str, units) {
  2227. var c, hi, lo
  2228. var byteArray = []
  2229. for (var i = 0; i < str.length; ++i) {
  2230. if ((units -= 2) < 0) break
  2231. c = str.charCodeAt(i)
  2232. hi = c >> 8
  2233. lo = c % 256
  2234. byteArray.push(lo)
  2235. byteArray.push(hi)
  2236. }
  2237. return byteArray
  2238. }
  2239. function base64ToBytes (str) {
  2240. return base64.toByteArray(base64clean(str))
  2241. }
  2242. function blitBuffer (src, dst, offset, length) {
  2243. for (var i = 0; i < length; ++i) {
  2244. if ((i + offset >= dst.length) || (i >= src.length)) break
  2245. dst[i + offset] = src[i]
  2246. }
  2247. return i
  2248. }
  2249. function isnan (val) {
  2250. return val !== val // eslint-disable-line no-self-compare
  2251. }
  2252. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2253. },{"base64-js":4,"ieee754":16,"isarray":22}],8:[function(_dereq_,module,exports){
  2254. /**
  2255. * This is the web browser implementation of `debug()`.
  2256. *
  2257. * Expose `debug()` as the module.
  2258. */
  2259. exports = module.exports = _dereq_('./debug');
  2260. exports.log = log;
  2261. exports.formatArgs = formatArgs;
  2262. exports.save = save;
  2263. exports.load = load;
  2264. exports.useColors = useColors;
  2265. exports.storage = 'undefined' != typeof chrome
  2266. && 'undefined' != typeof chrome.storage
  2267. ? chrome.storage.local
  2268. : localstorage();
  2269. /**
  2270. * Colors.
  2271. */
  2272. exports.colors = [
  2273. 'lightseagreen',
  2274. 'forestgreen',
  2275. 'goldenrod',
  2276. 'dodgerblue',
  2277. 'darkorchid',
  2278. 'crimson'
  2279. ];
  2280. /**
  2281. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  2282. * and the Firebug extension (any Firefox version) are known
  2283. * to support "%c" CSS customizations.
  2284. *
  2285. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  2286. */
  2287. function useColors() {
  2288. // is webkit? http://stackoverflow.com/a/16459606/376773
  2289. return ('WebkitAppearance' in document.documentElement.style) ||
  2290. // is firebug? http://stackoverflow.com/a/398120/376773
  2291. (window.console && (console.firebug || (console.exception && console.table))) ||
  2292. // is firefox >= v31?
  2293. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  2294. (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
  2295. }
  2296. /**
  2297. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  2298. */
  2299. exports.formatters.j = function(v) {
  2300. return JSON.stringify(v);
  2301. };
  2302. /**
  2303. * Colorize log arguments if enabled.
  2304. *
  2305. * @api public
  2306. */
  2307. function formatArgs() {
  2308. var args = arguments;
  2309. var useColors = this.useColors;
  2310. args[0] = (useColors ? '%c' : '')
  2311. + this.namespace
  2312. + (useColors ? ' %c' : ' ')
  2313. + args[0]
  2314. + (useColors ? '%c ' : ' ');
  2315. if (!useColors) return args;
  2316. var c = 'color: ' + this.color;
  2317. args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
  2318. // the final "%c" is somewhat tricky, because there could be other
  2319. // arguments passed either before or after the %c, so we need to
  2320. // figure out the correct index to insert the CSS into
  2321. var index = 0;
  2322. var lastC = 0;
  2323. args[0].replace(/%[a-z%]/g, function(match) {
  2324. if ('%%' === match) return;
  2325. index++;
  2326. if ('%c' === match) {
  2327. // we only are interested in the *last* %c
  2328. // (the user may have provided their own)
  2329. lastC = index;
  2330. }
  2331. });
  2332. args.splice(lastC, 0, c);
  2333. return args;
  2334. }
  2335. /**
  2336. * Invokes `console.log()` when available.
  2337. * No-op when `console.log` is not a "function".
  2338. *
  2339. * @api public
  2340. */
  2341. function log() {
  2342. // this hackery is required for IE8/9, where
  2343. // the `console.log` function doesn't have 'apply'
  2344. return 'object' === typeof console
  2345. && console.log
  2346. && Function.prototype.apply.call(console.log, console, arguments);
  2347. }
  2348. /**
  2349. * Save `namespaces`.
  2350. *
  2351. * @param {String} namespaces
  2352. * @api private
  2353. */
  2354. function save(namespaces) {
  2355. try {
  2356. if (null == namespaces) {
  2357. exports.storage.removeItem('debug');
  2358. } else {
  2359. exports.storage.debug = namespaces;
  2360. }
  2361. } catch(e) {}
  2362. }
  2363. /**
  2364. * Load `namespaces`.
  2365. *
  2366. * @return {String} returns the previously persisted debug modes
  2367. * @api private
  2368. */
  2369. function load() {
  2370. var r;
  2371. try {
  2372. r = exports.storage.debug;
  2373. } catch(e) {}
  2374. return r;
  2375. }
  2376. /**
  2377. * Enable namespaces listed in `localStorage.debug` initially.
  2378. */
  2379. exports.enable(load());
  2380. /**
  2381. * Localstorage attempts to return the localstorage.
  2382. *
  2383. * This is necessary because safari throws
  2384. * when a user disables cookies/localstorage
  2385. * and you attempt to access it.
  2386. *
  2387. * @return {LocalStorage}
  2388. * @api private
  2389. */
  2390. function localstorage(){
  2391. try {
  2392. return window.localStorage;
  2393. } catch (e) {}
  2394. }
  2395. },{"./debug":9}],9:[function(_dereq_,module,exports){
  2396. /**
  2397. * This is the common logic for both the Node.js and web browser
  2398. * implementations of `debug()`.
  2399. *
  2400. * Expose `debug()` as the module.
  2401. */
  2402. exports = module.exports = debug;
  2403. exports.coerce = coerce;
  2404. exports.disable = disable;
  2405. exports.enable = enable;
  2406. exports.enabled = enabled;
  2407. /**
  2408. * The currently active debug mode names, and names to skip.
  2409. */
  2410. exports.names = [];
  2411. exports.skips = [];
  2412. /**
  2413. * Map of special "%n" handling functions, for the debug "format" argument.
  2414. *
  2415. * Valid key names are a single, lowercased letter, i.e. "n".
  2416. */
  2417. exports.formatters = {};
  2418. /**
  2419. * Previously assigned color.
  2420. */
  2421. var prevColor = 0;
  2422. /**
  2423. * Select a color.
  2424. *
  2425. * @return {Number}
  2426. * @api private
  2427. */
  2428. function selectColor() {
  2429. return exports.colors[prevColor++ % exports.colors.length];
  2430. }
  2431. /**
  2432. * Create a debugger with the given `namespace`.
  2433. *
  2434. * @param {String} namespace
  2435. * @return {Function}
  2436. * @api public
  2437. */
  2438. function debug(namespace) {
  2439. // define the `disabled` version
  2440. function disabled() {
  2441. }
  2442. disabled.enabled = false;
  2443. // define the `enabled` version
  2444. function enabled() {
  2445. var self = enabled;
  2446. // add the `color` if not set
  2447. if (null == self.useColors) self.useColors = exports.useColors();
  2448. if (null == self.color && self.useColors) self.color = selectColor();
  2449. var args = Array.prototype.slice.call(arguments);
  2450. args[0] = exports.coerce(args[0]);
  2451. if ('string' !== typeof args[0]) {
  2452. // anything else let's inspect with %o
  2453. args = ['%o'].concat(args);
  2454. }
  2455. // apply any `formatters` transformations
  2456. var index = 0;
  2457. args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
  2458. // if we encounter an escaped % then don't increase the array index
  2459. if (match === '%%') return match;
  2460. index++;
  2461. var formatter = exports.formatters[format];
  2462. if ('function' === typeof formatter) {
  2463. var val = args[index];
  2464. match = formatter.call(self, val);
  2465. // now we need to remove `args[index]` since it's inlined in the `format`
  2466. args.splice(index, 1);
  2467. index--;
  2468. }
  2469. return match;
  2470. });
  2471. if ('function' === typeof exports.formatArgs) {
  2472. args = exports.formatArgs.apply(self, args);
  2473. }
  2474. var logFn = enabled.log || exports.log || console.log.bind(console);
  2475. logFn.apply(self, args);
  2476. }
  2477. enabled.enabled = true;
  2478. var fn = exports.enabled(namespace) ? enabled : disabled;
  2479. fn.namespace = namespace;
  2480. return fn;
  2481. }
  2482. /**
  2483. * Enables a debug mode by namespaces. This can include modes
  2484. * separated by a colon and wildcards.
  2485. *
  2486. * @param {String} namespaces
  2487. * @api public
  2488. */
  2489. function enable(namespaces) {
  2490. exports.save(namespaces);
  2491. var split = (namespaces || '').split(/[\s,]+/);
  2492. var len = split.length;
  2493. for (var i = 0; i < len; i++) {
  2494. if (!split[i]) continue; // ignore empty strings
  2495. namespaces = split[i].replace(/\*/g, '.*?');
  2496. if (namespaces[0] === '-') {
  2497. exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  2498. } else {
  2499. exports.names.push(new RegExp('^' + namespaces + '$'));
  2500. }
  2501. }
  2502. }
  2503. /**
  2504. * Disable debug output.
  2505. *
  2506. * @api public
  2507. */
  2508. function disable() {
  2509. exports.enable('');
  2510. }
  2511. /**
  2512. * Returns true if the given mode name is enabled, false otherwise.
  2513. *
  2514. * @param {String} name
  2515. * @return {Boolean}
  2516. * @api public
  2517. */
  2518. function enabled(name) {
  2519. var i, len;
  2520. for (i = 0, len = exports.skips.length; i < len; i++) {
  2521. if (exports.skips[i].test(name)) {
  2522. return false;
  2523. }
  2524. }
  2525. for (i = 0, len = exports.names.length; i < len; i++) {
  2526. if (exports.names[i].test(name)) {
  2527. return true;
  2528. }
  2529. }
  2530. return false;
  2531. }
  2532. /**
  2533. * Coerce `val`.
  2534. *
  2535. * @param {Mixed} val
  2536. * @return {Mixed}
  2537. * @api private
  2538. */
  2539. function coerce(val) {
  2540. if (val instanceof Error) return val.stack || val.message;
  2541. return val;
  2542. }
  2543. },{}],10:[function(_dereq_,module,exports){
  2544. 'use strict';
  2545. var isObj = _dereq_('is-obj');
  2546. var hasOwnProperty = Object.prototype.hasOwnProperty;
  2547. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  2548. function toObject(val) {
  2549. if (val === null || val === undefined) {
  2550. throw new TypeError('Sources cannot be null or undefined');
  2551. }
  2552. return Object(val);
  2553. }
  2554. function assignKey(to, from, key) {
  2555. var val = from[key];
  2556. if (val === undefined || val === null) {
  2557. return;
  2558. }
  2559. if (hasOwnProperty.call(to, key)) {
  2560. if (to[key] === undefined || to[key] === null) {
  2561. throw new TypeError('Cannot convert undefined or null to object (' + key + ')');
  2562. }
  2563. }
  2564. if (!hasOwnProperty.call(to, key) || !isObj(val)) {
  2565. to[key] = val;
  2566. } else {
  2567. to[key] = assign(Object(to[key]), from[key]);
  2568. }
  2569. }
  2570. function assign(to, from) {
  2571. if (to === from) {
  2572. return to;
  2573. }
  2574. from = Object(from);
  2575. for (var key in from) {
  2576. if (hasOwnProperty.call(from, key)) {
  2577. assignKey(to, from, key);
  2578. }
  2579. }
  2580. if (Object.getOwnPropertySymbols) {
  2581. var symbols = Object.getOwnPropertySymbols(from);
  2582. for (var i = 0; i < symbols.length; i++) {
  2583. if (propIsEnumerable.call(from, symbols[i])) {
  2584. assignKey(to, from, symbols[i]);
  2585. }
  2586. }
  2587. }
  2588. return to;
  2589. }
  2590. module.exports = function deepAssign(target) {
  2591. target = toObject(target);
  2592. for (var s = 1; s < arguments.length; s++) {
  2593. assign(target, arguments[s]);
  2594. }
  2595. return target;
  2596. };
  2597. },{"is-obj":21}],11:[function(_dereq_,module,exports){
  2598. /*! (C) WebReflection Mit Style License */
  2599. (function(t,n,r,i){"use strict";function st(e,t){for(var n=0,r=e.length;n<r;n++)gt(e[n],t)}function ot(e){for(var t=0,n=e.length,r;t<n;t++)r=e[t],it(r,w[at(r)])}function ut(e){return function(t){F(t)&&(gt(t,e),st(t.querySelectorAll(E),e))}}function at(e){var t=R.call(e,"is"),n=e.nodeName.toUpperCase(),r=x.call(b,t?m+t.toUpperCase():v+n);return t&&-1<r&&!ft(n,t)?-1:r}function ft(e,t){return-1<E.indexOf(e+'[is="'+t+'"]')}function lt(e){var t=e.currentTarget,n=e.attrChange,r=e.attrName,i=e.target;Y&&(!i||i===t)&&t.attributeChangedCallback&&r!=="style"&&e.prevValue!==e.newValue&&t.attributeChangedCallback(r,n===e[f]?null:e.prevValue,n===e[c]?null:e.newValue)}function ct(e){var t=ut(e);return function(e){$.push(t,e.target)}}function ht(e){G&&(G=!1,e.currentTarget.removeEventListener(p,ht)),st((e.target||n).querySelectorAll(E),e.detail===u?u:o),j&&vt()}function pt(e,t){var n=this;U.call(n,e,t),Z.call(n,{target:n})}function dt(e,t){P(e,t),nt?nt.observe(e,X):(Q&&(e.setAttribute=pt,e[s]=tt(e),e.addEventListener(d,Z)),e.addEventListener(h,lt)),e.createdCallback&&Y&&(e.created=!0,e.createdCallback(),e.created=!1)}function vt(){for(var e,t=0,n=I.length;t<n;t++)e=I[t],S.contains(e)||(n--,I.splice(t--,1),gt(e,u))}function mt(e){throw new Error("A "+e+" type is already registered")}function gt(e,t){var n,r=at(e);-1<r&&(rt(e,w[r]),r=0,t===o&&!e[o]?(e[u]=!1,e[o]=!0,r=1,j&&x.call(I,e)<0&&I.push(e)):t===u&&!e[u]&&(e[o]=!1,e[u]=!0,r=1),r&&(n=e[t+"Callback"])&&n.call(e))}if(i in n)return;var s="__"+i+(Math.random()*1e5>>0),o="attached",u="detached",a="extends",f="ADDITION",l="MODIFICATION",c="REMOVAL",h="DOMAttrModified",p="DOMContentLoaded",d="DOMSubtreeModified",v="<",m="=",g=/^[A-Z][A-Z0-9]*(?:-[A-Z0-9]+)+$/,y=["ANNOTATION-XML","COLOR-PROFILE","FONT-FACE","FONT-FACE-SRC","FONT-FACE-URI","FONT-FACE-FORMAT","FONT-FACE-NAME","MISSING-GLYPH"],b=[],w=[],E="",S=n.documentElement,x=b.indexOf||function(e){for(var t=this.length;t--&&this[t]!==e;);return t},T=r.prototype,N=T.hasOwnProperty,C=T.isPrototypeOf,k=r.defineProperty,L=r.getOwnPropertyDescriptor,A=r.getOwnPropertyNames,O=r.getPrototypeOf,M=r.setPrototypeOf,_=!!r.__proto__,D=r.create||function yt(e){return e?(yt.prototype=e,new yt):this},P=M||(_?function(e,t){return e.__proto__=t,e}:A&&L?function(){function e(e,t){for(var n,r=A(t),i=0,s=r.length;i<s;i++)n=r[i],N.call(e,n)||k(e,n,L(t,n))}return function(t,n){do e(t,n);while((n=O(n))&&!C.call(n,t));return t}}():function(e,t){for(var n in t)e[n]=t[n];return e}),H=t.MutationObserver||t.WebKitMutationObserver,B=(t.HTMLElement||t.Element||t.Node).prototype,j=!C.call(B,S),F=j?function(e){return e.nodeType===1}:function(e){return C.call(B,e)},I=j&&[],q=B.cloneNode,R=B.getAttribute,U=B.setAttribute,z=B.removeAttribute,W=n.createElement,X=H&&{attributes:!0,characterData:!0,attributeOldValue:!0},V=H||function(e){Q=!1,S.removeEventListener(h,V)},$,J=t.requestAnimationFrame||t.webkitRequestAnimationFrame||t.mozRequestAnimationFrame||t.msRequestAnimationFrame||function(e){setTimeout(e,10)},K=!1,Q=!0,G=!0,Y=!0,Z,et,tt,nt,rt,it;M||_?(rt=function(e,t){C.call(t,e)||dt(e,t)},it=dt):(rt=function(e,t){e[s]||(e[s]=r(!0),dt(e,t))},it=rt),j?(Q=!1,function(){var t=L(B,"addEventListener"),n=t.value,r=function(e){var t=new CustomEvent(h,{bubbles:!0});t.attrName=e,t.prevValue=R.call(this,e),t.newValue=null,t[c]=t.attrChange=2,z.call(this,e),this.dispatchEvent(t)},i=function(t,n){var r=this.hasAttribute(t),i=r&&R.call(this,t);e=new CustomEvent(h,{bubbles:!0}),U.call(this,t,n),e.attrName=t,e.prevValue=r?i:null,e.newValue=n,r?e[l]=e.attrChange=1:e[f]=e.attrChange=0,this.dispatchEvent(e)},o=function(e){var t=e.currentTarget,n=t[s],r=e.propertyName,i;n.hasOwnProperty(r)&&(n=n[r],i=new CustomEvent(h,{bubbles:!0}),i.attrName=n.name,i.prevValue=n.value||null,i.newValue=n.value=t[r]||null,i.prevValue==null?i[f]=i.attrChange=0:i[l]=i.attrChange=1,t.dispatchEvent(i))};t.value=function(e,t,u){e===h&&this.attributeChangedCallback&&this.setAttribute!==i&&(this[s]={className:{name:"class",value:this.className}},this.setAttribute=i,this.removeAttribute=r,n.call(this,"propertychange",o)),n.call(this,e,t,u)},k(B,"addEventListener",t)}()):H||(S.addEventListener(h,V),S.setAttribute(s,1),S.removeAttribute(s),Q&&(Z=function(e){var t=this,n,r,i;if(t===e.target){n=t[s],t[s]=r=tt(t);for(i in r){if(!(i in n))return et(0,t,i,n[i],r[i],f);if(r[i]!==n[i])return et(1,t,i,n[i],r[i],l)}for(i in n)if(!(i in r))return et(2,t,i,n[i],r[i],c)}},et=function(e,t,n,r,i,s){var o={attrChange:e,currentTarget:t,attrName:n,prevValue:r,newValue:i};o[s]=e,lt(o)},tt=function(e){for(var t,n,r={},i=e.attributes,s=0,o=i.length;s<o;s++)t=i[s],n=t.name,n!=="setAttribute"&&(r[n]=t.value);return r})),n[i]=function(t,r){c=t.toUpperCase(),K||(K=!0,H?(nt=function(e,t){function n(e,t){for(var n=0,r=e.length;n<r;t(e[n++]));}return new H(function(r){for(var i,s,o,u=0,a=r.length;u<a;u++)i=r[u],i.type==="childList"?(n(i.addedNodes,e),n(i.removedNodes,t)):(s=i.target,Y&&s.attributeChangedCallback&&i.attributeName!=="style"&&(o=R.call(s,i.attributeName),o!==i.oldValue&&s.attributeChangedCallback(i.attributeName,i.oldValue,o)))})}(ut(o),ut(u)),nt.observe(n,{childList:!0,subtree:!0})):($=[],J(function d(){while($.length)$.shift().call(null,$.shift());J(d)}),n.addEventListener("DOMNodeInserted",ct(o)),n.addEventListener("DOMNodeRemoved",ct(u))),n.addEventListener(p,ht),n.addEventListener("readystatechange",ht),n.createElement=function(e,t){var r=W.apply(n,arguments),i=""+e,s=x.call(b,(t?m:v)+(t||i).toUpperCase()),o=-1<s;return t&&(r.setAttribute("is",t=t.toLowerCase()),o&&(o=ft(i.toUpperCase(),t))),Y=!n.createElement.innerHTMLHelper,o&&it(r,w[s]),r},B.cloneNode=function(e){var t=q.call(this,!!e),n=at(t);return-1<n&&it(t,w[n]),e&&ot(t.querySelectorAll(E)),t}),-2<x.call(b,m+c)+x.call(b,v+c)&&mt(t);if(!g.test(c)||-1<x.call(y,c))throw new Error("The type "+t+" is invalid");var i=function(){return f?n.createElement(l,c):n.createElement(l)},s=r||T,f=N.call(s,a),l=f?r[a].toUpperCase():c,c,h;return f&&-1<x.call(b,v+l)&&mt(l),h=b.push((f?m:v)+c)-1,E=E.concat(E.length?",":"",f?l+'[is="'+t.toLowerCase()+'"]':l),i.prototype=w[h]=N.call(s,"prototype")?s.prototype:D(B),st(n.querySelectorAll(E),o),i}})(window,document,Object,"registerElement");
  2600. },{}],12:[function(_dereq_,module,exports){
  2601. module.exports = function(dtype) {
  2602. switch (dtype) {
  2603. case 'int8':
  2604. return Int8Array
  2605. case 'int16':
  2606. return Int16Array
  2607. case 'int32':
  2608. return Int32Array
  2609. case 'uint8':
  2610. return Uint8Array
  2611. case 'uint16':
  2612. return Uint16Array
  2613. case 'uint32':
  2614. return Uint32Array
  2615. case 'float32':
  2616. return Float32Array
  2617. case 'float64':
  2618. return Float64Array
  2619. case 'array':
  2620. return Array
  2621. case 'uint8_clamped':
  2622. return Uint8ClampedArray
  2623. }
  2624. }
  2625. },{}],13:[function(_dereq_,module,exports){
  2626. /*eslint new-cap:0*/
  2627. var dtype = _dereq_('dtype')
  2628. module.exports = flattenVertexData
  2629. function flattenVertexData (data, output, offset) {
  2630. if (!data) throw new TypeError('must specify data as first parameter')
  2631. offset = +(offset || 0) | 0
  2632. if (Array.isArray(data) && Array.isArray(data[0])) {
  2633. var dim = data[0].length
  2634. var length = data.length * dim
  2635. // no output specified, create a new typed array
  2636. if (!output || typeof output === 'string') {
  2637. output = new (dtype(output || 'float32'))(length + offset)
  2638. }
  2639. var dstLength = output.length - offset
  2640. if (length !== dstLength) {
  2641. throw new Error('source length ' + length + ' (' + dim + 'x' + data.length + ')' +
  2642. ' does not match destination length ' + dstLength)
  2643. }
  2644. for (var i = 0, k = offset; i < data.length; i++) {
  2645. for (var j = 0; j < dim; j++) {
  2646. output[k++] = data[i][j]
  2647. }
  2648. }
  2649. } else {
  2650. if (!output || typeof output === 'string') {
  2651. // no output, create a new one
  2652. var Ctor = dtype(output || 'float32')
  2653. if (offset === 0) {
  2654. output = new Ctor(data)
  2655. } else {
  2656. output = new Ctor(data.length + offset)
  2657. output.set(data, offset)
  2658. }
  2659. } else {
  2660. // store output in existing array
  2661. output.set(data, offset)
  2662. }
  2663. }
  2664. return output
  2665. }
  2666. },{"dtype":12}],14:[function(_dereq_,module,exports){
  2667. var isFunction = _dereq_('is-function')
  2668. module.exports = forEach
  2669. var toString = Object.prototype.toString
  2670. var hasOwnProperty = Object.prototype.hasOwnProperty
  2671. function forEach(list, iterator, context) {
  2672. if (!isFunction(iterator)) {
  2673. throw new TypeError('iterator must be a function')
  2674. }
  2675. if (arguments.length < 3) {
  2676. context = this
  2677. }
  2678. if (toString.call(list) === '[object Array]')
  2679. forEachArray(list, iterator, context)
  2680. else if (typeof list === 'string')
  2681. forEachString(list, iterator, context)
  2682. else
  2683. forEachObject(list, iterator, context)
  2684. }
  2685. function forEachArray(array, iterator, context) {
  2686. for (var i = 0, len = array.length; i < len; i++) {
  2687. if (hasOwnProperty.call(array, i)) {
  2688. iterator.call(context, array[i], i, array)
  2689. }
  2690. }
  2691. }
  2692. function forEachString(string, iterator, context) {
  2693. for (var i = 0, len = string.length; i < len; i++) {
  2694. // no such thing as a sparse string.
  2695. iterator.call(context, string.charAt(i), i, string)
  2696. }
  2697. }
  2698. function forEachObject(object, iterator, context) {
  2699. for (var k in object) {
  2700. if (hasOwnProperty.call(object, k)) {
  2701. iterator.call(context, object[k], k, object)
  2702. }
  2703. }
  2704. }
  2705. },{"is-function":20}],15:[function(_dereq_,module,exports){
  2706. (function (global){
  2707. if (typeof window !== "undefined") {
  2708. module.exports = window;
  2709. } else if (typeof global !== "undefined") {
  2710. module.exports = global;
  2711. } else if (typeof self !== "undefined"){
  2712. module.exports = self;
  2713. } else {
  2714. module.exports = {};
  2715. }
  2716. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2717. },{}],16:[function(_dereq_,module,exports){
  2718. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  2719. var e, m
  2720. var eLen = nBytes * 8 - mLen - 1
  2721. var eMax = (1 << eLen) - 1
  2722. var eBias = eMax >> 1
  2723. var nBits = -7
  2724. var i = isLE ? (nBytes - 1) : 0
  2725. var d = isLE ? -1 : 1
  2726. var s = buffer[offset + i]
  2727. i += d
  2728. e = s & ((1 << (-nBits)) - 1)
  2729. s >>= (-nBits)
  2730. nBits += eLen
  2731. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  2732. m = e & ((1 << (-nBits)) - 1)
  2733. e >>= (-nBits)
  2734. nBits += mLen
  2735. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  2736. if (e === 0) {
  2737. e = 1 - eBias
  2738. } else if (e === eMax) {
  2739. return m ? NaN : ((s ? -1 : 1) * Infinity)
  2740. } else {
  2741. m = m + Math.pow(2, mLen)
  2742. e = e - eBias
  2743. }
  2744. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  2745. }
  2746. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  2747. var e, m, c
  2748. var eLen = nBytes * 8 - mLen - 1
  2749. var eMax = (1 << eLen) - 1
  2750. var eBias = eMax >> 1
  2751. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  2752. var i = isLE ? 0 : (nBytes - 1)
  2753. var d = isLE ? 1 : -1
  2754. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  2755. value = Math.abs(value)
  2756. if (isNaN(value) || value === Infinity) {
  2757. m = isNaN(value) ? 1 : 0
  2758. e = eMax
  2759. } else {
  2760. e = Math.floor(Math.log(value) / Math.LN2)
  2761. if (value * (c = Math.pow(2, -e)) < 1) {
  2762. e--
  2763. c *= 2
  2764. }
  2765. if (e + eBias >= 1) {
  2766. value += rt / c
  2767. } else {
  2768. value += rt * Math.pow(2, 1 - eBias)
  2769. }
  2770. if (value * c >= 2) {
  2771. e++
  2772. c /= 2
  2773. }
  2774. if (e + eBias >= eMax) {
  2775. m = 0
  2776. e = eMax
  2777. } else if (e + eBias >= 1) {
  2778. m = (value * c - 1) * Math.pow(2, mLen)
  2779. e = e + eBias
  2780. } else {
  2781. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  2782. e = 0
  2783. }
  2784. }
  2785. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  2786. e = (e << mLen) | m
  2787. eLen += mLen
  2788. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  2789. buffer[offset + i - d] |= s * 128
  2790. }
  2791. },{}],17:[function(_dereq_,module,exports){
  2792. module.exports = function compile(property) {
  2793. if (!property || typeof property !== 'string')
  2794. throw new Error('must specify property for indexof search')
  2795. return new Function('array', 'value', 'start', [
  2796. 'start = start || 0',
  2797. 'for (var i=start; i<array.length; i++)',
  2798. ' if (array[i]["' + property +'"] === value)',
  2799. ' return i',
  2800. 'return -1'
  2801. ].join('\n'))
  2802. }
  2803. },{}],18:[function(_dereq_,module,exports){
  2804. if (typeof Object.create === 'function') {
  2805. // implementation from standard node.js 'util' module
  2806. module.exports = function inherits(ctor, superCtor) {
  2807. ctor.super_ = superCtor
  2808. ctor.prototype = Object.create(superCtor.prototype, {
  2809. constructor: {
  2810. value: ctor,
  2811. enumerable: false,
  2812. writable: true,
  2813. configurable: true
  2814. }
  2815. });
  2816. };
  2817. } else {
  2818. // old school shim for old browsers
  2819. module.exports = function inherits(ctor, superCtor) {
  2820. ctor.super_ = superCtor
  2821. var TempCtor = function () {}
  2822. TempCtor.prototype = superCtor.prototype
  2823. ctor.prototype = new TempCtor()
  2824. ctor.prototype.constructor = ctor
  2825. }
  2826. }
  2827. },{}],19:[function(_dereq_,module,exports){
  2828. /*!
  2829. * Determine if an object is a Buffer
  2830. *
  2831. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  2832. * @license MIT
  2833. */
  2834. // The _isBuffer check is for Safari 5-7 support, because it's missing
  2835. // Object.prototype.constructor. Remove this eventually
  2836. module.exports = function (obj) {
  2837. return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
  2838. }
  2839. function isBuffer (obj) {
  2840. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  2841. }
  2842. // For Node v0.10 support. Remove this eventually.
  2843. function isSlowBuffer (obj) {
  2844. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
  2845. }
  2846. },{}],20:[function(_dereq_,module,exports){
  2847. module.exports = isFunction
  2848. var toString = Object.prototype.toString
  2849. function isFunction (fn) {
  2850. var string = toString.call(fn)
  2851. return string === '[object Function]' ||
  2852. (typeof fn === 'function' && string !== '[object RegExp]') ||
  2853. (typeof window !== 'undefined' &&
  2854. // IE8 and below
  2855. (fn === window.setTimeout ||
  2856. fn === window.alert ||
  2857. fn === window.confirm ||
  2858. fn === window.prompt))
  2859. };
  2860. },{}],21:[function(_dereq_,module,exports){
  2861. 'use strict';
  2862. module.exports = function (x) {
  2863. var type = typeof x;
  2864. return x !== null && (type === 'object' || type === 'function');
  2865. };
  2866. },{}],22:[function(_dereq_,module,exports){
  2867. var toString = {}.toString;
  2868. module.exports = Array.isArray || function (arr) {
  2869. return toString.call(arr) == '[object Array]';
  2870. };
  2871. },{}],23:[function(_dereq_,module,exports){
  2872. var wordWrap = _dereq_('word-wrapper')
  2873. var xtend = _dereq_('xtend')
  2874. var findChar = _dereq_('indexof-property')('id')
  2875. var number = _dereq_('as-number')
  2876. var X_HEIGHTS = ['x', 'e', 'a', 'o', 'n', 's', 'r', 'c', 'u', 'm', 'v', 'w', 'z']
  2877. var M_WIDTHS = ['m', 'w']
  2878. var CAP_HEIGHTS = ['H', 'I', 'N', 'E', 'F', 'K', 'L', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  2879. var TAB_ID = '\t'.charCodeAt(0)
  2880. var SPACE_ID = ' '.charCodeAt(0)
  2881. var ALIGN_LEFT = 0,
  2882. ALIGN_CENTER = 1,
  2883. ALIGN_RIGHT = 2
  2884. module.exports = function createLayout(opt) {
  2885. return new TextLayout(opt)
  2886. }
  2887. function TextLayout(opt) {
  2888. this.glyphs = []
  2889. this._measure = this.computeMetrics.bind(this)
  2890. this.update(opt)
  2891. }
  2892. TextLayout.prototype.update = function(opt) {
  2893. opt = xtend({
  2894. measure: this._measure
  2895. }, opt)
  2896. this._opt = opt
  2897. this._opt.tabSize = number(this._opt.tabSize, 4)
  2898. if (!opt.font)
  2899. throw new Error('must provide a valid bitmap font')
  2900. var glyphs = this.glyphs
  2901. var text = opt.text||''
  2902. var font = opt.font
  2903. this._setupSpaceGlyphs(font)
  2904. var lines = wordWrap.lines(text, opt)
  2905. var minWidth = opt.width || 0
  2906. //clear glyphs
  2907. glyphs.length = 0
  2908. //get max line width
  2909. var maxLineWidth = lines.reduce(function(prev, line) {
  2910. return Math.max(prev, line.width, minWidth)
  2911. }, 0)
  2912. //the pen position
  2913. var x = 0
  2914. var y = 0
  2915. var lineHeight = number(opt.lineHeight, font.common.lineHeight)
  2916. var baseline = font.common.base
  2917. var descender = lineHeight-baseline
  2918. var letterSpacing = opt.letterSpacing || 0
  2919. var height = lineHeight * lines.length - descender
  2920. var align = getAlignType(this._opt.align)
  2921. //draw text along baseline
  2922. y -= height
  2923. //the metrics for this text layout
  2924. this._width = maxLineWidth
  2925. this._height = height
  2926. this._descender = lineHeight - baseline
  2927. this._baseline = baseline
  2928. this._xHeight = getXHeight(font)
  2929. this._capHeight = getCapHeight(font)
  2930. this._lineHeight = lineHeight
  2931. this._ascender = lineHeight - descender - this._xHeight
  2932. //layout each glyph
  2933. var self = this
  2934. lines.forEach(function(line, lineIndex) {
  2935. var start = line.start
  2936. var end = line.end
  2937. var lineWidth = line.width
  2938. var lastGlyph
  2939. //for each glyph in that line...
  2940. for (var i=start; i<end; i++) {
  2941. var id = text.charCodeAt(i)
  2942. var glyph = self.getGlyph(font, id)
  2943. if (glyph) {
  2944. if (lastGlyph)
  2945. x += getKerning(font, lastGlyph.id, glyph.id)
  2946. var tx = x
  2947. if (align === ALIGN_CENTER)
  2948. tx += (maxLineWidth-lineWidth)/2
  2949. else if (align === ALIGN_RIGHT)
  2950. tx += (maxLineWidth-lineWidth)
  2951. glyphs.push({
  2952. position: [tx, y],
  2953. data: glyph,
  2954. index: i,
  2955. line: lineIndex
  2956. })
  2957. //move pen forward
  2958. x += glyph.xadvance + letterSpacing
  2959. lastGlyph = glyph
  2960. }
  2961. }
  2962. //next line down
  2963. y += lineHeight
  2964. x = 0
  2965. })
  2966. this._linesTotal = lines.length;
  2967. }
  2968. TextLayout.prototype._setupSpaceGlyphs = function(font) {
  2969. //These are fallbacks, when the font doesn't include
  2970. //' ' or '\t' glyphs
  2971. this._fallbackSpaceGlyph = null
  2972. this._fallbackTabGlyph = null
  2973. if (!font.chars || font.chars.length === 0)
  2974. return
  2975. //try to get space glyph
  2976. //then fall back to the 'm' or 'w' glyphs
  2977. //then fall back to the first glyph available
  2978. var space = getGlyphById(font, SPACE_ID)
  2979. || getMGlyph(font)
  2980. || font.chars[0]
  2981. //and create a fallback for tab
  2982. var tabWidth = this._opt.tabSize * space.xadvance
  2983. this._fallbackSpaceGlyph = space
  2984. this._fallbackTabGlyph = xtend(space, {
  2985. x: 0, y: 0, xadvance: tabWidth, id: TAB_ID,
  2986. xoffset: 0, yoffset: 0, width: 0, height: 0
  2987. })
  2988. }
  2989. TextLayout.prototype.getGlyph = function(font, id) {
  2990. var glyph = getGlyphById(font, id)
  2991. if (glyph)
  2992. return glyph
  2993. else if (id === TAB_ID)
  2994. return this._fallbackTabGlyph
  2995. else if (id === SPACE_ID)
  2996. return this._fallbackSpaceGlyph
  2997. return null
  2998. }
  2999. TextLayout.prototype.computeMetrics = function(text, start, end, width) {
  3000. var letterSpacing = this._opt.letterSpacing || 0
  3001. var font = this._opt.font
  3002. var curPen = 0
  3003. var curWidth = 0
  3004. var count = 0
  3005. var glyph
  3006. var lastGlyph
  3007. if (!font.chars || font.chars.length === 0) {
  3008. return {
  3009. start: start,
  3010. end: start,
  3011. width: 0
  3012. }
  3013. }
  3014. end = Math.min(text.length, end)
  3015. for (var i=start; i < end; i++) {
  3016. var id = text.charCodeAt(i)
  3017. var glyph = this.getGlyph(font, id)
  3018. if (glyph) {
  3019. //move pen forward
  3020. var xoff = glyph.xoffset
  3021. var kern = lastGlyph ? getKerning(font, lastGlyph.id, glyph.id) : 0
  3022. curPen += kern
  3023. var nextPen = curPen + glyph.xadvance + letterSpacing
  3024. var nextWidth = curPen + glyph.width
  3025. //we've hit our limit; we can't move onto the next glyph
  3026. if (nextWidth >= width || nextPen >= width)
  3027. break
  3028. //otherwise continue along our line
  3029. curPen = nextPen
  3030. curWidth = nextWidth
  3031. lastGlyph = glyph
  3032. }
  3033. count++
  3034. }
  3035. //make sure rightmost edge lines up with rendered glyphs
  3036. if (lastGlyph)
  3037. curWidth += lastGlyph.xoffset
  3038. return {
  3039. start: start,
  3040. end: start + count,
  3041. width: curWidth
  3042. }
  3043. }
  3044. //getters for the private vars
  3045. ;['width', 'height',
  3046. 'descender', 'ascender',
  3047. 'xHeight', 'baseline',
  3048. 'capHeight',
  3049. 'lineHeight' ].forEach(addGetter)
  3050. function addGetter(name) {
  3051. Object.defineProperty(TextLayout.prototype, name, {
  3052. get: wrapper(name),
  3053. configurable: true
  3054. })
  3055. }
  3056. //create lookups for private vars
  3057. function wrapper(name) {
  3058. return (new Function([
  3059. 'return function '+name+'() {',
  3060. ' return this._'+name,
  3061. '}'
  3062. ].join('\n')))()
  3063. }
  3064. function getGlyphById(font, id) {
  3065. if (!font.chars || font.chars.length === 0)
  3066. return null
  3067. var glyphIdx = findChar(font.chars, id)
  3068. if (glyphIdx >= 0)
  3069. return font.chars[glyphIdx]
  3070. return null
  3071. }
  3072. function getXHeight(font) {
  3073. for (var i=0; i<X_HEIGHTS.length; i++) {
  3074. var id = X_HEIGHTS[i].charCodeAt(0)
  3075. var idx = findChar(font.chars, id)
  3076. if (idx >= 0)
  3077. return font.chars[idx].height
  3078. }
  3079. return 0
  3080. }
  3081. function getMGlyph(font) {
  3082. for (var i=0; i<M_WIDTHS.length; i++) {
  3083. var id = M_WIDTHS[i].charCodeAt(0)
  3084. var idx = findChar(font.chars, id)
  3085. if (idx >= 0)
  3086. return font.chars[idx]
  3087. }
  3088. return 0
  3089. }
  3090. function getCapHeight(font) {
  3091. for (var i=0; i<CAP_HEIGHTS.length; i++) {
  3092. var id = CAP_HEIGHTS[i].charCodeAt(0)
  3093. var idx = findChar(font.chars, id)
  3094. if (idx >= 0)
  3095. return font.chars[idx].height
  3096. }
  3097. return 0
  3098. }
  3099. function getKerning(font, left, right) {
  3100. if (!font.kernings || font.kernings.length === 0)
  3101. return 0
  3102. var table = font.kernings
  3103. for (var i=0; i<table.length; i++) {
  3104. var kern = table[i]
  3105. if (kern.first === left && kern.second === right)
  3106. return kern.amount
  3107. }
  3108. return 0
  3109. }
  3110. function getAlignType(align) {
  3111. if (align === 'center')
  3112. return ALIGN_CENTER
  3113. else if (align === 'right')
  3114. return ALIGN_RIGHT
  3115. return ALIGN_LEFT
  3116. }
  3117. },{"as-number":3,"indexof-property":17,"word-wrapper":73,"xtend":76}],24:[function(_dereq_,module,exports){
  3118. (function (Buffer){
  3119. var xhr = _dereq_('xhr')
  3120. var noop = function(){}
  3121. var parseASCII = _dereq_('parse-bmfont-ascii')
  3122. var parseXML = _dereq_('parse-bmfont-xml')
  3123. var readBinary = _dereq_('parse-bmfont-binary')
  3124. var isBinaryFormat = _dereq_('./lib/is-binary')
  3125. var xtend = _dereq_('xtend')
  3126. var xml2 = (function hasXML2() {
  3127. return window.XMLHttpRequest && "withCredentials" in new XMLHttpRequest
  3128. })()
  3129. module.exports = function(opt, cb) {
  3130. cb = typeof cb === 'function' ? cb : noop
  3131. if (typeof opt === 'string')
  3132. opt = { uri: opt }
  3133. else if (!opt)
  3134. opt = {}
  3135. var expectBinary = opt.binary
  3136. if (expectBinary)
  3137. opt = getBinaryOpts(opt)
  3138. xhr(opt, function(err, res, body) {
  3139. if (err)
  3140. return cb(err)
  3141. if (!/^2/.test(res.statusCode))
  3142. return cb(new Error('http status code: '+res.statusCode))
  3143. if (!body)
  3144. return cb(new Error('no body result'))
  3145. var binary = false
  3146. //if the response type is an array buffer,
  3147. //we need to convert it into a regular Buffer object
  3148. if (isArrayBuffer(body)) {
  3149. var array = new Uint8Array(body)
  3150. body = new Buffer(array, 'binary')
  3151. }
  3152. //now check the string/Buffer response
  3153. //and see if it has a binary BMF header
  3154. if (isBinaryFormat(body)) {
  3155. binary = true
  3156. //if we have a string, turn it into a Buffer
  3157. if (typeof body === 'string')
  3158. body = new Buffer(body, 'binary')
  3159. }
  3160. //we are not parsing a binary format, just ASCII/XML/etc
  3161. if (!binary) {
  3162. //might still be a buffer if responseType is 'arraybuffer'
  3163. if (Buffer.isBuffer(body))
  3164. body = body.toString(opt.encoding)
  3165. body = body.trim()
  3166. }
  3167. var result
  3168. try {
  3169. var type = res.headers['content-type']
  3170. if (binary)
  3171. result = readBinary(body)
  3172. else if (/json/.test(type) || body.charAt(0) === '{')
  3173. result = JSON.parse(body)
  3174. else if (/xml/.test(type) || body.charAt(0) === '<')
  3175. result = parseXML(body)
  3176. else
  3177. result = parseASCII(body)
  3178. } catch (e) {
  3179. cb(new Error('error parsing font '+e.message))
  3180. cb = noop
  3181. }
  3182. cb(null, result)
  3183. })
  3184. }
  3185. function isArrayBuffer(arr) {
  3186. var str = Object.prototype.toString
  3187. return str.call(arr) === '[object ArrayBuffer]'
  3188. }
  3189. function getBinaryOpts(opt) {
  3190. //IE10+ and other modern browsers support array buffers
  3191. if (xml2)
  3192. return xtend(opt, { responseType: 'arraybuffer' })
  3193. if (typeof window.XMLHttpRequest === 'undefined')
  3194. throw new Error('your browser does not support XHR loading')
  3195. //IE9 and XML1 browsers could still use an override
  3196. var req = new window.XMLHttpRequest()
  3197. req.overrideMimeType('text/plain; charset=x-user-defined')
  3198. return xtend({
  3199. xhr: req
  3200. }, opt)
  3201. }
  3202. }).call(this,_dereq_("buffer").Buffer)
  3203. },{"./lib/is-binary":25,"buffer":7,"parse-bmfont-ascii":27,"parse-bmfont-binary":28,"parse-bmfont-xml":29,"xhr":74,"xtend":76}],25:[function(_dereq_,module,exports){
  3204. (function (Buffer){
  3205. var equal = _dereq_('buffer-equal')
  3206. var HEADER = new Buffer([66, 77, 70, 3])
  3207. module.exports = function(buf) {
  3208. if (typeof buf === 'string')
  3209. return buf.substring(0, 3) === 'BMF'
  3210. return buf.length > 4 && equal(buf.slice(0, 4), HEADER)
  3211. }
  3212. }).call(this,_dereq_("buffer").Buffer)
  3213. },{"buffer":7,"buffer-equal":6}],26:[function(_dereq_,module,exports){
  3214. 'use strict';
  3215. /* eslint-disable no-unused-vars */
  3216. var hasOwnProperty = Object.prototype.hasOwnProperty;
  3217. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  3218. function toObject(val) {
  3219. if (val === null || val === undefined) {
  3220. throw new TypeError('Object.assign cannot be called with null or undefined');
  3221. }
  3222. return Object(val);
  3223. }
  3224. function shouldUseNative() {
  3225. try {
  3226. if (!Object.assign) {
  3227. return false;
  3228. }
  3229. // Detect buggy property enumeration order in older V8 versions.
  3230. // https://bugs.chromium.org/p/v8/issues/detail?id=4118
  3231. var test1 = new String('abc'); // eslint-disable-line
  3232. test1[5] = 'de';
  3233. if (Object.getOwnPropertyNames(test1)[0] === '5') {
  3234. return false;
  3235. }
  3236. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  3237. var test2 = {};
  3238. for (var i = 0; i < 10; i++) {
  3239. test2['_' + String.fromCharCode(i)] = i;
  3240. }
  3241. var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
  3242. return test2[n];
  3243. });
  3244. if (order2.join('') !== '0123456789') {
  3245. return false;
  3246. }
  3247. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  3248. var test3 = {};
  3249. 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
  3250. test3[letter] = letter;
  3251. });
  3252. if (Object.keys(Object.assign({}, test3)).join('') !==
  3253. 'abcdefghijklmnopqrst') {
  3254. return false;
  3255. }
  3256. return true;
  3257. } catch (e) {
  3258. // We don't expect any of the above to throw, but better to be safe.
  3259. return false;
  3260. }
  3261. }
  3262. module.exports = shouldUseNative() ? Object.assign : function (target, source) {
  3263. var from;
  3264. var to = toObject(target);
  3265. var symbols;
  3266. for (var s = 1; s < arguments.length; s++) {
  3267. from = Object(arguments[s]);
  3268. for (var key in from) {
  3269. if (hasOwnProperty.call(from, key)) {
  3270. to[key] = from[key];
  3271. }
  3272. }
  3273. if (Object.getOwnPropertySymbols) {
  3274. symbols = Object.getOwnPropertySymbols(from);
  3275. for (var i = 0; i < symbols.length; i++) {
  3276. if (propIsEnumerable.call(from, symbols[i])) {
  3277. to[symbols[i]] = from[symbols[i]];
  3278. }
  3279. }
  3280. }
  3281. }
  3282. return to;
  3283. };
  3284. },{}],27:[function(_dereq_,module,exports){
  3285. module.exports = function parseBMFontAscii(data) {
  3286. if (!data)
  3287. throw new Error('no data provided')
  3288. data = data.toString().trim()
  3289. var output = {
  3290. pages: [],
  3291. chars: [],
  3292. kernings: []
  3293. }
  3294. var lines = data.split(/\r\n?|\n/g)
  3295. if (lines.length === 0)
  3296. throw new Error('no data in BMFont file')
  3297. for (var i = 0; i < lines.length; i++) {
  3298. var lineData = splitLine(lines[i], i)
  3299. if (!lineData) //skip empty lines
  3300. continue
  3301. if (lineData.key === 'page') {
  3302. if (typeof lineData.data.id !== 'number')
  3303. throw new Error('malformed file at line ' + i + ' -- needs page id=N')
  3304. if (typeof lineData.data.file !== 'string')
  3305. throw new Error('malformed file at line ' + i + ' -- needs page file="path"')
  3306. output.pages[lineData.data.id] = lineData.data.file
  3307. } else if (lineData.key === 'chars' || lineData.key === 'kernings') {
  3308. //... do nothing for these two ...
  3309. } else if (lineData.key === 'char') {
  3310. output.chars.push(lineData.data)
  3311. } else if (lineData.key === 'kerning') {
  3312. output.kernings.push(lineData.data)
  3313. } else {
  3314. output[lineData.key] = lineData.data
  3315. }
  3316. }
  3317. return output
  3318. }
  3319. function splitLine(line, idx) {
  3320. line = line.replace(/\t+/g, ' ').trim()
  3321. if (!line)
  3322. return null
  3323. var space = line.indexOf(' ')
  3324. if (space === -1)
  3325. throw new Error("no named row at line " + idx)
  3326. var key = line.substring(0, space)
  3327. line = line.substring(space + 1)
  3328. //clear "letter" field as it is non-standard and
  3329. //requires additional complexity to parse " / = symbols
  3330. line = line.replace(/letter=[\'\"]\S+[\'\"]/gi, '')
  3331. line = line.split("=")
  3332. line = line.map(function(str) {
  3333. return str.trim().match((/(".*?"|[^"\s]+)+(?=\s*|\s*$)/g))
  3334. })
  3335. var data = []
  3336. for (var i = 0; i < line.length; i++) {
  3337. var dt = line[i]
  3338. if (i === 0) {
  3339. data.push({
  3340. key: dt[0],
  3341. data: ""
  3342. })
  3343. } else if (i === line.length - 1) {
  3344. data[data.length - 1].data = parseData(dt[0])
  3345. } else {
  3346. data[data.length - 1].data = parseData(dt[0])
  3347. data.push({
  3348. key: dt[1],
  3349. data: ""
  3350. })
  3351. }
  3352. }
  3353. var out = {
  3354. key: key,
  3355. data: {}
  3356. }
  3357. data.forEach(function(v) {
  3358. out.data[v.key] = v.data;
  3359. })
  3360. return out
  3361. }
  3362. function parseData(data) {
  3363. if (!data || data.length === 0)
  3364. return ""
  3365. if (data.indexOf('"') === 0 || data.indexOf("'") === 0)
  3366. return data.substring(1, data.length - 1)
  3367. if (data.indexOf(',') !== -1)
  3368. return parseIntList(data)
  3369. return parseInt(data, 10)
  3370. }
  3371. function parseIntList(data) {
  3372. return data.split(',').map(function(val) {
  3373. return parseInt(val, 10)
  3374. })
  3375. }
  3376. },{}],28:[function(_dereq_,module,exports){
  3377. var HEADER = [66, 77, 70]
  3378. module.exports = function readBMFontBinary(buf) {
  3379. if (buf.length < 6)
  3380. throw new Error('invalid buffer length for BMFont')
  3381. var header = HEADER.every(function(byte, i) {
  3382. return buf.readUInt8(i) === byte
  3383. })
  3384. if (!header)
  3385. throw new Error('BMFont missing BMF byte header')
  3386. var i = 3
  3387. var vers = buf.readUInt8(i++)
  3388. if (vers > 3)
  3389. throw new Error('Only supports BMFont Binary v3 (BMFont App v1.10)')
  3390. var target = { kernings: [], chars: [] }
  3391. for (var b=0; b<5; b++)
  3392. i += readBlock(target, buf, i)
  3393. return target
  3394. }
  3395. function readBlock(target, buf, i) {
  3396. if (i > buf.length-1)
  3397. return 0
  3398. var blockID = buf.readUInt8(i++)
  3399. var blockSize = buf.readInt32LE(i)
  3400. i += 4
  3401. switch(blockID) {
  3402. case 1:
  3403. target.info = readInfo(buf, i)
  3404. break
  3405. case 2:
  3406. target.common = readCommon(buf, i)
  3407. break
  3408. case 3:
  3409. target.pages = readPages(buf, i, blockSize)
  3410. break
  3411. case 4:
  3412. target.chars = readChars(buf, i, blockSize)
  3413. break
  3414. case 5:
  3415. target.kernings = readKernings(buf, i, blockSize)
  3416. break
  3417. }
  3418. return 5 + blockSize
  3419. }
  3420. function readInfo(buf, i) {
  3421. var info = {}
  3422. info.size = buf.readInt16LE(i)
  3423. var bitField = buf.readUInt8(i+2)
  3424. info.smooth = (bitField >> 7) & 1
  3425. info.unicode = (bitField >> 6) & 1
  3426. info.italic = (bitField >> 5) & 1
  3427. info.bold = (bitField >> 4) & 1
  3428. //fixedHeight is only mentioned in binary spec
  3429. if ((bitField >> 3) & 1)
  3430. info.fixedHeight = 1
  3431. info.charset = buf.readUInt8(i+3) || ''
  3432. info.stretchH = buf.readUInt16LE(i+4)
  3433. info.aa = buf.readUInt8(i+6)
  3434. info.padding = [
  3435. buf.readInt8(i+7),
  3436. buf.readInt8(i+8),
  3437. buf.readInt8(i+9),
  3438. buf.readInt8(i+10)
  3439. ]
  3440. info.spacing = [
  3441. buf.readInt8(i+11),
  3442. buf.readInt8(i+12)
  3443. ]
  3444. info.outline = buf.readUInt8(i+13)
  3445. info.face = readStringNT(buf, i+14)
  3446. return info
  3447. }
  3448. function readCommon(buf, i) {
  3449. var common = {}
  3450. common.lineHeight = buf.readUInt16LE(i)
  3451. common.base = buf.readUInt16LE(i+2)
  3452. common.scaleW = buf.readUInt16LE(i+4)
  3453. common.scaleH = buf.readUInt16LE(i+6)
  3454. common.pages = buf.readUInt16LE(i+8)
  3455. var bitField = buf.readUInt8(i+10)
  3456. common.packed = 0
  3457. common.alphaChnl = buf.readUInt8(i+11)
  3458. common.redChnl = buf.readUInt8(i+12)
  3459. common.greenChnl = buf.readUInt8(i+13)
  3460. common.blueChnl = buf.readUInt8(i+14)
  3461. return common
  3462. }
  3463. function readPages(buf, i, size) {
  3464. var pages = []
  3465. var text = readNameNT(buf, i)
  3466. var len = text.length+1
  3467. var count = size / len
  3468. for (var c=0; c<count; c++) {
  3469. pages[c] = buf.slice(i, i+text.length).toString('utf8')
  3470. i += len
  3471. }
  3472. return pages
  3473. }
  3474. function readChars(buf, i, blockSize) {
  3475. var chars = []
  3476. var count = blockSize / 20
  3477. for (var c=0; c<count; c++) {
  3478. var char = {}
  3479. var off = c*20
  3480. char.id = buf.readUInt32LE(i + 0 + off)
  3481. char.x = buf.readUInt16LE(i + 4 + off)
  3482. char.y = buf.readUInt16LE(i + 6 + off)
  3483. char.width = buf.readUInt16LE(i + 8 + off)
  3484. char.height = buf.readUInt16LE(i + 10 + off)
  3485. char.xoffset = buf.readInt16LE(i + 12 + off)
  3486. char.yoffset = buf.readInt16LE(i + 14 + off)
  3487. char.xadvance = buf.readInt16LE(i + 16 + off)
  3488. char.page = buf.readUInt8(i + 18 + off)
  3489. char.chnl = buf.readUInt8(i + 19 + off)
  3490. chars[c] = char
  3491. }
  3492. return chars
  3493. }
  3494. function readKernings(buf, i, blockSize) {
  3495. var kernings = []
  3496. var count = blockSize / 10
  3497. for (var c=0; c<count; c++) {
  3498. var kern = {}
  3499. var off = c*10
  3500. kern.first = buf.readUInt32LE(i + 0 + off)
  3501. kern.second = buf.readUInt32LE(i + 4 + off)
  3502. kern.amount = buf.readInt16LE(i + 8 + off)
  3503. kernings[c] = kern
  3504. }
  3505. return kernings
  3506. }
  3507. function readNameNT(buf, offset) {
  3508. var pos=offset
  3509. for (; pos<buf.length; pos++) {
  3510. if (buf[pos] === 0x00)
  3511. break
  3512. }
  3513. return buf.slice(offset, pos)
  3514. }
  3515. function readStringNT(buf, offset) {
  3516. return readNameNT(buf, offset).toString('utf8')
  3517. }
  3518. },{}],29:[function(_dereq_,module,exports){
  3519. var parseAttributes = _dereq_('./parse-attribs')
  3520. var parseFromString = _dereq_('xml-parse-from-string')
  3521. //In some cases element.attribute.nodeName can return
  3522. //all lowercase values.. so we need to map them to the correct
  3523. //case
  3524. var NAME_MAP = {
  3525. scaleh: 'scaleH',
  3526. scalew: 'scaleW',
  3527. stretchh: 'stretchH',
  3528. lineheight: 'lineHeight',
  3529. alphachnl: 'alphaChnl',
  3530. redchnl: 'redChnl',
  3531. greenchnl: 'greenChnl',
  3532. bluechnl: 'blueChnl'
  3533. }
  3534. module.exports = function parse(data) {
  3535. data = data.toString()
  3536. var xmlRoot = parseFromString(data)
  3537. var output = {
  3538. pages: [],
  3539. chars: [],
  3540. kernings: []
  3541. }
  3542. //get config settings
  3543. ;['info', 'common'].forEach(function(key) {
  3544. var element = xmlRoot.getElementsByTagName(key)[0]
  3545. if (element)
  3546. output[key] = parseAttributes(getAttribs(element))
  3547. })
  3548. //get page info
  3549. var pageRoot = xmlRoot.getElementsByTagName('pages')[0]
  3550. if (!pageRoot)
  3551. throw new Error('malformed file -- no <pages> element')
  3552. var pages = pageRoot.getElementsByTagName('page')
  3553. for (var i=0; i<pages.length; i++) {
  3554. var p = pages[i]
  3555. var id = parseInt(p.getAttribute('id'), 10)
  3556. var file = p.getAttribute('file')
  3557. if (isNaN(id))
  3558. throw new Error('malformed file -- page "id" attribute is NaN')
  3559. if (!file)
  3560. throw new Error('malformed file -- needs page "file" attribute')
  3561. output.pages[parseInt(id, 10)] = file
  3562. }
  3563. //get kernings / chars
  3564. ;['chars', 'kernings'].forEach(function(key) {
  3565. var element = xmlRoot.getElementsByTagName(key)[0]
  3566. if (!element)
  3567. return
  3568. var childTag = key.substring(0, key.length-1)
  3569. var children = element.getElementsByTagName(childTag)
  3570. for (var i=0; i<children.length; i++) {
  3571. var child = children[i]
  3572. output[key].push(parseAttributes(getAttribs(child)))
  3573. }
  3574. })
  3575. return output
  3576. }
  3577. function getAttribs(element) {
  3578. var attribs = getAttribList(element)
  3579. return attribs.reduce(function(dict, attrib) {
  3580. var key = mapName(attrib.nodeName)
  3581. dict[key] = attrib.nodeValue
  3582. return dict
  3583. }, {})
  3584. }
  3585. function getAttribList(element) {
  3586. //IE8+ and modern browsers
  3587. var attribs = []
  3588. for (var i=0; i<element.attributes.length; i++)
  3589. attribs.push(element.attributes[i])
  3590. return attribs
  3591. }
  3592. function mapName(nodeName) {
  3593. return NAME_MAP[nodeName.toLowerCase()] || nodeName
  3594. }
  3595. },{"./parse-attribs":30,"xml-parse-from-string":75}],30:[function(_dereq_,module,exports){
  3596. //Some versions of GlyphDesigner have a typo
  3597. //that causes some bugs with parsing.
  3598. //Need to confirm with recent version of the software
  3599. //to see whether this is still an issue or not.
  3600. var GLYPH_DESIGNER_ERROR = 'chasrset'
  3601. module.exports = function parseAttributes(obj) {
  3602. if (GLYPH_DESIGNER_ERROR in obj) {
  3603. obj['charset'] = obj[GLYPH_DESIGNER_ERROR]
  3604. delete obj[GLYPH_DESIGNER_ERROR]
  3605. }
  3606. for (var k in obj) {
  3607. if (k === 'face' || k === 'charset')
  3608. continue
  3609. else if (k === 'padding' || k === 'spacing')
  3610. obj[k] = parseIntList(obj[k])
  3611. else
  3612. obj[k] = parseInt(obj[k], 10)
  3613. }
  3614. return obj
  3615. }
  3616. function parseIntList(data) {
  3617. return data.split(',').map(function(val) {
  3618. return parseInt(val, 10)
  3619. })
  3620. }
  3621. },{}],31:[function(_dereq_,module,exports){
  3622. var trim = _dereq_('trim')
  3623. , forEach = _dereq_('for-each')
  3624. , isArray = function(arg) {
  3625. return Object.prototype.toString.call(arg) === '[object Array]';
  3626. }
  3627. module.exports = function (headers) {
  3628. if (!headers)
  3629. return {}
  3630. var result = {}
  3631. forEach(
  3632. trim(headers).split('\n')
  3633. , function (row) {
  3634. var index = row.indexOf(':')
  3635. , key = trim(row.slice(0, index)).toLowerCase()
  3636. , value = trim(row.slice(index + 1))
  3637. if (typeof(result[key]) === 'undefined') {
  3638. result[key] = value
  3639. } else if (isArray(result[key])) {
  3640. result[key].push(value)
  3641. } else {
  3642. result[key] = [ result[key], value ]
  3643. }
  3644. }
  3645. )
  3646. return result
  3647. }
  3648. },{"for-each":14,"trim":47}],32:[function(_dereq_,module,exports){
  3649. (function (process){
  3650. // Copyright Joyent, Inc. and other Node contributors.
  3651. //
  3652. // Permission is hereby granted, free of charge, to any person obtaining a
  3653. // copy of this software and associated documentation files (the
  3654. // "Software"), to deal in the Software without restriction, including
  3655. // without limitation the rights to use, copy, modify, merge, publish,
  3656. // distribute, sublicense, and/or sell copies of the Software, and to permit
  3657. // persons to whom the Software is furnished to do so, subject to the
  3658. // following conditions:
  3659. //
  3660. // The above copyright notice and this permission notice shall be included
  3661. // in all copies or substantial portions of the Software.
  3662. //
  3663. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  3664. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  3665. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  3666. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  3667. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  3668. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  3669. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  3670. // resolves . and .. elements in a path array with directory names there
  3671. // must be no slashes, empty elements, or device names (c:\) in the array
  3672. // (so also no leading and trailing slashes - it does not distinguish
  3673. // relative and absolute paths)
  3674. function normalizeArray(parts, allowAboveRoot) {
  3675. // if the path tries to go above the root, `up` ends up > 0
  3676. var up = 0;
  3677. for (var i = parts.length - 1; i >= 0; i--) {
  3678. var last = parts[i];
  3679. if (last === '.') {
  3680. parts.splice(i, 1);
  3681. } else if (last === '..') {
  3682. parts.splice(i, 1);
  3683. up++;
  3684. } else if (up) {
  3685. parts.splice(i, 1);
  3686. up--;
  3687. }
  3688. }
  3689. // if the path is allowed to go above the root, restore leading ..s
  3690. if (allowAboveRoot) {
  3691. for (; up--; up) {
  3692. parts.unshift('..');
  3693. }
  3694. }
  3695. return parts;
  3696. }
  3697. // Split a filename into [root, dir, basename, ext], unix version
  3698. // 'root' is just a slash, or nothing.
  3699. var splitPathRe =
  3700. /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
  3701. var splitPath = function(filename) {
  3702. return splitPathRe.exec(filename).slice(1);
  3703. };
  3704. // path.resolve([from ...], to)
  3705. // posix version
  3706. exports.resolve = function() {
  3707. var resolvedPath = '',
  3708. resolvedAbsolute = false;
  3709. for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
  3710. var path = (i >= 0) ? arguments[i] : process.cwd();
  3711. // Skip empty and invalid entries
  3712. if (typeof path !== 'string') {
  3713. throw new TypeError('Arguments to path.resolve must be strings');
  3714. } else if (!path) {
  3715. continue;
  3716. }
  3717. resolvedPath = path + '/' + resolvedPath;
  3718. resolvedAbsolute = path.charAt(0) === '/';
  3719. }
  3720. // At this point the path should be resolved to a full absolute path, but
  3721. // handle relative paths to be safe (might happen when process.cwd() fails)
  3722. // Normalize the path
  3723. resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
  3724. return !!p;
  3725. }), !resolvedAbsolute).join('/');
  3726. return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
  3727. };
  3728. // path.normalize(path)
  3729. // posix version
  3730. exports.normalize = function(path) {
  3731. var isAbsolute = exports.isAbsolute(path),
  3732. trailingSlash = substr(path, -1) === '/';
  3733. // Normalize the path
  3734. path = normalizeArray(filter(path.split('/'), function(p) {
  3735. return !!p;
  3736. }), !isAbsolute).join('/');
  3737. if (!path && !isAbsolute) {
  3738. path = '.';
  3739. }
  3740. if (path && trailingSlash) {
  3741. path += '/';
  3742. }
  3743. return (isAbsolute ? '/' : '') + path;
  3744. };
  3745. // posix version
  3746. exports.isAbsolute = function(path) {
  3747. return path.charAt(0) === '/';
  3748. };
  3749. // posix version
  3750. exports.join = function() {
  3751. var paths = Array.prototype.slice.call(arguments, 0);
  3752. return exports.normalize(filter(paths, function(p, index) {
  3753. if (typeof p !== 'string') {
  3754. throw new TypeError('Arguments to path.join must be strings');
  3755. }
  3756. return p;
  3757. }).join('/'));
  3758. };
  3759. // path.relative(from, to)
  3760. // posix version
  3761. exports.relative = function(from, to) {
  3762. from = exports.resolve(from).substr(1);
  3763. to = exports.resolve(to).substr(1);
  3764. function trim(arr) {
  3765. var start = 0;
  3766. for (; start < arr.length; start++) {
  3767. if (arr[start] !== '') break;
  3768. }
  3769. var end = arr.length - 1;
  3770. for (; end >= 0; end--) {
  3771. if (arr[end] !== '') break;
  3772. }
  3773. if (start > end) return [];
  3774. return arr.slice(start, end - start + 1);
  3775. }
  3776. var fromParts = trim(from.split('/'));
  3777. var toParts = trim(to.split('/'));
  3778. var length = Math.min(fromParts.length, toParts.length);
  3779. var samePartsLength = length;
  3780. for (var i = 0; i < length; i++) {
  3781. if (fromParts[i] !== toParts[i]) {
  3782. samePartsLength = i;
  3783. break;
  3784. }
  3785. }
  3786. var outputParts = [];
  3787. for (var i = samePartsLength; i < fromParts.length; i++) {
  3788. outputParts.push('..');
  3789. }
  3790. outputParts = outputParts.concat(toParts.slice(samePartsLength));
  3791. return outputParts.join('/');
  3792. };
  3793. exports.sep = '/';
  3794. exports.delimiter = ':';
  3795. exports.dirname = function(path) {
  3796. var result = splitPath(path),
  3797. root = result[0],
  3798. dir = result[1];
  3799. if (!root && !dir) {
  3800. // No dirname whatsoever
  3801. return '.';
  3802. }
  3803. if (dir) {
  3804. // It has a dirname, strip trailing slash
  3805. dir = dir.substr(0, dir.length - 1);
  3806. }
  3807. return root + dir;
  3808. };
  3809. exports.basename = function(path, ext) {
  3810. var f = splitPath(path)[2];
  3811. // TODO: make this comparison case-insensitive on windows?
  3812. if (ext && f.substr(-1 * ext.length) === ext) {
  3813. f = f.substr(0, f.length - ext.length);
  3814. }
  3815. return f;
  3816. };
  3817. exports.extname = function(path) {
  3818. return splitPath(path)[3];
  3819. };
  3820. function filter (xs, f) {
  3821. if (xs.filter) return xs.filter(f);
  3822. var res = [];
  3823. for (var i = 0; i < xs.length; i++) {
  3824. if (f(xs[i], i, xs)) res.push(xs[i]);
  3825. }
  3826. return res;
  3827. }
  3828. // String.prototype.substr - negative index don't work in IE8
  3829. var substr = 'ab'.substr(-1) === 'b'
  3830. ? function (str, start, len) { return str.substr(start, len) }
  3831. : function (str, start, len) {
  3832. if (start < 0) start = str.length + start;
  3833. return str.substr(start, len);
  3834. }
  3835. ;
  3836. }).call(this,_dereq_('_process'))
  3837. },{"_process":34}],33:[function(_dereq_,module,exports){
  3838. (function (global){
  3839. var performance = global.performance || {};
  3840. var present = (function () {
  3841. var names = ['now', 'webkitNow', 'msNow', 'mozNow', 'oNow'];
  3842. while (names.length) {
  3843. var name = names.shift();
  3844. if (name in performance) {
  3845. return performance[name].bind(performance);
  3846. }
  3847. }
  3848. var dateNow = Date.now || function () { return new Date().getTime(); };
  3849. var navigationStart = (performance.timing || {}).navigationStart || dateNow();
  3850. return function () {
  3851. return dateNow() - navigationStart;
  3852. };
  3853. }());
  3854. present.performanceNow = performance.now;
  3855. present.noConflict = function () {
  3856. performance.now = present.performanceNow;
  3857. };
  3858. present.conflict = function () {
  3859. performance.now = present;
  3860. };
  3861. present.conflict();
  3862. module.exports = present;
  3863. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  3864. },{}],34:[function(_dereq_,module,exports){
  3865. // shim for using process in browser
  3866. var process = module.exports = {};
  3867. // cached from whatever global is present so that test runners that stub it
  3868. // don't break things. But we need to wrap it in a try catch in case it is
  3869. // wrapped in strict mode code which doesn't define any globals. It's inside a
  3870. // function because try/catches deoptimize in certain engines.
  3871. var cachedSetTimeout;
  3872. var cachedClearTimeout;
  3873. function defaultSetTimout() {
  3874. throw new Error('setTimeout has not been defined');
  3875. }
  3876. function defaultClearTimeout () {
  3877. throw new Error('clearTimeout has not been defined');
  3878. }
  3879. (function () {
  3880. try {
  3881. if (typeof setTimeout === 'function') {
  3882. cachedSetTimeout = setTimeout;
  3883. } else {
  3884. cachedSetTimeout = defaultSetTimout;
  3885. }
  3886. } catch (e) {
  3887. cachedSetTimeout = defaultSetTimout;
  3888. }
  3889. try {
  3890. if (typeof clearTimeout === 'function') {
  3891. cachedClearTimeout = clearTimeout;
  3892. } else {
  3893. cachedClearTimeout = defaultClearTimeout;
  3894. }
  3895. } catch (e) {
  3896. cachedClearTimeout = defaultClearTimeout;
  3897. }
  3898. } ())
  3899. function runTimeout(fun) {
  3900. if (cachedSetTimeout === setTimeout) {
  3901. //normal enviroments in sane situations
  3902. return setTimeout(fun, 0);
  3903. }
  3904. // if setTimeout wasn't available but was latter defined
  3905. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  3906. cachedSetTimeout = setTimeout;
  3907. return setTimeout(fun, 0);
  3908. }
  3909. try {
  3910. // when when somebody has screwed with setTimeout but no I.E. maddness
  3911. return cachedSetTimeout(fun, 0);
  3912. } catch(e){
  3913. try {
  3914. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  3915. return cachedSetTimeout.call(null, fun, 0);
  3916. } catch(e){
  3917. // 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
  3918. return cachedSetTimeout.call(this, fun, 0);
  3919. }
  3920. }
  3921. }
  3922. function runClearTimeout(marker) {
  3923. if (cachedClearTimeout === clearTimeout) {
  3924. //normal enviroments in sane situations
  3925. return clearTimeout(marker);
  3926. }
  3927. // if clearTimeout wasn't available but was latter defined
  3928. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  3929. cachedClearTimeout = clearTimeout;
  3930. return clearTimeout(marker);
  3931. }
  3932. try {
  3933. // when when somebody has screwed with setTimeout but no I.E. maddness
  3934. return cachedClearTimeout(marker);
  3935. } catch (e){
  3936. try {
  3937. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  3938. return cachedClearTimeout.call(null, marker);
  3939. } catch (e){
  3940. // 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.
  3941. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  3942. return cachedClearTimeout.call(this, marker);
  3943. }
  3944. }
  3945. }
  3946. var queue = [];
  3947. var draining = false;
  3948. var currentQueue;
  3949. var queueIndex = -1;
  3950. function cleanUpNextTick() {
  3951. if (!draining || !currentQueue) {
  3952. return;
  3953. }
  3954. draining = false;
  3955. if (currentQueue.length) {
  3956. queue = currentQueue.concat(queue);
  3957. } else {
  3958. queueIndex = -1;
  3959. }
  3960. if (queue.length) {
  3961. drainQueue();
  3962. }
  3963. }
  3964. function drainQueue() {
  3965. if (draining) {
  3966. return;
  3967. }
  3968. var timeout = runTimeout(cleanUpNextTick);
  3969. draining = true;
  3970. var len = queue.length;
  3971. while(len) {
  3972. currentQueue = queue;
  3973. queue = [];
  3974. while (++queueIndex < len) {
  3975. if (currentQueue) {
  3976. currentQueue[queueIndex].run();
  3977. }
  3978. }
  3979. queueIndex = -1;
  3980. len = queue.length;
  3981. }
  3982. currentQueue = null;
  3983. draining = false;
  3984. runClearTimeout(timeout);
  3985. }
  3986. process.nextTick = function (fun) {
  3987. var args = new Array(arguments.length - 1);
  3988. if (arguments.length > 1) {
  3989. for (var i = 1; i < arguments.length; i++) {
  3990. args[i - 1] = arguments[i];
  3991. }
  3992. }
  3993. queue.push(new Item(fun, args));
  3994. if (queue.length === 1 && !draining) {
  3995. runTimeout(drainQueue);
  3996. }
  3997. };
  3998. // v8 likes predictible objects
  3999. function Item(fun, array) {
  4000. this.fun = fun;
  4001. this.array = array;
  4002. }
  4003. Item.prototype.run = function () {
  4004. this.fun.apply(null, this.array);
  4005. };
  4006. process.title = 'browser';
  4007. process.browser = true;
  4008. process.env = {};
  4009. process.argv = [];
  4010. process.version = ''; // empty string to avoid regexp issues
  4011. process.versions = {};
  4012. function noop() {}
  4013. process.on = noop;
  4014. process.addListener = noop;
  4015. process.once = noop;
  4016. process.off = noop;
  4017. process.removeListener = noop;
  4018. process.removeAllListeners = noop;
  4019. process.emit = noop;
  4020. process.binding = function (name) {
  4021. throw new Error('process.binding is not supported');
  4022. };
  4023. process.cwd = function () { return '/' };
  4024. process.chdir = function (dir) {
  4025. throw new Error('process.chdir is not supported');
  4026. };
  4027. process.umask = function() { return 0; };
  4028. },{}],35:[function(_dereq_,module,exports){
  4029. (function(root) {
  4030. // Store setTimeout reference so promise-polyfill will be unaffected by
  4031. // other code modifying setTimeout (like sinon.useFakeTimers())
  4032. var setTimeoutFunc = setTimeout;
  4033. // Use polyfill for setImmediate for performance gains
  4034. var asap = (typeof setImmediate === 'function' && setImmediate) ||
  4035. function(fn) { setTimeoutFunc(fn, 1); };
  4036. // Polyfill for Function.prototype.bind
  4037. function bind(fn, thisArg) {
  4038. return function() {
  4039. fn.apply(thisArg, arguments);
  4040. }
  4041. }
  4042. var isArray = Array.isArray || function(value) { return Object.prototype.toString.call(value) === "[object Array]" };
  4043. function Promise(fn) {
  4044. if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new');
  4045. if (typeof fn !== 'function') throw new TypeError('not a function');
  4046. this._state = null;
  4047. this._value = null;
  4048. this._deferreds = []
  4049. doResolve(fn, bind(resolve, this), bind(reject, this))
  4050. }
  4051. function handle(deferred) {
  4052. var me = this;
  4053. if (this._state === null) {
  4054. this._deferreds.push(deferred);
  4055. return
  4056. }
  4057. asap(function() {
  4058. var cb = me._state ? deferred.onFulfilled : deferred.onRejected
  4059. if (cb === null) {
  4060. (me._state ? deferred.resolve : deferred.reject)(me._value);
  4061. return;
  4062. }
  4063. var ret;
  4064. try {
  4065. ret = cb(me._value);
  4066. }
  4067. catch (e) {
  4068. deferred.reject(e);
  4069. return;
  4070. }
  4071. deferred.resolve(ret);
  4072. })
  4073. }
  4074. function resolve(newValue) {
  4075. try { //Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
  4076. if (newValue === this) throw new TypeError('A promise cannot be resolved with itself.');
  4077. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  4078. var then = newValue.then;
  4079. if (typeof then === 'function') {
  4080. doResolve(bind(then, newValue), bind(resolve, this), bind(reject, this));
  4081. return;
  4082. }
  4083. }
  4084. this._state = true;
  4085. this._value = newValue;
  4086. finale.call(this);
  4087. } catch (e) { reject.call(this, e); }
  4088. }
  4089. function reject(newValue) {
  4090. this._state = false;
  4091. this._value = newValue;
  4092. finale.call(this);
  4093. }
  4094. function finale() {
  4095. for (var i = 0, len = this._deferreds.length; i < len; i++) {
  4096. handle.call(this, this._deferreds[i]);
  4097. }
  4098. this._deferreds = null;
  4099. }
  4100. function Handler(onFulfilled, onRejected, resolve, reject){
  4101. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  4102. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  4103. this.resolve = resolve;
  4104. this.reject = reject;
  4105. }
  4106. /**
  4107. * Take a potentially misbehaving resolver function and make sure
  4108. * onFulfilled and onRejected are only called once.
  4109. *
  4110. * Makes no guarantees about asynchrony.
  4111. */
  4112. function doResolve(fn, onFulfilled, onRejected) {
  4113. var done = false;
  4114. try {
  4115. fn(function (value) {
  4116. if (done) return;
  4117. done = true;
  4118. onFulfilled(value);
  4119. }, function (reason) {
  4120. if (done) return;
  4121. done = true;
  4122. onRejected(reason);
  4123. })
  4124. } catch (ex) {
  4125. if (done) return;
  4126. done = true;
  4127. onRejected(ex);
  4128. }
  4129. }
  4130. Promise.prototype['catch'] = function (onRejected) {
  4131. return this.then(null, onRejected);
  4132. };
  4133. Promise.prototype.then = function(onFulfilled, onRejected) {
  4134. var me = this;
  4135. return new Promise(function(resolve, reject) {
  4136. handle.call(me, new Handler(onFulfilled, onRejected, resolve, reject));
  4137. })
  4138. };
  4139. Promise.all = function () {
  4140. var args = Array.prototype.slice.call(arguments.length === 1 && isArray(arguments[0]) ? arguments[0] : arguments);
  4141. return new Promise(function (resolve, reject) {
  4142. if (args.length === 0) return resolve([]);
  4143. var remaining = args.length;
  4144. function res(i, val) {
  4145. try {
  4146. if (val && (typeof val === 'object' || typeof val === 'function')) {
  4147. var then = val.then;
  4148. if (typeof then === 'function') {
  4149. then.call(val, function (val) { res(i, val) }, reject);
  4150. return;
  4151. }
  4152. }
  4153. args[i] = val;
  4154. if (--remaining === 0) {
  4155. resolve(args);
  4156. }
  4157. } catch (ex) {
  4158. reject(ex);
  4159. }
  4160. }
  4161. for (var i = 0; i < args.length; i++) {
  4162. res(i, args[i]);
  4163. }
  4164. });
  4165. };
  4166. Promise.resolve = function (value) {
  4167. if (value && typeof value === 'object' && value.constructor === Promise) {
  4168. return value;
  4169. }
  4170. return new Promise(function (resolve) {
  4171. resolve(value);
  4172. });
  4173. };
  4174. Promise.reject = function (value) {
  4175. return new Promise(function (resolve, reject) {
  4176. reject(value);
  4177. });
  4178. };
  4179. Promise.race = function (values) {
  4180. return new Promise(function (resolve, reject) {
  4181. for(var i = 0, len = values.length; i < len; i++) {
  4182. values[i].then(resolve, reject);
  4183. }
  4184. });
  4185. };
  4186. /**
  4187. * Set the immediate function to execute callbacks
  4188. * @param fn {function} Function to execute
  4189. * @private
  4190. */
  4191. Promise._setImmediateFn = function _setImmediateFn(fn) {
  4192. asap = fn;
  4193. };
  4194. if (typeof module !== 'undefined' && module.exports) {
  4195. module.exports = Promise;
  4196. } else if (!root.Promise) {
  4197. root.Promise = Promise;
  4198. }
  4199. })(this);
  4200. },{}],36:[function(_dereq_,module,exports){
  4201. var dtype = _dereq_('dtype')
  4202. var anArray = _dereq_('an-array')
  4203. var isBuffer = _dereq_('is-buffer')
  4204. var CW = [0, 2, 3]
  4205. var CCW = [2, 1, 3]
  4206. module.exports = function createQuadElements(array, opt) {
  4207. //if user didn't specify an output array
  4208. if (!array || !(anArray(array) || isBuffer(array))) {
  4209. opt = array || {}
  4210. array = null
  4211. }
  4212. if (typeof opt === 'number') //backwards-compatible
  4213. opt = { count: opt }
  4214. else
  4215. opt = opt || {}
  4216. var type = typeof opt.type === 'string' ? opt.type : 'uint16'
  4217. var count = typeof opt.count === 'number' ? opt.count : 1
  4218. var start = (opt.start || 0)
  4219. var dir = opt.clockwise !== false ? CW : CCW,
  4220. a = dir[0],
  4221. b = dir[1],
  4222. c = dir[2]
  4223. var numIndices = count * 6
  4224. var indices = array || new (dtype(type))(numIndices)
  4225. for (var i = 0, j = 0; i < numIndices; i += 6, j += 4) {
  4226. var x = i + start
  4227. indices[x + 0] = j + 0
  4228. indices[x + 1] = j + 1
  4229. indices[x + 2] = j + 2
  4230. indices[x + 3] = j + a
  4231. indices[x + 4] = j + b
  4232. indices[x + 5] = j + c
  4233. }
  4234. return indices
  4235. }
  4236. },{"an-array":2,"dtype":12,"is-buffer":19}],37:[function(_dereq_,module,exports){
  4237. /*:: type Attr = { [key: string]: string } */
  4238. /*
  4239. style-attr
  4240. ====
  4241. Very simple parsing and stringifying of style attributes.
  4242. `parse`
  4243. ----
  4244. Convert a style attribute string to an object.
  4245. */
  4246. /*:: declare function parse (raw: string): Attr */
  4247. function parse(raw) {
  4248. var trim = function (s) {
  4249. return s.trim();
  4250. };
  4251. var obj = {};
  4252. getKeyValueChunks(raw).map(trim).filter(Boolean).forEach(function (item) {
  4253. // split with `.indexOf` rather than `.split` because the value may also contain colons.
  4254. var pos = item.indexOf(':');
  4255. var key = item.substr(0, pos).trim();
  4256. var val = item.substr(pos + 1).trim();
  4257. obj[key] = val;
  4258. });
  4259. return obj;
  4260. }
  4261. /*
  4262. `getKeyValueChunks`
  4263. ----
  4264. Split a string into chunks matching `<key>: <value>`
  4265. */
  4266. /*:: declare function getKeyValueChunks (raw: string): Array<string> */
  4267. function getKeyValueChunks(raw) {
  4268. var chunks = [];
  4269. var offset = 0;
  4270. var sep = ';';
  4271. var hasUnclosedUrl = /url\([^\)]+$/;
  4272. var chunk = '';
  4273. var nextSplit;
  4274. while (offset < raw.length) {
  4275. nextSplit = raw.indexOf(sep, offset);
  4276. if (nextSplit === -1) {
  4277. nextSplit = raw.length;
  4278. }
  4279. chunk += raw.substring(offset, nextSplit);
  4280. // data URIs can contain semicolons, so make sure we get the whole thing
  4281. if (hasUnclosedUrl.test(chunk)) {
  4282. chunk += ';';
  4283. offset = nextSplit + 1;
  4284. continue;
  4285. }
  4286. chunks.push(chunk);
  4287. chunk = '';
  4288. offset = nextSplit + 1;
  4289. }
  4290. return chunks;
  4291. }
  4292. /*
  4293. `stringify`
  4294. ----
  4295. Convert an object into an attribute string
  4296. */
  4297. /*:: declare function stringify (obj: Attr): string */
  4298. function stringify(obj) {
  4299. return Object.keys(obj).map(function (key) {
  4300. return key + ':' + obj[key];
  4301. }).join(';');
  4302. }
  4303. /*
  4304. `normalize`
  4305. ----
  4306. Normalize an attribute string (eg. collapse duplicates)
  4307. */
  4308. /*:: declare function normalize (str: string): string */
  4309. function normalize(str) {
  4310. return stringify(parse(str));
  4311. }
  4312. module.exports.parse = parse;
  4313. module.exports.stringify = stringify;
  4314. module.exports.normalize = normalize;
  4315. },{}],38:[function(_dereq_,module,exports){
  4316. var createLayout = _dereq_('layout-bmfont-text')
  4317. var inherits = _dereq_('inherits')
  4318. var createIndices = _dereq_('quad-indices')
  4319. var buffer = _dereq_('three-buffer-vertex-data')
  4320. var assign = _dereq_('object-assign')
  4321. var vertices = _dereq_('./lib/vertices')
  4322. var utils = _dereq_('./lib/utils')
  4323. var Base = THREE.BufferGeometry
  4324. module.exports = function createTextGeometry (opt) {
  4325. return new TextGeometry(opt)
  4326. }
  4327. function TextGeometry (opt) {
  4328. Base.call(this)
  4329. if (typeof opt === 'string') {
  4330. opt = { text: opt }
  4331. }
  4332. // use these as default values for any subsequent
  4333. // calls to update()
  4334. this._opt = assign({}, opt)
  4335. // also do an initial setup...
  4336. if (opt) this.update(opt)
  4337. }
  4338. inherits(TextGeometry, Base)
  4339. TextGeometry.prototype.update = function (opt) {
  4340. if (typeof opt === 'string') {
  4341. opt = { text: opt }
  4342. }
  4343. // use constructor defaults
  4344. opt = assign({}, this._opt, opt)
  4345. if (!opt.font) {
  4346. throw new TypeError('must specify a { font } in options')
  4347. }
  4348. this.layout = createLayout(opt)
  4349. // get vec2 texcoords
  4350. var flipY = opt.flipY !== false
  4351. // the desired BMFont data
  4352. var font = opt.font
  4353. // determine texture size from font file
  4354. var texWidth = font.common.scaleW
  4355. var texHeight = font.common.scaleH
  4356. // get visible glyphs
  4357. var glyphs = this.layout.glyphs.filter(function (glyph) {
  4358. var bitmap = glyph.data
  4359. return bitmap.width * bitmap.height > 0
  4360. })
  4361. // provide visible glyphs for convenience
  4362. this.visibleGlyphs = glyphs
  4363. // get common vertex data
  4364. var positions = vertices.positions(glyphs)
  4365. var uvs = vertices.uvs(glyphs, texWidth, texHeight, flipY)
  4366. var indices = createIndices({
  4367. clockwise: true,
  4368. type: 'uint16',
  4369. count: glyphs.length
  4370. })
  4371. // update vertex data
  4372. buffer.index(this, indices, 1, 'uint16')
  4373. buffer.attr(this, 'position', positions, 2)
  4374. buffer.attr(this, 'uv', uvs, 2)
  4375. // update multipage data
  4376. if (!opt.multipage && 'page' in this.attributes) {
  4377. // disable multipage rendering
  4378. this.removeAttribute('page')
  4379. } else if (opt.multipage) {
  4380. var pages = vertices.pages(glyphs)
  4381. // enable multipage rendering
  4382. buffer.attr(this, 'page', pages, 1)
  4383. }
  4384. }
  4385. TextGeometry.prototype.computeBoundingSphere = function () {
  4386. if (this.boundingSphere === null) {
  4387. this.boundingSphere = new THREE.Sphere()
  4388. }
  4389. var positions = this.attributes.position.array
  4390. var itemSize = this.attributes.position.itemSize
  4391. if (!positions || !itemSize || positions.length < 2) {
  4392. this.boundingSphere.radius = 0
  4393. this.boundingSphere.center.set(0, 0, 0)
  4394. return
  4395. }
  4396. utils.computeSphere(positions, this.boundingSphere)
  4397. if (isNaN(this.boundingSphere.radius)) {
  4398. console.error('THREE.BufferGeometry.computeBoundingSphere(): ' +
  4399. 'Computed radius is NaN. The ' +
  4400. '"position" attribute is likely to have NaN values.')
  4401. }
  4402. }
  4403. TextGeometry.prototype.computeBoundingBox = function () {
  4404. if (this.boundingBox === null) {
  4405. this.boundingBox = new THREE.Box3()
  4406. }
  4407. var bbox = this.boundingBox
  4408. var positions = this.attributes.position.array
  4409. var itemSize = this.attributes.position.itemSize
  4410. if (!positions || !itemSize || positions.length < 2) {
  4411. bbox.makeEmpty()
  4412. return
  4413. }
  4414. utils.computeBox(positions, bbox)
  4415. }
  4416. },{"./lib/utils":39,"./lib/vertices":40,"inherits":18,"layout-bmfont-text":23,"object-assign":26,"quad-indices":36,"three-buffer-vertex-data":41}],39:[function(_dereq_,module,exports){
  4417. var itemSize = 2
  4418. var box = { min: [0, 0], max: [0, 0] }
  4419. function bounds (positions) {
  4420. var count = positions.length / itemSize
  4421. box.min[0] = positions[0]
  4422. box.min[1] = positions[1]
  4423. box.max[0] = positions[0]
  4424. box.max[1] = positions[1]
  4425. for (var i = 0; i < count; i++) {
  4426. var x = positions[i * itemSize + 0]
  4427. var y = positions[i * itemSize + 1]
  4428. box.min[0] = Math.min(x, box.min[0])
  4429. box.min[1] = Math.min(y, box.min[1])
  4430. box.max[0] = Math.max(x, box.max[0])
  4431. box.max[1] = Math.max(y, box.max[1])
  4432. }
  4433. }
  4434. module.exports.computeBox = function (positions, output) {
  4435. bounds(positions)
  4436. output.min.set(box.min[0], box.min[1], 0)
  4437. output.max.set(box.max[0], box.max[1], 0)
  4438. }
  4439. module.exports.computeSphere = function (positions, output) {
  4440. bounds(positions)
  4441. var minX = box.min[0]
  4442. var minY = box.min[1]
  4443. var maxX = box.max[0]
  4444. var maxY = box.max[1]
  4445. var width = maxX - minX
  4446. var height = maxY - minY
  4447. var length = Math.sqrt(width * width + height * height)
  4448. output.center.set(minX + width / 2, minY + height / 2, 0)
  4449. output.radius = length / 2
  4450. }
  4451. },{}],40:[function(_dereq_,module,exports){
  4452. module.exports.pages = function pages (glyphs) {
  4453. var pages = new Float32Array(glyphs.length * 4 * 1)
  4454. var i = 0
  4455. glyphs.forEach(function (glyph) {
  4456. var id = glyph.data.page || 0
  4457. pages[i++] = id
  4458. pages[i++] = id
  4459. pages[i++] = id
  4460. pages[i++] = id
  4461. })
  4462. return pages
  4463. }
  4464. module.exports.uvs = function uvs (glyphs, texWidth, texHeight, flipY) {
  4465. var uvs = new Float32Array(glyphs.length * 4 * 2)
  4466. var i = 0
  4467. glyphs.forEach(function (glyph) {
  4468. var bitmap = glyph.data
  4469. var bw = (bitmap.x + bitmap.width)
  4470. var bh = (bitmap.y + bitmap.height)
  4471. // top left position
  4472. var u0 = bitmap.x / texWidth
  4473. var v1 = bitmap.y / texHeight
  4474. var u1 = bw / texWidth
  4475. var v0 = bh / texHeight
  4476. if (flipY) {
  4477. v1 = (texHeight - bitmap.y) / texHeight
  4478. v0 = (texHeight - bh) / texHeight
  4479. }
  4480. // BL
  4481. uvs[i++] = u0
  4482. uvs[i++] = v1
  4483. // TL
  4484. uvs[i++] = u0
  4485. uvs[i++] = v0
  4486. // TR
  4487. uvs[i++] = u1
  4488. uvs[i++] = v0
  4489. // BR
  4490. uvs[i++] = u1
  4491. uvs[i++] = v1
  4492. })
  4493. return uvs
  4494. }
  4495. module.exports.positions = function positions (glyphs) {
  4496. var positions = new Float32Array(glyphs.length * 4 * 2)
  4497. var i = 0
  4498. glyphs.forEach(function (glyph) {
  4499. var bitmap = glyph.data
  4500. // bottom left position
  4501. var x = glyph.position[0] + bitmap.xoffset
  4502. var y = glyph.position[1] + bitmap.yoffset
  4503. // quad size
  4504. var w = bitmap.width
  4505. var h = bitmap.height
  4506. // BL
  4507. positions[i++] = x
  4508. positions[i++] = y
  4509. // TL
  4510. positions[i++] = x
  4511. positions[i++] = y + h
  4512. // TR
  4513. positions[i++] = x + w
  4514. positions[i++] = y + h
  4515. // BR
  4516. positions[i++] = x + w
  4517. positions[i++] = y
  4518. })
  4519. return positions
  4520. }
  4521. },{}],41:[function(_dereq_,module,exports){
  4522. var flatten = _dereq_('flatten-vertex-data')
  4523. var warned = false;
  4524. module.exports.attr = setAttribute
  4525. module.exports.index = setIndex
  4526. function setIndex (geometry, data, itemSize, dtype) {
  4527. if (typeof itemSize !== 'number') itemSize = 1
  4528. if (typeof dtype !== 'string') dtype = 'uint16'
  4529. var isR69 = !geometry.index && typeof geometry.setIndex !== 'function'
  4530. var attrib = isR69 ? geometry.getAttribute('index') : geometry.index
  4531. var newAttrib = updateAttribute(attrib, data, itemSize, dtype)
  4532. if (newAttrib) {
  4533. if (isR69) geometry.addAttribute('index', newAttrib)
  4534. else geometry.index = newAttrib
  4535. }
  4536. }
  4537. function setAttribute (geometry, key, data, itemSize, dtype) {
  4538. if (typeof itemSize !== 'number') itemSize = 3
  4539. if (typeof dtype !== 'string') dtype = 'float32'
  4540. if (Array.isArray(data) &&
  4541. Array.isArray(data[0]) &&
  4542. data[0].length !== itemSize) {
  4543. throw new Error('Nested vertex array has unexpected size; expected ' +
  4544. itemSize + ' but found ' + data[0].length)
  4545. }
  4546. var attrib = geometry.getAttribute(key)
  4547. var newAttrib = updateAttribute(attrib, data, itemSize, dtype)
  4548. if (newAttrib) {
  4549. geometry.addAttribute(key, newAttrib)
  4550. }
  4551. }
  4552. function updateAttribute (attrib, data, itemSize, dtype) {
  4553. data = data || []
  4554. if (!attrib || rebuildAttribute(attrib, data, itemSize)) {
  4555. // create a new array with desired type
  4556. data = flatten(data, dtype)
  4557. var needsNewBuffer = attrib && typeof attrib.setArray !== 'function'
  4558. if (!attrib || needsNewBuffer) {
  4559. // We are on an old version of ThreeJS which can't
  4560. // support growing / shrinking buffers, so we need
  4561. // to build a new buffer
  4562. if (needsNewBuffer && !warned) {
  4563. warned = true
  4564. console.warn([
  4565. 'A WebGL buffer is being updated with a new size or itemSize, ',
  4566. 'however this version of ThreeJS only supports fixed-size buffers.',
  4567. '\nThe old buffer may still be kept in memory.\n',
  4568. 'To avoid memory leaks, it is recommended that you dispose ',
  4569. 'your geometries and create new ones, or update to ThreeJS r82 or newer.\n',
  4570. 'See here for discussion:\n',
  4571. 'https://github.com/mrdoob/three.js/pull/9631'
  4572. ].join(''))
  4573. }
  4574. // Build a new attribute
  4575. attrib = new THREE.BufferAttribute(data, itemSize);
  4576. }
  4577. attrib.itemSize = itemSize
  4578. attrib.needsUpdate = true
  4579. // New versions of ThreeJS suggest using setArray
  4580. // to change the data. It will use bufferData internally,
  4581. // so you can change the array size without any issues
  4582. if (typeof attrib.setArray === 'function') {
  4583. attrib.setArray(data)
  4584. }
  4585. return attrib
  4586. } else {
  4587. // copy data into the existing array
  4588. flatten(data, attrib.array)
  4589. attrib.needsUpdate = true
  4590. return null
  4591. }
  4592. }
  4593. // Test whether the attribute needs to be re-created,
  4594. // returns false if we can re-use it as-is.
  4595. function rebuildAttribute (attrib, data, itemSize) {
  4596. if (attrib.itemSize !== itemSize) return true
  4597. if (!attrib.array) return true
  4598. var attribLength = attrib.array.length
  4599. if (Array.isArray(data) && Array.isArray(data[0])) {
  4600. // [ [ x, y, z ] ]
  4601. return attribLength !== data.length * itemSize
  4602. } else {
  4603. // [ x, y, z ]
  4604. return attribLength !== data.length
  4605. }
  4606. return false
  4607. }
  4608. },{"flatten-vertex-data":13}],42:[function(_dereq_,module,exports){
  4609. (function (global, factory) {
  4610. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  4611. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4612. (factory((global.THREE = global.THREE || {})));
  4613. }(this, (function (exports) { 'use strict';
  4614. // Polyfills
  4615. if ( Number.EPSILON === undefined ) {
  4616. Number.EPSILON = Math.pow( 2, - 52 );
  4617. }
  4618. //
  4619. if ( Math.sign === undefined ) {
  4620. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  4621. Math.sign = function ( x ) {
  4622. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x;
  4623. };
  4624. }
  4625. if ( Function.prototype.name === undefined ) {
  4626. // Missing in IE9-11.
  4627. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  4628. Object.defineProperty( Function.prototype, 'name', {
  4629. get: function () {
  4630. return this.toString().match( /^\s*function\s*([^\(\s]*)/ )[ 1 ];
  4631. }
  4632. } );
  4633. }
  4634. if ( Object.assign === undefined ) {
  4635. // Missing in IE.
  4636. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  4637. ( function () {
  4638. Object.assign = function ( target ) {
  4639. 'use strict';
  4640. if ( target === undefined || target === null ) {
  4641. throw new TypeError( 'Cannot convert undefined or null to object' );
  4642. }
  4643. var output = Object( target );
  4644. for ( var index = 1; index < arguments.length; index ++ ) {
  4645. var source = arguments[ index ];
  4646. if ( source !== undefined && source !== null ) {
  4647. for ( var nextKey in source ) {
  4648. if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) {
  4649. output[ nextKey ] = source[ nextKey ];
  4650. }
  4651. }
  4652. }
  4653. }
  4654. return output;
  4655. };
  4656. } )();
  4657. }
  4658. /**
  4659. * https://github.com/mrdoob/eventdispatcher.js/
  4660. */
  4661. function EventDispatcher() {}
  4662. EventDispatcher.prototype = {
  4663. addEventListener: function ( type, listener ) {
  4664. if ( this._listeners === undefined ) this._listeners = {};
  4665. var listeners = this._listeners;
  4666. if ( listeners[ type ] === undefined ) {
  4667. listeners[ type ] = [];
  4668. }
  4669. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  4670. listeners[ type ].push( listener );
  4671. }
  4672. },
  4673. hasEventListener: function ( type, listener ) {
  4674. if ( this._listeners === undefined ) return false;
  4675. var listeners = this._listeners;
  4676. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  4677. },
  4678. removeEventListener: function ( type, listener ) {
  4679. if ( this._listeners === undefined ) return;
  4680. var listeners = this._listeners;
  4681. var listenerArray = listeners[ type ];
  4682. if ( listenerArray !== undefined ) {
  4683. var index = listenerArray.indexOf( listener );
  4684. if ( index !== - 1 ) {
  4685. listenerArray.splice( index, 1 );
  4686. }
  4687. }
  4688. },
  4689. dispatchEvent: function ( event ) {
  4690. if ( this._listeners === undefined ) return;
  4691. var listeners = this._listeners;
  4692. var listenerArray = listeners[ event.type ];
  4693. if ( listenerArray !== undefined ) {
  4694. event.target = this;
  4695. var array = [], i = 0;
  4696. var length = listenerArray.length;
  4697. for ( i = 0; i < length; i ++ ) {
  4698. array[ i ] = listenerArray[ i ];
  4699. }
  4700. for ( i = 0; i < length; i ++ ) {
  4701. array[ i ].call( this, event );
  4702. }
  4703. }
  4704. }
  4705. };
  4706. var REVISION = '84';
  4707. var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 };
  4708. var CullFaceNone = 0;
  4709. var CullFaceBack = 1;
  4710. var CullFaceFront = 2;
  4711. var CullFaceFrontBack = 3;
  4712. var FrontFaceDirectionCW = 0;
  4713. var FrontFaceDirectionCCW = 1;
  4714. var BasicShadowMap = 0;
  4715. var PCFShadowMap = 1;
  4716. var PCFSoftShadowMap = 2;
  4717. var FrontSide = 0;
  4718. var BackSide = 1;
  4719. var DoubleSide = 2;
  4720. var FlatShading = 1;
  4721. var SmoothShading = 2;
  4722. var NoColors = 0;
  4723. var FaceColors = 1;
  4724. var VertexColors = 2;
  4725. var NoBlending = 0;
  4726. var NormalBlending = 1;
  4727. var AdditiveBlending = 2;
  4728. var SubtractiveBlending = 3;
  4729. var MultiplyBlending = 4;
  4730. var CustomBlending = 5;
  4731. var AddEquation = 100;
  4732. var SubtractEquation = 101;
  4733. var ReverseSubtractEquation = 102;
  4734. var MinEquation = 103;
  4735. var MaxEquation = 104;
  4736. var ZeroFactor = 200;
  4737. var OneFactor = 201;
  4738. var SrcColorFactor = 202;
  4739. var OneMinusSrcColorFactor = 203;
  4740. var SrcAlphaFactor = 204;
  4741. var OneMinusSrcAlphaFactor = 205;
  4742. var DstAlphaFactor = 206;
  4743. var OneMinusDstAlphaFactor = 207;
  4744. var DstColorFactor = 208;
  4745. var OneMinusDstColorFactor = 209;
  4746. var SrcAlphaSaturateFactor = 210;
  4747. var NeverDepth = 0;
  4748. var AlwaysDepth = 1;
  4749. var LessDepth = 2;
  4750. var LessEqualDepth = 3;
  4751. var EqualDepth = 4;
  4752. var GreaterEqualDepth = 5;
  4753. var GreaterDepth = 6;
  4754. var NotEqualDepth = 7;
  4755. var MultiplyOperation = 0;
  4756. var MixOperation = 1;
  4757. var AddOperation = 2;
  4758. var NoToneMapping = 0;
  4759. var LinearToneMapping = 1;
  4760. var ReinhardToneMapping = 2;
  4761. var Uncharted2ToneMapping = 3;
  4762. var CineonToneMapping = 4;
  4763. var UVMapping = 300;
  4764. var CubeReflectionMapping = 301;
  4765. var CubeRefractionMapping = 302;
  4766. var EquirectangularReflectionMapping = 303;
  4767. var EquirectangularRefractionMapping = 304;
  4768. var SphericalReflectionMapping = 305;
  4769. var CubeUVReflectionMapping = 306;
  4770. var CubeUVRefractionMapping = 307;
  4771. var RepeatWrapping = 1000;
  4772. var ClampToEdgeWrapping = 1001;
  4773. var MirroredRepeatWrapping = 1002;
  4774. var NearestFilter = 1003;
  4775. var NearestMipMapNearestFilter = 1004;
  4776. var NearestMipMapLinearFilter = 1005;
  4777. var LinearFilter = 1006;
  4778. var LinearMipMapNearestFilter = 1007;
  4779. var LinearMipMapLinearFilter = 1008;
  4780. var UnsignedByteType = 1009;
  4781. var ByteType = 1010;
  4782. var ShortType = 1011;
  4783. var UnsignedShortType = 1012;
  4784. var IntType = 1013;
  4785. var UnsignedIntType = 1014;
  4786. var FloatType = 1015;
  4787. var HalfFloatType = 1016;
  4788. var UnsignedShort4444Type = 1017;
  4789. var UnsignedShort5551Type = 1018;
  4790. var UnsignedShort565Type = 1019;
  4791. var UnsignedInt248Type = 1020;
  4792. var AlphaFormat = 1021;
  4793. var RGBFormat = 1022;
  4794. var RGBAFormat = 1023;
  4795. var LuminanceFormat = 1024;
  4796. var LuminanceAlphaFormat = 1025;
  4797. var RGBEFormat = RGBAFormat;
  4798. var DepthFormat = 1026;
  4799. var DepthStencilFormat = 1027;
  4800. var RGB_S3TC_DXT1_Format = 2001;
  4801. var RGBA_S3TC_DXT1_Format = 2002;
  4802. var RGBA_S3TC_DXT3_Format = 2003;
  4803. var RGBA_S3TC_DXT5_Format = 2004;
  4804. var RGB_PVRTC_4BPPV1_Format = 2100;
  4805. var RGB_PVRTC_2BPPV1_Format = 2101;
  4806. var RGBA_PVRTC_4BPPV1_Format = 2102;
  4807. var RGBA_PVRTC_2BPPV1_Format = 2103;
  4808. var RGB_ETC1_Format = 2151;
  4809. var LoopOnce = 2200;
  4810. var LoopRepeat = 2201;
  4811. var LoopPingPong = 2202;
  4812. var InterpolateDiscrete = 2300;
  4813. var InterpolateLinear = 2301;
  4814. var InterpolateSmooth = 2302;
  4815. var ZeroCurvatureEnding = 2400;
  4816. var ZeroSlopeEnding = 2401;
  4817. var WrapAroundEnding = 2402;
  4818. var TrianglesDrawMode = 0;
  4819. var TriangleStripDrawMode = 1;
  4820. var TriangleFanDrawMode = 2;
  4821. var LinearEncoding = 3000;
  4822. var sRGBEncoding = 3001;
  4823. var GammaEncoding = 3007;
  4824. var RGBEEncoding = 3002;
  4825. var LogLuvEncoding = 3003;
  4826. var RGBM7Encoding = 3004;
  4827. var RGBM16Encoding = 3005;
  4828. var RGBDEncoding = 3006;
  4829. var BasicDepthPacking = 3200;
  4830. var RGBADepthPacking = 3201;
  4831. /**
  4832. * @author alteredq / http://alteredqualia.com/
  4833. * @author mrdoob / http://mrdoob.com/
  4834. */
  4835. var _Math = {
  4836. DEG2RAD: Math.PI / 180,
  4837. RAD2DEG: 180 / Math.PI,
  4838. generateUUID: function () {
  4839. // http://www.broofa.com/Tools/Math.uuid.htm
  4840. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' );
  4841. var uuid = new Array( 36 );
  4842. var rnd = 0, r;
  4843. return function generateUUID() {
  4844. for ( var i = 0; i < 36; i ++ ) {
  4845. if ( i === 8 || i === 13 || i === 18 || i === 23 ) {
  4846. uuid[ i ] = '-';
  4847. } else if ( i === 14 ) {
  4848. uuid[ i ] = '4';
  4849. } else {
  4850. if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0;
  4851. r = rnd & 0xf;
  4852. rnd = rnd >> 4;
  4853. uuid[ i ] = chars[ ( i === 19 ) ? ( r & 0x3 ) | 0x8 : r ];
  4854. }
  4855. }
  4856. return uuid.join( '' );
  4857. };
  4858. }(),
  4859. clamp: function ( value, min, max ) {
  4860. return Math.max( min, Math.min( max, value ) );
  4861. },
  4862. // compute euclidian modulo of m % n
  4863. // https://en.wikipedia.org/wiki/Modulo_operation
  4864. euclideanModulo: function ( n, m ) {
  4865. return ( ( n % m ) + m ) % m;
  4866. },
  4867. // Linear mapping from range <a1, a2> to range <b1, b2>
  4868. mapLinear: function ( x, a1, a2, b1, b2 ) {
  4869. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  4870. },
  4871. // https://en.wikipedia.org/wiki/Linear_interpolation
  4872. lerp: function ( x, y, t ) {
  4873. return ( 1 - t ) * x + t * y;
  4874. },
  4875. // http://en.wikipedia.org/wiki/Smoothstep
  4876. smoothstep: function ( x, min, max ) {
  4877. if ( x <= min ) return 0;
  4878. if ( x >= max ) return 1;
  4879. x = ( x - min ) / ( max - min );
  4880. return x * x * ( 3 - 2 * x );
  4881. },
  4882. smootherstep: function ( x, min, max ) {
  4883. if ( x <= min ) return 0;
  4884. if ( x >= max ) return 1;
  4885. x = ( x - min ) / ( max - min );
  4886. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  4887. },
  4888. // Random integer from <low, high> interval
  4889. randInt: function ( low, high ) {
  4890. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  4891. },
  4892. // Random float from <low, high> interval
  4893. randFloat: function ( low, high ) {
  4894. return low + Math.random() * ( high - low );
  4895. },
  4896. // Random float from <-range/2, range/2> interval
  4897. randFloatSpread: function ( range ) {
  4898. return range * ( 0.5 - Math.random() );
  4899. },
  4900. degToRad: function ( degrees ) {
  4901. return degrees * _Math.DEG2RAD;
  4902. },
  4903. radToDeg: function ( radians ) {
  4904. return radians * _Math.RAD2DEG;
  4905. },
  4906. isPowerOfTwo: function ( value ) {
  4907. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  4908. },
  4909. nearestPowerOfTwo: function ( value ) {
  4910. return Math.pow( 2, Math.round( Math.log( value ) / Math.LN2 ) );
  4911. },
  4912. nextPowerOfTwo: function ( value ) {
  4913. value --;
  4914. value |= value >> 1;
  4915. value |= value >> 2;
  4916. value |= value >> 4;
  4917. value |= value >> 8;
  4918. value |= value >> 16;
  4919. value ++;
  4920. return value;
  4921. }
  4922. };
  4923. /**
  4924. * @author mrdoob / http://mrdoob.com/
  4925. * @author philogb / http://blog.thejit.org/
  4926. * @author egraether / http://egraether.com/
  4927. * @author zz85 / http://www.lab4games.net/zz85/blog
  4928. */
  4929. function Vector2( x, y ) {
  4930. this.x = x || 0;
  4931. this.y = y || 0;
  4932. }
  4933. Vector2.prototype = {
  4934. constructor: Vector2,
  4935. isVector2: true,
  4936. get width() {
  4937. return this.x;
  4938. },
  4939. set width( value ) {
  4940. this.x = value;
  4941. },
  4942. get height() {
  4943. return this.y;
  4944. },
  4945. set height( value ) {
  4946. this.y = value;
  4947. },
  4948. //
  4949. set: function ( x, y ) {
  4950. this.x = x;
  4951. this.y = y;
  4952. return this;
  4953. },
  4954. setScalar: function ( scalar ) {
  4955. this.x = scalar;
  4956. this.y = scalar;
  4957. return this;
  4958. },
  4959. setX: function ( x ) {
  4960. this.x = x;
  4961. return this;
  4962. },
  4963. setY: function ( y ) {
  4964. this.y = y;
  4965. return this;
  4966. },
  4967. setComponent: function ( index, value ) {
  4968. switch ( index ) {
  4969. case 0: this.x = value; break;
  4970. case 1: this.y = value; break;
  4971. default: throw new Error( 'index is out of range: ' + index );
  4972. }
  4973. return this;
  4974. },
  4975. getComponent: function ( index ) {
  4976. switch ( index ) {
  4977. case 0: return this.x;
  4978. case 1: return this.y;
  4979. default: throw new Error( 'index is out of range: ' + index );
  4980. }
  4981. },
  4982. clone: function () {
  4983. return new this.constructor( this.x, this.y );
  4984. },
  4985. copy: function ( v ) {
  4986. this.x = v.x;
  4987. this.y = v.y;
  4988. return this;
  4989. },
  4990. add: function ( v, w ) {
  4991. if ( w !== undefined ) {
  4992. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  4993. return this.addVectors( v, w );
  4994. }
  4995. this.x += v.x;
  4996. this.y += v.y;
  4997. return this;
  4998. },
  4999. addScalar: function ( s ) {
  5000. this.x += s;
  5001. this.y += s;
  5002. return this;
  5003. },
  5004. addVectors: function ( a, b ) {
  5005. this.x = a.x + b.x;
  5006. this.y = a.y + b.y;
  5007. return this;
  5008. },
  5009. addScaledVector: function ( v, s ) {
  5010. this.x += v.x * s;
  5011. this.y += v.y * s;
  5012. return this;
  5013. },
  5014. sub: function ( v, w ) {
  5015. if ( w !== undefined ) {
  5016. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  5017. return this.subVectors( v, w );
  5018. }
  5019. this.x -= v.x;
  5020. this.y -= v.y;
  5021. return this;
  5022. },
  5023. subScalar: function ( s ) {
  5024. this.x -= s;
  5025. this.y -= s;
  5026. return this;
  5027. },
  5028. subVectors: function ( a, b ) {
  5029. this.x = a.x - b.x;
  5030. this.y = a.y - b.y;
  5031. return this;
  5032. },
  5033. multiply: function ( v ) {
  5034. this.x *= v.x;
  5035. this.y *= v.y;
  5036. return this;
  5037. },
  5038. multiplyScalar: function ( scalar ) {
  5039. if ( isFinite( scalar ) ) {
  5040. this.x *= scalar;
  5041. this.y *= scalar;
  5042. } else {
  5043. this.x = 0;
  5044. this.y = 0;
  5045. }
  5046. return this;
  5047. },
  5048. divide: function ( v ) {
  5049. this.x /= v.x;
  5050. this.y /= v.y;
  5051. return this;
  5052. },
  5053. divideScalar: function ( scalar ) {
  5054. return this.multiplyScalar( 1 / scalar );
  5055. },
  5056. min: function ( v ) {
  5057. this.x = Math.min( this.x, v.x );
  5058. this.y = Math.min( this.y, v.y );
  5059. return this;
  5060. },
  5061. max: function ( v ) {
  5062. this.x = Math.max( this.x, v.x );
  5063. this.y = Math.max( this.y, v.y );
  5064. return this;
  5065. },
  5066. clamp: function ( min, max ) {
  5067. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  5068. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  5069. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  5070. return this;
  5071. },
  5072. clampScalar: function () {
  5073. var min, max;
  5074. return function clampScalar( minVal, maxVal ) {
  5075. if ( min === undefined ) {
  5076. min = new Vector2();
  5077. max = new Vector2();
  5078. }
  5079. min.set( minVal, minVal );
  5080. max.set( maxVal, maxVal );
  5081. return this.clamp( min, max );
  5082. };
  5083. }(),
  5084. clampLength: function ( min, max ) {
  5085. var length = this.length();
  5086. return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  5087. },
  5088. floor: function () {
  5089. this.x = Math.floor( this.x );
  5090. this.y = Math.floor( this.y );
  5091. return this;
  5092. },
  5093. ceil: function () {
  5094. this.x = Math.ceil( this.x );
  5095. this.y = Math.ceil( this.y );
  5096. return this;
  5097. },
  5098. round: function () {
  5099. this.x = Math.round( this.x );
  5100. this.y = Math.round( this.y );
  5101. return this;
  5102. },
  5103. roundToZero: function () {
  5104. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  5105. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  5106. return this;
  5107. },
  5108. negate: function () {
  5109. this.x = - this.x;
  5110. this.y = - this.y;
  5111. return this;
  5112. },
  5113. dot: function ( v ) {
  5114. return this.x * v.x + this.y * v.y;
  5115. },
  5116. lengthSq: function () {
  5117. return this.x * this.x + this.y * this.y;
  5118. },
  5119. length: function () {
  5120. return Math.sqrt( this.x * this.x + this.y * this.y );
  5121. },
  5122. lengthManhattan: function() {
  5123. return Math.abs( this.x ) + Math.abs( this.y );
  5124. },
  5125. normalize: function () {
  5126. return this.divideScalar( this.length() );
  5127. },
  5128. angle: function () {
  5129. // computes the angle in radians with respect to the positive x-axis
  5130. var angle = Math.atan2( this.y, this.x );
  5131. if ( angle < 0 ) angle += 2 * Math.PI;
  5132. return angle;
  5133. },
  5134. distanceTo: function ( v ) {
  5135. return Math.sqrt( this.distanceToSquared( v ) );
  5136. },
  5137. distanceToSquared: function ( v ) {
  5138. var dx = this.x - v.x, dy = this.y - v.y;
  5139. return dx * dx + dy * dy;
  5140. },
  5141. distanceToManhattan: function ( v ) {
  5142. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  5143. },
  5144. setLength: function ( length ) {
  5145. return this.multiplyScalar( length / this.length() );
  5146. },
  5147. lerp: function ( v, alpha ) {
  5148. this.x += ( v.x - this.x ) * alpha;
  5149. this.y += ( v.y - this.y ) * alpha;
  5150. return this;
  5151. },
  5152. lerpVectors: function ( v1, v2, alpha ) {
  5153. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  5154. },
  5155. equals: function ( v ) {
  5156. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  5157. },
  5158. fromArray: function ( array, offset ) {
  5159. if ( offset === undefined ) offset = 0;
  5160. this.x = array[ offset ];
  5161. this.y = array[ offset + 1 ];
  5162. return this;
  5163. },
  5164. toArray: function ( array, offset ) {
  5165. if ( array === undefined ) array = [];
  5166. if ( offset === undefined ) offset = 0;
  5167. array[ offset ] = this.x;
  5168. array[ offset + 1 ] = this.y;
  5169. return array;
  5170. },
  5171. fromBufferAttribute: function ( attribute, index, offset ) {
  5172. if ( offset !== undefined ) {
  5173. console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' );
  5174. }
  5175. this.x = attribute.getX( index );
  5176. this.y = attribute.getY( index );
  5177. return this;
  5178. },
  5179. rotateAround: function ( center, angle ) {
  5180. var c = Math.cos( angle ), s = Math.sin( angle );
  5181. var x = this.x - center.x;
  5182. var y = this.y - center.y;
  5183. this.x = x * c - y * s + center.x;
  5184. this.y = x * s + y * c + center.y;
  5185. return this;
  5186. }
  5187. };
  5188. /**
  5189. * @author mrdoob / http://mrdoob.com/
  5190. * @author alteredq / http://alteredqualia.com/
  5191. * @author szimek / https://github.com/szimek/
  5192. */
  5193. var textureId = 0;
  5194. function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  5195. Object.defineProperty( this, 'id', { value: textureId ++ } );
  5196. this.uuid = _Math.generateUUID();
  5197. this.name = '';
  5198. this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
  5199. this.mipmaps = [];
  5200. this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
  5201. this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
  5202. this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
  5203. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  5204. this.minFilter = minFilter !== undefined ? minFilter : LinearMipMapLinearFilter;
  5205. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  5206. this.format = format !== undefined ? format : RGBAFormat;
  5207. this.type = type !== undefined ? type : UnsignedByteType;
  5208. this.offset = new Vector2( 0, 0 );
  5209. this.repeat = new Vector2( 1, 1 );
  5210. this.generateMipmaps = true;
  5211. this.premultiplyAlpha = false;
  5212. this.flipY = true;
  5213. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  5214. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  5215. //
  5216. // Also changing the encoding after already used by a Material will not automatically make the Material
  5217. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  5218. this.encoding = encoding !== undefined ? encoding : LinearEncoding;
  5219. this.version = 0;
  5220. this.onUpdate = null;
  5221. }
  5222. Texture.DEFAULT_IMAGE = undefined;
  5223. Texture.DEFAULT_MAPPING = UVMapping;
  5224. Texture.prototype = {
  5225. constructor: Texture,
  5226. isTexture: true,
  5227. set needsUpdate( value ) {
  5228. if ( value === true ) this.version ++;
  5229. },
  5230. clone: function () {
  5231. return new this.constructor().copy( this );
  5232. },
  5233. copy: function ( source ) {
  5234. this.image = source.image;
  5235. this.mipmaps = source.mipmaps.slice( 0 );
  5236. this.mapping = source.mapping;
  5237. this.wrapS = source.wrapS;
  5238. this.wrapT = source.wrapT;
  5239. this.magFilter = source.magFilter;
  5240. this.minFilter = source.minFilter;
  5241. this.anisotropy = source.anisotropy;
  5242. this.format = source.format;
  5243. this.type = source.type;
  5244. this.offset.copy( source.offset );
  5245. this.repeat.copy( source.repeat );
  5246. this.generateMipmaps = source.generateMipmaps;
  5247. this.premultiplyAlpha = source.premultiplyAlpha;
  5248. this.flipY = source.flipY;
  5249. this.unpackAlignment = source.unpackAlignment;
  5250. this.encoding = source.encoding;
  5251. return this;
  5252. },
  5253. toJSON: function ( meta ) {
  5254. if ( meta.textures[ this.uuid ] !== undefined ) {
  5255. return meta.textures[ this.uuid ];
  5256. }
  5257. function getDataURL( image ) {
  5258. var canvas;
  5259. if ( image.toDataURL !== undefined ) {
  5260. canvas = image;
  5261. } else {
  5262. canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  5263. canvas.width = image.width;
  5264. canvas.height = image.height;
  5265. canvas.getContext( '2d' ).drawImage( image, 0, 0, image.width, image.height );
  5266. }
  5267. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  5268. return canvas.toDataURL( 'image/jpeg', 0.6 );
  5269. } else {
  5270. return canvas.toDataURL( 'image/png' );
  5271. }
  5272. }
  5273. var output = {
  5274. metadata: {
  5275. version: 4.4,
  5276. type: 'Texture',
  5277. generator: 'Texture.toJSON'
  5278. },
  5279. uuid: this.uuid,
  5280. name: this.name,
  5281. mapping: this.mapping,
  5282. repeat: [ this.repeat.x, this.repeat.y ],
  5283. offset: [ this.offset.x, this.offset.y ],
  5284. wrap: [ this.wrapS, this.wrapT ],
  5285. minFilter: this.minFilter,
  5286. magFilter: this.magFilter,
  5287. anisotropy: this.anisotropy,
  5288. flipY: this.flipY
  5289. };
  5290. if ( this.image !== undefined ) {
  5291. // TODO: Move to THREE.Image
  5292. var image = this.image;
  5293. if ( image.uuid === undefined ) {
  5294. image.uuid = _Math.generateUUID(); // UGH
  5295. }
  5296. if ( meta.images[ image.uuid ] === undefined ) {
  5297. meta.images[ image.uuid ] = {
  5298. uuid: image.uuid,
  5299. url: getDataURL( image )
  5300. };
  5301. }
  5302. output.image = image.uuid;
  5303. }
  5304. meta.textures[ this.uuid ] = output;
  5305. return output;
  5306. },
  5307. dispose: function () {
  5308. this.dispatchEvent( { type: 'dispose' } );
  5309. },
  5310. transformUv: function ( uv ) {
  5311. if ( this.mapping !== UVMapping ) return;
  5312. uv.multiply( this.repeat );
  5313. uv.add( this.offset );
  5314. if ( uv.x < 0 || uv.x > 1 ) {
  5315. switch ( this.wrapS ) {
  5316. case RepeatWrapping:
  5317. uv.x = uv.x - Math.floor( uv.x );
  5318. break;
  5319. case ClampToEdgeWrapping:
  5320. uv.x = uv.x < 0 ? 0 : 1;
  5321. break;
  5322. case MirroredRepeatWrapping:
  5323. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  5324. uv.x = Math.ceil( uv.x ) - uv.x;
  5325. } else {
  5326. uv.x = uv.x - Math.floor( uv.x );
  5327. }
  5328. break;
  5329. }
  5330. }
  5331. if ( uv.y < 0 || uv.y > 1 ) {
  5332. switch ( this.wrapT ) {
  5333. case RepeatWrapping:
  5334. uv.y = uv.y - Math.floor( uv.y );
  5335. break;
  5336. case ClampToEdgeWrapping:
  5337. uv.y = uv.y < 0 ? 0 : 1;
  5338. break;
  5339. case MirroredRepeatWrapping:
  5340. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  5341. uv.y = Math.ceil( uv.y ) - uv.y;
  5342. } else {
  5343. uv.y = uv.y - Math.floor( uv.y );
  5344. }
  5345. break;
  5346. }
  5347. }
  5348. if ( this.flipY ) {
  5349. uv.y = 1 - uv.y;
  5350. }
  5351. }
  5352. };
  5353. Object.assign( Texture.prototype, EventDispatcher.prototype );
  5354. /**
  5355. * @author supereggbert / http://www.paulbrunt.co.uk/
  5356. * @author philogb / http://blog.thejit.org/
  5357. * @author mikael emtinger / http://gomo.se/
  5358. * @author egraether / http://egraether.com/
  5359. * @author WestLangley / http://github.com/WestLangley
  5360. */
  5361. function Vector4( x, y, z, w ) {
  5362. this.x = x || 0;
  5363. this.y = y || 0;
  5364. this.z = z || 0;
  5365. this.w = ( w !== undefined ) ? w : 1;
  5366. }
  5367. Vector4.prototype = {
  5368. constructor: Vector4,
  5369. isVector4: true,
  5370. set: function ( x, y, z, w ) {
  5371. this.x = x;
  5372. this.y = y;
  5373. this.z = z;
  5374. this.w = w;
  5375. return this;
  5376. },
  5377. setScalar: function ( scalar ) {
  5378. this.x = scalar;
  5379. this.y = scalar;
  5380. this.z = scalar;
  5381. this.w = scalar;
  5382. return this;
  5383. },
  5384. setX: function ( x ) {
  5385. this.x = x;
  5386. return this;
  5387. },
  5388. setY: function ( y ) {
  5389. this.y = y;
  5390. return this;
  5391. },
  5392. setZ: function ( z ) {
  5393. this.z = z;
  5394. return this;
  5395. },
  5396. setW: function ( w ) {
  5397. this.w = w;
  5398. return this;
  5399. },
  5400. setComponent: function ( index, value ) {
  5401. switch ( index ) {
  5402. case 0: this.x = value; break;
  5403. case 1: this.y = value; break;
  5404. case 2: this.z = value; break;
  5405. case 3: this.w = value; break;
  5406. default: throw new Error( 'index is out of range: ' + index );
  5407. }
  5408. return this;
  5409. },
  5410. getComponent: function ( index ) {
  5411. switch ( index ) {
  5412. case 0: return this.x;
  5413. case 1: return this.y;
  5414. case 2: return this.z;
  5415. case 3: return this.w;
  5416. default: throw new Error( 'index is out of range: ' + index );
  5417. }
  5418. },
  5419. clone: function () {
  5420. return new this.constructor( this.x, this.y, this.z, this.w );
  5421. },
  5422. copy: function ( v ) {
  5423. this.x = v.x;
  5424. this.y = v.y;
  5425. this.z = v.z;
  5426. this.w = ( v.w !== undefined ) ? v.w : 1;
  5427. return this;
  5428. },
  5429. add: function ( v, w ) {
  5430. if ( w !== undefined ) {
  5431. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  5432. return this.addVectors( v, w );
  5433. }
  5434. this.x += v.x;
  5435. this.y += v.y;
  5436. this.z += v.z;
  5437. this.w += v.w;
  5438. return this;
  5439. },
  5440. addScalar: function ( s ) {
  5441. this.x += s;
  5442. this.y += s;
  5443. this.z += s;
  5444. this.w += s;
  5445. return this;
  5446. },
  5447. addVectors: function ( a, b ) {
  5448. this.x = a.x + b.x;
  5449. this.y = a.y + b.y;
  5450. this.z = a.z + b.z;
  5451. this.w = a.w + b.w;
  5452. return this;
  5453. },
  5454. addScaledVector: function ( v, s ) {
  5455. this.x += v.x * s;
  5456. this.y += v.y * s;
  5457. this.z += v.z * s;
  5458. this.w += v.w * s;
  5459. return this;
  5460. },
  5461. sub: function ( v, w ) {
  5462. if ( w !== undefined ) {
  5463. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  5464. return this.subVectors( v, w );
  5465. }
  5466. this.x -= v.x;
  5467. this.y -= v.y;
  5468. this.z -= v.z;
  5469. this.w -= v.w;
  5470. return this;
  5471. },
  5472. subScalar: function ( s ) {
  5473. this.x -= s;
  5474. this.y -= s;
  5475. this.z -= s;
  5476. this.w -= s;
  5477. return this;
  5478. },
  5479. subVectors: function ( a, b ) {
  5480. this.x = a.x - b.x;
  5481. this.y = a.y - b.y;
  5482. this.z = a.z - b.z;
  5483. this.w = a.w - b.w;
  5484. return this;
  5485. },
  5486. multiplyScalar: function ( scalar ) {
  5487. if ( isFinite( scalar ) ) {
  5488. this.x *= scalar;
  5489. this.y *= scalar;
  5490. this.z *= scalar;
  5491. this.w *= scalar;
  5492. } else {
  5493. this.x = 0;
  5494. this.y = 0;
  5495. this.z = 0;
  5496. this.w = 0;
  5497. }
  5498. return this;
  5499. },
  5500. applyMatrix4: function ( m ) {
  5501. var x = this.x, y = this.y, z = this.z, w = this.w;
  5502. var e = m.elements;
  5503. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  5504. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  5505. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  5506. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  5507. return this;
  5508. },
  5509. divideScalar: function ( scalar ) {
  5510. return this.multiplyScalar( 1 / scalar );
  5511. },
  5512. setAxisAngleFromQuaternion: function ( q ) {
  5513. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  5514. // q is assumed to be normalized
  5515. this.w = 2 * Math.acos( q.w );
  5516. var s = Math.sqrt( 1 - q.w * q.w );
  5517. if ( s < 0.0001 ) {
  5518. this.x = 1;
  5519. this.y = 0;
  5520. this.z = 0;
  5521. } else {
  5522. this.x = q.x / s;
  5523. this.y = q.y / s;
  5524. this.z = q.z / s;
  5525. }
  5526. return this;
  5527. },
  5528. setAxisAngleFromRotationMatrix: function ( m ) {
  5529. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  5530. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  5531. var angle, x, y, z, // variables for result
  5532. epsilon = 0.01, // margin to allow for rounding errors
  5533. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  5534. te = m.elements,
  5535. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  5536. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  5537. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  5538. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  5539. ( Math.abs( m13 - m31 ) < epsilon ) &&
  5540. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  5541. // singularity found
  5542. // first check for identity matrix which must have +1 for all terms
  5543. // in leading diagonal and zero in other terms
  5544. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  5545. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  5546. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  5547. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  5548. // this singularity is identity matrix so angle = 0
  5549. this.set( 1, 0, 0, 0 );
  5550. return this; // zero angle, arbitrary axis
  5551. }
  5552. // otherwise this singularity is angle = 180
  5553. angle = Math.PI;
  5554. var xx = ( m11 + 1 ) / 2;
  5555. var yy = ( m22 + 1 ) / 2;
  5556. var zz = ( m33 + 1 ) / 2;
  5557. var xy = ( m12 + m21 ) / 4;
  5558. var xz = ( m13 + m31 ) / 4;
  5559. var yz = ( m23 + m32 ) / 4;
  5560. if ( ( xx > yy ) && ( xx > zz ) ) {
  5561. // m11 is the largest diagonal term
  5562. if ( xx < epsilon ) {
  5563. x = 0;
  5564. y = 0.707106781;
  5565. z = 0.707106781;
  5566. } else {
  5567. x = Math.sqrt( xx );
  5568. y = xy / x;
  5569. z = xz / x;
  5570. }
  5571. } else if ( yy > zz ) {
  5572. // m22 is the largest diagonal term
  5573. if ( yy < epsilon ) {
  5574. x = 0.707106781;
  5575. y = 0;
  5576. z = 0.707106781;
  5577. } else {
  5578. y = Math.sqrt( yy );
  5579. x = xy / y;
  5580. z = yz / y;
  5581. }
  5582. } else {
  5583. // m33 is the largest diagonal term so base result on this
  5584. if ( zz < epsilon ) {
  5585. x = 0.707106781;
  5586. y = 0.707106781;
  5587. z = 0;
  5588. } else {
  5589. z = Math.sqrt( zz );
  5590. x = xz / z;
  5591. y = yz / z;
  5592. }
  5593. }
  5594. this.set( x, y, z, angle );
  5595. return this; // return 180 deg rotation
  5596. }
  5597. // as we have reached here there are no singularities so we can handle normally
  5598. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  5599. ( m13 - m31 ) * ( m13 - m31 ) +
  5600. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  5601. if ( Math.abs( s ) < 0.001 ) s = 1;
  5602. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  5603. // caught by singularity test above, but I've left it in just in case
  5604. this.x = ( m32 - m23 ) / s;
  5605. this.y = ( m13 - m31 ) / s;
  5606. this.z = ( m21 - m12 ) / s;
  5607. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  5608. return this;
  5609. },
  5610. min: function ( v ) {
  5611. this.x = Math.min( this.x, v.x );
  5612. this.y = Math.min( this.y, v.y );
  5613. this.z = Math.min( this.z, v.z );
  5614. this.w = Math.min( this.w, v.w );
  5615. return this;
  5616. },
  5617. max: function ( v ) {
  5618. this.x = Math.max( this.x, v.x );
  5619. this.y = Math.max( this.y, v.y );
  5620. this.z = Math.max( this.z, v.z );
  5621. this.w = Math.max( this.w, v.w );
  5622. return this;
  5623. },
  5624. clamp: function ( min, max ) {
  5625. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  5626. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  5627. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  5628. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  5629. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  5630. return this;
  5631. },
  5632. clampScalar: function () {
  5633. var min, max;
  5634. return function clampScalar( minVal, maxVal ) {
  5635. if ( min === undefined ) {
  5636. min = new Vector4();
  5637. max = new Vector4();
  5638. }
  5639. min.set( minVal, minVal, minVal, minVal );
  5640. max.set( maxVal, maxVal, maxVal, maxVal );
  5641. return this.clamp( min, max );
  5642. };
  5643. }(),
  5644. floor: function () {
  5645. this.x = Math.floor( this.x );
  5646. this.y = Math.floor( this.y );
  5647. this.z = Math.floor( this.z );
  5648. this.w = Math.floor( this.w );
  5649. return this;
  5650. },
  5651. ceil: function () {
  5652. this.x = Math.ceil( this.x );
  5653. this.y = Math.ceil( this.y );
  5654. this.z = Math.ceil( this.z );
  5655. this.w = Math.ceil( this.w );
  5656. return this;
  5657. },
  5658. round: function () {
  5659. this.x = Math.round( this.x );
  5660. this.y = Math.round( this.y );
  5661. this.z = Math.round( this.z );
  5662. this.w = Math.round( this.w );
  5663. return this;
  5664. },
  5665. roundToZero: function () {
  5666. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  5667. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  5668. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  5669. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  5670. return this;
  5671. },
  5672. negate: function () {
  5673. this.x = - this.x;
  5674. this.y = - this.y;
  5675. this.z = - this.z;
  5676. this.w = - this.w;
  5677. return this;
  5678. },
  5679. dot: function ( v ) {
  5680. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  5681. },
  5682. lengthSq: function () {
  5683. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  5684. },
  5685. length: function () {
  5686. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  5687. },
  5688. lengthManhattan: function () {
  5689. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  5690. },
  5691. normalize: function () {
  5692. return this.divideScalar( this.length() );
  5693. },
  5694. setLength: function ( length ) {
  5695. return this.multiplyScalar( length / this.length() );
  5696. },
  5697. lerp: function ( v, alpha ) {
  5698. this.x += ( v.x - this.x ) * alpha;
  5699. this.y += ( v.y - this.y ) * alpha;
  5700. this.z += ( v.z - this.z ) * alpha;
  5701. this.w += ( v.w - this.w ) * alpha;
  5702. return this;
  5703. },
  5704. lerpVectors: function ( v1, v2, alpha ) {
  5705. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  5706. },
  5707. equals: function ( v ) {
  5708. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  5709. },
  5710. fromArray: function ( array, offset ) {
  5711. if ( offset === undefined ) offset = 0;
  5712. this.x = array[ offset ];
  5713. this.y = array[ offset + 1 ];
  5714. this.z = array[ offset + 2 ];
  5715. this.w = array[ offset + 3 ];
  5716. return this;
  5717. },
  5718. toArray: function ( array, offset ) {
  5719. if ( array === undefined ) array = [];
  5720. if ( offset === undefined ) offset = 0;
  5721. array[ offset ] = this.x;
  5722. array[ offset + 1 ] = this.y;
  5723. array[ offset + 2 ] = this.z;
  5724. array[ offset + 3 ] = this.w;
  5725. return array;
  5726. },
  5727. fromBufferAttribute: function ( attribute, index, offset ) {
  5728. if ( offset !== undefined ) {
  5729. console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' );
  5730. }
  5731. this.x = attribute.getX( index );
  5732. this.y = attribute.getY( index );
  5733. this.z = attribute.getZ( index );
  5734. this.w = attribute.getW( index );
  5735. return this;
  5736. }
  5737. };
  5738. /**
  5739. * @author szimek / https://github.com/szimek/
  5740. * @author alteredq / http://alteredqualia.com/
  5741. * @author Marius Kintel / https://github.com/kintel
  5742. */
  5743. /*
  5744. In options, we can specify:
  5745. * Texture parameters for an auto-generated target texture
  5746. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  5747. */
  5748. function WebGLRenderTarget( width, height, options ) {
  5749. this.uuid = _Math.generateUUID();
  5750. this.width = width;
  5751. this.height = height;
  5752. this.scissor = new Vector4( 0, 0, width, height );
  5753. this.scissorTest = false;
  5754. this.viewport = new Vector4( 0, 0, width, height );
  5755. options = options || {};
  5756. if ( options.minFilter === undefined ) options.minFilter = LinearFilter;
  5757. this.texture = new Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  5758. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  5759. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  5760. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  5761. }
  5762. WebGLRenderTarget.prototype = {
  5763. constructor: WebGLRenderTarget,
  5764. isWebGLRenderTarget: true,
  5765. setSize: function ( width, height ) {
  5766. if ( this.width !== width || this.height !== height ) {
  5767. this.width = width;
  5768. this.height = height;
  5769. this.dispose();
  5770. }
  5771. this.viewport.set( 0, 0, width, height );
  5772. this.scissor.set( 0, 0, width, height );
  5773. },
  5774. clone: function () {
  5775. return new this.constructor().copy( this );
  5776. },
  5777. copy: function ( source ) {
  5778. this.width = source.width;
  5779. this.height = source.height;
  5780. this.viewport.copy( source.viewport );
  5781. this.texture = source.texture.clone();
  5782. this.depthBuffer = source.depthBuffer;
  5783. this.stencilBuffer = source.stencilBuffer;
  5784. this.depthTexture = source.depthTexture;
  5785. return this;
  5786. },
  5787. dispose: function () {
  5788. this.dispatchEvent( { type: 'dispose' } );
  5789. }
  5790. };
  5791. Object.assign( WebGLRenderTarget.prototype, EventDispatcher.prototype );
  5792. /**
  5793. * @author alteredq / http://alteredqualia.com
  5794. */
  5795. function WebGLRenderTargetCube( width, height, options ) {
  5796. WebGLRenderTarget.call( this, width, height, options );
  5797. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  5798. this.activeMipMapLevel = 0;
  5799. }
  5800. WebGLRenderTargetCube.prototype = Object.create( WebGLRenderTarget.prototype );
  5801. WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube;
  5802. WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true;
  5803. /**
  5804. * @author mikael emtinger / http://gomo.se/
  5805. * @author alteredq / http://alteredqualia.com/
  5806. * @author WestLangley / http://github.com/WestLangley
  5807. * @author bhouston / http://clara.io
  5808. */
  5809. function Quaternion( x, y, z, w ) {
  5810. this._x = x || 0;
  5811. this._y = y || 0;
  5812. this._z = z || 0;
  5813. this._w = ( w !== undefined ) ? w : 1;
  5814. }
  5815. Quaternion.prototype = {
  5816. constructor: Quaternion,
  5817. get x () {
  5818. return this._x;
  5819. },
  5820. set x ( value ) {
  5821. this._x = value;
  5822. this.onChangeCallback();
  5823. },
  5824. get y () {
  5825. return this._y;
  5826. },
  5827. set y ( value ) {
  5828. this._y = value;
  5829. this.onChangeCallback();
  5830. },
  5831. get z () {
  5832. return this._z;
  5833. },
  5834. set z ( value ) {
  5835. this._z = value;
  5836. this.onChangeCallback();
  5837. },
  5838. get w () {
  5839. return this._w;
  5840. },
  5841. set w ( value ) {
  5842. this._w = value;
  5843. this.onChangeCallback();
  5844. },
  5845. set: function ( x, y, z, w ) {
  5846. this._x = x;
  5847. this._y = y;
  5848. this._z = z;
  5849. this._w = w;
  5850. this.onChangeCallback();
  5851. return this;
  5852. },
  5853. clone: function () {
  5854. return new this.constructor( this._x, this._y, this._z, this._w );
  5855. },
  5856. copy: function ( quaternion ) {
  5857. this._x = quaternion.x;
  5858. this._y = quaternion.y;
  5859. this._z = quaternion.z;
  5860. this._w = quaternion.w;
  5861. this.onChangeCallback();
  5862. return this;
  5863. },
  5864. setFromEuler: function ( euler, update ) {
  5865. if ( (euler && euler.isEuler) === false ) {
  5866. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  5867. }
  5868. // http://www.mathworks.com/matlabcentral/fileexchange/
  5869. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  5870. // content/SpinCalc.m
  5871. var c1 = Math.cos( euler._x / 2 );
  5872. var c2 = Math.cos( euler._y / 2 );
  5873. var c3 = Math.cos( euler._z / 2 );
  5874. var s1 = Math.sin( euler._x / 2 );
  5875. var s2 = Math.sin( euler._y / 2 );
  5876. var s3 = Math.sin( euler._z / 2 );
  5877. var order = euler.order;
  5878. if ( order === 'XYZ' ) {
  5879. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  5880. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  5881. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  5882. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  5883. } else if ( order === 'YXZ' ) {
  5884. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  5885. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  5886. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  5887. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  5888. } else if ( order === 'ZXY' ) {
  5889. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  5890. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  5891. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  5892. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  5893. } else if ( order === 'ZYX' ) {
  5894. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  5895. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  5896. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  5897. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  5898. } else if ( order === 'YZX' ) {
  5899. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  5900. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  5901. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  5902. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  5903. } else if ( order === 'XZY' ) {
  5904. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  5905. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  5906. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  5907. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  5908. }
  5909. if ( update !== false ) this.onChangeCallback();
  5910. return this;
  5911. },
  5912. setFromAxisAngle: function ( axis, angle ) {
  5913. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  5914. // assumes axis is normalized
  5915. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  5916. this._x = axis.x * s;
  5917. this._y = axis.y * s;
  5918. this._z = axis.z * s;
  5919. this._w = Math.cos( halfAngle );
  5920. this.onChangeCallback();
  5921. return this;
  5922. },
  5923. setFromRotationMatrix: function ( m ) {
  5924. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  5925. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  5926. var te = m.elements,
  5927. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  5928. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  5929. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  5930. trace = m11 + m22 + m33,
  5931. s;
  5932. if ( trace > 0 ) {
  5933. s = 0.5 / Math.sqrt( trace + 1.0 );
  5934. this._w = 0.25 / s;
  5935. this._x = ( m32 - m23 ) * s;
  5936. this._y = ( m13 - m31 ) * s;
  5937. this._z = ( m21 - m12 ) * s;
  5938. } else if ( m11 > m22 && m11 > m33 ) {
  5939. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  5940. this._w = ( m32 - m23 ) / s;
  5941. this._x = 0.25 * s;
  5942. this._y = ( m12 + m21 ) / s;
  5943. this._z = ( m13 + m31 ) / s;
  5944. } else if ( m22 > m33 ) {
  5945. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  5946. this._w = ( m13 - m31 ) / s;
  5947. this._x = ( m12 + m21 ) / s;
  5948. this._y = 0.25 * s;
  5949. this._z = ( m23 + m32 ) / s;
  5950. } else {
  5951. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  5952. this._w = ( m21 - m12 ) / s;
  5953. this._x = ( m13 + m31 ) / s;
  5954. this._y = ( m23 + m32 ) / s;
  5955. this._z = 0.25 * s;
  5956. }
  5957. this.onChangeCallback();
  5958. return this;
  5959. },
  5960. setFromUnitVectors: function () {
  5961. // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final
  5962. // assumes direction vectors vFrom and vTo are normalized
  5963. var v1, r;
  5964. var EPS = 0.000001;
  5965. return function setFromUnitVectors( vFrom, vTo ) {
  5966. if ( v1 === undefined ) v1 = new Vector3();
  5967. r = vFrom.dot( vTo ) + 1;
  5968. if ( r < EPS ) {
  5969. r = 0;
  5970. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  5971. v1.set( - vFrom.y, vFrom.x, 0 );
  5972. } else {
  5973. v1.set( 0, - vFrom.z, vFrom.y );
  5974. }
  5975. } else {
  5976. v1.crossVectors( vFrom, vTo );
  5977. }
  5978. this._x = v1.x;
  5979. this._y = v1.y;
  5980. this._z = v1.z;
  5981. this._w = r;
  5982. return this.normalize();
  5983. };
  5984. }(),
  5985. inverse: function () {
  5986. return this.conjugate().normalize();
  5987. },
  5988. conjugate: function () {
  5989. this._x *= - 1;
  5990. this._y *= - 1;
  5991. this._z *= - 1;
  5992. this.onChangeCallback();
  5993. return this;
  5994. },
  5995. dot: function ( v ) {
  5996. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  5997. },
  5998. lengthSq: function () {
  5999. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  6000. },
  6001. length: function () {
  6002. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  6003. },
  6004. normalize: function () {
  6005. var l = this.length();
  6006. if ( l === 0 ) {
  6007. this._x = 0;
  6008. this._y = 0;
  6009. this._z = 0;
  6010. this._w = 1;
  6011. } else {
  6012. l = 1 / l;
  6013. this._x = this._x * l;
  6014. this._y = this._y * l;
  6015. this._z = this._z * l;
  6016. this._w = this._w * l;
  6017. }
  6018. this.onChangeCallback();
  6019. return this;
  6020. },
  6021. multiply: function ( q, p ) {
  6022. if ( p !== undefined ) {
  6023. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  6024. return this.multiplyQuaternions( q, p );
  6025. }
  6026. return this.multiplyQuaternions( this, q );
  6027. },
  6028. premultiply: function ( q ) {
  6029. return this.multiplyQuaternions( q, this );
  6030. },
  6031. multiplyQuaternions: function ( a, b ) {
  6032. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  6033. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  6034. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  6035. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  6036. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  6037. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  6038. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  6039. this.onChangeCallback();
  6040. return this;
  6041. },
  6042. slerp: function ( qb, t ) {
  6043. if ( t === 0 ) return this;
  6044. if ( t === 1 ) return this.copy( qb );
  6045. var x = this._x, y = this._y, z = this._z, w = this._w;
  6046. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  6047. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  6048. if ( cosHalfTheta < 0 ) {
  6049. this._w = - qb._w;
  6050. this._x = - qb._x;
  6051. this._y = - qb._y;
  6052. this._z = - qb._z;
  6053. cosHalfTheta = - cosHalfTheta;
  6054. } else {
  6055. this.copy( qb );
  6056. }
  6057. if ( cosHalfTheta >= 1.0 ) {
  6058. this._w = w;
  6059. this._x = x;
  6060. this._y = y;
  6061. this._z = z;
  6062. return this;
  6063. }
  6064. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  6065. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  6066. this._w = 0.5 * ( w + this._w );
  6067. this._x = 0.5 * ( x + this._x );
  6068. this._y = 0.5 * ( y + this._y );
  6069. this._z = 0.5 * ( z + this._z );
  6070. return this;
  6071. }
  6072. var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  6073. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  6074. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  6075. this._w = ( w * ratioA + this._w * ratioB );
  6076. this._x = ( x * ratioA + this._x * ratioB );
  6077. this._y = ( y * ratioA + this._y * ratioB );
  6078. this._z = ( z * ratioA + this._z * ratioB );
  6079. this.onChangeCallback();
  6080. return this;
  6081. },
  6082. equals: function ( quaternion ) {
  6083. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  6084. },
  6085. fromArray: function ( array, offset ) {
  6086. if ( offset === undefined ) offset = 0;
  6087. this._x = array[ offset ];
  6088. this._y = array[ offset + 1 ];
  6089. this._z = array[ offset + 2 ];
  6090. this._w = array[ offset + 3 ];
  6091. this.onChangeCallback();
  6092. return this;
  6093. },
  6094. toArray: function ( array, offset ) {
  6095. if ( array === undefined ) array = [];
  6096. if ( offset === undefined ) offset = 0;
  6097. array[ offset ] = this._x;
  6098. array[ offset + 1 ] = this._y;
  6099. array[ offset + 2 ] = this._z;
  6100. array[ offset + 3 ] = this._w;
  6101. return array;
  6102. },
  6103. onChange: function ( callback ) {
  6104. this.onChangeCallback = callback;
  6105. return this;
  6106. },
  6107. onChangeCallback: function () {}
  6108. };
  6109. Object.assign( Quaternion, {
  6110. slerp: function( qa, qb, qm, t ) {
  6111. return qm.copy( qa ).slerp( qb, t );
  6112. },
  6113. slerpFlat: function(
  6114. dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  6115. // fuzz-free, array-based Quaternion SLERP operation
  6116. var x0 = src0[ srcOffset0 + 0 ],
  6117. y0 = src0[ srcOffset0 + 1 ],
  6118. z0 = src0[ srcOffset0 + 2 ],
  6119. w0 = src0[ srcOffset0 + 3 ],
  6120. x1 = src1[ srcOffset1 + 0 ],
  6121. y1 = src1[ srcOffset1 + 1 ],
  6122. z1 = src1[ srcOffset1 + 2 ],
  6123. w1 = src1[ srcOffset1 + 3 ];
  6124. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  6125. var s = 1 - t,
  6126. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  6127. dir = ( cos >= 0 ? 1 : - 1 ),
  6128. sqrSin = 1 - cos * cos;
  6129. // Skip the Slerp for tiny steps to avoid numeric problems:
  6130. if ( sqrSin > Number.EPSILON ) {
  6131. var sin = Math.sqrt( sqrSin ),
  6132. len = Math.atan2( sin, cos * dir );
  6133. s = Math.sin( s * len ) / sin;
  6134. t = Math.sin( t * len ) / sin;
  6135. }
  6136. var tDir = t * dir;
  6137. x0 = x0 * s + x1 * tDir;
  6138. y0 = y0 * s + y1 * tDir;
  6139. z0 = z0 * s + z1 * tDir;
  6140. w0 = w0 * s + w1 * tDir;
  6141. // Normalize in case we just did a lerp:
  6142. if ( s === 1 - t ) {
  6143. var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  6144. x0 *= f;
  6145. y0 *= f;
  6146. z0 *= f;
  6147. w0 *= f;
  6148. }
  6149. }
  6150. dst[ dstOffset ] = x0;
  6151. dst[ dstOffset + 1 ] = y0;
  6152. dst[ dstOffset + 2 ] = z0;
  6153. dst[ dstOffset + 3 ] = w0;
  6154. }
  6155. } );
  6156. /**
  6157. * @author mrdoob / http://mrdoob.com/
  6158. * @author *kile / http://kile.stravaganza.org/
  6159. * @author philogb / http://blog.thejit.org/
  6160. * @author mikael emtinger / http://gomo.se/
  6161. * @author egraether / http://egraether.com/
  6162. * @author WestLangley / http://github.com/WestLangley
  6163. */
  6164. function Vector3( x, y, z ) {
  6165. this.x = x || 0;
  6166. this.y = y || 0;
  6167. this.z = z || 0;
  6168. }
  6169. Vector3.prototype = {
  6170. constructor: Vector3,
  6171. isVector3: true,
  6172. set: function ( x, y, z ) {
  6173. this.x = x;
  6174. this.y = y;
  6175. this.z = z;
  6176. return this;
  6177. },
  6178. setScalar: function ( scalar ) {
  6179. this.x = scalar;
  6180. this.y = scalar;
  6181. this.z = scalar;
  6182. return this;
  6183. },
  6184. setX: function ( x ) {
  6185. this.x = x;
  6186. return this;
  6187. },
  6188. setY: function ( y ) {
  6189. this.y = y;
  6190. return this;
  6191. },
  6192. setZ: function ( z ) {
  6193. this.z = z;
  6194. return this;
  6195. },
  6196. setComponent: function ( index, value ) {
  6197. switch ( index ) {
  6198. case 0: this.x = value; break;
  6199. case 1: this.y = value; break;
  6200. case 2: this.z = value; break;
  6201. default: throw new Error( 'index is out of range: ' + index );
  6202. }
  6203. return this;
  6204. },
  6205. getComponent: function ( index ) {
  6206. switch ( index ) {
  6207. case 0: return this.x;
  6208. case 1: return this.y;
  6209. case 2: return this.z;
  6210. default: throw new Error( 'index is out of range: ' + index );
  6211. }
  6212. },
  6213. clone: function () {
  6214. return new this.constructor( this.x, this.y, this.z );
  6215. },
  6216. copy: function ( v ) {
  6217. this.x = v.x;
  6218. this.y = v.y;
  6219. this.z = v.z;
  6220. return this;
  6221. },
  6222. add: function ( v, w ) {
  6223. if ( w !== undefined ) {
  6224. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  6225. return this.addVectors( v, w );
  6226. }
  6227. this.x += v.x;
  6228. this.y += v.y;
  6229. this.z += v.z;
  6230. return this;
  6231. },
  6232. addScalar: function ( s ) {
  6233. this.x += s;
  6234. this.y += s;
  6235. this.z += s;
  6236. return this;
  6237. },
  6238. addVectors: function ( a, b ) {
  6239. this.x = a.x + b.x;
  6240. this.y = a.y + b.y;
  6241. this.z = a.z + b.z;
  6242. return this;
  6243. },
  6244. addScaledVector: function ( v, s ) {
  6245. this.x += v.x * s;
  6246. this.y += v.y * s;
  6247. this.z += v.z * s;
  6248. return this;
  6249. },
  6250. sub: function ( v, w ) {
  6251. if ( w !== undefined ) {
  6252. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  6253. return this.subVectors( v, w );
  6254. }
  6255. this.x -= v.x;
  6256. this.y -= v.y;
  6257. this.z -= v.z;
  6258. return this;
  6259. },
  6260. subScalar: function ( s ) {
  6261. this.x -= s;
  6262. this.y -= s;
  6263. this.z -= s;
  6264. return this;
  6265. },
  6266. subVectors: function ( a, b ) {
  6267. this.x = a.x - b.x;
  6268. this.y = a.y - b.y;
  6269. this.z = a.z - b.z;
  6270. return this;
  6271. },
  6272. multiply: function ( v, w ) {
  6273. if ( w !== undefined ) {
  6274. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  6275. return this.multiplyVectors( v, w );
  6276. }
  6277. this.x *= v.x;
  6278. this.y *= v.y;
  6279. this.z *= v.z;
  6280. return this;
  6281. },
  6282. multiplyScalar: function ( scalar ) {
  6283. if ( isFinite( scalar ) ) {
  6284. this.x *= scalar;
  6285. this.y *= scalar;
  6286. this.z *= scalar;
  6287. } else {
  6288. this.x = 0;
  6289. this.y = 0;
  6290. this.z = 0;
  6291. }
  6292. return this;
  6293. },
  6294. multiplyVectors: function ( a, b ) {
  6295. this.x = a.x * b.x;
  6296. this.y = a.y * b.y;
  6297. this.z = a.z * b.z;
  6298. return this;
  6299. },
  6300. applyEuler: function () {
  6301. var quaternion;
  6302. return function applyEuler( euler ) {
  6303. if ( (euler && euler.isEuler) === false ) {
  6304. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  6305. }
  6306. if ( quaternion === undefined ) quaternion = new Quaternion();
  6307. return this.applyQuaternion( quaternion.setFromEuler( euler ) );
  6308. };
  6309. }(),
  6310. applyAxisAngle: function () {
  6311. var quaternion;
  6312. return function applyAxisAngle( axis, angle ) {
  6313. if ( quaternion === undefined ) quaternion = new Quaternion();
  6314. return this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  6315. };
  6316. }(),
  6317. applyMatrix3: function ( m ) {
  6318. var x = this.x, y = this.y, z = this.z;
  6319. var e = m.elements;
  6320. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  6321. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  6322. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  6323. return this;
  6324. },
  6325. applyMatrix4: function ( m ) {
  6326. var x = this.x, y = this.y, z = this.z;
  6327. var e = m.elements;
  6328. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ];
  6329. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ];
  6330. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ];
  6331. var w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ];
  6332. return this.divideScalar( w );
  6333. },
  6334. applyQuaternion: function ( q ) {
  6335. var x = this.x, y = this.y, z = this.z;
  6336. var qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  6337. // calculate quat * vector
  6338. var ix = qw * x + qy * z - qz * y;
  6339. var iy = qw * y + qz * x - qx * z;
  6340. var iz = qw * z + qx * y - qy * x;
  6341. var iw = - qx * x - qy * y - qz * z;
  6342. // calculate result * inverse quat
  6343. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  6344. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  6345. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  6346. return this;
  6347. },
  6348. project: function () {
  6349. var matrix;
  6350. return function project( camera ) {
  6351. if ( matrix === undefined ) matrix = new Matrix4();
  6352. matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) );
  6353. return this.applyMatrix4( matrix );
  6354. };
  6355. }(),
  6356. unproject: function () {
  6357. var matrix;
  6358. return function unproject( camera ) {
  6359. if ( matrix === undefined ) matrix = new Matrix4();
  6360. matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) );
  6361. return this.applyMatrix4( matrix );
  6362. };
  6363. }(),
  6364. transformDirection: function ( m ) {
  6365. // input: THREE.Matrix4 affine matrix
  6366. // vector interpreted as a direction
  6367. var x = this.x, y = this.y, z = this.z;
  6368. var e = m.elements;
  6369. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  6370. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  6371. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  6372. return this.normalize();
  6373. },
  6374. divide: function ( v ) {
  6375. this.x /= v.x;
  6376. this.y /= v.y;
  6377. this.z /= v.z;
  6378. return this;
  6379. },
  6380. divideScalar: function ( scalar ) {
  6381. return this.multiplyScalar( 1 / scalar );
  6382. },
  6383. min: function ( v ) {
  6384. this.x = Math.min( this.x, v.x );
  6385. this.y = Math.min( this.y, v.y );
  6386. this.z = Math.min( this.z, v.z );
  6387. return this;
  6388. },
  6389. max: function ( v ) {
  6390. this.x = Math.max( this.x, v.x );
  6391. this.y = Math.max( this.y, v.y );
  6392. this.z = Math.max( this.z, v.z );
  6393. return this;
  6394. },
  6395. clamp: function ( min, max ) {
  6396. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  6397. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  6398. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  6399. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  6400. return this;
  6401. },
  6402. clampScalar: function () {
  6403. var min, max;
  6404. return function clampScalar( minVal, maxVal ) {
  6405. if ( min === undefined ) {
  6406. min = new Vector3();
  6407. max = new Vector3();
  6408. }
  6409. min.set( minVal, minVal, minVal );
  6410. max.set( maxVal, maxVal, maxVal );
  6411. return this.clamp( min, max );
  6412. };
  6413. }(),
  6414. clampLength: function ( min, max ) {
  6415. var length = this.length();
  6416. return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  6417. },
  6418. floor: function () {
  6419. this.x = Math.floor( this.x );
  6420. this.y = Math.floor( this.y );
  6421. this.z = Math.floor( this.z );
  6422. return this;
  6423. },
  6424. ceil: function () {
  6425. this.x = Math.ceil( this.x );
  6426. this.y = Math.ceil( this.y );
  6427. this.z = Math.ceil( this.z );
  6428. return this;
  6429. },
  6430. round: function () {
  6431. this.x = Math.round( this.x );
  6432. this.y = Math.round( this.y );
  6433. this.z = Math.round( this.z );
  6434. return this;
  6435. },
  6436. roundToZero: function () {
  6437. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  6438. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  6439. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  6440. return this;
  6441. },
  6442. negate: function () {
  6443. this.x = - this.x;
  6444. this.y = - this.y;
  6445. this.z = - this.z;
  6446. return this;
  6447. },
  6448. dot: function ( v ) {
  6449. return this.x * v.x + this.y * v.y + this.z * v.z;
  6450. },
  6451. lengthSq: function () {
  6452. return this.x * this.x + this.y * this.y + this.z * this.z;
  6453. },
  6454. length: function () {
  6455. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  6456. },
  6457. lengthManhattan: function () {
  6458. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  6459. },
  6460. normalize: function () {
  6461. return this.divideScalar( this.length() );
  6462. },
  6463. setLength: function ( length ) {
  6464. return this.multiplyScalar( length / this.length() );
  6465. },
  6466. lerp: function ( v, alpha ) {
  6467. this.x += ( v.x - this.x ) * alpha;
  6468. this.y += ( v.y - this.y ) * alpha;
  6469. this.z += ( v.z - this.z ) * alpha;
  6470. return this;
  6471. },
  6472. lerpVectors: function ( v1, v2, alpha ) {
  6473. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  6474. },
  6475. cross: function ( v, w ) {
  6476. if ( w !== undefined ) {
  6477. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  6478. return this.crossVectors( v, w );
  6479. }
  6480. var x = this.x, y = this.y, z = this.z;
  6481. this.x = y * v.z - z * v.y;
  6482. this.y = z * v.x - x * v.z;
  6483. this.z = x * v.y - y * v.x;
  6484. return this;
  6485. },
  6486. crossVectors: function ( a, b ) {
  6487. var ax = a.x, ay = a.y, az = a.z;
  6488. var bx = b.x, by = b.y, bz = b.z;
  6489. this.x = ay * bz - az * by;
  6490. this.y = az * bx - ax * bz;
  6491. this.z = ax * by - ay * bx;
  6492. return this;
  6493. },
  6494. projectOnVector: function ( vector ) {
  6495. var scalar = vector.dot( this ) / vector.lengthSq();
  6496. return this.copy( vector ).multiplyScalar( scalar );
  6497. },
  6498. projectOnPlane: function () {
  6499. var v1;
  6500. return function projectOnPlane( planeNormal ) {
  6501. if ( v1 === undefined ) v1 = new Vector3();
  6502. v1.copy( this ).projectOnVector( planeNormal );
  6503. return this.sub( v1 );
  6504. };
  6505. }(),
  6506. reflect: function () {
  6507. // reflect incident vector off plane orthogonal to normal
  6508. // normal is assumed to have unit length
  6509. var v1;
  6510. return function reflect( normal ) {
  6511. if ( v1 === undefined ) v1 = new Vector3();
  6512. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  6513. };
  6514. }(),
  6515. angleTo: function ( v ) {
  6516. var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) );
  6517. // clamp, to handle numerical problems
  6518. return Math.acos( _Math.clamp( theta, - 1, 1 ) );
  6519. },
  6520. distanceTo: function ( v ) {
  6521. return Math.sqrt( this.distanceToSquared( v ) );
  6522. },
  6523. distanceToSquared: function ( v ) {
  6524. var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  6525. return dx * dx + dy * dy + dz * dz;
  6526. },
  6527. distanceToManhattan: function ( v ) {
  6528. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  6529. },
  6530. setFromSpherical: function( s ) {
  6531. var sinPhiRadius = Math.sin( s.phi ) * s.radius;
  6532. this.x = sinPhiRadius * Math.sin( s.theta );
  6533. this.y = Math.cos( s.phi ) * s.radius;
  6534. this.z = sinPhiRadius * Math.cos( s.theta );
  6535. return this;
  6536. },
  6537. setFromCylindrical: function( c ) {
  6538. this.x = c.radius * Math.sin( c.theta );
  6539. this.y = c.y;
  6540. this.z = c.radius * Math.cos( c.theta );
  6541. return this;
  6542. },
  6543. setFromMatrixPosition: function ( m ) {
  6544. return this.setFromMatrixColumn( m, 3 );
  6545. },
  6546. setFromMatrixScale: function ( m ) {
  6547. var sx = this.setFromMatrixColumn( m, 0 ).length();
  6548. var sy = this.setFromMatrixColumn( m, 1 ).length();
  6549. var sz = this.setFromMatrixColumn( m, 2 ).length();
  6550. this.x = sx;
  6551. this.y = sy;
  6552. this.z = sz;
  6553. return this;
  6554. },
  6555. setFromMatrixColumn: function ( m, index ) {
  6556. if ( typeof m === 'number' ) {
  6557. console.warn( 'THREE.Vector3: setFromMatrixColumn now expects ( matrix, index ).' );
  6558. var temp = m;
  6559. m = index;
  6560. index = temp;
  6561. }
  6562. return this.fromArray( m.elements, index * 4 );
  6563. },
  6564. equals: function ( v ) {
  6565. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  6566. },
  6567. fromArray: function ( array, offset ) {
  6568. if ( offset === undefined ) offset = 0;
  6569. this.x = array[ offset ];
  6570. this.y = array[ offset + 1 ];
  6571. this.z = array[ offset + 2 ];
  6572. return this;
  6573. },
  6574. toArray: function ( array, offset ) {
  6575. if ( array === undefined ) array = [];
  6576. if ( offset === undefined ) offset = 0;
  6577. array[ offset ] = this.x;
  6578. array[ offset + 1 ] = this.y;
  6579. array[ offset + 2 ] = this.z;
  6580. return array;
  6581. },
  6582. fromBufferAttribute: function ( attribute, index, offset ) {
  6583. if ( offset !== undefined ) {
  6584. console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' );
  6585. }
  6586. this.x = attribute.getX( index );
  6587. this.y = attribute.getY( index );
  6588. this.z = attribute.getZ( index );
  6589. return this;
  6590. }
  6591. };
  6592. /**
  6593. * @author mrdoob / http://mrdoob.com/
  6594. * @author supereggbert / http://www.paulbrunt.co.uk/
  6595. * @author philogb / http://blog.thejit.org/
  6596. * @author jordi_ros / http://plattsoft.com
  6597. * @author D1plo1d / http://github.com/D1plo1d
  6598. * @author alteredq / http://alteredqualia.com/
  6599. * @author mikael emtinger / http://gomo.se/
  6600. * @author timknip / http://www.floorplanner.com/
  6601. * @author bhouston / http://clara.io
  6602. * @author WestLangley / http://github.com/WestLangley
  6603. */
  6604. function Matrix4() {
  6605. this.elements = new Float32Array( [
  6606. 1, 0, 0, 0,
  6607. 0, 1, 0, 0,
  6608. 0, 0, 1, 0,
  6609. 0, 0, 0, 1
  6610. ] );
  6611. if ( arguments.length > 0 ) {
  6612. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  6613. }
  6614. }
  6615. Matrix4.prototype = {
  6616. constructor: Matrix4,
  6617. isMatrix4: true,
  6618. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  6619. var te = this.elements;
  6620. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  6621. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  6622. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  6623. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  6624. return this;
  6625. },
  6626. identity: function () {
  6627. this.set(
  6628. 1, 0, 0, 0,
  6629. 0, 1, 0, 0,
  6630. 0, 0, 1, 0,
  6631. 0, 0, 0, 1
  6632. );
  6633. return this;
  6634. },
  6635. clone: function () {
  6636. return new Matrix4().fromArray( this.elements );
  6637. },
  6638. copy: function ( m ) {
  6639. this.elements.set( m.elements );
  6640. return this;
  6641. },
  6642. copyPosition: function ( m ) {
  6643. var te = this.elements;
  6644. var me = m.elements;
  6645. te[ 12 ] = me[ 12 ];
  6646. te[ 13 ] = me[ 13 ];
  6647. te[ 14 ] = me[ 14 ];
  6648. return this;
  6649. },
  6650. extractBasis: function ( xAxis, yAxis, zAxis ) {
  6651. xAxis.setFromMatrixColumn( this, 0 );
  6652. yAxis.setFromMatrixColumn( this, 1 );
  6653. zAxis.setFromMatrixColumn( this, 2 );
  6654. return this;
  6655. },
  6656. makeBasis: function ( xAxis, yAxis, zAxis ) {
  6657. this.set(
  6658. xAxis.x, yAxis.x, zAxis.x, 0,
  6659. xAxis.y, yAxis.y, zAxis.y, 0,
  6660. xAxis.z, yAxis.z, zAxis.z, 0,
  6661. 0, 0, 0, 1
  6662. );
  6663. return this;
  6664. },
  6665. extractRotation: function () {
  6666. var v1;
  6667. return function extractRotation( m ) {
  6668. if ( v1 === undefined ) v1 = new Vector3();
  6669. var te = this.elements;
  6670. var me = m.elements;
  6671. var scaleX = 1 / v1.setFromMatrixColumn( m, 0 ).length();
  6672. var scaleY = 1 / v1.setFromMatrixColumn( m, 1 ).length();
  6673. var scaleZ = 1 / v1.setFromMatrixColumn( m, 2 ).length();
  6674. te[ 0 ] = me[ 0 ] * scaleX;
  6675. te[ 1 ] = me[ 1 ] * scaleX;
  6676. te[ 2 ] = me[ 2 ] * scaleX;
  6677. te[ 4 ] = me[ 4 ] * scaleY;
  6678. te[ 5 ] = me[ 5 ] * scaleY;
  6679. te[ 6 ] = me[ 6 ] * scaleY;
  6680. te[ 8 ] = me[ 8 ] * scaleZ;
  6681. te[ 9 ] = me[ 9 ] * scaleZ;
  6682. te[ 10 ] = me[ 10 ] * scaleZ;
  6683. return this;
  6684. };
  6685. }(),
  6686. makeRotationFromEuler: function ( euler ) {
  6687. if ( (euler && euler.isEuler) === false ) {
  6688. console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  6689. }
  6690. var te = this.elements;
  6691. var x = euler.x, y = euler.y, z = euler.z;
  6692. var a = Math.cos( x ), b = Math.sin( x );
  6693. var c = Math.cos( y ), d = Math.sin( y );
  6694. var e = Math.cos( z ), f = Math.sin( z );
  6695. if ( euler.order === 'XYZ' ) {
  6696. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  6697. te[ 0 ] = c * e;
  6698. te[ 4 ] = - c * f;
  6699. te[ 8 ] = d;
  6700. te[ 1 ] = af + be * d;
  6701. te[ 5 ] = ae - bf * d;
  6702. te[ 9 ] = - b * c;
  6703. te[ 2 ] = bf - ae * d;
  6704. te[ 6 ] = be + af * d;
  6705. te[ 10 ] = a * c;
  6706. } else if ( euler.order === 'YXZ' ) {
  6707. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  6708. te[ 0 ] = ce + df * b;
  6709. te[ 4 ] = de * b - cf;
  6710. te[ 8 ] = a * d;
  6711. te[ 1 ] = a * f;
  6712. te[ 5 ] = a * e;
  6713. te[ 9 ] = - b;
  6714. te[ 2 ] = cf * b - de;
  6715. te[ 6 ] = df + ce * b;
  6716. te[ 10 ] = a * c;
  6717. } else if ( euler.order === 'ZXY' ) {
  6718. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  6719. te[ 0 ] = ce - df * b;
  6720. te[ 4 ] = - a * f;
  6721. te[ 8 ] = de + cf * b;
  6722. te[ 1 ] = cf + de * b;
  6723. te[ 5 ] = a * e;
  6724. te[ 9 ] = df - ce * b;
  6725. te[ 2 ] = - a * d;
  6726. te[ 6 ] = b;
  6727. te[ 10 ] = a * c;
  6728. } else if ( euler.order === 'ZYX' ) {
  6729. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  6730. te[ 0 ] = c * e;
  6731. te[ 4 ] = be * d - af;
  6732. te[ 8 ] = ae * d + bf;
  6733. te[ 1 ] = c * f;
  6734. te[ 5 ] = bf * d + ae;
  6735. te[ 9 ] = af * d - be;
  6736. te[ 2 ] = - d;
  6737. te[ 6 ] = b * c;
  6738. te[ 10 ] = a * c;
  6739. } else if ( euler.order === 'YZX' ) {
  6740. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  6741. te[ 0 ] = c * e;
  6742. te[ 4 ] = bd - ac * f;
  6743. te[ 8 ] = bc * f + ad;
  6744. te[ 1 ] = f;
  6745. te[ 5 ] = a * e;
  6746. te[ 9 ] = - b * e;
  6747. te[ 2 ] = - d * e;
  6748. te[ 6 ] = ad * f + bc;
  6749. te[ 10 ] = ac - bd * f;
  6750. } else if ( euler.order === 'XZY' ) {
  6751. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  6752. te[ 0 ] = c * e;
  6753. te[ 4 ] = - f;
  6754. te[ 8 ] = d * e;
  6755. te[ 1 ] = ac * f + bd;
  6756. te[ 5 ] = a * e;
  6757. te[ 9 ] = ad * f - bc;
  6758. te[ 2 ] = bc * f - ad;
  6759. te[ 6 ] = b * e;
  6760. te[ 10 ] = bd * f + ac;
  6761. }
  6762. // last column
  6763. te[ 3 ] = 0;
  6764. te[ 7 ] = 0;
  6765. te[ 11 ] = 0;
  6766. // bottom row
  6767. te[ 12 ] = 0;
  6768. te[ 13 ] = 0;
  6769. te[ 14 ] = 0;
  6770. te[ 15 ] = 1;
  6771. return this;
  6772. },
  6773. makeRotationFromQuaternion: function ( q ) {
  6774. var te = this.elements;
  6775. var x = q.x, y = q.y, z = q.z, w = q.w;
  6776. var x2 = x + x, y2 = y + y, z2 = z + z;
  6777. var xx = x * x2, xy = x * y2, xz = x * z2;
  6778. var yy = y * y2, yz = y * z2, zz = z * z2;
  6779. var wx = w * x2, wy = w * y2, wz = w * z2;
  6780. te[ 0 ] = 1 - ( yy + zz );
  6781. te[ 4 ] = xy - wz;
  6782. te[ 8 ] = xz + wy;
  6783. te[ 1 ] = xy + wz;
  6784. te[ 5 ] = 1 - ( xx + zz );
  6785. te[ 9 ] = yz - wx;
  6786. te[ 2 ] = xz - wy;
  6787. te[ 6 ] = yz + wx;
  6788. te[ 10 ] = 1 - ( xx + yy );
  6789. // last column
  6790. te[ 3 ] = 0;
  6791. te[ 7 ] = 0;
  6792. te[ 11 ] = 0;
  6793. // bottom row
  6794. te[ 12 ] = 0;
  6795. te[ 13 ] = 0;
  6796. te[ 14 ] = 0;
  6797. te[ 15 ] = 1;
  6798. return this;
  6799. },
  6800. lookAt: function () {
  6801. var x, y, z;
  6802. return function lookAt( eye, target, up ) {
  6803. if ( x === undefined ) {
  6804. x = new Vector3();
  6805. y = new Vector3();
  6806. z = new Vector3();
  6807. }
  6808. var te = this.elements;
  6809. z.subVectors( eye, target ).normalize();
  6810. if ( z.lengthSq() === 0 ) {
  6811. z.z = 1;
  6812. }
  6813. x.crossVectors( up, z ).normalize();
  6814. if ( x.lengthSq() === 0 ) {
  6815. z.z += 0.0001;
  6816. x.crossVectors( up, z ).normalize();
  6817. }
  6818. y.crossVectors( z, x );
  6819. te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x;
  6820. te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y;
  6821. te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z;
  6822. return this;
  6823. };
  6824. }(),
  6825. multiply: function ( m, n ) {
  6826. if ( n !== undefined ) {
  6827. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  6828. return this.multiplyMatrices( m, n );
  6829. }
  6830. return this.multiplyMatrices( this, m );
  6831. },
  6832. premultiply: function ( m ) {
  6833. return this.multiplyMatrices( m, this );
  6834. },
  6835. multiplyMatrices: function ( a, b ) {
  6836. var ae = a.elements;
  6837. var be = b.elements;
  6838. var te = this.elements;
  6839. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  6840. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  6841. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  6842. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  6843. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  6844. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  6845. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  6846. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  6847. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  6848. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  6849. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  6850. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  6851. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  6852. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  6853. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  6854. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  6855. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  6856. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  6857. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  6858. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  6859. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  6860. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  6861. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  6862. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  6863. return this;
  6864. },
  6865. multiplyToArray: function ( a, b, r ) {
  6866. var te = this.elements;
  6867. this.multiplyMatrices( a, b );
  6868. r[ 0 ] = te[ 0 ]; r[ 1 ] = te[ 1 ]; r[ 2 ] = te[ 2 ]; r[ 3 ] = te[ 3 ];
  6869. r[ 4 ] = te[ 4 ]; r[ 5 ] = te[ 5 ]; r[ 6 ] = te[ 6 ]; r[ 7 ] = te[ 7 ];
  6870. r[ 8 ] = te[ 8 ]; r[ 9 ] = te[ 9 ]; r[ 10 ] = te[ 10 ]; r[ 11 ] = te[ 11 ];
  6871. r[ 12 ] = te[ 12 ]; r[ 13 ] = te[ 13 ]; r[ 14 ] = te[ 14 ]; r[ 15 ] = te[ 15 ];
  6872. return this;
  6873. },
  6874. multiplyScalar: function ( s ) {
  6875. var te = this.elements;
  6876. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  6877. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  6878. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  6879. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  6880. return this;
  6881. },
  6882. applyToBufferAttribute: function () {
  6883. var v1;
  6884. return function applyToBufferAttribute( attribute ) {
  6885. if ( v1 === undefined ) v1 = new Vector3();
  6886. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  6887. v1.x = attribute.getX( i );
  6888. v1.y = attribute.getY( i );
  6889. v1.z = attribute.getZ( i );
  6890. v1.applyMatrix4( this );
  6891. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  6892. }
  6893. return attribute;
  6894. };
  6895. }(),
  6896. determinant: function () {
  6897. var te = this.elements;
  6898. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  6899. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  6900. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  6901. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  6902. //TODO: make this more efficient
  6903. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  6904. return (
  6905. n41 * (
  6906. + n14 * n23 * n32
  6907. - n13 * n24 * n32
  6908. - n14 * n22 * n33
  6909. + n12 * n24 * n33
  6910. + n13 * n22 * n34
  6911. - n12 * n23 * n34
  6912. ) +
  6913. n42 * (
  6914. + n11 * n23 * n34
  6915. - n11 * n24 * n33
  6916. + n14 * n21 * n33
  6917. - n13 * n21 * n34
  6918. + n13 * n24 * n31
  6919. - n14 * n23 * n31
  6920. ) +
  6921. n43 * (
  6922. + n11 * n24 * n32
  6923. - n11 * n22 * n34
  6924. - n14 * n21 * n32
  6925. + n12 * n21 * n34
  6926. + n14 * n22 * n31
  6927. - n12 * n24 * n31
  6928. ) +
  6929. n44 * (
  6930. - n13 * n22 * n31
  6931. - n11 * n23 * n32
  6932. + n11 * n22 * n33
  6933. + n13 * n21 * n32
  6934. - n12 * n21 * n33
  6935. + n12 * n23 * n31
  6936. )
  6937. );
  6938. },
  6939. transpose: function () {
  6940. var te = this.elements;
  6941. var tmp;
  6942. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  6943. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  6944. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  6945. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  6946. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  6947. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  6948. return this;
  6949. },
  6950. setPosition: function ( v ) {
  6951. var te = this.elements;
  6952. te[ 12 ] = v.x;
  6953. te[ 13 ] = v.y;
  6954. te[ 14 ] = v.z;
  6955. return this;
  6956. },
  6957. getInverse: function ( m, throwOnDegenerate ) {
  6958. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  6959. var te = this.elements,
  6960. me = m.elements,
  6961. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ],
  6962. n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ],
  6963. n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ],
  6964. n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ],
  6965. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  6966. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  6967. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  6968. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  6969. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  6970. if ( det === 0 ) {
  6971. var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0";
  6972. if ( throwOnDegenerate === true ) {
  6973. throw new Error( msg );
  6974. } else {
  6975. console.warn( msg );
  6976. }
  6977. return this.identity();
  6978. }
  6979. var detInv = 1 / det;
  6980. te[ 0 ] = t11 * detInv;
  6981. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  6982. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  6983. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  6984. te[ 4 ] = t12 * detInv;
  6985. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  6986. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  6987. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  6988. te[ 8 ] = t13 * detInv;
  6989. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  6990. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  6991. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  6992. te[ 12 ] = t14 * detInv;
  6993. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  6994. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  6995. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  6996. return this;
  6997. },
  6998. scale: function ( v ) {
  6999. var te = this.elements;
  7000. var x = v.x, y = v.y, z = v.z;
  7001. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  7002. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  7003. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  7004. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  7005. return this;
  7006. },
  7007. getMaxScaleOnAxis: function () {
  7008. var te = this.elements;
  7009. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  7010. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  7011. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  7012. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  7013. },
  7014. makeTranslation: function ( x, y, z ) {
  7015. this.set(
  7016. 1, 0, 0, x,
  7017. 0, 1, 0, y,
  7018. 0, 0, 1, z,
  7019. 0, 0, 0, 1
  7020. );
  7021. return this;
  7022. },
  7023. makeRotationX: function ( theta ) {
  7024. var c = Math.cos( theta ), s = Math.sin( theta );
  7025. this.set(
  7026. 1, 0, 0, 0,
  7027. 0, c, - s, 0,
  7028. 0, s, c, 0,
  7029. 0, 0, 0, 1
  7030. );
  7031. return this;
  7032. },
  7033. makeRotationY: function ( theta ) {
  7034. var c = Math.cos( theta ), s = Math.sin( theta );
  7035. this.set(
  7036. c, 0, s, 0,
  7037. 0, 1, 0, 0,
  7038. - s, 0, c, 0,
  7039. 0, 0, 0, 1
  7040. );
  7041. return this;
  7042. },
  7043. makeRotationZ: function ( theta ) {
  7044. var c = Math.cos( theta ), s = Math.sin( theta );
  7045. this.set(
  7046. c, - s, 0, 0,
  7047. s, c, 0, 0,
  7048. 0, 0, 1, 0,
  7049. 0, 0, 0, 1
  7050. );
  7051. return this;
  7052. },
  7053. makeRotationAxis: function ( axis, angle ) {
  7054. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  7055. var c = Math.cos( angle );
  7056. var s = Math.sin( angle );
  7057. var t = 1 - c;
  7058. var x = axis.x, y = axis.y, z = axis.z;
  7059. var tx = t * x, ty = t * y;
  7060. this.set(
  7061. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  7062. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  7063. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  7064. 0, 0, 0, 1
  7065. );
  7066. return this;
  7067. },
  7068. makeScale: function ( x, y, z ) {
  7069. this.set(
  7070. x, 0, 0, 0,
  7071. 0, y, 0, 0,
  7072. 0, 0, z, 0,
  7073. 0, 0, 0, 1
  7074. );
  7075. return this;
  7076. },
  7077. makeShear: function ( x, y, z ) {
  7078. this.set(
  7079. 1, y, z, 0,
  7080. x, 1, z, 0,
  7081. x, y, 1, 0,
  7082. 0, 0, 0, 1
  7083. );
  7084. return this;
  7085. },
  7086. compose: function ( position, quaternion, scale ) {
  7087. this.makeRotationFromQuaternion( quaternion );
  7088. this.scale( scale );
  7089. this.setPosition( position );
  7090. return this;
  7091. },
  7092. decompose: function () {
  7093. var vector, matrix;
  7094. return function decompose( position, quaternion, scale ) {
  7095. if ( vector === undefined ) {
  7096. vector = new Vector3();
  7097. matrix = new Matrix4();
  7098. }
  7099. var te = this.elements;
  7100. var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  7101. var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  7102. var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  7103. // if determine is negative, we need to invert one scale
  7104. var det = this.determinant();
  7105. if ( det < 0 ) {
  7106. sx = - sx;
  7107. }
  7108. position.x = te[ 12 ];
  7109. position.y = te[ 13 ];
  7110. position.z = te[ 14 ];
  7111. // scale the rotation part
  7112. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  7113. var invSX = 1 / sx;
  7114. var invSY = 1 / sy;
  7115. var invSZ = 1 / sz;
  7116. matrix.elements[ 0 ] *= invSX;
  7117. matrix.elements[ 1 ] *= invSX;
  7118. matrix.elements[ 2 ] *= invSX;
  7119. matrix.elements[ 4 ] *= invSY;
  7120. matrix.elements[ 5 ] *= invSY;
  7121. matrix.elements[ 6 ] *= invSY;
  7122. matrix.elements[ 8 ] *= invSZ;
  7123. matrix.elements[ 9 ] *= invSZ;
  7124. matrix.elements[ 10 ] *= invSZ;
  7125. quaternion.setFromRotationMatrix( matrix );
  7126. scale.x = sx;
  7127. scale.y = sy;
  7128. scale.z = sz;
  7129. return this;
  7130. };
  7131. }(),
  7132. makePerspective: function ( left, right, top, bottom, near, far ) {
  7133. if ( far === undefined ) {
  7134. console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' );
  7135. }
  7136. var te = this.elements;
  7137. var x = 2 * near / ( right - left );
  7138. var y = 2 * near / ( top - bottom );
  7139. var a = ( right + left ) / ( right - left );
  7140. var b = ( top + bottom ) / ( top - bottom );
  7141. var c = - ( far + near ) / ( far - near );
  7142. var d = - 2 * far * near / ( far - near );
  7143. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  7144. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  7145. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  7146. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  7147. return this;
  7148. },
  7149. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  7150. var te = this.elements;
  7151. var w = 1.0 / ( right - left );
  7152. var h = 1.0 / ( top - bottom );
  7153. var p = 1.0 / ( far - near );
  7154. var x = ( right + left ) * w;
  7155. var y = ( top + bottom ) * h;
  7156. var z = ( far + near ) * p;
  7157. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  7158. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  7159. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  7160. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  7161. return this;
  7162. },
  7163. equals: function ( matrix ) {
  7164. var te = this.elements;
  7165. var me = matrix.elements;
  7166. for ( var i = 0; i < 16; i ++ ) {
  7167. if ( te[ i ] !== me[ i ] ) return false;
  7168. }
  7169. return true;
  7170. },
  7171. fromArray: function ( array, offset ) {
  7172. if ( offset === undefined ) offset = 0;
  7173. for( var i = 0; i < 16; i ++ ) {
  7174. this.elements[ i ] = array[ i + offset ];
  7175. }
  7176. return this;
  7177. },
  7178. toArray: function ( array, offset ) {
  7179. if ( array === undefined ) array = [];
  7180. if ( offset === undefined ) offset = 0;
  7181. var te = this.elements;
  7182. array[ offset ] = te[ 0 ];
  7183. array[ offset + 1 ] = te[ 1 ];
  7184. array[ offset + 2 ] = te[ 2 ];
  7185. array[ offset + 3 ] = te[ 3 ];
  7186. array[ offset + 4 ] = te[ 4 ];
  7187. array[ offset + 5 ] = te[ 5 ];
  7188. array[ offset + 6 ] = te[ 6 ];
  7189. array[ offset + 7 ] = te[ 7 ];
  7190. array[ offset + 8 ] = te[ 8 ];
  7191. array[ offset + 9 ] = te[ 9 ];
  7192. array[ offset + 10 ] = te[ 10 ];
  7193. array[ offset + 11 ] = te[ 11 ];
  7194. array[ offset + 12 ] = te[ 12 ];
  7195. array[ offset + 13 ] = te[ 13 ];
  7196. array[ offset + 14 ] = te[ 14 ];
  7197. array[ offset + 15 ] = te[ 15 ];
  7198. return array;
  7199. }
  7200. };
  7201. /**
  7202. * @author mrdoob / http://mrdoob.com/
  7203. */
  7204. function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  7205. images = images !== undefined ? images : [];
  7206. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7207. Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  7208. this.flipY = false;
  7209. }
  7210. CubeTexture.prototype = Object.create( Texture.prototype );
  7211. CubeTexture.prototype.constructor = CubeTexture;
  7212. CubeTexture.prototype.isCubeTexture = true;
  7213. Object.defineProperty( CubeTexture.prototype, 'images', {
  7214. get: function () {
  7215. return this.image;
  7216. },
  7217. set: function ( value ) {
  7218. this.image = value;
  7219. }
  7220. } );
  7221. /**
  7222. * @author tschw
  7223. *
  7224. * Uniforms of a program.
  7225. * Those form a tree structure with a special top-level container for the root,
  7226. * which you get by calling 'new WebGLUniforms( gl, program, renderer )'.
  7227. *
  7228. *
  7229. * Properties of inner nodes including the top-level container:
  7230. *
  7231. * .seq - array of nested uniforms
  7232. * .map - nested uniforms by name
  7233. *
  7234. *
  7235. * Methods of all nodes except the top-level container:
  7236. *
  7237. * .setValue( gl, value, [renderer] )
  7238. *
  7239. * uploads a uniform value(s)
  7240. * the 'renderer' parameter is needed for sampler uniforms
  7241. *
  7242. *
  7243. * Static methods of the top-level container (renderer factorizations):
  7244. *
  7245. * .upload( gl, seq, values, renderer )
  7246. *
  7247. * sets uniforms in 'seq' to 'values[id].value'
  7248. *
  7249. * .seqWithValue( seq, values ) : filteredSeq
  7250. *
  7251. * filters 'seq' entries with corresponding entry in values
  7252. *
  7253. *
  7254. * Methods of the top-level container (renderer factorizations):
  7255. *
  7256. * .setValue( gl, name, value )
  7257. *
  7258. * sets uniform with name 'name' to 'value'
  7259. *
  7260. * .set( gl, obj, prop )
  7261. *
  7262. * sets uniform from object and property with same name than uniform
  7263. *
  7264. * .setOptional( gl, obj, prop )
  7265. *
  7266. * like .set for an optional property of the object
  7267. *
  7268. */
  7269. var emptyTexture = new Texture();
  7270. var emptyCubeTexture = new CubeTexture();
  7271. // --- Base for inner nodes (including the root) ---
  7272. function UniformContainer() {
  7273. this.seq = [];
  7274. this.map = {};
  7275. }
  7276. // --- Utilities ---
  7277. // Array Caches (provide typed arrays for temporary by size)
  7278. var arrayCacheF32 = [];
  7279. var arrayCacheI32 = [];
  7280. // Flattening for arrays of vectors and matrices
  7281. function flatten( array, nBlocks, blockSize ) {
  7282. var firstElem = array[ 0 ];
  7283. if ( firstElem <= 0 || firstElem > 0 ) return array;
  7284. // unoptimized: ! isNaN( firstElem )
  7285. // see http://jacksondunstan.com/articles/983
  7286. var n = nBlocks * blockSize,
  7287. r = arrayCacheF32[ n ];
  7288. if ( r === undefined ) {
  7289. r = new Float32Array( n );
  7290. arrayCacheF32[ n ] = r;
  7291. }
  7292. if ( nBlocks !== 0 ) {
  7293. firstElem.toArray( r, 0 );
  7294. for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) {
  7295. offset += blockSize;
  7296. array[ i ].toArray( r, offset );
  7297. }
  7298. }
  7299. return r;
  7300. }
  7301. // Texture unit allocation
  7302. function allocTexUnits( renderer, n ) {
  7303. var r = arrayCacheI32[ n ];
  7304. if ( r === undefined ) {
  7305. r = new Int32Array( n );
  7306. arrayCacheI32[ n ] = r;
  7307. }
  7308. for ( var i = 0; i !== n; ++ i )
  7309. r[ i ] = renderer.allocTextureUnit();
  7310. return r;
  7311. }
  7312. // --- Setters ---
  7313. // Note: Defining these methods externally, because they come in a bunch
  7314. // and this way their names minify.
  7315. // Single scalar
  7316. function setValue1f( gl, v ) { gl.uniform1f( this.addr, v ); }
  7317. function setValue1i( gl, v ) { gl.uniform1i( this.addr, v ); }
  7318. // Single float vector (from flat array or THREE.VectorN)
  7319. function setValue2fv( gl, v ) {
  7320. if ( v.x === undefined ) gl.uniform2fv( this.addr, v );
  7321. else gl.uniform2f( this.addr, v.x, v.y );
  7322. }
  7323. function setValue3fv( gl, v ) {
  7324. if ( v.x !== undefined )
  7325. gl.uniform3f( this.addr, v.x, v.y, v.z );
  7326. else if ( v.r !== undefined )
  7327. gl.uniform3f( this.addr, v.r, v.g, v.b );
  7328. else
  7329. gl.uniform3fv( this.addr, v );
  7330. }
  7331. function setValue4fv( gl, v ) {
  7332. if ( v.x === undefined ) gl.uniform4fv( this.addr, v );
  7333. else gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  7334. }
  7335. // Single matrix (from flat array or MatrixN)
  7336. function setValue2fm( gl, v ) {
  7337. gl.uniformMatrix2fv( this.addr, false, v.elements || v );
  7338. }
  7339. function setValue3fm( gl, v ) {
  7340. gl.uniformMatrix3fv( this.addr, false, v.elements || v );
  7341. }
  7342. function setValue4fm( gl, v ) {
  7343. gl.uniformMatrix4fv( this.addr, false, v.elements || v );
  7344. }
  7345. // Single texture (2D / Cube)
  7346. function setValueT1( gl, v, renderer ) {
  7347. var unit = renderer.allocTextureUnit();
  7348. gl.uniform1i( this.addr, unit );
  7349. renderer.setTexture2D( v || emptyTexture, unit );
  7350. }
  7351. function setValueT6( gl, v, renderer ) {
  7352. var unit = renderer.allocTextureUnit();
  7353. gl.uniform1i( this.addr, unit );
  7354. renderer.setTextureCube( v || emptyCubeTexture, unit );
  7355. }
  7356. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  7357. function setValue2iv( gl, v ) { gl.uniform2iv( this.addr, v ); }
  7358. function setValue3iv( gl, v ) { gl.uniform3iv( this.addr, v ); }
  7359. function setValue4iv( gl, v ) { gl.uniform4iv( this.addr, v ); }
  7360. // Helper to pick the right setter for the singular case
  7361. function getSingularSetter( type ) {
  7362. switch ( type ) {
  7363. case 0x1406: return setValue1f; // FLOAT
  7364. case 0x8b50: return setValue2fv; // _VEC2
  7365. case 0x8b51: return setValue3fv; // _VEC3
  7366. case 0x8b52: return setValue4fv; // _VEC4
  7367. case 0x8b5a: return setValue2fm; // _MAT2
  7368. case 0x8b5b: return setValue3fm; // _MAT3
  7369. case 0x8b5c: return setValue4fm; // _MAT4
  7370. case 0x8b5e: return setValueT1; // SAMPLER_2D
  7371. case 0x8b60: return setValueT6; // SAMPLER_CUBE
  7372. case 0x1404: case 0x8b56: return setValue1i; // INT, BOOL
  7373. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  7374. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  7375. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  7376. }
  7377. }
  7378. // Array of scalars
  7379. function setValue1fv( gl, v ) { gl.uniform1fv( this.addr, v ); }
  7380. function setValue1iv( gl, v ) { gl.uniform1iv( this.addr, v ); }
  7381. // Array of vectors (flat or from THREE classes)
  7382. function setValueV2a( gl, v ) {
  7383. gl.uniform2fv( this.addr, flatten( v, this.size, 2 ) );
  7384. }
  7385. function setValueV3a( gl, v ) {
  7386. gl.uniform3fv( this.addr, flatten( v, this.size, 3 ) );
  7387. }
  7388. function setValueV4a( gl, v ) {
  7389. gl.uniform4fv( this.addr, flatten( v, this.size, 4 ) );
  7390. }
  7391. // Array of matrices (flat or from THREE clases)
  7392. function setValueM2a( gl, v ) {
  7393. gl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) );
  7394. }
  7395. function setValueM3a( gl, v ) {
  7396. gl.uniformMatrix3fv( this.addr, false, flatten( v, this.size, 9 ) );
  7397. }
  7398. function setValueM4a( gl, v ) {
  7399. gl.uniformMatrix4fv( this.addr, false, flatten( v, this.size, 16 ) );
  7400. }
  7401. // Array of textures (2D / Cube)
  7402. function setValueT1a( gl, v, renderer ) {
  7403. var n = v.length,
  7404. units = allocTexUnits( renderer, n );
  7405. gl.uniform1iv( this.addr, units );
  7406. for ( var i = 0; i !== n; ++ i ) {
  7407. renderer.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  7408. }
  7409. }
  7410. function setValueT6a( gl, v, renderer ) {
  7411. var n = v.length,
  7412. units = allocTexUnits( renderer, n );
  7413. gl.uniform1iv( this.addr, units );
  7414. for ( var i = 0; i !== n; ++ i ) {
  7415. renderer.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  7416. }
  7417. }
  7418. // Helper to pick the right setter for a pure (bottom-level) array
  7419. function getPureArraySetter( type ) {
  7420. switch ( type ) {
  7421. case 0x1406: return setValue1fv; // FLOAT
  7422. case 0x8b50: return setValueV2a; // _VEC2
  7423. case 0x8b51: return setValueV3a; // _VEC3
  7424. case 0x8b52: return setValueV4a; // _VEC4
  7425. case 0x8b5a: return setValueM2a; // _MAT2
  7426. case 0x8b5b: return setValueM3a; // _MAT3
  7427. case 0x8b5c: return setValueM4a; // _MAT4
  7428. case 0x8b5e: return setValueT1a; // SAMPLER_2D
  7429. case 0x8b60: return setValueT6a; // SAMPLER_CUBE
  7430. case 0x1404: case 0x8b56: return setValue1iv; // INT, BOOL
  7431. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  7432. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  7433. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  7434. }
  7435. }
  7436. // --- Uniform Classes ---
  7437. function SingleUniform( id, activeInfo, addr ) {
  7438. this.id = id;
  7439. this.addr = addr;
  7440. this.setValue = getSingularSetter( activeInfo.type );
  7441. // this.path = activeInfo.name; // DEBUG
  7442. }
  7443. function PureArrayUniform( id, activeInfo, addr ) {
  7444. this.id = id;
  7445. this.addr = addr;
  7446. this.size = activeInfo.size;
  7447. this.setValue = getPureArraySetter( activeInfo.type );
  7448. // this.path = activeInfo.name; // DEBUG
  7449. }
  7450. function StructuredUniform( id ) {
  7451. this.id = id;
  7452. UniformContainer.call( this ); // mix-in
  7453. }
  7454. StructuredUniform.prototype.setValue = function( gl, value ) {
  7455. // Note: Don't need an extra 'renderer' parameter, since samplers
  7456. // are not allowed in structured uniforms.
  7457. var seq = this.seq;
  7458. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  7459. var u = seq[ i ];
  7460. u.setValue( gl, value[ u.id ] );
  7461. }
  7462. };
  7463. // --- Top-level ---
  7464. // Parser - builds up the property tree from the path strings
  7465. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g;
  7466. // extracts
  7467. // - the identifier (member name or array index)
  7468. // - followed by an optional right bracket (found when array index)
  7469. // - followed by an optional left bracket or dot (type of subscript)
  7470. //
  7471. // Note: These portions can be read in a non-overlapping fashion and
  7472. // allow straightforward parsing of the hierarchy that WebGL encodes
  7473. // in the uniform names.
  7474. function addUniform( container, uniformObject ) {
  7475. container.seq.push( uniformObject );
  7476. container.map[ uniformObject.id ] = uniformObject;
  7477. }
  7478. function parseUniform( activeInfo, addr, container ) {
  7479. var path = activeInfo.name,
  7480. pathLength = path.length;
  7481. // reset RegExp object, because of the early exit of a previous run
  7482. RePathPart.lastIndex = 0;
  7483. for (; ;) {
  7484. var match = RePathPart.exec( path ),
  7485. matchEnd = RePathPart.lastIndex,
  7486. id = match[ 1 ],
  7487. idIsIndex = match[ 2 ] === ']',
  7488. subscript = match[ 3 ];
  7489. if ( idIsIndex ) id = id | 0; // convert to integer
  7490. if ( subscript === undefined ||
  7491. subscript === '[' && matchEnd + 2 === pathLength ) {
  7492. // bare name or "pure" bottom-level array "[0]" suffix
  7493. addUniform( container, subscript === undefined ?
  7494. new SingleUniform( id, activeInfo, addr ) :
  7495. new PureArrayUniform( id, activeInfo, addr ) );
  7496. break;
  7497. } else {
  7498. // step into inner node / create it in case it doesn't exist
  7499. var map = container.map,
  7500. next = map[ id ];
  7501. if ( next === undefined ) {
  7502. next = new StructuredUniform( id );
  7503. addUniform( container, next );
  7504. }
  7505. container = next;
  7506. }
  7507. }
  7508. }
  7509. // Root Container
  7510. function WebGLUniforms( gl, program, renderer ) {
  7511. UniformContainer.call( this );
  7512. this.renderer = renderer;
  7513. var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  7514. for ( var i = 0; i < n; ++ i ) {
  7515. var info = gl.getActiveUniform( program, i ),
  7516. path = info.name,
  7517. addr = gl.getUniformLocation( program, path );
  7518. parseUniform( info, addr, this );
  7519. }
  7520. }
  7521. WebGLUniforms.prototype.setValue = function( gl, name, value ) {
  7522. var u = this.map[ name ];
  7523. if ( u !== undefined ) u.setValue( gl, value, this.renderer );
  7524. };
  7525. WebGLUniforms.prototype.set = function( gl, object, name ) {
  7526. var u = this.map[ name ];
  7527. if ( u !== undefined ) u.setValue( gl, object[ name ], this.renderer );
  7528. };
  7529. WebGLUniforms.prototype.setOptional = function( gl, object, name ) {
  7530. var v = object[ name ];
  7531. if ( v !== undefined ) this.setValue( gl, name, v );
  7532. };
  7533. // Static interface
  7534. WebGLUniforms.upload = function( gl, seq, values, renderer ) {
  7535. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  7536. var u = seq[ i ],
  7537. v = values[ u.id ];
  7538. if ( v.needsUpdate !== false ) {
  7539. // note: always updating when .needsUpdate is undefined
  7540. u.setValue( gl, v.value, renderer );
  7541. }
  7542. }
  7543. };
  7544. WebGLUniforms.seqWithValue = function( seq, values ) {
  7545. var r = [];
  7546. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  7547. var u = seq[ i ];
  7548. if ( u.id in values ) r.push( u );
  7549. }
  7550. return r;
  7551. };
  7552. /**
  7553. * Uniform Utilities
  7554. */
  7555. var UniformsUtils = {
  7556. merge: function ( uniforms ) {
  7557. var merged = {};
  7558. for ( var u = 0; u < uniforms.length; u ++ ) {
  7559. var tmp = this.clone( uniforms[ u ] );
  7560. for ( var p in tmp ) {
  7561. merged[ p ] = tmp[ p ];
  7562. }
  7563. }
  7564. return merged;
  7565. },
  7566. clone: function ( uniforms_src ) {
  7567. var uniforms_dst = {};
  7568. for ( var u in uniforms_src ) {
  7569. uniforms_dst[ u ] = {};
  7570. for ( var p in uniforms_src[ u ] ) {
  7571. var parameter_src = uniforms_src[ u ][ p ];
  7572. if ( parameter_src && ( parameter_src.isColor ||
  7573. parameter_src.isMatrix3 || parameter_src.isMatrix4 ||
  7574. parameter_src.isVector2 || parameter_src.isVector3 || parameter_src.isVector4 ||
  7575. parameter_src.isTexture ) ) {
  7576. uniforms_dst[ u ][ p ] = parameter_src.clone();
  7577. } else if ( Array.isArray( parameter_src ) ) {
  7578. uniforms_dst[ u ][ p ] = parameter_src.slice();
  7579. } else {
  7580. uniforms_dst[ u ][ p ] = parameter_src;
  7581. }
  7582. }
  7583. }
  7584. return uniforms_dst;
  7585. }
  7586. };
  7587. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n";
  7588. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif\n";
  7589. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n";
  7590. 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";
  7591. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7592. var begin_vertex = "\nvec3 transformed = vec3( position );\n";
  7593. var beginnormal_vertex = "\nvec3 objectNormal = vec3( normal );\n";
  7594. 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";
  7595. 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";
  7596. 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";
  7597. 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";
  7598. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n";
  7599. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n";
  7600. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7601. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif\n";
  7602. var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  7603. var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";
  7604. 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";
  7605. 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";
  7606. var defaultnormal_vertex = "#ifdef FLIP_SIDED\n\tobjectNormal = -objectNormal;\n#endif\nvec3 transformedNormal = normalMatrix * objectNormal;\n";
  7607. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif\n";
  7608. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normal * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n";
  7609. 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";
  7610. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif\n";
  7611. var encodings_fragment = " gl_FragColor = linearToOutputTexel( gl_FragColor );\n";
  7612. 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";
  7613. 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";
  7614. 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";
  7615. 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";
  7616. 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";
  7617. var fog_vertex = "\n#ifdef USE_FOG\nfogDepth = -mvPosition.z;\n#endif";
  7618. var fog_pars_vertex = "#ifdef USE_FOG\n varying float fogDepth;\n#endif\n";
  7619. 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";
  7620. 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";
  7621. 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";
  7622. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n";
  7623. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7624. 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";
  7625. 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";
  7626. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n";
  7627. 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";
  7628. 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";
  7629. 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";
  7630. 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";
  7631. var logdepthbuf_fragment = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\tgl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n#endif";
  7632. 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";
  7633. 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";
  7634. 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";
  7635. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif\n";
  7636. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n";
  7637. 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";
  7638. var map_particle_pars_fragment = "#ifdef USE_MAP\n\tuniform vec4 offsetRepeat;\n\tuniform sampler2D map;\n#endif\n";
  7639. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.r;\n#endif\n";
  7640. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  7641. 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";
  7642. 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";
  7643. 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";
  7644. 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";
  7645. 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";
  7646. 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";
  7647. 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";
  7648. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif\n";
  7649. 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";
  7650. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.r;\n#endif\n";
  7651. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  7652. 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";
  7653. 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";
  7654. 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";
  7655. 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";
  7656. 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";
  7657. 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";
  7658. 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";
  7659. 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";
  7660. 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";
  7661. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  7662. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n";
  7663. 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";
  7664. 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";
  7665. 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";
  7666. 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";
  7667. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  7668. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif";
  7669. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif";
  7670. 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";
  7671. 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";
  7672. 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";
  7673. 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";
  7674. 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";
  7675. 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";
  7676. 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";
  7677. 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";
  7678. 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";
  7679. 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";
  7680. 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";
  7681. 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";
  7682. 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";
  7683. 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";
  7684. 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";
  7685. 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";
  7686. 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";
  7687. 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";
  7688. 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";
  7689. 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";
  7690. 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";
  7691. 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";
  7692. 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";
  7693. 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";
  7694. 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";
  7695. var ShaderChunk = {
  7696. alphamap_fragment: alphamap_fragment,
  7697. alphamap_pars_fragment: alphamap_pars_fragment,
  7698. alphatest_fragment: alphatest_fragment,
  7699. aomap_fragment: aomap_fragment,
  7700. aomap_pars_fragment: aomap_pars_fragment,
  7701. begin_vertex: begin_vertex,
  7702. beginnormal_vertex: beginnormal_vertex,
  7703. bsdfs: bsdfs,
  7704. bumpmap_pars_fragment: bumpmap_pars_fragment,
  7705. clipping_planes_fragment: clipping_planes_fragment,
  7706. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  7707. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  7708. clipping_planes_vertex: clipping_planes_vertex,
  7709. color_fragment: color_fragment,
  7710. color_pars_fragment: color_pars_fragment,
  7711. color_pars_vertex: color_pars_vertex,
  7712. color_vertex: color_vertex,
  7713. common: common,
  7714. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  7715. defaultnormal_vertex: defaultnormal_vertex,
  7716. displacementmap_pars_vertex: displacementmap_pars_vertex,
  7717. displacementmap_vertex: displacementmap_vertex,
  7718. emissivemap_fragment: emissivemap_fragment,
  7719. emissivemap_pars_fragment: emissivemap_pars_fragment,
  7720. encodings_fragment: encodings_fragment,
  7721. encodings_pars_fragment: encodings_pars_fragment,
  7722. envmap_fragment: envmap_fragment,
  7723. envmap_pars_fragment: envmap_pars_fragment,
  7724. envmap_pars_vertex: envmap_pars_vertex,
  7725. envmap_vertex: envmap_vertex,
  7726. fog_vertex: fog_vertex,
  7727. fog_pars_vertex: fog_pars_vertex,
  7728. fog_fragment: fog_fragment,
  7729. fog_pars_fragment: fog_pars_fragment,
  7730. gradientmap_pars_fragment: gradientmap_pars_fragment,
  7731. lightmap_fragment: lightmap_fragment,
  7732. lightmap_pars_fragment: lightmap_pars_fragment,
  7733. lights_lambert_vertex: lights_lambert_vertex,
  7734. lights_pars: lights_pars,
  7735. lights_phong_fragment: lights_phong_fragment,
  7736. lights_phong_pars_fragment: lights_phong_pars_fragment,
  7737. lights_physical_fragment: lights_physical_fragment,
  7738. lights_physical_pars_fragment: lights_physical_pars_fragment,
  7739. lights_template: lights_template,
  7740. logdepthbuf_fragment: logdepthbuf_fragment,
  7741. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  7742. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  7743. logdepthbuf_vertex: logdepthbuf_vertex,
  7744. map_fragment: map_fragment,
  7745. map_pars_fragment: map_pars_fragment,
  7746. map_particle_fragment: map_particle_fragment,
  7747. map_particle_pars_fragment: map_particle_pars_fragment,
  7748. metalnessmap_fragment: metalnessmap_fragment,
  7749. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  7750. morphnormal_vertex: morphnormal_vertex,
  7751. morphtarget_pars_vertex: morphtarget_pars_vertex,
  7752. morphtarget_vertex: morphtarget_vertex,
  7753. normal_flip: normal_flip,
  7754. normal_fragment: normal_fragment,
  7755. normalmap_pars_fragment: normalmap_pars_fragment,
  7756. packing: packing,
  7757. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  7758. project_vertex: project_vertex,
  7759. roughnessmap_fragment: roughnessmap_fragment,
  7760. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  7761. shadowmap_pars_fragment: shadowmap_pars_fragment,
  7762. shadowmap_pars_vertex: shadowmap_pars_vertex,
  7763. shadowmap_vertex: shadowmap_vertex,
  7764. shadowmask_pars_fragment: shadowmask_pars_fragment,
  7765. skinbase_vertex: skinbase_vertex,
  7766. skinning_pars_vertex: skinning_pars_vertex,
  7767. skinning_vertex: skinning_vertex,
  7768. skinnormal_vertex: skinnormal_vertex,
  7769. specularmap_fragment: specularmap_fragment,
  7770. specularmap_pars_fragment: specularmap_pars_fragment,
  7771. tonemapping_fragment: tonemapping_fragment,
  7772. tonemapping_pars_fragment: tonemapping_pars_fragment,
  7773. uv_pars_fragment: uv_pars_fragment,
  7774. uv_pars_vertex: uv_pars_vertex,
  7775. uv_vertex: uv_vertex,
  7776. uv2_pars_fragment: uv2_pars_fragment,
  7777. uv2_pars_vertex: uv2_pars_vertex,
  7778. uv2_vertex: uv2_vertex,
  7779. worldpos_vertex: worldpos_vertex,
  7780. cube_frag: cube_frag,
  7781. cube_vert: cube_vert,
  7782. depth_frag: depth_frag,
  7783. depth_vert: depth_vert,
  7784. distanceRGBA_frag: distanceRGBA_frag,
  7785. distanceRGBA_vert: distanceRGBA_vert,
  7786. equirect_frag: equirect_frag,
  7787. equirect_vert: equirect_vert,
  7788. linedashed_frag: linedashed_frag,
  7789. linedashed_vert: linedashed_vert,
  7790. meshbasic_frag: meshbasic_frag,
  7791. meshbasic_vert: meshbasic_vert,
  7792. meshlambert_frag: meshlambert_frag,
  7793. meshlambert_vert: meshlambert_vert,
  7794. meshphong_frag: meshphong_frag,
  7795. meshphong_vert: meshphong_vert,
  7796. meshphysical_frag: meshphysical_frag,
  7797. meshphysical_vert: meshphysical_vert,
  7798. normal_frag: normal_frag,
  7799. normal_vert: normal_vert,
  7800. points_frag: points_frag,
  7801. points_vert: points_vert,
  7802. shadow_frag: shadow_frag,
  7803. shadow_vert: shadow_vert
  7804. };
  7805. /**
  7806. * @author mrdoob / http://mrdoob.com/
  7807. */
  7808. function Color( r, g, b ) {
  7809. if ( g === undefined && b === undefined ) {
  7810. // r is THREE.Color, hex or string
  7811. return this.set( r );
  7812. }
  7813. return this.setRGB( r, g, b );
  7814. }
  7815. Color.prototype = {
  7816. constructor: Color,
  7817. isColor: true,
  7818. r: 1, g: 1, b: 1,
  7819. set: function ( value ) {
  7820. if ( value && value.isColor ) {
  7821. this.copy( value );
  7822. } else if ( typeof value === 'number' ) {
  7823. this.setHex( value );
  7824. } else if ( typeof value === 'string' ) {
  7825. this.setStyle( value );
  7826. }
  7827. return this;
  7828. },
  7829. setScalar: function ( scalar ) {
  7830. this.r = scalar;
  7831. this.g = scalar;
  7832. this.b = scalar;
  7833. return this;
  7834. },
  7835. setHex: function ( hex ) {
  7836. hex = Math.floor( hex );
  7837. this.r = ( hex >> 16 & 255 ) / 255;
  7838. this.g = ( hex >> 8 & 255 ) / 255;
  7839. this.b = ( hex & 255 ) / 255;
  7840. return this;
  7841. },
  7842. setRGB: function ( r, g, b ) {
  7843. this.r = r;
  7844. this.g = g;
  7845. this.b = b;
  7846. return this;
  7847. },
  7848. setHSL: function () {
  7849. function hue2rgb( p, q, t ) {
  7850. if ( t < 0 ) t += 1;
  7851. if ( t > 1 ) t -= 1;
  7852. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  7853. if ( t < 1 / 2 ) return q;
  7854. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  7855. return p;
  7856. }
  7857. return function setHSL( h, s, l ) {
  7858. // h,s,l ranges are in 0.0 - 1.0
  7859. h = _Math.euclideanModulo( h, 1 );
  7860. s = _Math.clamp( s, 0, 1 );
  7861. l = _Math.clamp( l, 0, 1 );
  7862. if ( s === 0 ) {
  7863. this.r = this.g = this.b = l;
  7864. } else {
  7865. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  7866. var q = ( 2 * l ) - p;
  7867. this.r = hue2rgb( q, p, h + 1 / 3 );
  7868. this.g = hue2rgb( q, p, h );
  7869. this.b = hue2rgb( q, p, h - 1 / 3 );
  7870. }
  7871. return this;
  7872. };
  7873. }(),
  7874. setStyle: function ( style ) {
  7875. function handleAlpha( string ) {
  7876. if ( string === undefined ) return;
  7877. if ( parseFloat( string ) < 1 ) {
  7878. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  7879. }
  7880. }
  7881. var m;
  7882. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  7883. // rgb / hsl
  7884. var color;
  7885. var name = m[ 1 ];
  7886. var components = m[ 2 ];
  7887. switch ( name ) {
  7888. case 'rgb':
  7889. case 'rgba':
  7890. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  7891. // rgb(255,0,0) rgba(255,0,0,0.5)
  7892. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  7893. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  7894. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  7895. handleAlpha( color[ 5 ] );
  7896. return this;
  7897. }
  7898. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  7899. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  7900. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  7901. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  7902. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  7903. handleAlpha( color[ 5 ] );
  7904. return this;
  7905. }
  7906. break;
  7907. case 'hsl':
  7908. case 'hsla':
  7909. if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  7910. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  7911. var h = parseFloat( color[ 1 ] ) / 360;
  7912. var s = parseInt( color[ 2 ], 10 ) / 100;
  7913. var l = parseInt( color[ 3 ], 10 ) / 100;
  7914. handleAlpha( color[ 5 ] );
  7915. return this.setHSL( h, s, l );
  7916. }
  7917. break;
  7918. }
  7919. } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {
  7920. // hex color
  7921. var hex = m[ 1 ];
  7922. var size = hex.length;
  7923. if ( size === 3 ) {
  7924. // #ff0
  7925. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  7926. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  7927. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  7928. return this;
  7929. } else if ( size === 6 ) {
  7930. // #ff0000
  7931. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  7932. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  7933. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  7934. return this;
  7935. }
  7936. }
  7937. if ( style && style.length > 0 ) {
  7938. // color keywords
  7939. var hex = ColorKeywords[ style ];
  7940. if ( hex !== undefined ) {
  7941. // red
  7942. this.setHex( hex );
  7943. } else {
  7944. // unknown color
  7945. console.warn( 'THREE.Color: Unknown color ' + style );
  7946. }
  7947. }
  7948. return this;
  7949. },
  7950. clone: function () {
  7951. return new this.constructor( this.r, this.g, this.b );
  7952. },
  7953. copy: function ( color ) {
  7954. this.r = color.r;
  7955. this.g = color.g;
  7956. this.b = color.b;
  7957. return this;
  7958. },
  7959. copyGammaToLinear: function ( color, gammaFactor ) {
  7960. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  7961. this.r = Math.pow( color.r, gammaFactor );
  7962. this.g = Math.pow( color.g, gammaFactor );
  7963. this.b = Math.pow( color.b, gammaFactor );
  7964. return this;
  7965. },
  7966. copyLinearToGamma: function ( color, gammaFactor ) {
  7967. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  7968. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  7969. this.r = Math.pow( color.r, safeInverse );
  7970. this.g = Math.pow( color.g, safeInverse );
  7971. this.b = Math.pow( color.b, safeInverse );
  7972. return this;
  7973. },
  7974. convertGammaToLinear: function () {
  7975. var r = this.r, g = this.g, b = this.b;
  7976. this.r = r * r;
  7977. this.g = g * g;
  7978. this.b = b * b;
  7979. return this;
  7980. },
  7981. convertLinearToGamma: function () {
  7982. this.r = Math.sqrt( this.r );
  7983. this.g = Math.sqrt( this.g );
  7984. this.b = Math.sqrt( this.b );
  7985. return this;
  7986. },
  7987. getHex: function () {
  7988. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  7989. },
  7990. getHexString: function () {
  7991. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  7992. },
  7993. getHSL: function ( optionalTarget ) {
  7994. // h,s,l ranges are in 0.0 - 1.0
  7995. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  7996. var r = this.r, g = this.g, b = this.b;
  7997. var max = Math.max( r, g, b );
  7998. var min = Math.min( r, g, b );
  7999. var hue, saturation;
  8000. var lightness = ( min + max ) / 2.0;
  8001. if ( min === max ) {
  8002. hue = 0;
  8003. saturation = 0;
  8004. } else {
  8005. var delta = max - min;
  8006. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  8007. switch ( max ) {
  8008. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  8009. case g: hue = ( b - r ) / delta + 2; break;
  8010. case b: hue = ( r - g ) / delta + 4; break;
  8011. }
  8012. hue /= 6;
  8013. }
  8014. hsl.h = hue;
  8015. hsl.s = saturation;
  8016. hsl.l = lightness;
  8017. return hsl;
  8018. },
  8019. getStyle: function () {
  8020. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  8021. },
  8022. offsetHSL: function ( h, s, l ) {
  8023. var hsl = this.getHSL();
  8024. hsl.h += h; hsl.s += s; hsl.l += l;
  8025. this.setHSL( hsl.h, hsl.s, hsl.l );
  8026. return this;
  8027. },
  8028. add: function ( color ) {
  8029. this.r += color.r;
  8030. this.g += color.g;
  8031. this.b += color.b;
  8032. return this;
  8033. },
  8034. addColors: function ( color1, color2 ) {
  8035. this.r = color1.r + color2.r;
  8036. this.g = color1.g + color2.g;
  8037. this.b = color1.b + color2.b;
  8038. return this;
  8039. },
  8040. addScalar: function ( s ) {
  8041. this.r += s;
  8042. this.g += s;
  8043. this.b += s;
  8044. return this;
  8045. },
  8046. sub: function( color ) {
  8047. this.r = Math.max( 0, this.r - color.r );
  8048. this.g = Math.max( 0, this.g - color.g );
  8049. this.b = Math.max( 0, this.b - color.b );
  8050. return this;
  8051. },
  8052. multiply: function ( color ) {
  8053. this.r *= color.r;
  8054. this.g *= color.g;
  8055. this.b *= color.b;
  8056. return this;
  8057. },
  8058. multiplyScalar: function ( s ) {
  8059. this.r *= s;
  8060. this.g *= s;
  8061. this.b *= s;
  8062. return this;
  8063. },
  8064. lerp: function ( color, alpha ) {
  8065. this.r += ( color.r - this.r ) * alpha;
  8066. this.g += ( color.g - this.g ) * alpha;
  8067. this.b += ( color.b - this.b ) * alpha;
  8068. return this;
  8069. },
  8070. equals: function ( c ) {
  8071. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  8072. },
  8073. fromArray: function ( array, offset ) {
  8074. if ( offset === undefined ) offset = 0;
  8075. this.r = array[ offset ];
  8076. this.g = array[ offset + 1 ];
  8077. this.b = array[ offset + 2 ];
  8078. return this;
  8079. },
  8080. toArray: function ( array, offset ) {
  8081. if ( array === undefined ) array = [];
  8082. if ( offset === undefined ) offset = 0;
  8083. array[ offset ] = this.r;
  8084. array[ offset + 1 ] = this.g;
  8085. array[ offset + 2 ] = this.b;
  8086. return array;
  8087. },
  8088. toJSON: function () {
  8089. return this.getHex();
  8090. }
  8091. };
  8092. var ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  8093. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  8094. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  8095. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  8096. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  8097. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  8098. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  8099. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  8100. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  8101. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  8102. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  8103. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  8104. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  8105. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  8106. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  8107. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  8108. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  8109. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  8110. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  8111. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  8112. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  8113. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  8114. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  8115. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  8116. /**
  8117. * @author alteredq / http://alteredqualia.com/
  8118. */
  8119. function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  8120. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  8121. this.image = { data: data, width: width, height: height };
  8122. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  8123. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  8124. this.generateMipmaps = false;
  8125. this.flipY = false;
  8126. this.unpackAlignment = 1;
  8127. }
  8128. DataTexture.prototype = Object.create( Texture.prototype );
  8129. DataTexture.prototype.constructor = DataTexture;
  8130. DataTexture.prototype.isDataTexture = true;
  8131. /**
  8132. * Uniforms library for shared webgl shaders
  8133. */
  8134. var UniformsLib = {
  8135. common: {
  8136. diffuse: { value: new Color( 0xeeeeee ) },
  8137. opacity: { value: 1.0 },
  8138. map: { value: null },
  8139. offsetRepeat: { value: new Vector4( 0, 0, 1, 1 ) },
  8140. specularMap: { value: null },
  8141. alphaMap: { value: null },
  8142. envMap: { value: null },
  8143. flipEnvMap: { value: - 1 },
  8144. reflectivity: { value: 1.0 },
  8145. refractionRatio: { value: 0.98 }
  8146. },
  8147. aomap: {
  8148. aoMap: { value: null },
  8149. aoMapIntensity: { value: 1 }
  8150. },
  8151. lightmap: {
  8152. lightMap: { value: null },
  8153. lightMapIntensity: { value: 1 }
  8154. },
  8155. emissivemap: {
  8156. emissiveMap: { value: null }
  8157. },
  8158. bumpmap: {
  8159. bumpMap: { value: null },
  8160. bumpScale: { value: 1 }
  8161. },
  8162. normalmap: {
  8163. normalMap: { value: null },
  8164. normalScale: { value: new Vector2( 1, 1 ) }
  8165. },
  8166. displacementmap: {
  8167. displacementMap: { value: null },
  8168. displacementScale: { value: 1 },
  8169. displacementBias: { value: 0 }
  8170. },
  8171. roughnessmap: {
  8172. roughnessMap: { value: null }
  8173. },
  8174. metalnessmap: {
  8175. metalnessMap: { value: null }
  8176. },
  8177. gradientmap: {
  8178. gradientMap: { value: null }
  8179. },
  8180. fog: {
  8181. fogDensity: { value: 0.00025 },
  8182. fogNear: { value: 1 },
  8183. fogFar: { value: 2000 },
  8184. fogColor: { value: new Color( 0xffffff ) }
  8185. },
  8186. lights: {
  8187. ambientLightColor: { value: [] },
  8188. directionalLights: { value: [], properties: {
  8189. direction: {},
  8190. color: {},
  8191. shadow: {},
  8192. shadowBias: {},
  8193. shadowRadius: {},
  8194. shadowMapSize: {}
  8195. } },
  8196. directionalShadowMap: { value: [] },
  8197. directionalShadowMatrix: { value: [] },
  8198. spotLights: { value: [], properties: {
  8199. color: {},
  8200. position: {},
  8201. direction: {},
  8202. distance: {},
  8203. coneCos: {},
  8204. penumbraCos: {},
  8205. decay: {},
  8206. shadow: {},
  8207. shadowBias: {},
  8208. shadowRadius: {},
  8209. shadowMapSize: {}
  8210. } },
  8211. spotShadowMap: { value: [] },
  8212. spotShadowMatrix: { value: [] },
  8213. pointLights: { value: [], properties: {
  8214. color: {},
  8215. position: {},
  8216. decay: {},
  8217. distance: {},
  8218. shadow: {},
  8219. shadowBias: {},
  8220. shadowRadius: {},
  8221. shadowMapSize: {}
  8222. } },
  8223. pointShadowMap: { value: [] },
  8224. pointShadowMatrix: { value: [] },
  8225. hemisphereLights: { value: [], properties: {
  8226. direction: {},
  8227. skyColor: {},
  8228. groundColor: {}
  8229. } },
  8230. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8231. rectAreaLights: { value: [], properties: {
  8232. color: {},
  8233. position: {},
  8234. width: {},
  8235. height: {}
  8236. } }
  8237. },
  8238. points: {
  8239. diffuse: { value: new Color( 0xeeeeee ) },
  8240. opacity: { value: 1.0 },
  8241. size: { value: 1.0 },
  8242. scale: { value: 1.0 },
  8243. map: { value: null },
  8244. offsetRepeat: { value: new Vector4( 0, 0, 1, 1 ) }
  8245. }
  8246. };
  8247. /**
  8248. * @author alteredq / http://alteredqualia.com/
  8249. * @author mrdoob / http://mrdoob.com/
  8250. * @author mikael emtinger / http://gomo.se/
  8251. */
  8252. var ShaderLib = {
  8253. basic: {
  8254. uniforms: UniformsUtils.merge( [
  8255. UniformsLib.common,
  8256. UniformsLib.aomap,
  8257. UniformsLib.lightmap,
  8258. UniformsLib.fog
  8259. ] ),
  8260. vertexShader: ShaderChunk.meshbasic_vert,
  8261. fragmentShader: ShaderChunk.meshbasic_frag
  8262. },
  8263. lambert: {
  8264. uniforms: UniformsUtils.merge( [
  8265. UniformsLib.common,
  8266. UniformsLib.aomap,
  8267. UniformsLib.lightmap,
  8268. UniformsLib.emissivemap,
  8269. UniformsLib.fog,
  8270. UniformsLib.lights,
  8271. {
  8272. emissive: { value: new Color( 0x000000 ) }
  8273. }
  8274. ] ),
  8275. vertexShader: ShaderChunk.meshlambert_vert,
  8276. fragmentShader: ShaderChunk.meshlambert_frag
  8277. },
  8278. phong: {
  8279. uniforms: UniformsUtils.merge( [
  8280. UniformsLib.common,
  8281. UniformsLib.aomap,
  8282. UniformsLib.lightmap,
  8283. UniformsLib.emissivemap,
  8284. UniformsLib.bumpmap,
  8285. UniformsLib.normalmap,
  8286. UniformsLib.displacementmap,
  8287. UniformsLib.gradientmap,
  8288. UniformsLib.fog,
  8289. UniformsLib.lights,
  8290. {
  8291. emissive: { value: new Color( 0x000000 ) },
  8292. specular: { value: new Color( 0x111111 ) },
  8293. shininess: { value: 30 }
  8294. }
  8295. ] ),
  8296. vertexShader: ShaderChunk.meshphong_vert,
  8297. fragmentShader: ShaderChunk.meshphong_frag
  8298. },
  8299. standard: {
  8300. uniforms: UniformsUtils.merge( [
  8301. UniformsLib.common,
  8302. UniformsLib.aomap,
  8303. UniformsLib.lightmap,
  8304. UniformsLib.emissivemap,
  8305. UniformsLib.bumpmap,
  8306. UniformsLib.normalmap,
  8307. UniformsLib.displacementmap,
  8308. UniformsLib.roughnessmap,
  8309. UniformsLib.metalnessmap,
  8310. UniformsLib.fog,
  8311. UniformsLib.lights,
  8312. {
  8313. emissive: { value: new Color( 0x000000 ) },
  8314. roughness: { value: 0.5 },
  8315. metalness: { value: 0 },
  8316. envMapIntensity: { value: 1 } // temporary
  8317. }
  8318. ] ),
  8319. vertexShader: ShaderChunk.meshphysical_vert,
  8320. fragmentShader: ShaderChunk.meshphysical_frag
  8321. },
  8322. points: {
  8323. uniforms: UniformsUtils.merge( [
  8324. UniformsLib.points,
  8325. UniformsLib.fog
  8326. ] ),
  8327. vertexShader: ShaderChunk.points_vert,
  8328. fragmentShader: ShaderChunk.points_frag
  8329. },
  8330. dashed: {
  8331. uniforms: UniformsUtils.merge( [
  8332. UniformsLib.common,
  8333. UniformsLib.fog,
  8334. {
  8335. scale: { value: 1 },
  8336. dashSize: { value: 1 },
  8337. totalSize: { value: 2 }
  8338. }
  8339. ] ),
  8340. vertexShader: ShaderChunk.linedashed_vert,
  8341. fragmentShader: ShaderChunk.linedashed_frag
  8342. },
  8343. depth: {
  8344. uniforms: UniformsUtils.merge( [
  8345. UniformsLib.common,
  8346. UniformsLib.displacementmap
  8347. ] ),
  8348. vertexShader: ShaderChunk.depth_vert,
  8349. fragmentShader: ShaderChunk.depth_frag
  8350. },
  8351. normal: {
  8352. uniforms: UniformsUtils.merge( [
  8353. UniformsLib.common,
  8354. UniformsLib.bumpmap,
  8355. UniformsLib.normalmap,
  8356. UniformsLib.displacementmap,
  8357. {
  8358. opacity: { value: 1.0 }
  8359. }
  8360. ] ),
  8361. vertexShader: ShaderChunk.normal_vert,
  8362. fragmentShader: ShaderChunk.normal_frag
  8363. },
  8364. /* -------------------------------------------------------------------------
  8365. // Cube map shader
  8366. ------------------------------------------------------------------------- */
  8367. cube: {
  8368. uniforms: {
  8369. tCube: { value: null },
  8370. tFlip: { value: - 1 },
  8371. opacity: { value: 1.0 }
  8372. },
  8373. vertexShader: ShaderChunk.cube_vert,
  8374. fragmentShader: ShaderChunk.cube_frag
  8375. },
  8376. /* -------------------------------------------------------------------------
  8377. // Cube map shader
  8378. ------------------------------------------------------------------------- */
  8379. equirect: {
  8380. uniforms: {
  8381. tEquirect: { value: null },
  8382. tFlip: { value: - 1 }
  8383. },
  8384. vertexShader: ShaderChunk.equirect_vert,
  8385. fragmentShader: ShaderChunk.equirect_frag
  8386. },
  8387. distanceRGBA: {
  8388. uniforms: {
  8389. lightPos: { value: new Vector3() }
  8390. },
  8391. vertexShader: ShaderChunk.distanceRGBA_vert,
  8392. fragmentShader: ShaderChunk.distanceRGBA_frag
  8393. }
  8394. };
  8395. ShaderLib.physical = {
  8396. uniforms: UniformsUtils.merge( [
  8397. ShaderLib.standard.uniforms,
  8398. {
  8399. clearCoat: { value: 0 },
  8400. clearCoatRoughness: { value: 0 }
  8401. }
  8402. ] ),
  8403. vertexShader: ShaderChunk.meshphysical_vert,
  8404. fragmentShader: ShaderChunk.meshphysical_frag
  8405. };
  8406. /**
  8407. * @author bhouston / http://clara.io
  8408. */
  8409. function Box2( min, max ) {
  8410. this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity );
  8411. this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity );
  8412. }
  8413. Box2.prototype = {
  8414. constructor: Box2,
  8415. set: function ( min, max ) {
  8416. this.min.copy( min );
  8417. this.max.copy( max );
  8418. return this;
  8419. },
  8420. setFromPoints: function ( points ) {
  8421. this.makeEmpty();
  8422. for ( var i = 0, il = points.length; i < il; i ++ ) {
  8423. this.expandByPoint( points[ i ] );
  8424. }
  8425. return this;
  8426. },
  8427. setFromCenterAndSize: function () {
  8428. var v1 = new Vector2();
  8429. return function setFromCenterAndSize( center, size ) {
  8430. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  8431. this.min.copy( center ).sub( halfSize );
  8432. this.max.copy( center ).add( halfSize );
  8433. return this;
  8434. };
  8435. }(),
  8436. clone: function () {
  8437. return new this.constructor().copy( this );
  8438. },
  8439. copy: function ( box ) {
  8440. this.min.copy( box.min );
  8441. this.max.copy( box.max );
  8442. return this;
  8443. },
  8444. makeEmpty: function () {
  8445. this.min.x = this.min.y = + Infinity;
  8446. this.max.x = this.max.y = - Infinity;
  8447. return this;
  8448. },
  8449. isEmpty: function () {
  8450. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  8451. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  8452. },
  8453. getCenter: function ( optionalTarget ) {
  8454. var result = optionalTarget || new Vector2();
  8455. return this.isEmpty() ? result.set( 0, 0 ) : result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  8456. },
  8457. getSize: function ( optionalTarget ) {
  8458. var result = optionalTarget || new Vector2();
  8459. return this.isEmpty() ? result.set( 0, 0 ) : result.subVectors( this.max, this.min );
  8460. },
  8461. expandByPoint: function ( point ) {
  8462. this.min.min( point );
  8463. this.max.max( point );
  8464. return this;
  8465. },
  8466. expandByVector: function ( vector ) {
  8467. this.min.sub( vector );
  8468. this.max.add( vector );
  8469. return this;
  8470. },
  8471. expandByScalar: function ( scalar ) {
  8472. this.min.addScalar( - scalar );
  8473. this.max.addScalar( scalar );
  8474. return this;
  8475. },
  8476. containsPoint: function ( point ) {
  8477. return point.x < this.min.x || point.x > this.max.x ||
  8478. point.y < this.min.y || point.y > this.max.y ? false : true;
  8479. },
  8480. containsBox: function ( box ) {
  8481. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  8482. this.min.y <= box.min.y && box.max.y <= this.max.y;
  8483. },
  8484. getParameter: function ( point, optionalTarget ) {
  8485. // This can potentially have a divide by zero if the box
  8486. // has a size dimension of 0.
  8487. var result = optionalTarget || new Vector2();
  8488. return result.set(
  8489. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  8490. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  8491. );
  8492. },
  8493. intersectsBox: function ( box ) {
  8494. // using 6 splitting planes to rule out intersections.
  8495. return box.max.x < this.min.x || box.min.x > this.max.x ||
  8496. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  8497. },
  8498. clampPoint: function ( point, optionalTarget ) {
  8499. var result = optionalTarget || new Vector2();
  8500. return result.copy( point ).clamp( this.min, this.max );
  8501. },
  8502. distanceToPoint: function () {
  8503. var v1 = new Vector2();
  8504. return function distanceToPoint( point ) {
  8505. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  8506. return clampedPoint.sub( point ).length();
  8507. };
  8508. }(),
  8509. intersect: function ( box ) {
  8510. this.min.max( box.min );
  8511. this.max.min( box.max );
  8512. return this;
  8513. },
  8514. union: function ( box ) {
  8515. this.min.min( box.min );
  8516. this.max.max( box.max );
  8517. return this;
  8518. },
  8519. translate: function ( offset ) {
  8520. this.min.add( offset );
  8521. this.max.add( offset );
  8522. return this;
  8523. },
  8524. equals: function ( box ) {
  8525. return box.min.equals( this.min ) && box.max.equals( this.max );
  8526. }
  8527. };
  8528. /**
  8529. * @author mikael emtinger / http://gomo.se/
  8530. * @author alteredq / http://alteredqualia.com/
  8531. */
  8532. function LensFlarePlugin( renderer, flares ) {
  8533. var gl = renderer.context;
  8534. var state = renderer.state;
  8535. var vertexBuffer, elementBuffer;
  8536. var shader, program, attributes, uniforms;
  8537. var tempTexture, occlusionTexture;
  8538. function init() {
  8539. var vertices = new Float32Array( [
  8540. - 1, - 1, 0, 0,
  8541. 1, - 1, 1, 0,
  8542. 1, 1, 1, 1,
  8543. - 1, 1, 0, 1
  8544. ] );
  8545. var faces = new Uint16Array( [
  8546. 0, 1, 2,
  8547. 0, 2, 3
  8548. ] );
  8549. // buffers
  8550. vertexBuffer = gl.createBuffer();
  8551. elementBuffer = gl.createBuffer();
  8552. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  8553. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  8554. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  8555. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  8556. // textures
  8557. tempTexture = gl.createTexture();
  8558. occlusionTexture = gl.createTexture();
  8559. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  8560. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null );
  8561. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  8562. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  8563. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  8564. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  8565. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  8566. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null );
  8567. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  8568. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  8569. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  8570. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  8571. shader = {
  8572. vertexShader: [
  8573. "uniform lowp int renderType;",
  8574. "uniform vec3 screenPosition;",
  8575. "uniform vec2 scale;",
  8576. "uniform float rotation;",
  8577. "uniform sampler2D occlusionMap;",
  8578. "attribute vec2 position;",
  8579. "attribute vec2 uv;",
  8580. "varying vec2 vUV;",
  8581. "varying float vVisibility;",
  8582. "void main() {",
  8583. "vUV = uv;",
  8584. "vec2 pos = position;",
  8585. "if ( renderType == 2 ) {",
  8586. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  8587. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  8588. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  8589. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  8590. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  8591. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  8592. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  8593. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  8594. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  8595. "vVisibility = visibility.r / 9.0;",
  8596. "vVisibility *= 1.0 - visibility.g / 9.0;",
  8597. "vVisibility *= visibility.b / 9.0;",
  8598. "vVisibility *= 1.0 - visibility.a / 9.0;",
  8599. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  8600. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  8601. "}",
  8602. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  8603. "}"
  8604. ].join( "\n" ),
  8605. fragmentShader: [
  8606. "uniform lowp int renderType;",
  8607. "uniform sampler2D map;",
  8608. "uniform float opacity;",
  8609. "uniform vec3 color;",
  8610. "varying vec2 vUV;",
  8611. "varying float vVisibility;",
  8612. "void main() {",
  8613. // pink square
  8614. "if ( renderType == 0 ) {",
  8615. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  8616. // restore
  8617. "} else if ( renderType == 1 ) {",
  8618. "gl_FragColor = texture2D( map, vUV );",
  8619. // flare
  8620. "} else {",
  8621. "vec4 texture = texture2D( map, vUV );",
  8622. "texture.a *= opacity * vVisibility;",
  8623. "gl_FragColor = texture;",
  8624. "gl_FragColor.rgb *= color;",
  8625. "}",
  8626. "}"
  8627. ].join( "\n" )
  8628. };
  8629. program = createProgram( shader );
  8630. attributes = {
  8631. vertex: gl.getAttribLocation ( program, "position" ),
  8632. uv: gl.getAttribLocation ( program, "uv" )
  8633. };
  8634. uniforms = {
  8635. renderType: gl.getUniformLocation( program, "renderType" ),
  8636. map: gl.getUniformLocation( program, "map" ),
  8637. occlusionMap: gl.getUniformLocation( program, "occlusionMap" ),
  8638. opacity: gl.getUniformLocation( program, "opacity" ),
  8639. color: gl.getUniformLocation( program, "color" ),
  8640. scale: gl.getUniformLocation( program, "scale" ),
  8641. rotation: gl.getUniformLocation( program, "rotation" ),
  8642. screenPosition: gl.getUniformLocation( program, "screenPosition" )
  8643. };
  8644. }
  8645. /*
  8646. * Render lens flares
  8647. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  8648. * reads these back and calculates occlusion.
  8649. */
  8650. this.render = function ( scene, camera, viewport ) {
  8651. if ( flares.length === 0 ) return;
  8652. var tempPosition = new Vector3();
  8653. var invAspect = viewport.w / viewport.z,
  8654. halfViewportWidth = viewport.z * 0.5,
  8655. halfViewportHeight = viewport.w * 0.5;
  8656. var size = 16 / viewport.w,
  8657. scale = new Vector2( size * invAspect, size );
  8658. var screenPosition = new Vector3( 1, 1, 0 ),
  8659. screenPositionPixels = new Vector2( 1, 1 );
  8660. var validArea = new Box2();
  8661. validArea.min.set( viewport.x, viewport.y );
  8662. validArea.max.set( viewport.x + ( viewport.z - 16 ), viewport.y + ( viewport.w - 16 ) );
  8663. if ( program === undefined ) {
  8664. init();
  8665. }
  8666. gl.useProgram( program );
  8667. state.initAttributes();
  8668. state.enableAttribute( attributes.vertex );
  8669. state.enableAttribute( attributes.uv );
  8670. state.disableUnusedAttributes();
  8671. // loop through all lens flares to update their occlusion and positions
  8672. // setup gl and common used attribs/uniforms
  8673. gl.uniform1i( uniforms.occlusionMap, 0 );
  8674. gl.uniform1i( uniforms.map, 1 );
  8675. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  8676. gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 );
  8677. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  8678. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  8679. state.disable( gl.CULL_FACE );
  8680. state.setDepthWrite( false );
  8681. for ( var i = 0, l = flares.length; i < l; i ++ ) {
  8682. size = 16 / viewport.w;
  8683. scale.set( size * invAspect, size );
  8684. // calc object screen position
  8685. var flare = flares[ i ];
  8686. tempPosition.set( flare.matrixWorld.elements[ 12 ], flare.matrixWorld.elements[ 13 ], flare.matrixWorld.elements[ 14 ] );
  8687. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  8688. tempPosition.applyMatrix4( camera.projectionMatrix );
  8689. // setup arrays for gl programs
  8690. screenPosition.copy( tempPosition );
  8691. // horizontal and vertical coordinate of the lower left corner of the pixels to copy
  8692. screenPositionPixels.x = viewport.x + ( screenPosition.x * halfViewportWidth ) + halfViewportWidth - 8;
  8693. screenPositionPixels.y = viewport.y + ( screenPosition.y * halfViewportHeight ) + halfViewportHeight - 8;
  8694. // screen cull
  8695. if ( validArea.containsPoint( screenPositionPixels ) === true ) {
  8696. // save current RGB to temp texture
  8697. state.activeTexture( gl.TEXTURE0 );
  8698. state.bindTexture( gl.TEXTURE_2D, null );
  8699. state.activeTexture( gl.TEXTURE1 );
  8700. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  8701. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  8702. // render pink quad
  8703. gl.uniform1i( uniforms.renderType, 0 );
  8704. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  8705. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  8706. state.disable( gl.BLEND );
  8707. state.enable( gl.DEPTH_TEST );
  8708. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  8709. // copy result to occlusionMap
  8710. state.activeTexture( gl.TEXTURE0 );
  8711. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  8712. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  8713. // restore graphics
  8714. gl.uniform1i( uniforms.renderType, 1 );
  8715. state.disable( gl.DEPTH_TEST );
  8716. state.activeTexture( gl.TEXTURE1 );
  8717. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  8718. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  8719. // update object positions
  8720. flare.positionScreen.copy( screenPosition );
  8721. if ( flare.customUpdateCallback ) {
  8722. flare.customUpdateCallback( flare );
  8723. } else {
  8724. flare.updateLensFlares();
  8725. }
  8726. // render flares
  8727. gl.uniform1i( uniforms.renderType, 2 );
  8728. state.enable( gl.BLEND );
  8729. for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  8730. var sprite = flare.lensFlares[ j ];
  8731. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  8732. screenPosition.x = sprite.x;
  8733. screenPosition.y = sprite.y;
  8734. screenPosition.z = sprite.z;
  8735. size = sprite.size * sprite.scale / viewport.w;
  8736. scale.x = size * invAspect;
  8737. scale.y = size;
  8738. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  8739. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  8740. gl.uniform1f( uniforms.rotation, sprite.rotation );
  8741. gl.uniform1f( uniforms.opacity, sprite.opacity );
  8742. gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  8743. state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  8744. renderer.setTexture2D( sprite.texture, 1 );
  8745. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  8746. }
  8747. }
  8748. }
  8749. }
  8750. // restore gl
  8751. state.enable( gl.CULL_FACE );
  8752. state.enable( gl.DEPTH_TEST );
  8753. state.setDepthWrite( true );
  8754. renderer.resetGLState();
  8755. };
  8756. function createProgram( shader ) {
  8757. var program = gl.createProgram();
  8758. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  8759. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  8760. var prefix = "precision " + renderer.getPrecision() + " float;\n";
  8761. gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  8762. gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  8763. gl.compileShader( fragmentShader );
  8764. gl.compileShader( vertexShader );
  8765. gl.attachShader( program, fragmentShader );
  8766. gl.attachShader( program, vertexShader );
  8767. gl.linkProgram( program );
  8768. return program;
  8769. }
  8770. }
  8771. /**
  8772. * @author mikael emtinger / http://gomo.se/
  8773. * @author alteredq / http://alteredqualia.com/
  8774. */
  8775. function SpritePlugin( renderer, sprites ) {
  8776. var gl = renderer.context;
  8777. var state = renderer.state;
  8778. var vertexBuffer, elementBuffer;
  8779. var program, attributes, uniforms;
  8780. var texture;
  8781. // decompose matrixWorld
  8782. var spritePosition = new Vector3();
  8783. var spriteRotation = new Quaternion();
  8784. var spriteScale = new Vector3();
  8785. function init() {
  8786. var vertices = new Float32Array( [
  8787. - 0.5, - 0.5, 0, 0,
  8788. 0.5, - 0.5, 1, 0,
  8789. 0.5, 0.5, 1, 1,
  8790. - 0.5, 0.5, 0, 1
  8791. ] );
  8792. var faces = new Uint16Array( [
  8793. 0, 1, 2,
  8794. 0, 2, 3
  8795. ] );
  8796. vertexBuffer = gl.createBuffer();
  8797. elementBuffer = gl.createBuffer();
  8798. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  8799. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  8800. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  8801. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  8802. program = createProgram();
  8803. attributes = {
  8804. position: gl.getAttribLocation ( program, 'position' ),
  8805. uv: gl.getAttribLocation ( program, 'uv' )
  8806. };
  8807. uniforms = {
  8808. uvOffset: gl.getUniformLocation( program, 'uvOffset' ),
  8809. uvScale: gl.getUniformLocation( program, 'uvScale' ),
  8810. rotation: gl.getUniformLocation( program, 'rotation' ),
  8811. scale: gl.getUniformLocation( program, 'scale' ),
  8812. color: gl.getUniformLocation( program, 'color' ),
  8813. map: gl.getUniformLocation( program, 'map' ),
  8814. opacity: gl.getUniformLocation( program, 'opacity' ),
  8815. modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ),
  8816. projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ),
  8817. fogType: gl.getUniformLocation( program, 'fogType' ),
  8818. fogDensity: gl.getUniformLocation( program, 'fogDensity' ),
  8819. fogNear: gl.getUniformLocation( program, 'fogNear' ),
  8820. fogFar: gl.getUniformLocation( program, 'fogFar' ),
  8821. fogColor: gl.getUniformLocation( program, 'fogColor' ),
  8822. alphaTest: gl.getUniformLocation( program, 'alphaTest' )
  8823. };
  8824. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  8825. canvas.width = 8;
  8826. canvas.height = 8;
  8827. var context = canvas.getContext( '2d' );
  8828. context.fillStyle = 'white';
  8829. context.fillRect( 0, 0, 8, 8 );
  8830. texture = new Texture( canvas );
  8831. texture.needsUpdate = true;
  8832. }
  8833. this.render = function ( scene, camera ) {
  8834. if ( sprites.length === 0 ) return;
  8835. // setup gl
  8836. if ( program === undefined ) {
  8837. init();
  8838. }
  8839. gl.useProgram( program );
  8840. state.initAttributes();
  8841. state.enableAttribute( attributes.position );
  8842. state.enableAttribute( attributes.uv );
  8843. state.disableUnusedAttributes();
  8844. state.disable( gl.CULL_FACE );
  8845. state.enable( gl.BLEND );
  8846. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  8847. gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 );
  8848. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  8849. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  8850. gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  8851. state.activeTexture( gl.TEXTURE0 );
  8852. gl.uniform1i( uniforms.map, 0 );
  8853. var oldFogType = 0;
  8854. var sceneFogType = 0;
  8855. var fog = scene.fog;
  8856. if ( fog ) {
  8857. gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  8858. if ( fog.isFog ) {
  8859. gl.uniform1f( uniforms.fogNear, fog.near );
  8860. gl.uniform1f( uniforms.fogFar, fog.far );
  8861. gl.uniform1i( uniforms.fogType, 1 );
  8862. oldFogType = 1;
  8863. sceneFogType = 1;
  8864. } else if ( fog.isFogExp2 ) {
  8865. gl.uniform1f( uniforms.fogDensity, fog.density );
  8866. gl.uniform1i( uniforms.fogType, 2 );
  8867. oldFogType = 2;
  8868. sceneFogType = 2;
  8869. }
  8870. } else {
  8871. gl.uniform1i( uniforms.fogType, 0 );
  8872. oldFogType = 0;
  8873. sceneFogType = 0;
  8874. }
  8875. // update positions and sort
  8876. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  8877. var sprite = sprites[ i ];
  8878. sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  8879. sprite.z = - sprite.modelViewMatrix.elements[ 14 ];
  8880. }
  8881. sprites.sort( painterSortStable );
  8882. // render all sprites
  8883. var scale = [];
  8884. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  8885. var sprite = sprites[ i ];
  8886. var material = sprite.material;
  8887. if ( material.visible === false ) continue;
  8888. gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  8889. gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements );
  8890. sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale );
  8891. scale[ 0 ] = spriteScale.x;
  8892. scale[ 1 ] = spriteScale.y;
  8893. var fogType = 0;
  8894. if ( scene.fog && material.fog ) {
  8895. fogType = sceneFogType;
  8896. }
  8897. if ( oldFogType !== fogType ) {
  8898. gl.uniform1i( uniforms.fogType, fogType );
  8899. oldFogType = fogType;
  8900. }
  8901. if ( material.map !== null ) {
  8902. gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  8903. gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  8904. } else {
  8905. gl.uniform2f( uniforms.uvOffset, 0, 0 );
  8906. gl.uniform2f( uniforms.uvScale, 1, 1 );
  8907. }
  8908. gl.uniform1f( uniforms.opacity, material.opacity );
  8909. gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  8910. gl.uniform1f( uniforms.rotation, material.rotation );
  8911. gl.uniform2fv( uniforms.scale, scale );
  8912. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  8913. state.setDepthTest( material.depthTest );
  8914. state.setDepthWrite( material.depthWrite );
  8915. if ( material.map ) {
  8916. renderer.setTexture2D( material.map, 0 );
  8917. } else {
  8918. renderer.setTexture2D( texture, 0 );
  8919. }
  8920. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  8921. }
  8922. // restore gl
  8923. state.enable( gl.CULL_FACE );
  8924. renderer.resetGLState();
  8925. };
  8926. function createProgram() {
  8927. var program = gl.createProgram();
  8928. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  8929. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  8930. gl.shaderSource( vertexShader, [
  8931. 'precision ' + renderer.getPrecision() + ' float;',
  8932. 'uniform mat4 modelViewMatrix;',
  8933. 'uniform mat4 projectionMatrix;',
  8934. 'uniform float rotation;',
  8935. 'uniform vec2 scale;',
  8936. 'uniform vec2 uvOffset;',
  8937. 'uniform vec2 uvScale;',
  8938. 'attribute vec2 position;',
  8939. 'attribute vec2 uv;',
  8940. 'varying vec2 vUV;',
  8941. 'void main() {',
  8942. 'vUV = uvOffset + uv * uvScale;',
  8943. 'vec2 alignedPosition = position * scale;',
  8944. 'vec2 rotatedPosition;',
  8945. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  8946. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  8947. 'vec4 finalPosition;',
  8948. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  8949. 'finalPosition.xy += rotatedPosition;',
  8950. 'finalPosition = projectionMatrix * finalPosition;',
  8951. 'gl_Position = finalPosition;',
  8952. '}'
  8953. ].join( '\n' ) );
  8954. gl.shaderSource( fragmentShader, [
  8955. 'precision ' + renderer.getPrecision() + ' float;',
  8956. 'uniform vec3 color;',
  8957. 'uniform sampler2D map;',
  8958. 'uniform float opacity;',
  8959. 'uniform int fogType;',
  8960. 'uniform vec3 fogColor;',
  8961. 'uniform float fogDensity;',
  8962. 'uniform float fogNear;',
  8963. 'uniform float fogFar;',
  8964. 'uniform float alphaTest;',
  8965. 'varying vec2 vUV;',
  8966. 'void main() {',
  8967. 'vec4 texture = texture2D( map, vUV );',
  8968. 'if ( texture.a < alphaTest ) discard;',
  8969. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  8970. 'if ( fogType > 0 ) {',
  8971. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  8972. 'float fogFactor = 0.0;',
  8973. 'if ( fogType == 1 ) {',
  8974. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  8975. '} else {',
  8976. 'const float LOG2 = 1.442695;',
  8977. 'fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  8978. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  8979. '}',
  8980. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  8981. '}',
  8982. '}'
  8983. ].join( '\n' ) );
  8984. gl.compileShader( vertexShader );
  8985. gl.compileShader( fragmentShader );
  8986. gl.attachShader( program, vertexShader );
  8987. gl.attachShader( program, fragmentShader );
  8988. gl.linkProgram( program );
  8989. return program;
  8990. }
  8991. function painterSortStable( a, b ) {
  8992. if ( a.renderOrder !== b.renderOrder ) {
  8993. return a.renderOrder - b.renderOrder;
  8994. } else if ( a.z !== b.z ) {
  8995. return b.z - a.z;
  8996. } else {
  8997. return b.id - a.id;
  8998. }
  8999. }
  9000. }
  9001. /**
  9002. * @author mrdoob / http://mrdoob.com/
  9003. * @author alteredq / http://alteredqualia.com/
  9004. */
  9005. var materialId = 0;
  9006. function Material() {
  9007. Object.defineProperty( this, 'id', { value: materialId ++ } );
  9008. this.uuid = _Math.generateUUID();
  9009. this.name = '';
  9010. this.type = 'Material';
  9011. this.fog = true;
  9012. this.lights = true;
  9013. this.blending = NormalBlending;
  9014. this.side = FrontSide;
  9015. this.shading = SmoothShading; // THREE.FlatShading, THREE.SmoothShading
  9016. this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors
  9017. this.opacity = 1;
  9018. this.transparent = false;
  9019. this.blendSrc = SrcAlphaFactor;
  9020. this.blendDst = OneMinusSrcAlphaFactor;
  9021. this.blendEquation = AddEquation;
  9022. this.blendSrcAlpha = null;
  9023. this.blendDstAlpha = null;
  9024. this.blendEquationAlpha = null;
  9025. this.depthFunc = LessEqualDepth;
  9026. this.depthTest = true;
  9027. this.depthWrite = true;
  9028. this.clippingPlanes = null;
  9029. this.clipIntersection = false;
  9030. this.clipShadows = false;
  9031. this.colorWrite = true;
  9032. this.precision = null; // override the renderer's default precision for this material
  9033. this.polygonOffset = false;
  9034. this.polygonOffsetFactor = 0;
  9035. this.polygonOffsetUnits = 0;
  9036. this.alphaTest = 0;
  9037. this.premultipliedAlpha = false;
  9038. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  9039. this.visible = true;
  9040. this._needsUpdate = true;
  9041. }
  9042. Material.prototype = {
  9043. constructor: Material,
  9044. isMaterial: true,
  9045. get needsUpdate() {
  9046. return this._needsUpdate;
  9047. },
  9048. set needsUpdate( value ) {
  9049. if ( value === true ) this.update();
  9050. this._needsUpdate = value;
  9051. },
  9052. setValues: function ( values ) {
  9053. if ( values === undefined ) return;
  9054. for ( var key in values ) {
  9055. var newValue = values[ key ];
  9056. if ( newValue === undefined ) {
  9057. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  9058. continue;
  9059. }
  9060. var currentValue = this[ key ];
  9061. if ( currentValue === undefined ) {
  9062. console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
  9063. continue;
  9064. }
  9065. if ( currentValue && currentValue.isColor ) {
  9066. currentValue.set( newValue );
  9067. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  9068. currentValue.copy( newValue );
  9069. } else if ( key === 'overdraw' ) {
  9070. // ensure overdraw is backwards-compatible with legacy boolean type
  9071. this[ key ] = Number( newValue );
  9072. } else {
  9073. this[ key ] = newValue;
  9074. }
  9075. }
  9076. },
  9077. toJSON: function ( meta ) {
  9078. var isRoot = meta === undefined;
  9079. if ( isRoot ) {
  9080. meta = {
  9081. textures: {},
  9082. images: {}
  9083. };
  9084. }
  9085. var data = {
  9086. metadata: {
  9087. version: 4.4,
  9088. type: 'Material',
  9089. generator: 'Material.toJSON'
  9090. }
  9091. };
  9092. // standard Material serialization
  9093. data.uuid = this.uuid;
  9094. data.type = this.type;
  9095. if ( this.name !== '' ) data.name = this.name;
  9096. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  9097. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  9098. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  9099. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  9100. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  9101. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  9102. if ( this.clearCoat !== undefined ) data.clearCoat = this.clearCoat;
  9103. if ( this.clearCoatRoughness !== undefined ) data.clearCoatRoughness = this.clearCoatRoughness;
  9104. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  9105. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  9106. if ( this.lightMap && this.lightMap.isTexture ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  9107. if ( this.bumpMap && this.bumpMap.isTexture ) {
  9108. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  9109. data.bumpScale = this.bumpScale;
  9110. }
  9111. if ( this.normalMap && this.normalMap.isTexture ) {
  9112. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  9113. data.normalScale = this.normalScale.toArray();
  9114. }
  9115. if ( this.displacementMap && this.displacementMap.isTexture ) {
  9116. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  9117. data.displacementScale = this.displacementScale;
  9118. data.displacementBias = this.displacementBias;
  9119. }
  9120. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  9121. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  9122. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  9123. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  9124. if ( this.envMap && this.envMap.isTexture ) {
  9125. data.envMap = this.envMap.toJSON( meta ).uuid;
  9126. data.reflectivity = this.reflectivity; // Scale behind envMap
  9127. }
  9128. if ( this.gradientMap && this.gradientMap.isTexture ) {
  9129. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  9130. }
  9131. if ( this.size !== undefined ) data.size = this.size;
  9132. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  9133. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  9134. if ( this.shading !== SmoothShading ) data.shading = this.shading;
  9135. if ( this.side !== FrontSide ) data.side = this.side;
  9136. if ( this.vertexColors !== NoColors ) data.vertexColors = this.vertexColors;
  9137. if ( this.opacity < 1 ) data.opacity = this.opacity;
  9138. if ( this.transparent === true ) data.transparent = this.transparent;
  9139. data.depthFunc = this.depthFunc;
  9140. data.depthTest = this.depthTest;
  9141. data.depthWrite = this.depthWrite;
  9142. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  9143. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  9144. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  9145. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  9146. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  9147. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  9148. data.skinning = this.skinning;
  9149. data.morphTargets = this.morphTargets;
  9150. // TODO: Copied from Object3D.toJSON
  9151. function extractFromCache( cache ) {
  9152. var values = [];
  9153. for ( var key in cache ) {
  9154. var data = cache[ key ];
  9155. delete data.metadata;
  9156. values.push( data );
  9157. }
  9158. return values;
  9159. }
  9160. if ( isRoot ) {
  9161. var textures = extractFromCache( meta.textures );
  9162. var images = extractFromCache( meta.images );
  9163. if ( textures.length > 0 ) data.textures = textures;
  9164. if ( images.length > 0 ) data.images = images;
  9165. }
  9166. return data;
  9167. },
  9168. clone: function () {
  9169. return new this.constructor().copy( this );
  9170. },
  9171. copy: function ( source ) {
  9172. this.name = source.name;
  9173. this.fog = source.fog;
  9174. this.lights = source.lights;
  9175. this.blending = source.blending;
  9176. this.side = source.side;
  9177. this.shading = source.shading;
  9178. this.vertexColors = source.vertexColors;
  9179. this.opacity = source.opacity;
  9180. this.transparent = source.transparent;
  9181. this.blendSrc = source.blendSrc;
  9182. this.blendDst = source.blendDst;
  9183. this.blendEquation = source.blendEquation;
  9184. this.blendSrcAlpha = source.blendSrcAlpha;
  9185. this.blendDstAlpha = source.blendDstAlpha;
  9186. this.blendEquationAlpha = source.blendEquationAlpha;
  9187. this.depthFunc = source.depthFunc;
  9188. this.depthTest = source.depthTest;
  9189. this.depthWrite = source.depthWrite;
  9190. this.colorWrite = source.colorWrite;
  9191. this.precision = source.precision;
  9192. this.polygonOffset = source.polygonOffset;
  9193. this.polygonOffsetFactor = source.polygonOffsetFactor;
  9194. this.polygonOffsetUnits = source.polygonOffsetUnits;
  9195. this.alphaTest = source.alphaTest;
  9196. this.premultipliedAlpha = source.premultipliedAlpha;
  9197. this.overdraw = source.overdraw;
  9198. this.visible = source.visible;
  9199. this.clipShadows = source.clipShadows;
  9200. this.clipIntersection = source.clipIntersection;
  9201. var srcPlanes = source.clippingPlanes,
  9202. dstPlanes = null;
  9203. if ( srcPlanes !== null ) {
  9204. var n = srcPlanes.length;
  9205. dstPlanes = new Array( n );
  9206. for ( var i = 0; i !== n; ++ i )
  9207. dstPlanes[ i ] = srcPlanes[ i ].clone();
  9208. }
  9209. this.clippingPlanes = dstPlanes;
  9210. return this;
  9211. },
  9212. update: function () {
  9213. this.dispatchEvent( { type: 'update' } );
  9214. },
  9215. dispose: function () {
  9216. this.dispatchEvent( { type: 'dispose' } );
  9217. }
  9218. };
  9219. Object.assign( Material.prototype, EventDispatcher.prototype );
  9220. /**
  9221. * @author alteredq / http://alteredqualia.com/
  9222. *
  9223. * parameters = {
  9224. * defines: { "label" : "value" },
  9225. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  9226. *
  9227. * fragmentShader: <string>,
  9228. * vertexShader: <string>,
  9229. *
  9230. * wireframe: <boolean>,
  9231. * wireframeLinewidth: <float>,
  9232. *
  9233. * lights: <bool>,
  9234. *
  9235. * skinning: <bool>,
  9236. * morphTargets: <bool>,
  9237. * morphNormals: <bool>
  9238. * }
  9239. */
  9240. function ShaderMaterial( parameters ) {
  9241. Material.call( this );
  9242. this.type = 'ShaderMaterial';
  9243. this.defines = {};
  9244. this.uniforms = {};
  9245. this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
  9246. this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
  9247. this.linewidth = 1;
  9248. this.wireframe = false;
  9249. this.wireframeLinewidth = 1;
  9250. this.fog = false; // set to use scene fog
  9251. this.lights = false; // set to use scene lights
  9252. this.clipping = false; // set to use user-defined clipping planes
  9253. this.skinning = false; // set to use skinning attribute streams
  9254. this.morphTargets = false; // set to use morph targets
  9255. this.morphNormals = false; // set to use morph normals
  9256. this.extensions = {
  9257. derivatives: false, // set to use derivatives
  9258. fragDepth: false, // set to use fragment depth values
  9259. drawBuffers: false, // set to use draw buffers
  9260. shaderTextureLOD: false // set to use shader texture LOD
  9261. };
  9262. // When rendered geometry doesn't include these attributes but the material does,
  9263. // use these default values in WebGL. This avoids errors when buffer data is missing.
  9264. this.defaultAttributeValues = {
  9265. 'color': [ 1, 1, 1 ],
  9266. 'uv': [ 0, 0 ],
  9267. 'uv2': [ 0, 0 ]
  9268. };
  9269. this.index0AttributeName = undefined;
  9270. if ( parameters !== undefined ) {
  9271. if ( parameters.attributes !== undefined ) {
  9272. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  9273. }
  9274. this.setValues( parameters );
  9275. }
  9276. }
  9277. ShaderMaterial.prototype = Object.create( Material.prototype );
  9278. ShaderMaterial.prototype.constructor = ShaderMaterial;
  9279. ShaderMaterial.prototype.isShaderMaterial = true;
  9280. ShaderMaterial.prototype.copy = function ( source ) {
  9281. Material.prototype.copy.call( this, source );
  9282. this.fragmentShader = source.fragmentShader;
  9283. this.vertexShader = source.vertexShader;
  9284. this.uniforms = UniformsUtils.clone( source.uniforms );
  9285. this.defines = source.defines;
  9286. this.wireframe = source.wireframe;
  9287. this.wireframeLinewidth = source.wireframeLinewidth;
  9288. this.lights = source.lights;
  9289. this.clipping = source.clipping;
  9290. this.skinning = source.skinning;
  9291. this.morphTargets = source.morphTargets;
  9292. this.morphNormals = source.morphNormals;
  9293. this.extensions = source.extensions;
  9294. return this;
  9295. };
  9296. ShaderMaterial.prototype.toJSON = function ( meta ) {
  9297. var data = Material.prototype.toJSON.call( this, meta );
  9298. data.uniforms = this.uniforms;
  9299. data.vertexShader = this.vertexShader;
  9300. data.fragmentShader = this.fragmentShader;
  9301. return data;
  9302. };
  9303. /**
  9304. * @author mrdoob / http://mrdoob.com/
  9305. * @author alteredq / http://alteredqualia.com/
  9306. * @author bhouston / https://clara.io
  9307. * @author WestLangley / http://github.com/WestLangley
  9308. *
  9309. * parameters = {
  9310. *
  9311. * opacity: <float>,
  9312. *
  9313. * map: new THREE.Texture( <Image> ),
  9314. *
  9315. * alphaMap: new THREE.Texture( <Image> ),
  9316. *
  9317. * displacementMap: new THREE.Texture( <Image> ),
  9318. * displacementScale: <float>,
  9319. * displacementBias: <float>,
  9320. *
  9321. * wireframe: <boolean>,
  9322. * wireframeLinewidth: <float>
  9323. * }
  9324. */
  9325. function MeshDepthMaterial( parameters ) {
  9326. Material.call( this );
  9327. this.type = 'MeshDepthMaterial';
  9328. this.depthPacking = BasicDepthPacking;
  9329. this.skinning = false;
  9330. this.morphTargets = false;
  9331. this.map = null;
  9332. this.alphaMap = null;
  9333. this.displacementMap = null;
  9334. this.displacementScale = 1;
  9335. this.displacementBias = 0;
  9336. this.wireframe = false;
  9337. this.wireframeLinewidth = 1;
  9338. this.fog = false;
  9339. this.lights = false;
  9340. this.setValues( parameters );
  9341. }
  9342. MeshDepthMaterial.prototype = Object.create( Material.prototype );
  9343. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  9344. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  9345. MeshDepthMaterial.prototype.copy = function ( source ) {
  9346. Material.prototype.copy.call( this, source );
  9347. this.depthPacking = source.depthPacking;
  9348. this.skinning = source.skinning;
  9349. this.morphTargets = source.morphTargets;
  9350. this.map = source.map;
  9351. this.alphaMap = source.alphaMap;
  9352. this.displacementMap = source.displacementMap;
  9353. this.displacementScale = source.displacementScale;
  9354. this.displacementBias = source.displacementBias;
  9355. this.wireframe = source.wireframe;
  9356. this.wireframeLinewidth = source.wireframeLinewidth;
  9357. return this;
  9358. };
  9359. /**
  9360. * @author bhouston / http://clara.io
  9361. * @author WestLangley / http://github.com/WestLangley
  9362. */
  9363. function Box3( min, max ) {
  9364. this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity );
  9365. this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity );
  9366. }
  9367. Box3.prototype = {
  9368. constructor: Box3,
  9369. isBox3: true,
  9370. set: function ( min, max ) {
  9371. this.min.copy( min );
  9372. this.max.copy( max );
  9373. return this;
  9374. },
  9375. setFromArray: function ( array ) {
  9376. var minX = + Infinity;
  9377. var minY = + Infinity;
  9378. var minZ = + Infinity;
  9379. var maxX = - Infinity;
  9380. var maxY = - Infinity;
  9381. var maxZ = - Infinity;
  9382. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  9383. var x = array[ i ];
  9384. var y = array[ i + 1 ];
  9385. var z = array[ i + 2 ];
  9386. if ( x < minX ) minX = x;
  9387. if ( y < minY ) minY = y;
  9388. if ( z < minZ ) minZ = z;
  9389. if ( x > maxX ) maxX = x;
  9390. if ( y > maxY ) maxY = y;
  9391. if ( z > maxZ ) maxZ = z;
  9392. }
  9393. this.min.set( minX, minY, minZ );
  9394. this.max.set( maxX, maxY, maxZ );
  9395. return this;
  9396. },
  9397. setFromBufferAttribute: function ( attribute ) {
  9398. var minX = + Infinity;
  9399. var minY = + Infinity;
  9400. var minZ = + Infinity;
  9401. var maxX = - Infinity;
  9402. var maxY = - Infinity;
  9403. var maxZ = - Infinity;
  9404. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  9405. var x = attribute.getX( i );
  9406. var y = attribute.getY( i );
  9407. var z = attribute.getZ( i );
  9408. if ( x < minX ) minX = x;
  9409. if ( y < minY ) minY = y;
  9410. if ( z < minZ ) minZ = z;
  9411. if ( x > maxX ) maxX = x;
  9412. if ( y > maxY ) maxY = y;
  9413. if ( z > maxZ ) maxZ = z;
  9414. }
  9415. this.min.set( minX, minY, minZ );
  9416. this.max.set( maxX, maxY, maxZ );
  9417. return this;
  9418. },
  9419. setFromPoints: function ( points ) {
  9420. this.makeEmpty();
  9421. for ( var i = 0, il = points.length; i < il; i ++ ) {
  9422. this.expandByPoint( points[ i ] );
  9423. }
  9424. return this;
  9425. },
  9426. setFromCenterAndSize: function () {
  9427. var v1 = new Vector3();
  9428. return function setFromCenterAndSize( center, size ) {
  9429. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  9430. this.min.copy( center ).sub( halfSize );
  9431. this.max.copy( center ).add( halfSize );
  9432. return this;
  9433. };
  9434. }(),
  9435. setFromObject: function ( object ) {
  9436. this.makeEmpty();
  9437. return this.expandByObject( object );
  9438. },
  9439. clone: function () {
  9440. return new this.constructor().copy( this );
  9441. },
  9442. copy: function ( box ) {
  9443. this.min.copy( box.min );
  9444. this.max.copy( box.max );
  9445. return this;
  9446. },
  9447. makeEmpty: function () {
  9448. this.min.x = this.min.y = this.min.z = + Infinity;
  9449. this.max.x = this.max.y = this.max.z = - Infinity;
  9450. return this;
  9451. },
  9452. isEmpty: function () {
  9453. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  9454. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  9455. },
  9456. getCenter: function ( optionalTarget ) {
  9457. var result = optionalTarget || new Vector3();
  9458. return this.isEmpty() ? result.set( 0, 0, 0 ) : result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  9459. },
  9460. getSize: function ( optionalTarget ) {
  9461. var result = optionalTarget || new Vector3();
  9462. return this.isEmpty() ? result.set( 0, 0, 0 ) : result.subVectors( this.max, this.min );
  9463. },
  9464. expandByPoint: function ( point ) {
  9465. this.min.min( point );
  9466. this.max.max( point );
  9467. return this;
  9468. },
  9469. expandByVector: function ( vector ) {
  9470. this.min.sub( vector );
  9471. this.max.add( vector );
  9472. return this;
  9473. },
  9474. expandByScalar: function ( scalar ) {
  9475. this.min.addScalar( - scalar );
  9476. this.max.addScalar( scalar );
  9477. return this;
  9478. },
  9479. expandByObject: function () {
  9480. // Computes the world-axis-aligned bounding box of an object (including its children),
  9481. // accounting for both the object's, and children's, world transforms
  9482. var v1 = new Vector3();
  9483. return function expandByObject( object ) {
  9484. var scope = this;
  9485. object.updateMatrixWorld( true );
  9486. object.traverse( function ( node ) {
  9487. var i, l;
  9488. var geometry = node.geometry;
  9489. if ( geometry !== undefined ) {
  9490. if ( geometry.isGeometry ) {
  9491. var vertices = geometry.vertices;
  9492. for ( i = 0, l = vertices.length; i < l; i ++ ) {
  9493. v1.copy( vertices[ i ] );
  9494. v1.applyMatrix4( node.matrixWorld );
  9495. scope.expandByPoint( v1 );
  9496. }
  9497. } else if ( geometry.isBufferGeometry ) {
  9498. var attribute = geometry.attributes.position;
  9499. if ( attribute !== undefined ) {
  9500. for ( i = 0, l = attribute.count; i < l; i ++ ) {
  9501. v1.fromBufferAttribute( attribute, i ).applyMatrix4( node.matrixWorld );
  9502. scope.expandByPoint( v1 );
  9503. }
  9504. }
  9505. }
  9506. }
  9507. } );
  9508. return this;
  9509. };
  9510. }(),
  9511. containsPoint: function ( point ) {
  9512. return point.x < this.min.x || point.x > this.max.x ||
  9513. point.y < this.min.y || point.y > this.max.y ||
  9514. point.z < this.min.z || point.z > this.max.z ? false : true;
  9515. },
  9516. containsBox: function ( box ) {
  9517. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  9518. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  9519. this.min.z <= box.min.z && box.max.z <= this.max.z;
  9520. },
  9521. getParameter: function ( point, optionalTarget ) {
  9522. // This can potentially have a divide by zero if the box
  9523. // has a size dimension of 0.
  9524. var result = optionalTarget || new Vector3();
  9525. return result.set(
  9526. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  9527. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  9528. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  9529. );
  9530. },
  9531. intersectsBox: function ( box ) {
  9532. // using 6 splitting planes to rule out intersections.
  9533. return box.max.x < this.min.x || box.min.x > this.max.x ||
  9534. box.max.y < this.min.y || box.min.y > this.max.y ||
  9535. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  9536. },
  9537. intersectsSphere: ( function () {
  9538. var closestPoint;
  9539. return function intersectsSphere( sphere ) {
  9540. if ( closestPoint === undefined ) closestPoint = new Vector3();
  9541. // Find the point on the AABB closest to the sphere center.
  9542. this.clampPoint( sphere.center, closestPoint );
  9543. // If that point is inside the sphere, the AABB and sphere intersect.
  9544. return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  9545. };
  9546. } )(),
  9547. intersectsPlane: function ( plane ) {
  9548. // We compute the minimum and maximum dot product values. If those values
  9549. // are on the same side (back or front) of the plane, then there is no intersection.
  9550. var min, max;
  9551. if ( plane.normal.x > 0 ) {
  9552. min = plane.normal.x * this.min.x;
  9553. max = plane.normal.x * this.max.x;
  9554. } else {
  9555. min = plane.normal.x * this.max.x;
  9556. max = plane.normal.x * this.min.x;
  9557. }
  9558. if ( plane.normal.y > 0 ) {
  9559. min += plane.normal.y * this.min.y;
  9560. max += plane.normal.y * this.max.y;
  9561. } else {
  9562. min += plane.normal.y * this.max.y;
  9563. max += plane.normal.y * this.min.y;
  9564. }
  9565. if ( plane.normal.z > 0 ) {
  9566. min += plane.normal.z * this.min.z;
  9567. max += plane.normal.z * this.max.z;
  9568. } else {
  9569. min += plane.normal.z * this.max.z;
  9570. max += plane.normal.z * this.min.z;
  9571. }
  9572. return ( min <= plane.constant && max >= plane.constant );
  9573. },
  9574. clampPoint: function ( point, optionalTarget ) {
  9575. var result = optionalTarget || new Vector3();
  9576. return result.copy( point ).clamp( this.min, this.max );
  9577. },
  9578. distanceToPoint: function () {
  9579. var v1 = new Vector3();
  9580. return function distanceToPoint( point ) {
  9581. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  9582. return clampedPoint.sub( point ).length();
  9583. };
  9584. }(),
  9585. getBoundingSphere: function () {
  9586. var v1 = new Vector3();
  9587. return function getBoundingSphere( optionalTarget ) {
  9588. var result = optionalTarget || new Sphere();
  9589. this.getCenter( result.center );
  9590. result.radius = this.getSize( v1 ).length() * 0.5;
  9591. return result;
  9592. };
  9593. }(),
  9594. intersect: function ( box ) {
  9595. this.min.max( box.min );
  9596. this.max.min( box.max );
  9597. // 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.
  9598. if( this.isEmpty() ) this.makeEmpty();
  9599. return this;
  9600. },
  9601. union: function ( box ) {
  9602. this.min.min( box.min );
  9603. this.max.max( box.max );
  9604. return this;
  9605. },
  9606. applyMatrix4: function () {
  9607. var points = [
  9608. new Vector3(),
  9609. new Vector3(),
  9610. new Vector3(),
  9611. new Vector3(),
  9612. new Vector3(),
  9613. new Vector3(),
  9614. new Vector3(),
  9615. new Vector3()
  9616. ];
  9617. return function applyMatrix4( matrix ) {
  9618. // transform of empty box is an empty box.
  9619. if( this.isEmpty() ) return this;
  9620. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  9621. points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  9622. points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  9623. points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  9624. points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  9625. points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  9626. points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  9627. points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  9628. points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  9629. this.setFromPoints( points );
  9630. return this;
  9631. };
  9632. }(),
  9633. translate: function ( offset ) {
  9634. this.min.add( offset );
  9635. this.max.add( offset );
  9636. return this;
  9637. },
  9638. equals: function ( box ) {
  9639. return box.min.equals( this.min ) && box.max.equals( this.max );
  9640. }
  9641. };
  9642. /**
  9643. * @author bhouston / http://clara.io
  9644. * @author mrdoob / http://mrdoob.com/
  9645. */
  9646. function Sphere( center, radius ) {
  9647. this.center = ( center !== undefined ) ? center : new Vector3();
  9648. this.radius = ( radius !== undefined ) ? radius : 0;
  9649. }
  9650. Sphere.prototype = {
  9651. constructor: Sphere,
  9652. set: function ( center, radius ) {
  9653. this.center.copy( center );
  9654. this.radius = radius;
  9655. return this;
  9656. },
  9657. setFromPoints: function () {
  9658. var box;
  9659. return function setFromPoints( points, optionalCenter ) {
  9660. if ( box === undefined ) box = new Box3(); // see #10547
  9661. var center = this.center;
  9662. if ( optionalCenter !== undefined ) {
  9663. center.copy( optionalCenter );
  9664. } else {
  9665. box.setFromPoints( points ).getCenter( center );
  9666. }
  9667. var maxRadiusSq = 0;
  9668. for ( var i = 0, il = points.length; i < il; i ++ ) {
  9669. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  9670. }
  9671. this.radius = Math.sqrt( maxRadiusSq );
  9672. return this;
  9673. };
  9674. }(),
  9675. clone: function () {
  9676. return new this.constructor().copy( this );
  9677. },
  9678. copy: function ( sphere ) {
  9679. this.center.copy( sphere.center );
  9680. this.radius = sphere.radius;
  9681. return this;
  9682. },
  9683. empty: function () {
  9684. return ( this.radius <= 0 );
  9685. },
  9686. containsPoint: function ( point ) {
  9687. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  9688. },
  9689. distanceToPoint: function ( point ) {
  9690. return ( point.distanceTo( this.center ) - this.radius );
  9691. },
  9692. intersectsSphere: function ( sphere ) {
  9693. var radiusSum = this.radius + sphere.radius;
  9694. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  9695. },
  9696. intersectsBox: function ( box ) {
  9697. return box.intersectsSphere( this );
  9698. },
  9699. intersectsPlane: function ( plane ) {
  9700. // We use the following equation to compute the signed distance from
  9701. // the center of the sphere to the plane.
  9702. //
  9703. // distance = q * n - d
  9704. //
  9705. // If this distance is greater than the radius of the sphere,
  9706. // then there is no intersection.
  9707. return Math.abs( this.center.dot( plane.normal ) - plane.constant ) <= this.radius;
  9708. },
  9709. clampPoint: function ( point, optionalTarget ) {
  9710. var deltaLengthSq = this.center.distanceToSquared( point );
  9711. var result = optionalTarget || new Vector3();
  9712. result.copy( point );
  9713. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  9714. result.sub( this.center ).normalize();
  9715. result.multiplyScalar( this.radius ).add( this.center );
  9716. }
  9717. return result;
  9718. },
  9719. getBoundingBox: function ( optionalTarget ) {
  9720. var box = optionalTarget || new Box3();
  9721. box.set( this.center, this.center );
  9722. box.expandByScalar( this.radius );
  9723. return box;
  9724. },
  9725. applyMatrix4: function ( matrix ) {
  9726. this.center.applyMatrix4( matrix );
  9727. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  9728. return this;
  9729. },
  9730. translate: function ( offset ) {
  9731. this.center.add( offset );
  9732. return this;
  9733. },
  9734. equals: function ( sphere ) {
  9735. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  9736. }
  9737. };
  9738. /**
  9739. * @author alteredq / http://alteredqualia.com/
  9740. * @author WestLangley / http://github.com/WestLangley
  9741. * @author bhouston / http://clara.io
  9742. * @author tschw
  9743. */
  9744. function Matrix3() {
  9745. this.elements = new Float32Array( [
  9746. 1, 0, 0,
  9747. 0, 1, 0,
  9748. 0, 0, 1
  9749. ] );
  9750. if ( arguments.length > 0 ) {
  9751. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  9752. }
  9753. }
  9754. Matrix3.prototype = {
  9755. constructor: Matrix3,
  9756. isMatrix3: true,
  9757. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  9758. var te = this.elements;
  9759. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  9760. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  9761. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  9762. return this;
  9763. },
  9764. identity: function () {
  9765. this.set(
  9766. 1, 0, 0,
  9767. 0, 1, 0,
  9768. 0, 0, 1
  9769. );
  9770. return this;
  9771. },
  9772. clone: function () {
  9773. return new this.constructor().fromArray( this.elements );
  9774. },
  9775. copy: function ( m ) {
  9776. var me = m.elements;
  9777. this.set(
  9778. me[ 0 ], me[ 3 ], me[ 6 ],
  9779. me[ 1 ], me[ 4 ], me[ 7 ],
  9780. me[ 2 ], me[ 5 ], me[ 8 ]
  9781. );
  9782. return this;
  9783. },
  9784. setFromMatrix4: function( m ) {
  9785. var me = m.elements;
  9786. this.set(
  9787. me[ 0 ], me[ 4 ], me[ 8 ],
  9788. me[ 1 ], me[ 5 ], me[ 9 ],
  9789. me[ 2 ], me[ 6 ], me[ 10 ]
  9790. );
  9791. return this;
  9792. },
  9793. applyToBufferAttribute: function () {
  9794. var v1;
  9795. return function applyToBufferAttribute( attribute ) {
  9796. if ( v1 === undefined ) v1 = new Vector3();
  9797. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  9798. v1.x = attribute.getX( i );
  9799. v1.y = attribute.getY( i );
  9800. v1.z = attribute.getZ( i );
  9801. v1.applyMatrix3( this );
  9802. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  9803. }
  9804. return attribute;
  9805. };
  9806. }(),
  9807. multiplyScalar: function ( s ) {
  9808. var te = this.elements;
  9809. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  9810. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  9811. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  9812. return this;
  9813. },
  9814. determinant: function () {
  9815. var te = this.elements;
  9816. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  9817. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  9818. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  9819. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  9820. },
  9821. getInverse: function ( matrix, throwOnDegenerate ) {
  9822. if ( matrix && matrix.isMatrix4 ) {
  9823. console.error( "THREE.Matrix3.getInverse no longer takes a Matrix4 argument." );
  9824. }
  9825. var me = matrix.elements,
  9826. te = this.elements,
  9827. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ],
  9828. n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ],
  9829. n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ],
  9830. t11 = n33 * n22 - n32 * n23,
  9831. t12 = n32 * n13 - n33 * n12,
  9832. t13 = n23 * n12 - n22 * n13,
  9833. det = n11 * t11 + n21 * t12 + n31 * t13;
  9834. if ( det === 0 ) {
  9835. var msg = "THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0";
  9836. if ( throwOnDegenerate === true ) {
  9837. throw new Error( msg );
  9838. } else {
  9839. console.warn( msg );
  9840. }
  9841. return this.identity();
  9842. }
  9843. var detInv = 1 / det;
  9844. te[ 0 ] = t11 * detInv;
  9845. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  9846. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  9847. te[ 3 ] = t12 * detInv;
  9848. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  9849. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  9850. te[ 6 ] = t13 * detInv;
  9851. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  9852. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  9853. return this;
  9854. },
  9855. transpose: function () {
  9856. var tmp, m = this.elements;
  9857. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  9858. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  9859. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  9860. return this;
  9861. },
  9862. getNormalMatrix: function ( matrix4 ) {
  9863. return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose();
  9864. },
  9865. transposeIntoArray: function ( r ) {
  9866. var m = this.elements;
  9867. r[ 0 ] = m[ 0 ];
  9868. r[ 1 ] = m[ 3 ];
  9869. r[ 2 ] = m[ 6 ];
  9870. r[ 3 ] = m[ 1 ];
  9871. r[ 4 ] = m[ 4 ];
  9872. r[ 5 ] = m[ 7 ];
  9873. r[ 6 ] = m[ 2 ];
  9874. r[ 7 ] = m[ 5 ];
  9875. r[ 8 ] = m[ 8 ];
  9876. return this;
  9877. },
  9878. fromArray: function ( array, offset ) {
  9879. if ( offset === undefined ) offset = 0;
  9880. for( var i = 0; i < 9; i ++ ) {
  9881. this.elements[ i ] = array[ i + offset ];
  9882. }
  9883. return this;
  9884. },
  9885. toArray: function ( array, offset ) {
  9886. if ( array === undefined ) array = [];
  9887. if ( offset === undefined ) offset = 0;
  9888. var te = this.elements;
  9889. array[ offset ] = te[ 0 ];
  9890. array[ offset + 1 ] = te[ 1 ];
  9891. array[ offset + 2 ] = te[ 2 ];
  9892. array[ offset + 3 ] = te[ 3 ];
  9893. array[ offset + 4 ] = te[ 4 ];
  9894. array[ offset + 5 ] = te[ 5 ];
  9895. array[ offset + 6 ] = te[ 6 ];
  9896. array[ offset + 7 ] = te[ 7 ];
  9897. array[ offset + 8 ] = te[ 8 ];
  9898. return array;
  9899. }
  9900. };
  9901. /**
  9902. * @author bhouston / http://clara.io
  9903. */
  9904. function Plane( normal, constant ) {
  9905. this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 );
  9906. this.constant = ( constant !== undefined ) ? constant : 0;
  9907. }
  9908. Plane.prototype = {
  9909. constructor: Plane,
  9910. set: function ( normal, constant ) {
  9911. this.normal.copy( normal );
  9912. this.constant = constant;
  9913. return this;
  9914. },
  9915. setComponents: function ( x, y, z, w ) {
  9916. this.normal.set( x, y, z );
  9917. this.constant = w;
  9918. return this;
  9919. },
  9920. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  9921. this.normal.copy( normal );
  9922. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  9923. return this;
  9924. },
  9925. setFromCoplanarPoints: function () {
  9926. var v1 = new Vector3();
  9927. var v2 = new Vector3();
  9928. return function setFromCoplanarPoints( a, b, c ) {
  9929. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  9930. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  9931. this.setFromNormalAndCoplanarPoint( normal, a );
  9932. return this;
  9933. };
  9934. }(),
  9935. clone: function () {
  9936. return new this.constructor().copy( this );
  9937. },
  9938. copy: function ( plane ) {
  9939. this.normal.copy( plane.normal );
  9940. this.constant = plane.constant;
  9941. return this;
  9942. },
  9943. normalize: function () {
  9944. // Note: will lead to a divide by zero if the plane is invalid.
  9945. var inverseNormalLength = 1.0 / this.normal.length();
  9946. this.normal.multiplyScalar( inverseNormalLength );
  9947. this.constant *= inverseNormalLength;
  9948. return this;
  9949. },
  9950. negate: function () {
  9951. this.constant *= - 1;
  9952. this.normal.negate();
  9953. return this;
  9954. },
  9955. distanceToPoint: function ( point ) {
  9956. return this.normal.dot( point ) + this.constant;
  9957. },
  9958. distanceToSphere: function ( sphere ) {
  9959. return this.distanceToPoint( sphere.center ) - sphere.radius;
  9960. },
  9961. projectPoint: function ( point, optionalTarget ) {
  9962. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  9963. },
  9964. orthoPoint: function ( point, optionalTarget ) {
  9965. var perpendicularMagnitude = this.distanceToPoint( point );
  9966. var result = optionalTarget || new Vector3();
  9967. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  9968. },
  9969. intersectLine: function () {
  9970. var v1 = new Vector3();
  9971. return function intersectLine( line, optionalTarget ) {
  9972. var result = optionalTarget || new Vector3();
  9973. var direction = line.delta( v1 );
  9974. var denominator = this.normal.dot( direction );
  9975. if ( denominator === 0 ) {
  9976. // line is coplanar, return origin
  9977. if ( this.distanceToPoint( line.start ) === 0 ) {
  9978. return result.copy( line.start );
  9979. }
  9980. // Unsure if this is the correct method to handle this case.
  9981. return undefined;
  9982. }
  9983. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  9984. if ( t < 0 || t > 1 ) {
  9985. return undefined;
  9986. }
  9987. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  9988. };
  9989. }(),
  9990. intersectsLine: function ( line ) {
  9991. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  9992. var startSign = this.distanceToPoint( line.start );
  9993. var endSign = this.distanceToPoint( line.end );
  9994. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  9995. },
  9996. intersectsBox: function ( box ) {
  9997. return box.intersectsPlane( this );
  9998. },
  9999. intersectsSphere: function ( sphere ) {
  10000. return sphere.intersectsPlane( this );
  10001. },
  10002. coplanarPoint: function ( optionalTarget ) {
  10003. var result = optionalTarget || new Vector3();
  10004. return result.copy( this.normal ).multiplyScalar( - this.constant );
  10005. },
  10006. applyMatrix4: function () {
  10007. var v1 = new Vector3();
  10008. var m1 = new Matrix3();
  10009. return function applyMatrix4( matrix, optionalNormalMatrix ) {
  10010. var referencePoint = this.coplanarPoint( v1 ).applyMatrix4( matrix );
  10011. // transform normal based on theory here:
  10012. // http://www.songho.ca/opengl/gl_normaltransform.html
  10013. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  10014. var normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  10015. // recalculate constant (like in setFromNormalAndCoplanarPoint)
  10016. this.constant = - referencePoint.dot( normal );
  10017. return this;
  10018. };
  10019. }(),
  10020. translate: function ( offset ) {
  10021. this.constant = this.constant - offset.dot( this.normal );
  10022. return this;
  10023. },
  10024. equals: function ( plane ) {
  10025. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  10026. }
  10027. };
  10028. /**
  10029. * @author mrdoob / http://mrdoob.com/
  10030. * @author alteredq / http://alteredqualia.com/
  10031. * @author bhouston / http://clara.io
  10032. */
  10033. function Frustum( p0, p1, p2, p3, p4, p5 ) {
  10034. this.planes = [
  10035. ( p0 !== undefined ) ? p0 : new Plane(),
  10036. ( p1 !== undefined ) ? p1 : new Plane(),
  10037. ( p2 !== undefined ) ? p2 : new Plane(),
  10038. ( p3 !== undefined ) ? p3 : new Plane(),
  10039. ( p4 !== undefined ) ? p4 : new Plane(),
  10040. ( p5 !== undefined ) ? p5 : new Plane()
  10041. ];
  10042. }
  10043. Frustum.prototype = {
  10044. constructor: Frustum,
  10045. set: function ( p0, p1, p2, p3, p4, p5 ) {
  10046. var planes = this.planes;
  10047. planes[ 0 ].copy( p0 );
  10048. planes[ 1 ].copy( p1 );
  10049. planes[ 2 ].copy( p2 );
  10050. planes[ 3 ].copy( p3 );
  10051. planes[ 4 ].copy( p4 );
  10052. planes[ 5 ].copy( p5 );
  10053. return this;
  10054. },
  10055. clone: function () {
  10056. return new this.constructor().copy( this );
  10057. },
  10058. copy: function ( frustum ) {
  10059. var planes = this.planes;
  10060. for ( var i = 0; i < 6; i ++ ) {
  10061. planes[ i ].copy( frustum.planes[ i ] );
  10062. }
  10063. return this;
  10064. },
  10065. setFromMatrix: function ( m ) {
  10066. var planes = this.planes;
  10067. var me = m.elements;
  10068. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  10069. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  10070. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  10071. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  10072. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  10073. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  10074. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  10075. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  10076. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  10077. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  10078. return this;
  10079. },
  10080. intersectsObject: function () {
  10081. var sphere = new Sphere();
  10082. return function intersectsObject( object ) {
  10083. var geometry = object.geometry;
  10084. if ( geometry.boundingSphere === null )
  10085. geometry.computeBoundingSphere();
  10086. sphere.copy( geometry.boundingSphere )
  10087. .applyMatrix4( object.matrixWorld );
  10088. return this.intersectsSphere( sphere );
  10089. };
  10090. }(),
  10091. intersectsSprite: function () {
  10092. var sphere = new Sphere();
  10093. return function intersectsSprite( sprite ) {
  10094. sphere.center.set( 0, 0, 0 );
  10095. sphere.radius = 0.7071067811865476;
  10096. sphere.applyMatrix4( sprite.matrixWorld );
  10097. return this.intersectsSphere( sphere );
  10098. };
  10099. }(),
  10100. intersectsSphere: function ( sphere ) {
  10101. var planes = this.planes;
  10102. var center = sphere.center;
  10103. var negRadius = - sphere.radius;
  10104. for ( var i = 0; i < 6; i ++ ) {
  10105. var distance = planes[ i ].distanceToPoint( center );
  10106. if ( distance < negRadius ) {
  10107. return false;
  10108. }
  10109. }
  10110. return true;
  10111. },
  10112. intersectsBox: function () {
  10113. var p1 = new Vector3(),
  10114. p2 = new Vector3();
  10115. return function intersectsBox( box ) {
  10116. var planes = this.planes;
  10117. for ( var i = 0; i < 6 ; i ++ ) {
  10118. var plane = planes[ i ];
  10119. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  10120. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  10121. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  10122. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  10123. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  10124. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  10125. var d1 = plane.distanceToPoint( p1 );
  10126. var d2 = plane.distanceToPoint( p2 );
  10127. // if both outside plane, no intersection
  10128. if ( d1 < 0 && d2 < 0 ) {
  10129. return false;
  10130. }
  10131. }
  10132. return true;
  10133. };
  10134. }(),
  10135. containsPoint: function ( point ) {
  10136. var planes = this.planes;
  10137. for ( var i = 0; i < 6; i ++ ) {
  10138. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  10139. return false;
  10140. }
  10141. }
  10142. return true;
  10143. }
  10144. };
  10145. /**
  10146. * @author alteredq / http://alteredqualia.com/
  10147. * @author mrdoob / http://mrdoob.com/
  10148. */
  10149. function WebGLShadowMap( _renderer, _lights, _objects, capabilities ) {
  10150. var _gl = _renderer.context,
  10151. _state = _renderer.state,
  10152. _frustum = new Frustum(),
  10153. _projScreenMatrix = new Matrix4(),
  10154. _lightShadows = _lights.shadows,
  10155. _shadowMapSize = new Vector2(),
  10156. _maxShadowMapSize = new Vector2( capabilities.maxTextureSize, capabilities.maxTextureSize ),
  10157. _lookTarget = new Vector3(),
  10158. _lightPositionWorld = new Vector3(),
  10159. _renderList = [],
  10160. _MorphingFlag = 1,
  10161. _SkinningFlag = 2,
  10162. _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1,
  10163. _depthMaterials = new Array( _NumberOfMaterialVariants ),
  10164. _distanceMaterials = new Array( _NumberOfMaterialVariants ),
  10165. _materialCache = {};
  10166. var cubeDirections = [
  10167. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  10168. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  10169. ];
  10170. var cubeUps = [
  10171. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  10172. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  10173. ];
  10174. var cube2DViewPorts = [
  10175. new Vector4(), new Vector4(), new Vector4(),
  10176. new Vector4(), new Vector4(), new Vector4()
  10177. ];
  10178. // init
  10179. var depthMaterialTemplate = new MeshDepthMaterial();
  10180. depthMaterialTemplate.depthPacking = RGBADepthPacking;
  10181. depthMaterialTemplate.clipping = true;
  10182. var distanceShader = ShaderLib[ "distanceRGBA" ];
  10183. var distanceUniforms = UniformsUtils.clone( distanceShader.uniforms );
  10184. for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) {
  10185. var useMorphing = ( i & _MorphingFlag ) !== 0;
  10186. var useSkinning = ( i & _SkinningFlag ) !== 0;
  10187. var depthMaterial = depthMaterialTemplate.clone();
  10188. depthMaterial.morphTargets = useMorphing;
  10189. depthMaterial.skinning = useSkinning;
  10190. _depthMaterials[ i ] = depthMaterial;
  10191. var distanceMaterial = new ShaderMaterial( {
  10192. defines: {
  10193. 'USE_SHADOWMAP': ''
  10194. },
  10195. uniforms: distanceUniforms,
  10196. vertexShader: distanceShader.vertexShader,
  10197. fragmentShader: distanceShader.fragmentShader,
  10198. morphTargets: useMorphing,
  10199. skinning: useSkinning,
  10200. clipping: true
  10201. } );
  10202. _distanceMaterials[ i ] = distanceMaterial;
  10203. }
  10204. //
  10205. var scope = this;
  10206. this.enabled = false;
  10207. this.autoUpdate = true;
  10208. this.needsUpdate = false;
  10209. this.type = PCFShadowMap;
  10210. this.renderReverseSided = true;
  10211. this.renderSingleSided = true;
  10212. this.render = function ( scene, camera ) {
  10213. if ( scope.enabled === false ) return;
  10214. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  10215. if ( _lightShadows.length === 0 ) return;
  10216. // Set GL state for depth map.
  10217. _state.buffers.color.setClear( 1, 1, 1, 1 );
  10218. _state.disable( _gl.BLEND );
  10219. _state.setDepthTest( true );
  10220. _state.setScissorTest( false );
  10221. // render depth map
  10222. var faceCount, isPointLight;
  10223. for ( var i = 0, il = _lightShadows.length; i < il; i ++ ) {
  10224. var light = _lightShadows[ i ];
  10225. var shadow = light.shadow;
  10226. if ( shadow === undefined ) {
  10227. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  10228. continue;
  10229. }
  10230. var shadowCamera = shadow.camera;
  10231. _shadowMapSize.copy( shadow.mapSize );
  10232. _shadowMapSize.min( _maxShadowMapSize );
  10233. if ( light && light.isPointLight ) {
  10234. faceCount = 6;
  10235. isPointLight = true;
  10236. var vpWidth = _shadowMapSize.x;
  10237. var vpHeight = _shadowMapSize.y;
  10238. // These viewports map a cube-map onto a 2D texture with the
  10239. // following orientation:
  10240. //
  10241. // xzXZ
  10242. // y Y
  10243. //
  10244. // X - Positive x direction
  10245. // x - Negative x direction
  10246. // Y - Positive y direction
  10247. // y - Negative y direction
  10248. // Z - Positive z direction
  10249. // z - Negative z direction
  10250. // positive X
  10251. cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight );
  10252. // negative X
  10253. cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight );
  10254. // positive Z
  10255. cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight );
  10256. // negative Z
  10257. cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight );
  10258. // positive Y
  10259. cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight );
  10260. // negative Y
  10261. cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight );
  10262. _shadowMapSize.x *= 4.0;
  10263. _shadowMapSize.y *= 2.0;
  10264. } else {
  10265. faceCount = 1;
  10266. isPointLight = false;
  10267. }
  10268. if ( shadow.map === null ) {
  10269. var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  10270. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  10271. shadowCamera.updateProjectionMatrix();
  10272. }
  10273. if ( shadow.isSpotLightShadow ) {
  10274. shadow.update( light );
  10275. }
  10276. // TODO (abelnation / sam-g-steel): is this needed?
  10277. if (shadow && shadow.isRectAreaLightShadow ) {
  10278. shadow.update( light );
  10279. }
  10280. var shadowMap = shadow.map;
  10281. var shadowMatrix = shadow.matrix;
  10282. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  10283. shadowCamera.position.copy( _lightPositionWorld );
  10284. _renderer.setRenderTarget( shadowMap );
  10285. _renderer.clear();
  10286. // render shadow map for each cube face (if omni-directional) or
  10287. // run a single pass if not
  10288. for ( var face = 0; face < faceCount; face ++ ) {
  10289. if ( isPointLight ) {
  10290. _lookTarget.copy( shadowCamera.position );
  10291. _lookTarget.add( cubeDirections[ face ] );
  10292. shadowCamera.up.copy( cubeUps[ face ] );
  10293. shadowCamera.lookAt( _lookTarget );
  10294. var vpDimensions = cube2DViewPorts[ face ];
  10295. _state.viewport( vpDimensions );
  10296. } else {
  10297. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  10298. shadowCamera.lookAt( _lookTarget );
  10299. }
  10300. shadowCamera.updateMatrixWorld();
  10301. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  10302. // compute shadow matrix
  10303. shadowMatrix.set(
  10304. 0.5, 0.0, 0.0, 0.5,
  10305. 0.0, 0.5, 0.0, 0.5,
  10306. 0.0, 0.0, 0.5, 0.5,
  10307. 0.0, 0.0, 0.0, 1.0
  10308. );
  10309. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  10310. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  10311. // update camera matrices and frustum
  10312. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  10313. _frustum.setFromMatrix( _projScreenMatrix );
  10314. // set object matrices & frustum culling
  10315. _renderList.length = 0;
  10316. projectObject( scene, camera, shadowCamera );
  10317. // render shadow map
  10318. // render regular objects
  10319. for ( var j = 0, jl = _renderList.length; j < jl; j ++ ) {
  10320. var object = _renderList[ j ];
  10321. var geometry = _objects.update( object );
  10322. var material = object.material;
  10323. if ( material && material.isMultiMaterial ) {
  10324. var groups = geometry.groups;
  10325. var materials = material.materials;
  10326. for ( var k = 0, kl = groups.length; k < kl; k ++ ) {
  10327. var group = groups[ k ];
  10328. var groupMaterial = materials[ group.materialIndex ];
  10329. if ( groupMaterial.visible === true ) {
  10330. var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld );
  10331. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  10332. }
  10333. }
  10334. } else {
  10335. var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld );
  10336. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  10337. }
  10338. }
  10339. }
  10340. }
  10341. // Restore GL state.
  10342. var clearColor = _renderer.getClearColor(),
  10343. clearAlpha = _renderer.getClearAlpha();
  10344. _renderer.setClearColor( clearColor, clearAlpha );
  10345. scope.needsUpdate = false;
  10346. };
  10347. function getDepthMaterial( object, material, isPointLight, lightPositionWorld ) {
  10348. var geometry = object.geometry;
  10349. var result = null;
  10350. var materialVariants = _depthMaterials;
  10351. var customMaterial = object.customDepthMaterial;
  10352. if ( isPointLight ) {
  10353. materialVariants = _distanceMaterials;
  10354. customMaterial = object.customDistanceMaterial;
  10355. }
  10356. if ( ! customMaterial ) {
  10357. var useMorphing = false;
  10358. if ( material.morphTargets ) {
  10359. if ( geometry && geometry.isBufferGeometry ) {
  10360. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  10361. } else if ( geometry && geometry.isGeometry ) {
  10362. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  10363. }
  10364. }
  10365. var useSkinning = object.isSkinnedMesh && material.skinning;
  10366. var variantIndex = 0;
  10367. if ( useMorphing ) variantIndex |= _MorphingFlag;
  10368. if ( useSkinning ) variantIndex |= _SkinningFlag;
  10369. result = materialVariants[ variantIndex ];
  10370. } else {
  10371. result = customMaterial;
  10372. }
  10373. if ( _renderer.localClippingEnabled &&
  10374. material.clipShadows === true &&
  10375. material.clippingPlanes.length !== 0 ) {
  10376. // in this case we need a unique material instance reflecting the
  10377. // appropriate state
  10378. var keyA = result.uuid, keyB = material.uuid;
  10379. var materialsForVariant = _materialCache[ keyA ];
  10380. if ( materialsForVariant === undefined ) {
  10381. materialsForVariant = {};
  10382. _materialCache[ keyA ] = materialsForVariant;
  10383. }
  10384. var cachedMaterial = materialsForVariant[ keyB ];
  10385. if ( cachedMaterial === undefined ) {
  10386. cachedMaterial = result.clone();
  10387. materialsForVariant[ keyB ] = cachedMaterial;
  10388. }
  10389. result = cachedMaterial;
  10390. }
  10391. result.visible = material.visible;
  10392. result.wireframe = material.wireframe;
  10393. var side = material.side;
  10394. if ( scope.renderSingleSided && side == DoubleSide ) {
  10395. side = FrontSide;
  10396. }
  10397. if ( scope.renderReverseSided ) {
  10398. if ( side === FrontSide ) side = BackSide;
  10399. else if ( side === BackSide ) side = FrontSide;
  10400. }
  10401. result.side = side;
  10402. result.clipShadows = material.clipShadows;
  10403. result.clippingPlanes = material.clippingPlanes;
  10404. result.wireframeLinewidth = material.wireframeLinewidth;
  10405. result.linewidth = material.linewidth;
  10406. if ( isPointLight && result.uniforms.lightPos !== undefined ) {
  10407. result.uniforms.lightPos.value.copy( lightPositionWorld );
  10408. }
  10409. return result;
  10410. }
  10411. function projectObject( object, camera, shadowCamera ) {
  10412. if ( object.visible === false ) return;
  10413. var visible = ( object.layers.mask & camera.layers.mask ) !== 0;
  10414. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  10415. if ( object.castShadow && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) {
  10416. var material = object.material;
  10417. if ( material.visible === true ) {
  10418. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  10419. _renderList.push( object );
  10420. }
  10421. }
  10422. }
  10423. var children = object.children;
  10424. for ( var i = 0, l = children.length; i < l; i ++ ) {
  10425. projectObject( children[ i ], camera, shadowCamera );
  10426. }
  10427. }
  10428. }
  10429. /**
  10430. * @author bhouston / http://clara.io
  10431. */
  10432. function Ray( origin, direction ) {
  10433. this.origin = ( origin !== undefined ) ? origin : new Vector3();
  10434. this.direction = ( direction !== undefined ) ? direction : new Vector3();
  10435. }
  10436. Ray.prototype = {
  10437. constructor: Ray,
  10438. set: function ( origin, direction ) {
  10439. this.origin.copy( origin );
  10440. this.direction.copy( direction );
  10441. return this;
  10442. },
  10443. clone: function () {
  10444. return new this.constructor().copy( this );
  10445. },
  10446. copy: function ( ray ) {
  10447. this.origin.copy( ray.origin );
  10448. this.direction.copy( ray.direction );
  10449. return this;
  10450. },
  10451. at: function ( t, optionalTarget ) {
  10452. var result = optionalTarget || new Vector3();
  10453. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  10454. },
  10455. lookAt: function ( v ) {
  10456. this.direction.copy( v ).sub( this.origin ).normalize();
  10457. return this;
  10458. },
  10459. recast: function () {
  10460. var v1 = new Vector3();
  10461. return function recast( t ) {
  10462. this.origin.copy( this.at( t, v1 ) );
  10463. return this;
  10464. };
  10465. }(),
  10466. closestPointToPoint: function ( point, optionalTarget ) {
  10467. var result = optionalTarget || new Vector3();
  10468. result.subVectors( point, this.origin );
  10469. var directionDistance = result.dot( this.direction );
  10470. if ( directionDistance < 0 ) {
  10471. return result.copy( this.origin );
  10472. }
  10473. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  10474. },
  10475. distanceToPoint: function ( point ) {
  10476. return Math.sqrt( this.distanceSqToPoint( point ) );
  10477. },
  10478. distanceSqToPoint: function () {
  10479. var v1 = new Vector3();
  10480. return function distanceSqToPoint( point ) {
  10481. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  10482. // point behind the ray
  10483. if ( directionDistance < 0 ) {
  10484. return this.origin.distanceToSquared( point );
  10485. }
  10486. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  10487. return v1.distanceToSquared( point );
  10488. };
  10489. }(),
  10490. distanceSqToSegment: function () {
  10491. var segCenter = new Vector3();
  10492. var segDir = new Vector3();
  10493. var diff = new Vector3();
  10494. return function distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  10495. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  10496. // It returns the min distance between the ray and the segment
  10497. // defined by v0 and v1
  10498. // It can also set two optional targets :
  10499. // - The closest point on the ray
  10500. // - The closest point on the segment
  10501. segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  10502. segDir.copy( v1 ).sub( v0 ).normalize();
  10503. diff.copy( this.origin ).sub( segCenter );
  10504. var segExtent = v0.distanceTo( v1 ) * 0.5;
  10505. var a01 = - this.direction.dot( segDir );
  10506. var b0 = diff.dot( this.direction );
  10507. var b1 = - diff.dot( segDir );
  10508. var c = diff.lengthSq();
  10509. var det = Math.abs( 1 - a01 * a01 );
  10510. var s0, s1, sqrDist, extDet;
  10511. if ( det > 0 ) {
  10512. // The ray and segment are not parallel.
  10513. s0 = a01 * b1 - b0;
  10514. s1 = a01 * b0 - b1;
  10515. extDet = segExtent * det;
  10516. if ( s0 >= 0 ) {
  10517. if ( s1 >= - extDet ) {
  10518. if ( s1 <= extDet ) {
  10519. // region 0
  10520. // Minimum at interior points of ray and segment.
  10521. var invDet = 1 / det;
  10522. s0 *= invDet;
  10523. s1 *= invDet;
  10524. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  10525. } else {
  10526. // region 1
  10527. s1 = segExtent;
  10528. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  10529. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  10530. }
  10531. } else {
  10532. // region 5
  10533. s1 = - segExtent;
  10534. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  10535. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  10536. }
  10537. } else {
  10538. if ( s1 <= - extDet ) {
  10539. // region 4
  10540. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  10541. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  10542. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  10543. } else if ( s1 <= extDet ) {
  10544. // region 3
  10545. s0 = 0;
  10546. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  10547. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  10548. } else {
  10549. // region 2
  10550. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  10551. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  10552. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  10553. }
  10554. }
  10555. } else {
  10556. // Ray and segment are parallel.
  10557. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  10558. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  10559. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  10560. }
  10561. if ( optionalPointOnRay ) {
  10562. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  10563. }
  10564. if ( optionalPointOnSegment ) {
  10565. optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter );
  10566. }
  10567. return sqrDist;
  10568. };
  10569. }(),
  10570. intersectSphere: function () {
  10571. var v1 = new Vector3();
  10572. return function intersectSphere( sphere, optionalTarget ) {
  10573. v1.subVectors( sphere.center, this.origin );
  10574. var tca = v1.dot( this.direction );
  10575. var d2 = v1.dot( v1 ) - tca * tca;
  10576. var radius2 = sphere.radius * sphere.radius;
  10577. if ( d2 > radius2 ) return null;
  10578. var thc = Math.sqrt( radius2 - d2 );
  10579. // t0 = first intersect point - entrance on front of sphere
  10580. var t0 = tca - thc;
  10581. // t1 = second intersect point - exit point on back of sphere
  10582. var t1 = tca + thc;
  10583. // test to see if both t0 and t1 are behind the ray - if so, return null
  10584. if ( t0 < 0 && t1 < 0 ) return null;
  10585. // test to see if t0 is behind the ray:
  10586. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  10587. // in order to always return an intersect point that is in front of the ray.
  10588. if ( t0 < 0 ) return this.at( t1, optionalTarget );
  10589. // else t0 is in front of the ray, so return the first collision point scaled by t0
  10590. return this.at( t0, optionalTarget );
  10591. };
  10592. }(),
  10593. intersectsSphere: function ( sphere ) {
  10594. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  10595. },
  10596. distanceToPlane: function ( plane ) {
  10597. var denominator = plane.normal.dot( this.direction );
  10598. if ( denominator === 0 ) {
  10599. // line is coplanar, return origin
  10600. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  10601. return 0;
  10602. }
  10603. // Null is preferable to undefined since undefined means.... it is undefined
  10604. return null;
  10605. }
  10606. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  10607. // Return if the ray never intersects the plane
  10608. return t >= 0 ? t : null;
  10609. },
  10610. intersectPlane: function ( plane, optionalTarget ) {
  10611. var t = this.distanceToPlane( plane );
  10612. if ( t === null ) {
  10613. return null;
  10614. }
  10615. return this.at( t, optionalTarget );
  10616. },
  10617. intersectsPlane: function ( plane ) {
  10618. // check if the ray lies on the plane first
  10619. var distToPoint = plane.distanceToPoint( this.origin );
  10620. if ( distToPoint === 0 ) {
  10621. return true;
  10622. }
  10623. var denominator = plane.normal.dot( this.direction );
  10624. if ( denominator * distToPoint < 0 ) {
  10625. return true;
  10626. }
  10627. // ray origin is behind the plane (and is pointing behind it)
  10628. return false;
  10629. },
  10630. intersectBox: function ( box, optionalTarget ) {
  10631. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  10632. var invdirx = 1 / this.direction.x,
  10633. invdiry = 1 / this.direction.y,
  10634. invdirz = 1 / this.direction.z;
  10635. var origin = this.origin;
  10636. if ( invdirx >= 0 ) {
  10637. tmin = ( box.min.x - origin.x ) * invdirx;
  10638. tmax = ( box.max.x - origin.x ) * invdirx;
  10639. } else {
  10640. tmin = ( box.max.x - origin.x ) * invdirx;
  10641. tmax = ( box.min.x - origin.x ) * invdirx;
  10642. }
  10643. if ( invdiry >= 0 ) {
  10644. tymin = ( box.min.y - origin.y ) * invdiry;
  10645. tymax = ( box.max.y - origin.y ) * invdiry;
  10646. } else {
  10647. tymin = ( box.max.y - origin.y ) * invdiry;
  10648. tymax = ( box.min.y - origin.y ) * invdiry;
  10649. }
  10650. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  10651. // These lines also handle the case where tmin or tmax is NaN
  10652. // (result of 0 * Infinity). x !== x returns true if x is NaN
  10653. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  10654. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  10655. if ( invdirz >= 0 ) {
  10656. tzmin = ( box.min.z - origin.z ) * invdirz;
  10657. tzmax = ( box.max.z - origin.z ) * invdirz;
  10658. } else {
  10659. tzmin = ( box.max.z - origin.z ) * invdirz;
  10660. tzmax = ( box.min.z - origin.z ) * invdirz;
  10661. }
  10662. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  10663. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  10664. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  10665. //return point closest to the ray (positive side)
  10666. if ( tmax < 0 ) return null;
  10667. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  10668. },
  10669. intersectsBox: ( function () {
  10670. var v = new Vector3();
  10671. return function intersectsBox( box ) {
  10672. return this.intersectBox( box, v ) !== null;
  10673. };
  10674. } )(),
  10675. intersectTriangle: function () {
  10676. // Compute the offset origin, edges, and normal.
  10677. var diff = new Vector3();
  10678. var edge1 = new Vector3();
  10679. var edge2 = new Vector3();
  10680. var normal = new Vector3();
  10681. return function intersectTriangle( a, b, c, backfaceCulling, optionalTarget ) {
  10682. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  10683. edge1.subVectors( b, a );
  10684. edge2.subVectors( c, a );
  10685. normal.crossVectors( edge1, edge2 );
  10686. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  10687. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  10688. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  10689. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  10690. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  10691. var DdN = this.direction.dot( normal );
  10692. var sign;
  10693. if ( DdN > 0 ) {
  10694. if ( backfaceCulling ) return null;
  10695. sign = 1;
  10696. } else if ( DdN < 0 ) {
  10697. sign = - 1;
  10698. DdN = - DdN;
  10699. } else {
  10700. return null;
  10701. }
  10702. diff.subVectors( this.origin, a );
  10703. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  10704. // b1 < 0, no intersection
  10705. if ( DdQxE2 < 0 ) {
  10706. return null;
  10707. }
  10708. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  10709. // b2 < 0, no intersection
  10710. if ( DdE1xQ < 0 ) {
  10711. return null;
  10712. }
  10713. // b1+b2 > 1, no intersection
  10714. if ( DdQxE2 + DdE1xQ > DdN ) {
  10715. return null;
  10716. }
  10717. // Line intersects triangle, check if ray does.
  10718. var QdN = - sign * diff.dot( normal );
  10719. // t < 0, no intersection
  10720. if ( QdN < 0 ) {
  10721. return null;
  10722. }
  10723. // Ray intersects triangle.
  10724. return this.at( QdN / DdN, optionalTarget );
  10725. };
  10726. }(),
  10727. applyMatrix4: function ( matrix4 ) {
  10728. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  10729. this.origin.applyMatrix4( matrix4 );
  10730. this.direction.sub( this.origin );
  10731. this.direction.normalize();
  10732. return this;
  10733. },
  10734. equals: function ( ray ) {
  10735. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  10736. }
  10737. };
  10738. /**
  10739. * @author mrdoob / http://mrdoob.com/
  10740. * @author WestLangley / http://github.com/WestLangley
  10741. * @author bhouston / http://clara.io
  10742. */
  10743. function Euler( x, y, z, order ) {
  10744. this._x = x || 0;
  10745. this._y = y || 0;
  10746. this._z = z || 0;
  10747. this._order = order || Euler.DefaultOrder;
  10748. }
  10749. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  10750. Euler.DefaultOrder = 'XYZ';
  10751. Euler.prototype = {
  10752. constructor: Euler,
  10753. isEuler: true,
  10754. get x () {
  10755. return this._x;
  10756. },
  10757. set x ( value ) {
  10758. this._x = value;
  10759. this.onChangeCallback();
  10760. },
  10761. get y () {
  10762. return this._y;
  10763. },
  10764. set y ( value ) {
  10765. this._y = value;
  10766. this.onChangeCallback();
  10767. },
  10768. get z () {
  10769. return this._z;
  10770. },
  10771. set z ( value ) {
  10772. this._z = value;
  10773. this.onChangeCallback();
  10774. },
  10775. get order () {
  10776. return this._order;
  10777. },
  10778. set order ( value ) {
  10779. this._order = value;
  10780. this.onChangeCallback();
  10781. },
  10782. set: function ( x, y, z, order ) {
  10783. this._x = x;
  10784. this._y = y;
  10785. this._z = z;
  10786. this._order = order || this._order;
  10787. this.onChangeCallback();
  10788. return this;
  10789. },
  10790. clone: function () {
  10791. return new this.constructor( this._x, this._y, this._z, this._order );
  10792. },
  10793. copy: function ( euler ) {
  10794. this._x = euler._x;
  10795. this._y = euler._y;
  10796. this._z = euler._z;
  10797. this._order = euler._order;
  10798. this.onChangeCallback();
  10799. return this;
  10800. },
  10801. setFromRotationMatrix: function ( m, order, update ) {
  10802. var clamp = _Math.clamp;
  10803. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  10804. var te = m.elements;
  10805. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  10806. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  10807. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  10808. order = order || this._order;
  10809. if ( order === 'XYZ' ) {
  10810. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  10811. if ( Math.abs( m13 ) < 0.99999 ) {
  10812. this._x = Math.atan2( - m23, m33 );
  10813. this._z = Math.atan2( - m12, m11 );
  10814. } else {
  10815. this._x = Math.atan2( m32, m22 );
  10816. this._z = 0;
  10817. }
  10818. } else if ( order === 'YXZ' ) {
  10819. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  10820. if ( Math.abs( m23 ) < 0.99999 ) {
  10821. this._y = Math.atan2( m13, m33 );
  10822. this._z = Math.atan2( m21, m22 );
  10823. } else {
  10824. this._y = Math.atan2( - m31, m11 );
  10825. this._z = 0;
  10826. }
  10827. } else if ( order === 'ZXY' ) {
  10828. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  10829. if ( Math.abs( m32 ) < 0.99999 ) {
  10830. this._y = Math.atan2( - m31, m33 );
  10831. this._z = Math.atan2( - m12, m22 );
  10832. } else {
  10833. this._y = 0;
  10834. this._z = Math.atan2( m21, m11 );
  10835. }
  10836. } else if ( order === 'ZYX' ) {
  10837. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  10838. if ( Math.abs( m31 ) < 0.99999 ) {
  10839. this._x = Math.atan2( m32, m33 );
  10840. this._z = Math.atan2( m21, m11 );
  10841. } else {
  10842. this._x = 0;
  10843. this._z = Math.atan2( - m12, m22 );
  10844. }
  10845. } else if ( order === 'YZX' ) {
  10846. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  10847. if ( Math.abs( m21 ) < 0.99999 ) {
  10848. this._x = Math.atan2( - m23, m22 );
  10849. this._y = Math.atan2( - m31, m11 );
  10850. } else {
  10851. this._x = 0;
  10852. this._y = Math.atan2( m13, m33 );
  10853. }
  10854. } else if ( order === 'XZY' ) {
  10855. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  10856. if ( Math.abs( m12 ) < 0.99999 ) {
  10857. this._x = Math.atan2( m32, m22 );
  10858. this._y = Math.atan2( m13, m11 );
  10859. } else {
  10860. this._x = Math.atan2( - m23, m33 );
  10861. this._y = 0;
  10862. }
  10863. } else {
  10864. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order );
  10865. }
  10866. this._order = order;
  10867. if ( update !== false ) this.onChangeCallback();
  10868. return this;
  10869. },
  10870. setFromQuaternion: function () {
  10871. var matrix;
  10872. return function setFromQuaternion( q, order, update ) {
  10873. if ( matrix === undefined ) matrix = new Matrix4();
  10874. matrix.makeRotationFromQuaternion( q );
  10875. return this.setFromRotationMatrix( matrix, order, update );
  10876. };
  10877. }(),
  10878. setFromVector3: function ( v, order ) {
  10879. return this.set( v.x, v.y, v.z, order || this._order );
  10880. },
  10881. reorder: function () {
  10882. // WARNING: this discards revolution information -bhouston
  10883. var q = new Quaternion();
  10884. return function reorder( newOrder ) {
  10885. q.setFromEuler( this );
  10886. return this.setFromQuaternion( q, newOrder );
  10887. };
  10888. }(),
  10889. equals: function ( euler ) {
  10890. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  10891. },
  10892. fromArray: function ( array ) {
  10893. this._x = array[ 0 ];
  10894. this._y = array[ 1 ];
  10895. this._z = array[ 2 ];
  10896. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  10897. this.onChangeCallback();
  10898. return this;
  10899. },
  10900. toArray: function ( array, offset ) {
  10901. if ( array === undefined ) array = [];
  10902. if ( offset === undefined ) offset = 0;
  10903. array[ offset ] = this._x;
  10904. array[ offset + 1 ] = this._y;
  10905. array[ offset + 2 ] = this._z;
  10906. array[ offset + 3 ] = this._order;
  10907. return array;
  10908. },
  10909. toVector3: function ( optionalResult ) {
  10910. if ( optionalResult ) {
  10911. return optionalResult.set( this._x, this._y, this._z );
  10912. } else {
  10913. return new Vector3( this._x, this._y, this._z );
  10914. }
  10915. },
  10916. onChange: function ( callback ) {
  10917. this.onChangeCallback = callback;
  10918. return this;
  10919. },
  10920. onChangeCallback: function () {}
  10921. };
  10922. /**
  10923. * @author mrdoob / http://mrdoob.com/
  10924. */
  10925. function Layers() {
  10926. this.mask = 1;
  10927. }
  10928. Layers.prototype = {
  10929. constructor: Layers,
  10930. set: function ( channel ) {
  10931. this.mask = 1 << channel;
  10932. },
  10933. enable: function ( channel ) {
  10934. this.mask |= 1 << channel;
  10935. },
  10936. toggle: function ( channel ) {
  10937. this.mask ^= 1 << channel;
  10938. },
  10939. disable: function ( channel ) {
  10940. this.mask &= ~ ( 1 << channel );
  10941. },
  10942. test: function ( layers ) {
  10943. return ( this.mask & layers.mask ) !== 0;
  10944. }
  10945. };
  10946. /**
  10947. * @author mrdoob / http://mrdoob.com/
  10948. * @author mikael emtinger / http://gomo.se/
  10949. * @author alteredq / http://alteredqualia.com/
  10950. * @author WestLangley / http://github.com/WestLangley
  10951. * @author elephantatwork / www.elephantatwork.ch
  10952. */
  10953. var object3DId = 0;
  10954. function Object3D() {
  10955. Object.defineProperty( this, 'id', { value: object3DId ++ } );
  10956. this.uuid = _Math.generateUUID();
  10957. this.name = '';
  10958. this.type = 'Object3D';
  10959. this.parent = null;
  10960. this.children = [];
  10961. this.up = Object3D.DefaultUp.clone();
  10962. var position = new Vector3();
  10963. var rotation = new Euler();
  10964. var quaternion = new Quaternion();
  10965. var scale = new Vector3( 1, 1, 1 );
  10966. function onRotationChange() {
  10967. quaternion.setFromEuler( rotation, false );
  10968. }
  10969. function onQuaternionChange() {
  10970. rotation.setFromQuaternion( quaternion, undefined, false );
  10971. }
  10972. rotation.onChange( onRotationChange );
  10973. quaternion.onChange( onQuaternionChange );
  10974. Object.defineProperties( this, {
  10975. position: {
  10976. enumerable: true,
  10977. value: position
  10978. },
  10979. rotation: {
  10980. enumerable: true,
  10981. value: rotation
  10982. },
  10983. quaternion: {
  10984. enumerable: true,
  10985. value: quaternion
  10986. },
  10987. scale: {
  10988. enumerable: true,
  10989. value: scale
  10990. },
  10991. modelViewMatrix: {
  10992. value: new Matrix4()
  10993. },
  10994. normalMatrix: {
  10995. value: new Matrix3()
  10996. }
  10997. } );
  10998. this.matrix = new Matrix4();
  10999. this.matrixWorld = new Matrix4();
  11000. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  11001. this.matrixWorldNeedsUpdate = false;
  11002. this.layers = new Layers();
  11003. this.visible = true;
  11004. this.castShadow = false;
  11005. this.receiveShadow = false;
  11006. this.frustumCulled = true;
  11007. this.renderOrder = 0;
  11008. this.userData = {};
  11009. this.onBeforeRender = function () {};
  11010. this.onAfterRender = function () {};
  11011. }
  11012. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  11013. Object3D.DefaultMatrixAutoUpdate = true;
  11014. Object3D.prototype = {
  11015. constructor: Object3D,
  11016. isObject3D: true,
  11017. applyMatrix: function ( matrix ) {
  11018. this.matrix.multiplyMatrices( matrix, this.matrix );
  11019. this.matrix.decompose( this.position, this.quaternion, this.scale );
  11020. },
  11021. setRotationFromAxisAngle: function ( axis, angle ) {
  11022. // assumes axis is normalized
  11023. this.quaternion.setFromAxisAngle( axis, angle );
  11024. },
  11025. setRotationFromEuler: function ( euler ) {
  11026. this.quaternion.setFromEuler( euler, true );
  11027. },
  11028. setRotationFromMatrix: function ( m ) {
  11029. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  11030. this.quaternion.setFromRotationMatrix( m );
  11031. },
  11032. setRotationFromQuaternion: function ( q ) {
  11033. // assumes q is normalized
  11034. this.quaternion.copy( q );
  11035. },
  11036. rotateOnAxis: function () {
  11037. // rotate object on axis in object space
  11038. // axis is assumed to be normalized
  11039. var q1 = new Quaternion();
  11040. return function rotateOnAxis( axis, angle ) {
  11041. q1.setFromAxisAngle( axis, angle );
  11042. this.quaternion.multiply( q1 );
  11043. return this;
  11044. };
  11045. }(),
  11046. rotateX: function () {
  11047. var v1 = new Vector3( 1, 0, 0 );
  11048. return function rotateX( angle ) {
  11049. return this.rotateOnAxis( v1, angle );
  11050. };
  11051. }(),
  11052. rotateY: function () {
  11053. var v1 = new Vector3( 0, 1, 0 );
  11054. return function rotateY( angle ) {
  11055. return this.rotateOnAxis( v1, angle );
  11056. };
  11057. }(),
  11058. rotateZ: function () {
  11059. var v1 = new Vector3( 0, 0, 1 );
  11060. return function rotateZ( angle ) {
  11061. return this.rotateOnAxis( v1, angle );
  11062. };
  11063. }(),
  11064. translateOnAxis: function () {
  11065. // translate object by distance along axis in object space
  11066. // axis is assumed to be normalized
  11067. var v1 = new Vector3();
  11068. return function translateOnAxis( axis, distance ) {
  11069. v1.copy( axis ).applyQuaternion( this.quaternion );
  11070. this.position.add( v1.multiplyScalar( distance ) );
  11071. return this;
  11072. };
  11073. }(),
  11074. translateX: function () {
  11075. var v1 = new Vector3( 1, 0, 0 );
  11076. return function translateX( distance ) {
  11077. return this.translateOnAxis( v1, distance );
  11078. };
  11079. }(),
  11080. translateY: function () {
  11081. var v1 = new Vector3( 0, 1, 0 );
  11082. return function translateY( distance ) {
  11083. return this.translateOnAxis( v1, distance );
  11084. };
  11085. }(),
  11086. translateZ: function () {
  11087. var v1 = new Vector3( 0, 0, 1 );
  11088. return function translateZ( distance ) {
  11089. return this.translateOnAxis( v1, distance );
  11090. };
  11091. }(),
  11092. localToWorld: function ( vector ) {
  11093. return vector.applyMatrix4( this.matrixWorld );
  11094. },
  11095. worldToLocal: function () {
  11096. var m1 = new Matrix4();
  11097. return function worldToLocal( vector ) {
  11098. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  11099. };
  11100. }(),
  11101. lookAt: function () {
  11102. // This routine does not support objects with rotated and/or translated parent(s)
  11103. var m1 = new Matrix4();
  11104. return function lookAt( vector ) {
  11105. m1.lookAt( vector, this.position, this.up );
  11106. this.quaternion.setFromRotationMatrix( m1 );
  11107. };
  11108. }(),
  11109. add: function ( object ) {
  11110. if ( arguments.length > 1 ) {
  11111. for ( var i = 0; i < arguments.length; i ++ ) {
  11112. this.add( arguments[ i ] );
  11113. }
  11114. return this;
  11115. }
  11116. if ( object === this ) {
  11117. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  11118. return this;
  11119. }
  11120. if ( ( object && object.isObject3D ) ) {
  11121. if ( object.parent !== null ) {
  11122. object.parent.remove( object );
  11123. }
  11124. object.parent = this;
  11125. object.dispatchEvent( { type: 'added' } );
  11126. this.children.push( object );
  11127. } else {
  11128. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  11129. }
  11130. return this;
  11131. },
  11132. remove: function ( object ) {
  11133. if ( arguments.length > 1 ) {
  11134. for ( var i = 0; i < arguments.length; i ++ ) {
  11135. this.remove( arguments[ i ] );
  11136. }
  11137. }
  11138. var index = this.children.indexOf( object );
  11139. if ( index !== - 1 ) {
  11140. object.parent = null;
  11141. object.dispatchEvent( { type: 'removed' } );
  11142. this.children.splice( index, 1 );
  11143. }
  11144. },
  11145. getObjectById: function ( id ) {
  11146. return this.getObjectByProperty( 'id', id );
  11147. },
  11148. getObjectByName: function ( name ) {
  11149. return this.getObjectByProperty( 'name', name );
  11150. },
  11151. getObjectByProperty: function ( name, value ) {
  11152. if ( this[ name ] === value ) return this;
  11153. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  11154. var child = this.children[ i ];
  11155. var object = child.getObjectByProperty( name, value );
  11156. if ( object !== undefined ) {
  11157. return object;
  11158. }
  11159. }
  11160. return undefined;
  11161. },
  11162. getWorldPosition: function ( optionalTarget ) {
  11163. var result = optionalTarget || new Vector3();
  11164. this.updateMatrixWorld( true );
  11165. return result.setFromMatrixPosition( this.matrixWorld );
  11166. },
  11167. getWorldQuaternion: function () {
  11168. var position = new Vector3();
  11169. var scale = new Vector3();
  11170. return function getWorldQuaternion( optionalTarget ) {
  11171. var result = optionalTarget || new Quaternion();
  11172. this.updateMatrixWorld( true );
  11173. this.matrixWorld.decompose( position, result, scale );
  11174. return result;
  11175. };
  11176. }(),
  11177. getWorldRotation: function () {
  11178. var quaternion = new Quaternion();
  11179. return function getWorldRotation( optionalTarget ) {
  11180. var result = optionalTarget || new Euler();
  11181. this.getWorldQuaternion( quaternion );
  11182. return result.setFromQuaternion( quaternion, this.rotation.order, false );
  11183. };
  11184. }(),
  11185. getWorldScale: function () {
  11186. var position = new Vector3();
  11187. var quaternion = new Quaternion();
  11188. return function getWorldScale( optionalTarget ) {
  11189. var result = optionalTarget || new Vector3();
  11190. this.updateMatrixWorld( true );
  11191. this.matrixWorld.decompose( position, quaternion, result );
  11192. return result;
  11193. };
  11194. }(),
  11195. getWorldDirection: function () {
  11196. var quaternion = new Quaternion();
  11197. return function getWorldDirection( optionalTarget ) {
  11198. var result = optionalTarget || new Vector3();
  11199. this.getWorldQuaternion( quaternion );
  11200. return result.set( 0, 0, 1 ).applyQuaternion( quaternion );
  11201. };
  11202. }(),
  11203. raycast: function () {},
  11204. traverse: function ( callback ) {
  11205. callback( this );
  11206. var children = this.children;
  11207. for ( var i = 0, l = children.length; i < l; i ++ ) {
  11208. children[ i ].traverse( callback );
  11209. }
  11210. },
  11211. traverseVisible: function ( callback ) {
  11212. if ( this.visible === false ) return;
  11213. callback( this );
  11214. var children = this.children;
  11215. for ( var i = 0, l = children.length; i < l; i ++ ) {
  11216. children[ i ].traverseVisible( callback );
  11217. }
  11218. },
  11219. traverseAncestors: function ( callback ) {
  11220. var parent = this.parent;
  11221. if ( parent !== null ) {
  11222. callback( parent );
  11223. parent.traverseAncestors( callback );
  11224. }
  11225. },
  11226. updateMatrix: function () {
  11227. this.matrix.compose( this.position, this.quaternion, this.scale );
  11228. this.matrixWorldNeedsUpdate = true;
  11229. },
  11230. updateMatrixWorld: function ( force ) {
  11231. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  11232. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  11233. if ( this.parent === null ) {
  11234. this.matrixWorld.copy( this.matrix );
  11235. } else {
  11236. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  11237. }
  11238. this.matrixWorldNeedsUpdate = false;
  11239. force = true;
  11240. }
  11241. // update children
  11242. var children = this.children;
  11243. for ( var i = 0, l = children.length; i < l; i ++ ) {
  11244. children[ i ].updateMatrixWorld( force );
  11245. }
  11246. },
  11247. toJSON: function ( meta ) {
  11248. // meta is '' when called from JSON.stringify
  11249. var isRootObject = ( meta === undefined || meta === '' );
  11250. var output = {};
  11251. // meta is a hash used to collect geometries, materials.
  11252. // not providing it implies that this is the root object
  11253. // being serialized.
  11254. if ( isRootObject ) {
  11255. // initialize meta obj
  11256. meta = {
  11257. geometries: {},
  11258. materials: {},
  11259. textures: {},
  11260. images: {}
  11261. };
  11262. output.metadata = {
  11263. version: 4.4,
  11264. type: 'Object',
  11265. generator: 'Object3D.toJSON'
  11266. };
  11267. }
  11268. // standard Object3D serialization
  11269. var object = {};
  11270. object.uuid = this.uuid;
  11271. object.type = this.type;
  11272. if ( this.name !== '' ) object.name = this.name;
  11273. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  11274. if ( this.castShadow === true ) object.castShadow = true;
  11275. if ( this.receiveShadow === true ) object.receiveShadow = true;
  11276. if ( this.visible === false ) object.visible = false;
  11277. object.matrix = this.matrix.toArray();
  11278. //
  11279. if ( this.geometry !== undefined ) {
  11280. if ( meta.geometries[ this.geometry.uuid ] === undefined ) {
  11281. meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON( meta );
  11282. }
  11283. object.geometry = this.geometry.uuid;
  11284. }
  11285. if ( this.material !== undefined ) {
  11286. if ( meta.materials[ this.material.uuid ] === undefined ) {
  11287. meta.materials[ this.material.uuid ] = this.material.toJSON( meta );
  11288. }
  11289. object.material = this.material.uuid;
  11290. }
  11291. //
  11292. if ( this.children.length > 0 ) {
  11293. object.children = [];
  11294. for ( var i = 0; i < this.children.length; i ++ ) {
  11295. object.children.push( this.children[ i ].toJSON( meta ).object );
  11296. }
  11297. }
  11298. if ( isRootObject ) {
  11299. var geometries = extractFromCache( meta.geometries );
  11300. var materials = extractFromCache( meta.materials );
  11301. var textures = extractFromCache( meta.textures );
  11302. var images = extractFromCache( meta.images );
  11303. if ( geometries.length > 0 ) output.geometries = geometries;
  11304. if ( materials.length > 0 ) output.materials = materials;
  11305. if ( textures.length > 0 ) output.textures = textures;
  11306. if ( images.length > 0 ) output.images = images;
  11307. }
  11308. output.object = object;
  11309. return output;
  11310. // extract data from the cache hash
  11311. // remove metadata on each item
  11312. // and return as array
  11313. function extractFromCache( cache ) {
  11314. var values = [];
  11315. for ( var key in cache ) {
  11316. var data = cache[ key ];
  11317. delete data.metadata;
  11318. values.push( data );
  11319. }
  11320. return values;
  11321. }
  11322. },
  11323. clone: function ( recursive ) {
  11324. return new this.constructor().copy( this, recursive );
  11325. },
  11326. copy: function ( source, recursive ) {
  11327. if ( recursive === undefined ) recursive = true;
  11328. this.name = source.name;
  11329. this.up.copy( source.up );
  11330. this.position.copy( source.position );
  11331. this.quaternion.copy( source.quaternion );
  11332. this.scale.copy( source.scale );
  11333. this.matrix.copy( source.matrix );
  11334. this.matrixWorld.copy( source.matrixWorld );
  11335. this.matrixAutoUpdate = source.matrixAutoUpdate;
  11336. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  11337. this.layers.mask = source.layers.mask;
  11338. this.visible = source.visible;
  11339. this.castShadow = source.castShadow;
  11340. this.receiveShadow = source.receiveShadow;
  11341. this.frustumCulled = source.frustumCulled;
  11342. this.renderOrder = source.renderOrder;
  11343. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  11344. if ( recursive === true ) {
  11345. for ( var i = 0; i < source.children.length; i ++ ) {
  11346. var child = source.children[ i ];
  11347. this.add( child.clone() );
  11348. }
  11349. }
  11350. return this;
  11351. }
  11352. };
  11353. Object.assign( Object3D.prototype, EventDispatcher.prototype );
  11354. /**
  11355. * @author bhouston / http://clara.io
  11356. */
  11357. function Line3( start, end ) {
  11358. this.start = ( start !== undefined ) ? start : new Vector3();
  11359. this.end = ( end !== undefined ) ? end : new Vector3();
  11360. }
  11361. Line3.prototype = {
  11362. constructor: Line3,
  11363. set: function ( start, end ) {
  11364. this.start.copy( start );
  11365. this.end.copy( end );
  11366. return this;
  11367. },
  11368. clone: function () {
  11369. return new this.constructor().copy( this );
  11370. },
  11371. copy: function ( line ) {
  11372. this.start.copy( line.start );
  11373. this.end.copy( line.end );
  11374. return this;
  11375. },
  11376. getCenter: function ( optionalTarget ) {
  11377. var result = optionalTarget || new Vector3();
  11378. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  11379. },
  11380. delta: function ( optionalTarget ) {
  11381. var result = optionalTarget || new Vector3();
  11382. return result.subVectors( this.end, this.start );
  11383. },
  11384. distanceSq: function () {
  11385. return this.start.distanceToSquared( this.end );
  11386. },
  11387. distance: function () {
  11388. return this.start.distanceTo( this.end );
  11389. },
  11390. at: function ( t, optionalTarget ) {
  11391. var result = optionalTarget || new Vector3();
  11392. return this.delta( result ).multiplyScalar( t ).add( this.start );
  11393. },
  11394. closestPointToPointParameter: function () {
  11395. var startP = new Vector3();
  11396. var startEnd = new Vector3();
  11397. return function closestPointToPointParameter( point, clampToLine ) {
  11398. startP.subVectors( point, this.start );
  11399. startEnd.subVectors( this.end, this.start );
  11400. var startEnd2 = startEnd.dot( startEnd );
  11401. var startEnd_startP = startEnd.dot( startP );
  11402. var t = startEnd_startP / startEnd2;
  11403. if ( clampToLine ) {
  11404. t = _Math.clamp( t, 0, 1 );
  11405. }
  11406. return t;
  11407. };
  11408. }(),
  11409. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  11410. var t = this.closestPointToPointParameter( point, clampToLine );
  11411. var result = optionalTarget || new Vector3();
  11412. return this.delta( result ).multiplyScalar( t ).add( this.start );
  11413. },
  11414. applyMatrix4: function ( matrix ) {
  11415. this.start.applyMatrix4( matrix );
  11416. this.end.applyMatrix4( matrix );
  11417. return this;
  11418. },
  11419. equals: function ( line ) {
  11420. return line.start.equals( this.start ) && line.end.equals( this.end );
  11421. }
  11422. };
  11423. /**
  11424. * @author bhouston / http://clara.io
  11425. * @author mrdoob / http://mrdoob.com/
  11426. */
  11427. function Triangle( a, b, c ) {
  11428. this.a = ( a !== undefined ) ? a : new Vector3();
  11429. this.b = ( b !== undefined ) ? b : new Vector3();
  11430. this.c = ( c !== undefined ) ? c : new Vector3();
  11431. }
  11432. Triangle.normal = function () {
  11433. var v0 = new Vector3();
  11434. return function normal( a, b, c, optionalTarget ) {
  11435. var result = optionalTarget || new Vector3();
  11436. result.subVectors( c, b );
  11437. v0.subVectors( a, b );
  11438. result.cross( v0 );
  11439. var resultLengthSq = result.lengthSq();
  11440. if ( resultLengthSq > 0 ) {
  11441. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  11442. }
  11443. return result.set( 0, 0, 0 );
  11444. };
  11445. }();
  11446. // static/instance method to calculate barycentric coordinates
  11447. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  11448. Triangle.barycoordFromPoint = function () {
  11449. var v0 = new Vector3();
  11450. var v1 = new Vector3();
  11451. var v2 = new Vector3();
  11452. return function barycoordFromPoint( point, a, b, c, optionalTarget ) {
  11453. v0.subVectors( c, a );
  11454. v1.subVectors( b, a );
  11455. v2.subVectors( point, a );
  11456. var dot00 = v0.dot( v0 );
  11457. var dot01 = v0.dot( v1 );
  11458. var dot02 = v0.dot( v2 );
  11459. var dot11 = v1.dot( v1 );
  11460. var dot12 = v1.dot( v2 );
  11461. var denom = ( dot00 * dot11 - dot01 * dot01 );
  11462. var result = optionalTarget || new Vector3();
  11463. // collinear or singular triangle
  11464. if ( denom === 0 ) {
  11465. // arbitrary location outside of triangle?
  11466. // not sure if this is the best idea, maybe should be returning undefined
  11467. return result.set( - 2, - 1, - 1 );
  11468. }
  11469. var invDenom = 1 / denom;
  11470. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  11471. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  11472. // barycentric coordinates must always sum to 1
  11473. return result.set( 1 - u - v, v, u );
  11474. };
  11475. }();
  11476. Triangle.containsPoint = function () {
  11477. var v1 = new Vector3();
  11478. return function containsPoint( point, a, b, c ) {
  11479. var result = Triangle.barycoordFromPoint( point, a, b, c, v1 );
  11480. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  11481. };
  11482. }();
  11483. Triangle.prototype = {
  11484. constructor: Triangle,
  11485. set: function ( a, b, c ) {
  11486. this.a.copy( a );
  11487. this.b.copy( b );
  11488. this.c.copy( c );
  11489. return this;
  11490. },
  11491. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  11492. this.a.copy( points[ i0 ] );
  11493. this.b.copy( points[ i1 ] );
  11494. this.c.copy( points[ i2 ] );
  11495. return this;
  11496. },
  11497. clone: function () {
  11498. return new this.constructor().copy( this );
  11499. },
  11500. copy: function ( triangle ) {
  11501. this.a.copy( triangle.a );
  11502. this.b.copy( triangle.b );
  11503. this.c.copy( triangle.c );
  11504. return this;
  11505. },
  11506. area: function () {
  11507. var v0 = new Vector3();
  11508. var v1 = new Vector3();
  11509. return function area() {
  11510. v0.subVectors( this.c, this.b );
  11511. v1.subVectors( this.a, this.b );
  11512. return v0.cross( v1 ).length() * 0.5;
  11513. };
  11514. }(),
  11515. midpoint: function ( optionalTarget ) {
  11516. var result = optionalTarget || new Vector3();
  11517. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  11518. },
  11519. normal: function ( optionalTarget ) {
  11520. return Triangle.normal( this.a, this.b, this.c, optionalTarget );
  11521. },
  11522. plane: function ( optionalTarget ) {
  11523. var result = optionalTarget || new Plane();
  11524. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  11525. },
  11526. barycoordFromPoint: function ( point, optionalTarget ) {
  11527. return Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  11528. },
  11529. containsPoint: function ( point ) {
  11530. return Triangle.containsPoint( point, this.a, this.b, this.c );
  11531. },
  11532. closestPointToPoint: function () {
  11533. var plane, edgeList, projectedPoint, closestPoint;
  11534. return function closestPointToPoint( point, optionalTarget ) {
  11535. if ( plane === undefined ) {
  11536. plane = new Plane();
  11537. edgeList = [ new Line3(), new Line3(), new Line3() ];
  11538. projectedPoint = new Vector3();
  11539. closestPoint = new Vector3();
  11540. }
  11541. var result = optionalTarget || new Vector3();
  11542. var minDistance = Infinity;
  11543. // project the point onto the plane of the triangle
  11544. plane.setFromCoplanarPoints( this.a, this.b, this.c );
  11545. plane.projectPoint( point, projectedPoint );
  11546. // check if the projection lies within the triangle
  11547. if( this.containsPoint( projectedPoint ) === true ) {
  11548. // if so, this is the closest point
  11549. result.copy( projectedPoint );
  11550. } else {
  11551. // if not, the point falls outside the triangle. the result is the closest point to the triangle's edges or vertices
  11552. edgeList[ 0 ].set( this.a, this.b );
  11553. edgeList[ 1 ].set( this.b, this.c );
  11554. edgeList[ 2 ].set( this.c, this.a );
  11555. for( var i = 0; i < edgeList.length; i ++ ) {
  11556. edgeList[ i ].closestPointToPoint( projectedPoint, true, closestPoint );
  11557. var distance = projectedPoint.distanceToSquared( closestPoint );
  11558. if( distance < minDistance ) {
  11559. minDistance = distance;
  11560. result.copy( closestPoint );
  11561. }
  11562. }
  11563. }
  11564. return result;
  11565. };
  11566. }(),
  11567. equals: function ( triangle ) {
  11568. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  11569. }
  11570. };
  11571. /**
  11572. * @author mrdoob / http://mrdoob.com/
  11573. * @author alteredq / http://alteredqualia.com/
  11574. */
  11575. function Face3( a, b, c, normal, color, materialIndex ) {
  11576. this.a = a;
  11577. this.b = b;
  11578. this.c = c;
  11579. this.normal = (normal && normal.isVector3) ? normal : new Vector3();
  11580. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  11581. this.color = (color && color.isColor) ? color : new Color();
  11582. this.vertexColors = Array.isArray( color ) ? color : [];
  11583. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  11584. }
  11585. Face3.prototype = {
  11586. constructor: Face3,
  11587. clone: function () {
  11588. return new this.constructor().copy( this );
  11589. },
  11590. copy: function ( source ) {
  11591. this.a = source.a;
  11592. this.b = source.b;
  11593. this.c = source.c;
  11594. this.normal.copy( source.normal );
  11595. this.color.copy( source.color );
  11596. this.materialIndex = source.materialIndex;
  11597. for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  11598. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  11599. }
  11600. for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  11601. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  11602. }
  11603. return this;
  11604. }
  11605. };
  11606. /**
  11607. * @author mrdoob / http://mrdoob.com/
  11608. * @author alteredq / http://alteredqualia.com/
  11609. *
  11610. * parameters = {
  11611. * color: <hex>,
  11612. * opacity: <float>,
  11613. * map: new THREE.Texture( <Image> ),
  11614. *
  11615. * lightMap: new THREE.Texture( <Image> ),
  11616. * lightMapIntensity: <float>
  11617. *
  11618. * aoMap: new THREE.Texture( <Image> ),
  11619. * aoMapIntensity: <float>
  11620. *
  11621. * specularMap: new THREE.Texture( <Image> ),
  11622. *
  11623. * alphaMap: new THREE.Texture( <Image> ),
  11624. *
  11625. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  11626. * combine: THREE.Multiply,
  11627. * reflectivity: <float>,
  11628. * refractionRatio: <float>,
  11629. *
  11630. * shading: THREE.SmoothShading,
  11631. * depthTest: <bool>,
  11632. * depthWrite: <bool>,
  11633. *
  11634. * wireframe: <boolean>,
  11635. * wireframeLinewidth: <float>,
  11636. *
  11637. * skinning: <bool>,
  11638. * morphTargets: <bool>
  11639. * }
  11640. */
  11641. function MeshBasicMaterial( parameters ) {
  11642. Material.call( this );
  11643. this.type = 'MeshBasicMaterial';
  11644. this.color = new Color( 0xffffff ); // emissive
  11645. this.map = null;
  11646. this.lightMap = null;
  11647. this.lightMapIntensity = 1.0;
  11648. this.aoMap = null;
  11649. this.aoMapIntensity = 1.0;
  11650. this.specularMap = null;
  11651. this.alphaMap = null;
  11652. this.envMap = null;
  11653. this.combine = MultiplyOperation;
  11654. this.reflectivity = 1;
  11655. this.refractionRatio = 0.98;
  11656. this.wireframe = false;
  11657. this.wireframeLinewidth = 1;
  11658. this.wireframeLinecap = 'round';
  11659. this.wireframeLinejoin = 'round';
  11660. this.skinning = false;
  11661. this.morphTargets = false;
  11662. this.lights = false;
  11663. this.setValues( parameters );
  11664. }
  11665. MeshBasicMaterial.prototype = Object.create( Material.prototype );
  11666. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  11667. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  11668. MeshBasicMaterial.prototype.copy = function ( source ) {
  11669. Material.prototype.copy.call( this, source );
  11670. this.color.copy( source.color );
  11671. this.map = source.map;
  11672. this.lightMap = source.lightMap;
  11673. this.lightMapIntensity = source.lightMapIntensity;
  11674. this.aoMap = source.aoMap;
  11675. this.aoMapIntensity = source.aoMapIntensity;
  11676. this.specularMap = source.specularMap;
  11677. this.alphaMap = source.alphaMap;
  11678. this.envMap = source.envMap;
  11679. this.combine = source.combine;
  11680. this.reflectivity = source.reflectivity;
  11681. this.refractionRatio = source.refractionRatio;
  11682. this.wireframe = source.wireframe;
  11683. this.wireframeLinewidth = source.wireframeLinewidth;
  11684. this.wireframeLinecap = source.wireframeLinecap;
  11685. this.wireframeLinejoin = source.wireframeLinejoin;
  11686. this.skinning = source.skinning;
  11687. this.morphTargets = source.morphTargets;
  11688. return this;
  11689. };
  11690. /**
  11691. * @author mrdoob / http://mrdoob.com/
  11692. */
  11693. function BufferAttribute( array, itemSize, normalized ) {
  11694. if ( Array.isArray( array ) ) {
  11695. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  11696. }
  11697. this.uuid = _Math.generateUUID();
  11698. this.array = array;
  11699. this.itemSize = itemSize;
  11700. this.count = array !== undefined ? array.length / itemSize : 0;
  11701. this.normalized = normalized === true;
  11702. this.dynamic = false;
  11703. this.updateRange = { offset: 0, count: - 1 };
  11704. this.onUploadCallback = function () {};
  11705. this.version = 0;
  11706. }
  11707. BufferAttribute.prototype = {
  11708. constructor: BufferAttribute,
  11709. isBufferAttribute: true,
  11710. set needsUpdate( value ) {
  11711. if ( value === true ) this.version ++;
  11712. },
  11713. setArray: function ( array ) {
  11714. if ( Array.isArray( array ) ) {
  11715. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  11716. }
  11717. this.count = array !== undefined ? array.length / this.itemSize : 0;
  11718. this.array = array;
  11719. },
  11720. setDynamic: function ( value ) {
  11721. this.dynamic = value;
  11722. return this;
  11723. },
  11724. copy: function ( source ) {
  11725. this.array = new source.array.constructor( source.array );
  11726. this.itemSize = source.itemSize;
  11727. this.count = source.count;
  11728. this.normalized = source.normalized;
  11729. this.dynamic = source.dynamic;
  11730. return this;
  11731. },
  11732. copyAt: function ( index1, attribute, index2 ) {
  11733. index1 *= this.itemSize;
  11734. index2 *= attribute.itemSize;
  11735. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  11736. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  11737. }
  11738. return this;
  11739. },
  11740. copyArray: function ( array ) {
  11741. this.array.set( array );
  11742. return this;
  11743. },
  11744. copyColorsArray: function ( colors ) {
  11745. var array = this.array, offset = 0;
  11746. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  11747. var color = colors[ i ];
  11748. if ( color === undefined ) {
  11749. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  11750. color = new Color();
  11751. }
  11752. array[ offset ++ ] = color.r;
  11753. array[ offset ++ ] = color.g;
  11754. array[ offset ++ ] = color.b;
  11755. }
  11756. return this;
  11757. },
  11758. copyIndicesArray: function ( indices ) {
  11759. var array = this.array, offset = 0;
  11760. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  11761. var index = indices[ i ];
  11762. array[ offset ++ ] = index.a;
  11763. array[ offset ++ ] = index.b;
  11764. array[ offset ++ ] = index.c;
  11765. }
  11766. return this;
  11767. },
  11768. copyVector2sArray: function ( vectors ) {
  11769. var array = this.array, offset = 0;
  11770. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  11771. var vector = vectors[ i ];
  11772. if ( vector === undefined ) {
  11773. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  11774. vector = new Vector2();
  11775. }
  11776. array[ offset ++ ] = vector.x;
  11777. array[ offset ++ ] = vector.y;
  11778. }
  11779. return this;
  11780. },
  11781. copyVector3sArray: function ( vectors ) {
  11782. var array = this.array, offset = 0;
  11783. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  11784. var vector = vectors[ i ];
  11785. if ( vector === undefined ) {
  11786. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  11787. vector = new Vector3();
  11788. }
  11789. array[ offset ++ ] = vector.x;
  11790. array[ offset ++ ] = vector.y;
  11791. array[ offset ++ ] = vector.z;
  11792. }
  11793. return this;
  11794. },
  11795. copyVector4sArray: function ( vectors ) {
  11796. var array = this.array, offset = 0;
  11797. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  11798. var vector = vectors[ i ];
  11799. if ( vector === undefined ) {
  11800. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  11801. vector = new Vector4();
  11802. }
  11803. array[ offset ++ ] = vector.x;
  11804. array[ offset ++ ] = vector.y;
  11805. array[ offset ++ ] = vector.z;
  11806. array[ offset ++ ] = vector.w;
  11807. }
  11808. return this;
  11809. },
  11810. set: function ( value, offset ) {
  11811. if ( offset === undefined ) offset = 0;
  11812. this.array.set( value, offset );
  11813. return this;
  11814. },
  11815. getX: function ( index ) {
  11816. return this.array[ index * this.itemSize ];
  11817. },
  11818. setX: function ( index, x ) {
  11819. this.array[ index * this.itemSize ] = x;
  11820. return this;
  11821. },
  11822. getY: function ( index ) {
  11823. return this.array[ index * this.itemSize + 1 ];
  11824. },
  11825. setY: function ( index, y ) {
  11826. this.array[ index * this.itemSize + 1 ] = y;
  11827. return this;
  11828. },
  11829. getZ: function ( index ) {
  11830. return this.array[ index * this.itemSize + 2 ];
  11831. },
  11832. setZ: function ( index, z ) {
  11833. this.array[ index * this.itemSize + 2 ] = z;
  11834. return this;
  11835. },
  11836. getW: function ( index ) {
  11837. return this.array[ index * this.itemSize + 3 ];
  11838. },
  11839. setW: function ( index, w ) {
  11840. this.array[ index * this.itemSize + 3 ] = w;
  11841. return this;
  11842. },
  11843. setXY: function ( index, x, y ) {
  11844. index *= this.itemSize;
  11845. this.array[ index + 0 ] = x;
  11846. this.array[ index + 1 ] = y;
  11847. return this;
  11848. },
  11849. setXYZ: function ( index, x, y, z ) {
  11850. index *= this.itemSize;
  11851. this.array[ index + 0 ] = x;
  11852. this.array[ index + 1 ] = y;
  11853. this.array[ index + 2 ] = z;
  11854. return this;
  11855. },
  11856. setXYZW: function ( index, x, y, z, w ) {
  11857. index *= this.itemSize;
  11858. this.array[ index + 0 ] = x;
  11859. this.array[ index + 1 ] = y;
  11860. this.array[ index + 2 ] = z;
  11861. this.array[ index + 3 ] = w;
  11862. return this;
  11863. },
  11864. onUpload: function ( callback ) {
  11865. this.onUploadCallback = callback;
  11866. return this;
  11867. },
  11868. clone: function () {
  11869. return new this.constructor( this.array, this.itemSize ).copy( this );
  11870. }
  11871. };
  11872. //
  11873. function Int8BufferAttribute( array, itemSize ) {
  11874. BufferAttribute.call( this, new Int8Array( array ), itemSize );
  11875. }
  11876. Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11877. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  11878. function Uint8BufferAttribute( array, itemSize ) {
  11879. BufferAttribute.call( this, new Uint8Array( array ), itemSize );
  11880. }
  11881. Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11882. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  11883. function Uint8ClampedBufferAttribute( array, itemSize ) {
  11884. BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize );
  11885. }
  11886. Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11887. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  11888. function Int16BufferAttribute( array, itemSize ) {
  11889. BufferAttribute.call( this, new Int16Array( array ), itemSize );
  11890. }
  11891. Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11892. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  11893. function Uint16BufferAttribute( array, itemSize ) {
  11894. BufferAttribute.call( this, new Uint16Array( array ), itemSize );
  11895. }
  11896. Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11897. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  11898. function Int32BufferAttribute( array, itemSize ) {
  11899. BufferAttribute.call( this, new Int32Array( array ), itemSize );
  11900. }
  11901. Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11902. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  11903. function Uint32BufferAttribute( array, itemSize ) {
  11904. BufferAttribute.call( this, new Uint32Array( array ), itemSize );
  11905. }
  11906. Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11907. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  11908. function Float32BufferAttribute( array, itemSize ) {
  11909. BufferAttribute.call( this, new Float32Array( array ), itemSize );
  11910. }
  11911. Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11912. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  11913. function Float64BufferAttribute( array, itemSize ) {
  11914. BufferAttribute.call( this, new Float64Array( array ), itemSize );
  11915. }
  11916. Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11917. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  11918. /**
  11919. * @author mrdoob / http://mrdoob.com/
  11920. */
  11921. function DirectGeometry() {
  11922. this.indices = [];
  11923. this.vertices = [];
  11924. this.normals = [];
  11925. this.colors = [];
  11926. this.uvs = [];
  11927. this.uvs2 = [];
  11928. this.groups = [];
  11929. this.morphTargets = {};
  11930. this.skinWeights = [];
  11931. this.skinIndices = [];
  11932. // this.lineDistances = [];
  11933. this.boundingBox = null;
  11934. this.boundingSphere = null;
  11935. // update flags
  11936. this.verticesNeedUpdate = false;
  11937. this.normalsNeedUpdate = false;
  11938. this.colorsNeedUpdate = false;
  11939. this.uvsNeedUpdate = false;
  11940. this.groupsNeedUpdate = false;
  11941. }
  11942. Object.assign( DirectGeometry.prototype, {
  11943. computeGroups: function ( geometry ) {
  11944. var group;
  11945. var groups = [];
  11946. var materialIndex = undefined;
  11947. var faces = geometry.faces;
  11948. for ( var i = 0; i < faces.length; i ++ ) {
  11949. var face = faces[ i ];
  11950. // materials
  11951. if ( face.materialIndex !== materialIndex ) {
  11952. materialIndex = face.materialIndex;
  11953. if ( group !== undefined ) {
  11954. group.count = ( i * 3 ) - group.start;
  11955. groups.push( group );
  11956. }
  11957. group = {
  11958. start: i * 3,
  11959. materialIndex: materialIndex
  11960. };
  11961. }
  11962. }
  11963. if ( group !== undefined ) {
  11964. group.count = ( i * 3 ) - group.start;
  11965. groups.push( group );
  11966. }
  11967. this.groups = groups;
  11968. },
  11969. fromGeometry: function ( geometry ) {
  11970. var faces = geometry.faces;
  11971. var vertices = geometry.vertices;
  11972. var faceVertexUvs = geometry.faceVertexUvs;
  11973. var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  11974. var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  11975. // morphs
  11976. var morphTargets = geometry.morphTargets;
  11977. var morphTargetsLength = morphTargets.length;
  11978. var morphTargetsPosition;
  11979. if ( morphTargetsLength > 0 ) {
  11980. morphTargetsPosition = [];
  11981. for ( var i = 0; i < morphTargetsLength; i ++ ) {
  11982. morphTargetsPosition[ i ] = [];
  11983. }
  11984. this.morphTargets.position = morphTargetsPosition;
  11985. }
  11986. var morphNormals = geometry.morphNormals;
  11987. var morphNormalsLength = morphNormals.length;
  11988. var morphTargetsNormal;
  11989. if ( morphNormalsLength > 0 ) {
  11990. morphTargetsNormal = [];
  11991. for ( var i = 0; i < morphNormalsLength; i ++ ) {
  11992. morphTargetsNormal[ i ] = [];
  11993. }
  11994. this.morphTargets.normal = morphTargetsNormal;
  11995. }
  11996. // skins
  11997. var skinIndices = geometry.skinIndices;
  11998. var skinWeights = geometry.skinWeights;
  11999. var hasSkinIndices = skinIndices.length === vertices.length;
  12000. var hasSkinWeights = skinWeights.length === vertices.length;
  12001. //
  12002. for ( var i = 0; i < faces.length; i ++ ) {
  12003. var face = faces[ i ];
  12004. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  12005. var vertexNormals = face.vertexNormals;
  12006. if ( vertexNormals.length === 3 ) {
  12007. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  12008. } else {
  12009. var normal = face.normal;
  12010. this.normals.push( normal, normal, normal );
  12011. }
  12012. var vertexColors = face.vertexColors;
  12013. if ( vertexColors.length === 3 ) {
  12014. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  12015. } else {
  12016. var color = face.color;
  12017. this.colors.push( color, color, color );
  12018. }
  12019. if ( hasFaceVertexUv === true ) {
  12020. var vertexUvs = faceVertexUvs[ 0 ][ i ];
  12021. if ( vertexUvs !== undefined ) {
  12022. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  12023. } else {
  12024. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  12025. this.uvs.push( new Vector2(), new Vector2(), new Vector2() );
  12026. }
  12027. }
  12028. if ( hasFaceVertexUv2 === true ) {
  12029. var vertexUvs = faceVertexUvs[ 1 ][ i ];
  12030. if ( vertexUvs !== undefined ) {
  12031. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  12032. } else {
  12033. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  12034. this.uvs2.push( new Vector2(), new Vector2(), new Vector2() );
  12035. }
  12036. }
  12037. // morphs
  12038. for ( var j = 0; j < morphTargetsLength; j ++ ) {
  12039. var morphTarget = morphTargets[ j ].vertices;
  12040. morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  12041. }
  12042. for ( var j = 0; j < morphNormalsLength; j ++ ) {
  12043. var morphNormal = morphNormals[ j ].vertexNormals[ i ];
  12044. morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c );
  12045. }
  12046. // skins
  12047. if ( hasSkinIndices ) {
  12048. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  12049. }
  12050. if ( hasSkinWeights ) {
  12051. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  12052. }
  12053. }
  12054. this.computeGroups( geometry );
  12055. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  12056. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  12057. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  12058. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  12059. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  12060. return this;
  12061. }
  12062. } );
  12063. // http://stackoverflow.com/questions/1669190/javascript-min-max-array-values/13440842#13440842
  12064. function arrayMax( array ) {
  12065. var length = array.length, max = - Infinity;
  12066. while ( length -- ) {
  12067. if ( array[ length ] > max ) {
  12068. max = array[ length ];
  12069. }
  12070. }
  12071. return max;
  12072. }
  12073. /**
  12074. * @author mrdoob / http://mrdoob.com/
  12075. * @author kile / http://kile.stravaganza.org/
  12076. * @author alteredq / http://alteredqualia.com/
  12077. * @author mikael emtinger / http://gomo.se/
  12078. * @author zz85 / http://www.lab4games.net/zz85/blog
  12079. * @author bhouston / http://clara.io
  12080. */
  12081. var count = 0;
  12082. function GeometryIdCount() { return count++; }
  12083. function Geometry() {
  12084. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  12085. this.uuid = _Math.generateUUID();
  12086. this.name = '';
  12087. this.type = 'Geometry';
  12088. this.vertices = [];
  12089. this.colors = [];
  12090. this.faces = [];
  12091. this.faceVertexUvs = [[]];
  12092. this.morphTargets = [];
  12093. this.morphNormals = [];
  12094. this.skinWeights = [];
  12095. this.skinIndices = [];
  12096. this.lineDistances = [];
  12097. this.boundingBox = null;
  12098. this.boundingSphere = null;
  12099. // update flags
  12100. this.elementsNeedUpdate = false;
  12101. this.verticesNeedUpdate = false;
  12102. this.uvsNeedUpdate = false;
  12103. this.normalsNeedUpdate = false;
  12104. this.colorsNeedUpdate = false;
  12105. this.lineDistancesNeedUpdate = false;
  12106. this.groupsNeedUpdate = false;
  12107. }
  12108. Geometry.prototype = {
  12109. constructor: Geometry,
  12110. isGeometry: true,
  12111. applyMatrix: function ( matrix ) {
  12112. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  12113. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  12114. var vertex = this.vertices[ i ];
  12115. vertex.applyMatrix4( matrix );
  12116. }
  12117. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  12118. var face = this.faces[ i ];
  12119. face.normal.applyMatrix3( normalMatrix ).normalize();
  12120. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  12121. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  12122. }
  12123. }
  12124. if ( this.boundingBox !== null ) {
  12125. this.computeBoundingBox();
  12126. }
  12127. if ( this.boundingSphere !== null ) {
  12128. this.computeBoundingSphere();
  12129. }
  12130. this.verticesNeedUpdate = true;
  12131. this.normalsNeedUpdate = true;
  12132. return this;
  12133. },
  12134. rotateX: function () {
  12135. // rotate geometry around world x-axis
  12136. var m1;
  12137. return function rotateX( angle ) {
  12138. if ( m1 === undefined ) m1 = new Matrix4();
  12139. m1.makeRotationX( angle );
  12140. this.applyMatrix( m1 );
  12141. return this;
  12142. };
  12143. }(),
  12144. rotateY: function () {
  12145. // rotate geometry around world y-axis
  12146. var m1;
  12147. return function rotateY( angle ) {
  12148. if ( m1 === undefined ) m1 = new Matrix4();
  12149. m1.makeRotationY( angle );
  12150. this.applyMatrix( m1 );
  12151. return this;
  12152. };
  12153. }(),
  12154. rotateZ: function () {
  12155. // rotate geometry around world z-axis
  12156. var m1;
  12157. return function rotateZ( angle ) {
  12158. if ( m1 === undefined ) m1 = new Matrix4();
  12159. m1.makeRotationZ( angle );
  12160. this.applyMatrix( m1 );
  12161. return this;
  12162. };
  12163. }(),
  12164. translate: function () {
  12165. // translate geometry
  12166. var m1;
  12167. return function translate( x, y, z ) {
  12168. if ( m1 === undefined ) m1 = new Matrix4();
  12169. m1.makeTranslation( x, y, z );
  12170. this.applyMatrix( m1 );
  12171. return this;
  12172. };
  12173. }(),
  12174. scale: function () {
  12175. // scale geometry
  12176. var m1;
  12177. return function scale( x, y, z ) {
  12178. if ( m1 === undefined ) m1 = new Matrix4();
  12179. m1.makeScale( x, y, z );
  12180. this.applyMatrix( m1 );
  12181. return this;
  12182. };
  12183. }(),
  12184. lookAt: function () {
  12185. var obj;
  12186. return function lookAt( vector ) {
  12187. if ( obj === undefined ) obj = new Object3D();
  12188. obj.lookAt( vector );
  12189. obj.updateMatrix();
  12190. this.applyMatrix( obj.matrix );
  12191. };
  12192. }(),
  12193. fromBufferGeometry: function ( geometry ) {
  12194. var scope = this;
  12195. var indices = geometry.index !== null ? geometry.index.array : undefined;
  12196. var attributes = geometry.attributes;
  12197. var positions = attributes.position.array;
  12198. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  12199. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  12200. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  12201. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  12202. if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
  12203. var tempNormals = [];
  12204. var tempUVs = [];
  12205. var tempUVs2 = [];
  12206. for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) {
  12207. scope.vertices.push( new Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) );
  12208. if ( normals !== undefined ) {
  12209. tempNormals.push( new Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) );
  12210. }
  12211. if ( colors !== undefined ) {
  12212. scope.colors.push( new Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) );
  12213. }
  12214. if ( uvs !== undefined ) {
  12215. tempUVs.push( new Vector2( uvs[ j ], uvs[ j + 1 ] ) );
  12216. }
  12217. if ( uvs2 !== undefined ) {
  12218. tempUVs2.push( new Vector2( uvs2[ j ], uvs2[ j + 1 ] ) );
  12219. }
  12220. }
  12221. function addFace( a, b, c, materialIndex ) {
  12222. var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : [];
  12223. var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : [];
  12224. var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex );
  12225. scope.faces.push( face );
  12226. if ( uvs !== undefined ) {
  12227. scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] );
  12228. }
  12229. if ( uvs2 !== undefined ) {
  12230. scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] );
  12231. }
  12232. }
  12233. if ( indices !== undefined ) {
  12234. var groups = geometry.groups;
  12235. if ( groups.length > 0 ) {
  12236. for ( var i = 0; i < groups.length; i ++ ) {
  12237. var group = groups[ i ];
  12238. var start = group.start;
  12239. var count = group.count;
  12240. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  12241. addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex );
  12242. }
  12243. }
  12244. } else {
  12245. for ( var i = 0; i < indices.length; i += 3 ) {
  12246. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  12247. }
  12248. }
  12249. } else {
  12250. for ( var i = 0; i < positions.length / 3; i += 3 ) {
  12251. addFace( i, i + 1, i + 2 );
  12252. }
  12253. }
  12254. this.computeFaceNormals();
  12255. if ( geometry.boundingBox !== null ) {
  12256. this.boundingBox = geometry.boundingBox.clone();
  12257. }
  12258. if ( geometry.boundingSphere !== null ) {
  12259. this.boundingSphere = geometry.boundingSphere.clone();
  12260. }
  12261. return this;
  12262. },
  12263. center: function () {
  12264. this.computeBoundingBox();
  12265. var offset = this.boundingBox.getCenter().negate();
  12266. this.translate( offset.x, offset.y, offset.z );
  12267. return offset;
  12268. },
  12269. normalize: function () {
  12270. this.computeBoundingSphere();
  12271. var center = this.boundingSphere.center;
  12272. var radius = this.boundingSphere.radius;
  12273. var s = radius === 0 ? 1 : 1.0 / radius;
  12274. var matrix = new Matrix4();
  12275. matrix.set(
  12276. s, 0, 0, - s * center.x,
  12277. 0, s, 0, - s * center.y,
  12278. 0, 0, s, - s * center.z,
  12279. 0, 0, 0, 1
  12280. );
  12281. this.applyMatrix( matrix );
  12282. return this;
  12283. },
  12284. computeFaceNormals: function () {
  12285. var cb = new Vector3(), ab = new Vector3();
  12286. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  12287. var face = this.faces[ f ];
  12288. var vA = this.vertices[ face.a ];
  12289. var vB = this.vertices[ face.b ];
  12290. var vC = this.vertices[ face.c ];
  12291. cb.subVectors( vC, vB );
  12292. ab.subVectors( vA, vB );
  12293. cb.cross( ab );
  12294. cb.normalize();
  12295. face.normal.copy( cb );
  12296. }
  12297. },
  12298. computeVertexNormals: function ( areaWeighted ) {
  12299. if ( areaWeighted === undefined ) areaWeighted = true;
  12300. var v, vl, f, fl, face, vertices;
  12301. vertices = new Array( this.vertices.length );
  12302. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  12303. vertices[ v ] = new Vector3();
  12304. }
  12305. if ( areaWeighted ) {
  12306. // vertex normals weighted by triangle areas
  12307. // http://www.iquilezles.org/www/articles/normals/normals.htm
  12308. var vA, vB, vC;
  12309. var cb = new Vector3(), ab = new Vector3();
  12310. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  12311. face = this.faces[ f ];
  12312. vA = this.vertices[ face.a ];
  12313. vB = this.vertices[ face.b ];
  12314. vC = this.vertices[ face.c ];
  12315. cb.subVectors( vC, vB );
  12316. ab.subVectors( vA, vB );
  12317. cb.cross( ab );
  12318. vertices[ face.a ].add( cb );
  12319. vertices[ face.b ].add( cb );
  12320. vertices[ face.c ].add( cb );
  12321. }
  12322. } else {
  12323. this.computeFaceNormals();
  12324. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  12325. face = this.faces[ f ];
  12326. vertices[ face.a ].add( face.normal );
  12327. vertices[ face.b ].add( face.normal );
  12328. vertices[ face.c ].add( face.normal );
  12329. }
  12330. }
  12331. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  12332. vertices[ v ].normalize();
  12333. }
  12334. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  12335. face = this.faces[ f ];
  12336. var vertexNormals = face.vertexNormals;
  12337. if ( vertexNormals.length === 3 ) {
  12338. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  12339. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  12340. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  12341. } else {
  12342. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  12343. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  12344. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  12345. }
  12346. }
  12347. if ( this.faces.length > 0 ) {
  12348. this.normalsNeedUpdate = true;
  12349. }
  12350. },
  12351. computeFlatVertexNormals: function () {
  12352. var f, fl, face;
  12353. this.computeFaceNormals();
  12354. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  12355. face = this.faces[ f ];
  12356. var vertexNormals = face.vertexNormals;
  12357. if ( vertexNormals.length === 3 ) {
  12358. vertexNormals[ 0 ].copy( face.normal );
  12359. vertexNormals[ 1 ].copy( face.normal );
  12360. vertexNormals[ 2 ].copy( face.normal );
  12361. } else {
  12362. vertexNormals[ 0 ] = face.normal.clone();
  12363. vertexNormals[ 1 ] = face.normal.clone();
  12364. vertexNormals[ 2 ] = face.normal.clone();
  12365. }
  12366. }
  12367. if ( this.faces.length > 0 ) {
  12368. this.normalsNeedUpdate = true;
  12369. }
  12370. },
  12371. computeMorphNormals: function () {
  12372. var i, il, f, fl, face;
  12373. // save original normals
  12374. // - create temp variables on first access
  12375. // otherwise just copy (for faster repeated calls)
  12376. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  12377. face = this.faces[ f ];
  12378. if ( ! face.__originalFaceNormal ) {
  12379. face.__originalFaceNormal = face.normal.clone();
  12380. } else {
  12381. face.__originalFaceNormal.copy( face.normal );
  12382. }
  12383. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  12384. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  12385. if ( ! face.__originalVertexNormals[ i ] ) {
  12386. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  12387. } else {
  12388. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  12389. }
  12390. }
  12391. }
  12392. // use temp geometry to compute face and vertex normals for each morph
  12393. var tmpGeo = new Geometry();
  12394. tmpGeo.faces = this.faces;
  12395. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  12396. // create on first access
  12397. if ( ! this.morphNormals[ i ] ) {
  12398. this.morphNormals[ i ] = {};
  12399. this.morphNormals[ i ].faceNormals = [];
  12400. this.morphNormals[ i ].vertexNormals = [];
  12401. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  12402. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  12403. var faceNormal, vertexNormals;
  12404. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  12405. faceNormal = new Vector3();
  12406. vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() };
  12407. dstNormalsFace.push( faceNormal );
  12408. dstNormalsVertex.push( vertexNormals );
  12409. }
  12410. }
  12411. var morphNormals = this.morphNormals[ i ];
  12412. // set vertices to morph target
  12413. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  12414. // compute morph normals
  12415. tmpGeo.computeFaceNormals();
  12416. tmpGeo.computeVertexNormals();
  12417. // store morph normals
  12418. var faceNormal, vertexNormals;
  12419. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  12420. face = this.faces[ f ];
  12421. faceNormal = morphNormals.faceNormals[ f ];
  12422. vertexNormals = morphNormals.vertexNormals[ f ];
  12423. faceNormal.copy( face.normal );
  12424. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  12425. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  12426. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  12427. }
  12428. }
  12429. // restore original normals
  12430. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  12431. face = this.faces[ f ];
  12432. face.normal = face.__originalFaceNormal;
  12433. face.vertexNormals = face.__originalVertexNormals;
  12434. }
  12435. },
  12436. computeLineDistances: function () {
  12437. var d = 0;
  12438. var vertices = this.vertices;
  12439. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  12440. if ( i > 0 ) {
  12441. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  12442. }
  12443. this.lineDistances[ i ] = d;
  12444. }
  12445. },
  12446. computeBoundingBox: function () {
  12447. if ( this.boundingBox === null ) {
  12448. this.boundingBox = new Box3();
  12449. }
  12450. this.boundingBox.setFromPoints( this.vertices );
  12451. },
  12452. computeBoundingSphere: function () {
  12453. if ( this.boundingSphere === null ) {
  12454. this.boundingSphere = new Sphere();
  12455. }
  12456. this.boundingSphere.setFromPoints( this.vertices );
  12457. },
  12458. merge: function ( geometry, matrix, materialIndexOffset ) {
  12459. if ( ( geometry && geometry.isGeometry ) === false ) {
  12460. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  12461. return;
  12462. }
  12463. var normalMatrix,
  12464. vertexOffset = this.vertices.length,
  12465. vertices1 = this.vertices,
  12466. vertices2 = geometry.vertices,
  12467. faces1 = this.faces,
  12468. faces2 = geometry.faces,
  12469. uvs1 = this.faceVertexUvs[ 0 ],
  12470. uvs2 = geometry.faceVertexUvs[ 0 ],
  12471. colors1 = this.colors,
  12472. colors2 = geometry.colors;
  12473. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  12474. if ( matrix !== undefined ) {
  12475. normalMatrix = new Matrix3().getNormalMatrix( matrix );
  12476. }
  12477. // vertices
  12478. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  12479. var vertex = vertices2[ i ];
  12480. var vertexCopy = vertex.clone();
  12481. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  12482. vertices1.push( vertexCopy );
  12483. }
  12484. // colors
  12485. for ( var i = 0, il = colors2.length; i < il; i ++ ) {
  12486. colors1.push( colors2[ i ].clone() );
  12487. }
  12488. // faces
  12489. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  12490. var face = faces2[ i ], faceCopy, normal, color,
  12491. faceVertexNormals = face.vertexNormals,
  12492. faceVertexColors = face.vertexColors;
  12493. faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  12494. faceCopy.normal.copy( face.normal );
  12495. if ( normalMatrix !== undefined ) {
  12496. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  12497. }
  12498. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  12499. normal = faceVertexNormals[ j ].clone();
  12500. if ( normalMatrix !== undefined ) {
  12501. normal.applyMatrix3( normalMatrix ).normalize();
  12502. }
  12503. faceCopy.vertexNormals.push( normal );
  12504. }
  12505. faceCopy.color.copy( face.color );
  12506. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  12507. color = faceVertexColors[ j ];
  12508. faceCopy.vertexColors.push( color.clone() );
  12509. }
  12510. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  12511. faces1.push( faceCopy );
  12512. }
  12513. // uvs
  12514. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  12515. var uv = uvs2[ i ], uvCopy = [];
  12516. if ( uv === undefined ) {
  12517. continue;
  12518. }
  12519. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  12520. uvCopy.push( uv[ j ].clone() );
  12521. }
  12522. uvs1.push( uvCopy );
  12523. }
  12524. },
  12525. mergeMesh: function ( mesh ) {
  12526. if ( ( mesh && mesh.isMesh ) === false ) {
  12527. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  12528. return;
  12529. }
  12530. mesh.matrixAutoUpdate && mesh.updateMatrix();
  12531. this.merge( mesh.geometry, mesh.matrix );
  12532. },
  12533. /*
  12534. * Checks for duplicate vertices with hashmap.
  12535. * Duplicated vertices are removed
  12536. * and faces' vertices are updated.
  12537. */
  12538. mergeVertices: function () {
  12539. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  12540. var unique = [], changes = [];
  12541. var v, key;
  12542. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  12543. var precision = Math.pow( 10, precisionPoints );
  12544. var i, il, face;
  12545. var indices, j, jl;
  12546. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  12547. v = this.vertices[ i ];
  12548. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  12549. if ( verticesMap[ key ] === undefined ) {
  12550. verticesMap[ key ] = i;
  12551. unique.push( this.vertices[ i ] );
  12552. changes[ i ] = unique.length - 1;
  12553. } else {
  12554. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  12555. changes[ i ] = changes[ verticesMap[ key ] ];
  12556. }
  12557. }
  12558. // if faces are completely degenerate after merging vertices, we
  12559. // have to remove them from the geometry.
  12560. var faceIndicesToRemove = [];
  12561. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  12562. face = this.faces[ i ];
  12563. face.a = changes[ face.a ];
  12564. face.b = changes[ face.b ];
  12565. face.c = changes[ face.c ];
  12566. indices = [ face.a, face.b, face.c ];
  12567. // if any duplicate vertices are found in a Face3
  12568. // we have to remove the face as nothing can be saved
  12569. for ( var n = 0; n < 3; n ++ ) {
  12570. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  12571. faceIndicesToRemove.push( i );
  12572. break;
  12573. }
  12574. }
  12575. }
  12576. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  12577. var idx = faceIndicesToRemove[ i ];
  12578. this.faces.splice( idx, 1 );
  12579. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  12580. this.faceVertexUvs[ j ].splice( idx, 1 );
  12581. }
  12582. }
  12583. // Use unique set of vertices
  12584. var diff = this.vertices.length - unique.length;
  12585. this.vertices = unique;
  12586. return diff;
  12587. },
  12588. sortFacesByMaterialIndex: function () {
  12589. var faces = this.faces;
  12590. var length = faces.length;
  12591. // tag faces
  12592. for ( var i = 0; i < length; i ++ ) {
  12593. faces[ i ]._id = i;
  12594. }
  12595. // sort faces
  12596. function materialIndexSort( a, b ) {
  12597. return a.materialIndex - b.materialIndex;
  12598. }
  12599. faces.sort( materialIndexSort );
  12600. // sort uvs
  12601. var uvs1 = this.faceVertexUvs[ 0 ];
  12602. var uvs2 = this.faceVertexUvs[ 1 ];
  12603. var newUvs1, newUvs2;
  12604. if ( uvs1 && uvs1.length === length ) newUvs1 = [];
  12605. if ( uvs2 && uvs2.length === length ) newUvs2 = [];
  12606. for ( var i = 0; i < length; i ++ ) {
  12607. var id = faces[ i ]._id;
  12608. if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
  12609. if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
  12610. }
  12611. if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
  12612. if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
  12613. },
  12614. toJSON: function () {
  12615. var data = {
  12616. metadata: {
  12617. version: 4.4,
  12618. type: 'Geometry',
  12619. generator: 'Geometry.toJSON'
  12620. }
  12621. };
  12622. // standard Geometry serialization
  12623. data.uuid = this.uuid;
  12624. data.type = this.type;
  12625. if ( this.name !== '' ) data.name = this.name;
  12626. if ( this.parameters !== undefined ) {
  12627. var parameters = this.parameters;
  12628. for ( var key in parameters ) {
  12629. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  12630. }
  12631. return data;
  12632. }
  12633. var vertices = [];
  12634. for ( var i = 0; i < this.vertices.length; i ++ ) {
  12635. var vertex = this.vertices[ i ];
  12636. vertices.push( vertex.x, vertex.y, vertex.z );
  12637. }
  12638. var faces = [];
  12639. var normals = [];
  12640. var normalsHash = {};
  12641. var colors = [];
  12642. var colorsHash = {};
  12643. var uvs = [];
  12644. var uvsHash = {};
  12645. for ( var i = 0; i < this.faces.length; i ++ ) {
  12646. var face = this.faces[ i ];
  12647. var hasMaterial = true;
  12648. var hasFaceUv = false; // deprecated
  12649. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  12650. var hasFaceNormal = face.normal.length() > 0;
  12651. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  12652. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  12653. var hasFaceVertexColor = face.vertexColors.length > 0;
  12654. var faceType = 0;
  12655. faceType = setBit( faceType, 0, 0 ); // isQuad
  12656. faceType = setBit( faceType, 1, hasMaterial );
  12657. faceType = setBit( faceType, 2, hasFaceUv );
  12658. faceType = setBit( faceType, 3, hasFaceVertexUv );
  12659. faceType = setBit( faceType, 4, hasFaceNormal );
  12660. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  12661. faceType = setBit( faceType, 6, hasFaceColor );
  12662. faceType = setBit( faceType, 7, hasFaceVertexColor );
  12663. faces.push( faceType );
  12664. faces.push( face.a, face.b, face.c );
  12665. faces.push( face.materialIndex );
  12666. if ( hasFaceVertexUv ) {
  12667. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  12668. faces.push(
  12669. getUvIndex( faceVertexUvs[ 0 ] ),
  12670. getUvIndex( faceVertexUvs[ 1 ] ),
  12671. getUvIndex( faceVertexUvs[ 2 ] )
  12672. );
  12673. }
  12674. if ( hasFaceNormal ) {
  12675. faces.push( getNormalIndex( face.normal ) );
  12676. }
  12677. if ( hasFaceVertexNormal ) {
  12678. var vertexNormals = face.vertexNormals;
  12679. faces.push(
  12680. getNormalIndex( vertexNormals[ 0 ] ),
  12681. getNormalIndex( vertexNormals[ 1 ] ),
  12682. getNormalIndex( vertexNormals[ 2 ] )
  12683. );
  12684. }
  12685. if ( hasFaceColor ) {
  12686. faces.push( getColorIndex( face.color ) );
  12687. }
  12688. if ( hasFaceVertexColor ) {
  12689. var vertexColors = face.vertexColors;
  12690. faces.push(
  12691. getColorIndex( vertexColors[ 0 ] ),
  12692. getColorIndex( vertexColors[ 1 ] ),
  12693. getColorIndex( vertexColors[ 2 ] )
  12694. );
  12695. }
  12696. }
  12697. function setBit( value, position, enabled ) {
  12698. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  12699. }
  12700. function getNormalIndex( normal ) {
  12701. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  12702. if ( normalsHash[ hash ] !== undefined ) {
  12703. return normalsHash[ hash ];
  12704. }
  12705. normalsHash[ hash ] = normals.length / 3;
  12706. normals.push( normal.x, normal.y, normal.z );
  12707. return normalsHash[ hash ];
  12708. }
  12709. function getColorIndex( color ) {
  12710. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  12711. if ( colorsHash[ hash ] !== undefined ) {
  12712. return colorsHash[ hash ];
  12713. }
  12714. colorsHash[ hash ] = colors.length;
  12715. colors.push( color.getHex() );
  12716. return colorsHash[ hash ];
  12717. }
  12718. function getUvIndex( uv ) {
  12719. var hash = uv.x.toString() + uv.y.toString();
  12720. if ( uvsHash[ hash ] !== undefined ) {
  12721. return uvsHash[ hash ];
  12722. }
  12723. uvsHash[ hash ] = uvs.length / 2;
  12724. uvs.push( uv.x, uv.y );
  12725. return uvsHash[ hash ];
  12726. }
  12727. data.data = {};
  12728. data.data.vertices = vertices;
  12729. data.data.normals = normals;
  12730. if ( colors.length > 0 ) data.data.colors = colors;
  12731. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  12732. data.data.faces = faces;
  12733. return data;
  12734. },
  12735. clone: function () {
  12736. /*
  12737. // Handle primitives
  12738. var parameters = this.parameters;
  12739. if ( parameters !== undefined ) {
  12740. var values = [];
  12741. for ( var key in parameters ) {
  12742. values.push( parameters[ key ] );
  12743. }
  12744. var geometry = Object.create( this.constructor.prototype );
  12745. this.constructor.apply( geometry, values );
  12746. return geometry;
  12747. }
  12748. return new this.constructor().copy( this );
  12749. */
  12750. return new Geometry().copy( this );
  12751. },
  12752. copy: function ( source ) {
  12753. var i, il, j, jl, k, kl;
  12754. // reset
  12755. this.vertices = [];
  12756. this.colors = [];
  12757. this.faces = [];
  12758. this.faceVertexUvs = [[]];
  12759. this.morphTargets = [];
  12760. this.morphNormals = [];
  12761. this.skinWeights = [];
  12762. this.skinIndices = [];
  12763. this.lineDistances = [];
  12764. this.boundingBox = null;
  12765. this.boundingSphere = null;
  12766. // name
  12767. this.name = source.name;
  12768. // vertices
  12769. var vertices = source.vertices;
  12770. for ( i = 0, il = vertices.length; i < il; i ++ ) {
  12771. this.vertices.push( vertices[ i ].clone() );
  12772. }
  12773. // colors
  12774. var colors = source.colors;
  12775. for ( i = 0, il = colors.length; i < il; i ++ ) {
  12776. this.colors.push( colors[ i ].clone() );
  12777. }
  12778. // faces
  12779. var faces = source.faces;
  12780. for ( i = 0, il = faces.length; i < il; i ++ ) {
  12781. this.faces.push( faces[ i ].clone() );
  12782. }
  12783. // face vertex uvs
  12784. for ( i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  12785. var faceVertexUvs = source.faceVertexUvs[ i ];
  12786. if ( this.faceVertexUvs[ i ] === undefined ) {
  12787. this.faceVertexUvs[ i ] = [];
  12788. }
  12789. for ( j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  12790. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  12791. for ( k = 0, kl = uvs.length; k < kl; k ++ ) {
  12792. var uv = uvs[ k ];
  12793. uvsCopy.push( uv.clone() );
  12794. }
  12795. this.faceVertexUvs[ i ].push( uvsCopy );
  12796. }
  12797. }
  12798. // morph targets
  12799. var morphTargets = source.morphTargets;
  12800. for ( i = 0, il = morphTargets.length; i < il; i ++ ) {
  12801. var morphTarget = {};
  12802. morphTarget.name = morphTargets[ i ].name;
  12803. // vertices
  12804. if ( morphTargets[ i ].vertices !== undefined ) {
  12805. morphTarget.vertices = [];
  12806. for ( j = 0, jl = morphTargets[ i ].vertices.length; j < jl; j ++ ) {
  12807. morphTarget.vertices.push( morphTargets[ i ].vertices[ j ].clone() );
  12808. }
  12809. }
  12810. // normals
  12811. if ( morphTargets[ i ].normals !== undefined ) {
  12812. morphTarget.normals = [];
  12813. for ( j = 0, jl = morphTargets[ i ].normals.length; j < jl; j ++ ) {
  12814. morphTarget.normals.push( morphTargets[ i ].normals[ j ].clone() );
  12815. }
  12816. }
  12817. this.morphTargets.push( morphTarget );
  12818. }
  12819. // morph normals
  12820. var morphNormals = source.morphNormals;
  12821. for ( i = 0, il = morphNormals.length; i < il; i ++ ) {
  12822. var morphNormal = {};
  12823. // vertex normals
  12824. if ( morphNormals[ i ].vertexNormals !== undefined ) {
  12825. morphNormal.vertexNormals = [];
  12826. for ( j = 0, jl = morphNormals[ i ].vertexNormals.length; j < jl; j ++ ) {
  12827. var srcVertexNormal = morphNormals[ i ].vertexNormals[ j ];
  12828. var destVertexNormal = {};
  12829. destVertexNormal.a = srcVertexNormal.a.clone();
  12830. destVertexNormal.b = srcVertexNormal.b.clone();
  12831. destVertexNormal.c = srcVertexNormal.c.clone();
  12832. morphNormal.vertexNormals.push( destVertexNormal );
  12833. }
  12834. }
  12835. // face normals
  12836. if ( morphNormals[ i ].faceNormals !== undefined ) {
  12837. morphNormal.faceNormals = [];
  12838. for ( j = 0, jl = morphNormals[ i ].faceNormals.length; j < jl; j ++ ) {
  12839. morphNormal.faceNormals.push( morphNormals[ i ].faceNormals[ j ].clone() );
  12840. }
  12841. }
  12842. this.morphNormals.push( morphNormal );
  12843. }
  12844. // skin weights
  12845. var skinWeights = source.skinWeights;
  12846. for ( i = 0, il = skinWeights.length; i < il; i ++ ) {
  12847. this.skinWeights.push( skinWeights[ i ].clone() );
  12848. }
  12849. // skin indices
  12850. var skinIndices = source.skinIndices;
  12851. for ( i = 0, il = skinIndices.length; i < il; i ++ ) {
  12852. this.skinIndices.push( skinIndices[ i ].clone() );
  12853. }
  12854. // line distances
  12855. var lineDistances = source.lineDistances;
  12856. for ( i = 0, il = lineDistances.length; i < il; i ++ ) {
  12857. this.lineDistances.push( lineDistances[ i ] );
  12858. }
  12859. // bounding box
  12860. var boundingBox = source.boundingBox;
  12861. if ( boundingBox !== null ) {
  12862. this.boundingBox = boundingBox.clone();
  12863. }
  12864. // bounding sphere
  12865. var boundingSphere = source.boundingSphere;
  12866. if ( boundingSphere !== null ) {
  12867. this.boundingSphere = boundingSphere.clone();
  12868. }
  12869. // update flags
  12870. this.elementsNeedUpdate = source.elementsNeedUpdate;
  12871. this.verticesNeedUpdate = source.verticesNeedUpdate;
  12872. this.uvsNeedUpdate = source.uvsNeedUpdate;
  12873. this.normalsNeedUpdate = source.normalsNeedUpdate;
  12874. this.colorsNeedUpdate = source.colorsNeedUpdate;
  12875. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  12876. this.groupsNeedUpdate = source.groupsNeedUpdate;
  12877. return this;
  12878. },
  12879. dispose: function () {
  12880. this.dispatchEvent( { type: 'dispose' } );
  12881. }
  12882. };
  12883. Object.assign( Geometry.prototype, EventDispatcher.prototype );
  12884. /**
  12885. * @author alteredq / http://alteredqualia.com/
  12886. * @author mrdoob / http://mrdoob.com/
  12887. */
  12888. function BufferGeometry() {
  12889. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  12890. this.uuid = _Math.generateUUID();
  12891. this.name = '';
  12892. this.type = 'BufferGeometry';
  12893. this.index = null;
  12894. this.attributes = {};
  12895. this.morphAttributes = {};
  12896. this.groups = [];
  12897. this.boundingBox = null;
  12898. this.boundingSphere = null;
  12899. this.drawRange = { start: 0, count: Infinity };
  12900. }
  12901. BufferGeometry.prototype = {
  12902. constructor: BufferGeometry,
  12903. isBufferGeometry: true,
  12904. getIndex: function () {
  12905. return this.index;
  12906. },
  12907. setIndex: function ( index ) {
  12908. if ( Array.isArray( index ) ) {
  12909. this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  12910. } else {
  12911. this.index = index;
  12912. }
  12913. },
  12914. addAttribute: function ( name, attribute ) {
  12915. if ( ( attribute && attribute.isBufferAttribute ) === false && ( attribute && attribute.isInterleavedBufferAttribute ) === false ) {
  12916. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  12917. this.addAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  12918. return;
  12919. }
  12920. if ( name === 'index' ) {
  12921. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  12922. this.setIndex( attribute );
  12923. return;
  12924. }
  12925. this.attributes[ name ] = attribute;
  12926. return this;
  12927. },
  12928. getAttribute: function ( name ) {
  12929. return this.attributes[ name ];
  12930. },
  12931. removeAttribute: function ( name ) {
  12932. delete this.attributes[ name ];
  12933. return this;
  12934. },
  12935. addGroup: function ( start, count, materialIndex ) {
  12936. this.groups.push( {
  12937. start: start,
  12938. count: count,
  12939. materialIndex: materialIndex !== undefined ? materialIndex : 0
  12940. } );
  12941. },
  12942. clearGroups: function () {
  12943. this.groups = [];
  12944. },
  12945. setDrawRange: function ( start, count ) {
  12946. this.drawRange.start = start;
  12947. this.drawRange.count = count;
  12948. },
  12949. applyMatrix: function ( matrix ) {
  12950. var position = this.attributes.position;
  12951. if ( position !== undefined ) {
  12952. matrix.applyToBufferAttribute( position );
  12953. position.needsUpdate = true;
  12954. }
  12955. var normal = this.attributes.normal;
  12956. if ( normal !== undefined ) {
  12957. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  12958. normalMatrix.applyToBufferAttribute( normal );
  12959. normal.needsUpdate = true;
  12960. }
  12961. if ( this.boundingBox !== null ) {
  12962. this.computeBoundingBox();
  12963. }
  12964. if ( this.boundingSphere !== null ) {
  12965. this.computeBoundingSphere();
  12966. }
  12967. return this;
  12968. },
  12969. rotateX: function () {
  12970. // rotate geometry around world x-axis
  12971. var m1;
  12972. return function rotateX( angle ) {
  12973. if ( m1 === undefined ) m1 = new Matrix4();
  12974. m1.makeRotationX( angle );
  12975. this.applyMatrix( m1 );
  12976. return this;
  12977. };
  12978. }(),
  12979. rotateY: function () {
  12980. // rotate geometry around world y-axis
  12981. var m1;
  12982. return function rotateY( angle ) {
  12983. if ( m1 === undefined ) m1 = new Matrix4();
  12984. m1.makeRotationY( angle );
  12985. this.applyMatrix( m1 );
  12986. return this;
  12987. };
  12988. }(),
  12989. rotateZ: function () {
  12990. // rotate geometry around world z-axis
  12991. var m1;
  12992. return function rotateZ( angle ) {
  12993. if ( m1 === undefined ) m1 = new Matrix4();
  12994. m1.makeRotationZ( angle );
  12995. this.applyMatrix( m1 );
  12996. return this;
  12997. };
  12998. }(),
  12999. translate: function () {
  13000. // translate geometry
  13001. var m1;
  13002. return function translate( x, y, z ) {
  13003. if ( m1 === undefined ) m1 = new Matrix4();
  13004. m1.makeTranslation( x, y, z );
  13005. this.applyMatrix( m1 );
  13006. return this;
  13007. };
  13008. }(),
  13009. scale: function () {
  13010. // scale geometry
  13011. var m1;
  13012. return function scale( x, y, z ) {
  13013. if ( m1 === undefined ) m1 = new Matrix4();
  13014. m1.makeScale( x, y, z );
  13015. this.applyMatrix( m1 );
  13016. return this;
  13017. };
  13018. }(),
  13019. lookAt: function () {
  13020. var obj;
  13021. return function lookAt( vector ) {
  13022. if ( obj === undefined ) obj = new Object3D();
  13023. obj.lookAt( vector );
  13024. obj.updateMatrix();
  13025. this.applyMatrix( obj.matrix );
  13026. };
  13027. }(),
  13028. center: function () {
  13029. this.computeBoundingBox();
  13030. var offset = this.boundingBox.getCenter().negate();
  13031. this.translate( offset.x, offset.y, offset.z );
  13032. return offset;
  13033. },
  13034. setFromObject: function ( object ) {
  13035. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  13036. var geometry = object.geometry;
  13037. if ( object.isPoints || object.isLine ) {
  13038. var positions = new Float32BufferAttribute( geometry.vertices.length * 3, 3 );
  13039. var colors = new Float32BufferAttribute( geometry.colors.length * 3, 3 );
  13040. this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  13041. this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  13042. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  13043. var lineDistances = new Float32BufferAttribute( geometry.lineDistances.length, 1 );
  13044. this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  13045. }
  13046. if ( geometry.boundingSphere !== null ) {
  13047. this.boundingSphere = geometry.boundingSphere.clone();
  13048. }
  13049. if ( geometry.boundingBox !== null ) {
  13050. this.boundingBox = geometry.boundingBox.clone();
  13051. }
  13052. } else if ( object.isMesh ) {
  13053. if ( geometry && geometry.isGeometry ) {
  13054. this.fromGeometry( geometry );
  13055. }
  13056. }
  13057. return this;
  13058. },
  13059. updateFromObject: function ( object ) {
  13060. var geometry = object.geometry;
  13061. if ( object.isMesh ) {
  13062. var direct = geometry.__directGeometry;
  13063. if ( geometry.elementsNeedUpdate === true ) {
  13064. direct = undefined;
  13065. geometry.elementsNeedUpdate = false;
  13066. }
  13067. if ( direct === undefined ) {
  13068. return this.fromGeometry( geometry );
  13069. }
  13070. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  13071. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  13072. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  13073. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  13074. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  13075. geometry.verticesNeedUpdate = false;
  13076. geometry.normalsNeedUpdate = false;
  13077. geometry.colorsNeedUpdate = false;
  13078. geometry.uvsNeedUpdate = false;
  13079. geometry.groupsNeedUpdate = false;
  13080. geometry = direct;
  13081. }
  13082. var attribute;
  13083. if ( geometry.verticesNeedUpdate === true ) {
  13084. attribute = this.attributes.position;
  13085. if ( attribute !== undefined ) {
  13086. attribute.copyVector3sArray( geometry.vertices );
  13087. attribute.needsUpdate = true;
  13088. }
  13089. geometry.verticesNeedUpdate = false;
  13090. }
  13091. if ( geometry.normalsNeedUpdate === true ) {
  13092. attribute = this.attributes.normal;
  13093. if ( attribute !== undefined ) {
  13094. attribute.copyVector3sArray( geometry.normals );
  13095. attribute.needsUpdate = true;
  13096. }
  13097. geometry.normalsNeedUpdate = false;
  13098. }
  13099. if ( geometry.colorsNeedUpdate === true ) {
  13100. attribute = this.attributes.color;
  13101. if ( attribute !== undefined ) {
  13102. attribute.copyColorsArray( geometry.colors );
  13103. attribute.needsUpdate = true;
  13104. }
  13105. geometry.colorsNeedUpdate = false;
  13106. }
  13107. if ( geometry.uvsNeedUpdate ) {
  13108. attribute = this.attributes.uv;
  13109. if ( attribute !== undefined ) {
  13110. attribute.copyVector2sArray( geometry.uvs );
  13111. attribute.needsUpdate = true;
  13112. }
  13113. geometry.uvsNeedUpdate = false;
  13114. }
  13115. if ( geometry.lineDistancesNeedUpdate ) {
  13116. attribute = this.attributes.lineDistance;
  13117. if ( attribute !== undefined ) {
  13118. attribute.copyArray( geometry.lineDistances );
  13119. attribute.needsUpdate = true;
  13120. }
  13121. geometry.lineDistancesNeedUpdate = false;
  13122. }
  13123. if ( geometry.groupsNeedUpdate ) {
  13124. geometry.computeGroups( object.geometry );
  13125. this.groups = geometry.groups;
  13126. geometry.groupsNeedUpdate = false;
  13127. }
  13128. return this;
  13129. },
  13130. fromGeometry: function ( geometry ) {
  13131. geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry );
  13132. return this.fromDirectGeometry( geometry.__directGeometry );
  13133. },
  13134. fromDirectGeometry: function ( geometry ) {
  13135. var positions = new Float32Array( geometry.vertices.length * 3 );
  13136. this.addAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  13137. if ( geometry.normals.length > 0 ) {
  13138. var normals = new Float32Array( geometry.normals.length * 3 );
  13139. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  13140. }
  13141. if ( geometry.colors.length > 0 ) {
  13142. var colors = new Float32Array( geometry.colors.length * 3 );
  13143. this.addAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  13144. }
  13145. if ( geometry.uvs.length > 0 ) {
  13146. var uvs = new Float32Array( geometry.uvs.length * 2 );
  13147. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  13148. }
  13149. if ( geometry.uvs2.length > 0 ) {
  13150. var uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  13151. this.addAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  13152. }
  13153. if ( geometry.indices.length > 0 ) {
  13154. var TypeArray = arrayMax( geometry.indices ) > 65535 ? Uint32Array : Uint16Array;
  13155. var indices = new TypeArray( geometry.indices.length * 3 );
  13156. this.setIndex( new BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) );
  13157. }
  13158. // groups
  13159. this.groups = geometry.groups;
  13160. // morphs
  13161. for ( var name in geometry.morphTargets ) {
  13162. var array = [];
  13163. var morphTargets = geometry.morphTargets[ name ];
  13164. for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {
  13165. var morphTarget = morphTargets[ i ];
  13166. var attribute = new Float32BufferAttribute( morphTarget.length * 3, 3 );
  13167. array.push( attribute.copyVector3sArray( morphTarget ) );
  13168. }
  13169. this.morphAttributes[ name ] = array;
  13170. }
  13171. // skinning
  13172. if ( geometry.skinIndices.length > 0 ) {
  13173. var skinIndices = new Float32BufferAttribute( geometry.skinIndices.length * 4, 4 );
  13174. this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  13175. }
  13176. if ( geometry.skinWeights.length > 0 ) {
  13177. var skinWeights = new Float32BufferAttribute( geometry.skinWeights.length * 4, 4 );
  13178. this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  13179. }
  13180. //
  13181. if ( geometry.boundingSphere !== null ) {
  13182. this.boundingSphere = geometry.boundingSphere.clone();
  13183. }
  13184. if ( geometry.boundingBox !== null ) {
  13185. this.boundingBox = geometry.boundingBox.clone();
  13186. }
  13187. return this;
  13188. },
  13189. computeBoundingBox: function () {
  13190. if ( this.boundingBox === null ) {
  13191. this.boundingBox = new Box3();
  13192. }
  13193. var position = this.attributes.position;
  13194. if ( position !== undefined ) {
  13195. this.boundingBox.setFromBufferAttribute( position );
  13196. } else {
  13197. this.boundingBox.makeEmpty();
  13198. }
  13199. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  13200. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  13201. }
  13202. },
  13203. computeBoundingSphere: function () {
  13204. var box = new Box3();
  13205. var vector = new Vector3();
  13206. return function computeBoundingSphere() {
  13207. if ( this.boundingSphere === null ) {
  13208. this.boundingSphere = new Sphere();
  13209. }
  13210. var position = this.attributes.position;
  13211. if ( position ) {
  13212. var center = this.boundingSphere.center;
  13213. box.setFromBufferAttribute( position );
  13214. box.getCenter( center );
  13215. // hoping to find a boundingSphere with a radius smaller than the
  13216. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  13217. var maxRadiusSq = 0;
  13218. for ( var i = 0, il = position.count; i < il; i ++ ) {
  13219. vector.x = position.getX( i );
  13220. vector.y = position.getY( i );
  13221. vector.z = position.getZ( i );
  13222. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  13223. }
  13224. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  13225. if ( isNaN( this.boundingSphere.radius ) ) {
  13226. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  13227. }
  13228. }
  13229. };
  13230. }(),
  13231. computeFaceNormals: function () {
  13232. // backwards compatibility
  13233. },
  13234. computeVertexNormals: function () {
  13235. var index = this.index;
  13236. var attributes = this.attributes;
  13237. var groups = this.groups;
  13238. if ( attributes.position ) {
  13239. var positions = attributes.position.array;
  13240. if ( attributes.normal === undefined ) {
  13241. this.addAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) );
  13242. } else {
  13243. // reset existing normals to zero
  13244. var array = attributes.normal.array;
  13245. for ( var i = 0, il = array.length; i < il; i ++ ) {
  13246. array[ i ] = 0;
  13247. }
  13248. }
  13249. var normals = attributes.normal.array;
  13250. var vA, vB, vC;
  13251. var pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  13252. var cb = new Vector3(), ab = new Vector3();
  13253. // indexed elements
  13254. if ( index ) {
  13255. var indices = index.array;
  13256. if ( groups.length === 0 ) {
  13257. this.addGroup( 0, indices.length );
  13258. }
  13259. for ( var j = 0, jl = groups.length; j < jl; ++ j ) {
  13260. var group = groups[ j ];
  13261. var start = group.start;
  13262. var count = group.count;
  13263. for ( var i = start, il = start + count; i < il; i += 3 ) {
  13264. vA = indices[ i + 0 ] * 3;
  13265. vB = indices[ i + 1 ] * 3;
  13266. vC = indices[ i + 2 ] * 3;
  13267. pA.fromArray( positions, vA );
  13268. pB.fromArray( positions, vB );
  13269. pC.fromArray( positions, vC );
  13270. cb.subVectors( pC, pB );
  13271. ab.subVectors( pA, pB );
  13272. cb.cross( ab );
  13273. normals[ vA ] += cb.x;
  13274. normals[ vA + 1 ] += cb.y;
  13275. normals[ vA + 2 ] += cb.z;
  13276. normals[ vB ] += cb.x;
  13277. normals[ vB + 1 ] += cb.y;
  13278. normals[ vB + 2 ] += cb.z;
  13279. normals[ vC ] += cb.x;
  13280. normals[ vC + 1 ] += cb.y;
  13281. normals[ vC + 2 ] += cb.z;
  13282. }
  13283. }
  13284. } else {
  13285. // non-indexed elements (unconnected triangle soup)
  13286. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  13287. pA.fromArray( positions, i );
  13288. pB.fromArray( positions, i + 3 );
  13289. pC.fromArray( positions, i + 6 );
  13290. cb.subVectors( pC, pB );
  13291. ab.subVectors( pA, pB );
  13292. cb.cross( ab );
  13293. normals[ i ] = cb.x;
  13294. normals[ i + 1 ] = cb.y;
  13295. normals[ i + 2 ] = cb.z;
  13296. normals[ i + 3 ] = cb.x;
  13297. normals[ i + 4 ] = cb.y;
  13298. normals[ i + 5 ] = cb.z;
  13299. normals[ i + 6 ] = cb.x;
  13300. normals[ i + 7 ] = cb.y;
  13301. normals[ i + 8 ] = cb.z;
  13302. }
  13303. }
  13304. this.normalizeNormals();
  13305. attributes.normal.needsUpdate = true;
  13306. }
  13307. },
  13308. merge: function ( geometry, offset ) {
  13309. if ( ( geometry && geometry.isBufferGeometry ) === false ) {
  13310. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  13311. return;
  13312. }
  13313. if ( offset === undefined ) offset = 0;
  13314. var attributes = this.attributes;
  13315. for ( var key in attributes ) {
  13316. if ( geometry.attributes[ key ] === undefined ) continue;
  13317. var attribute1 = attributes[ key ];
  13318. var attributeArray1 = attribute1.array;
  13319. var attribute2 = geometry.attributes[ key ];
  13320. var attributeArray2 = attribute2.array;
  13321. var attributeSize = attribute2.itemSize;
  13322. for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) {
  13323. attributeArray1[ j ] = attributeArray2[ i ];
  13324. }
  13325. }
  13326. return this;
  13327. },
  13328. normalizeNormals: function () {
  13329. var normals = this.attributes.normal.array;
  13330. var x, y, z, n;
  13331. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  13332. x = normals[ i ];
  13333. y = normals[ i + 1 ];
  13334. z = normals[ i + 2 ];
  13335. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  13336. normals[ i ] *= n;
  13337. normals[ i + 1 ] *= n;
  13338. normals[ i + 2 ] *= n;
  13339. }
  13340. },
  13341. toNonIndexed: function () {
  13342. if ( this.index === null ) {
  13343. console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' );
  13344. return this;
  13345. }
  13346. var geometry2 = new BufferGeometry();
  13347. var indices = this.index.array;
  13348. var attributes = this.attributes;
  13349. for ( var name in attributes ) {
  13350. var attribute = attributes[ name ];
  13351. var array = attribute.array;
  13352. var itemSize = attribute.itemSize;
  13353. var array2 = new array.constructor( indices.length * itemSize );
  13354. var index = 0, index2 = 0;
  13355. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  13356. index = indices[ i ] * itemSize;
  13357. for ( var j = 0; j < itemSize; j ++ ) {
  13358. array2[ index2 ++ ] = array[ index ++ ];
  13359. }
  13360. }
  13361. geometry2.addAttribute( name, new BufferAttribute( array2, itemSize ) );
  13362. }
  13363. return geometry2;
  13364. },
  13365. toJSON: function () {
  13366. var data = {
  13367. metadata: {
  13368. version: 4.4,
  13369. type: 'BufferGeometry',
  13370. generator: 'BufferGeometry.toJSON'
  13371. }
  13372. };
  13373. // standard BufferGeometry serialization
  13374. data.uuid = this.uuid;
  13375. data.type = this.type;
  13376. if ( this.name !== '' ) data.name = this.name;
  13377. if ( this.parameters !== undefined ) {
  13378. var parameters = this.parameters;
  13379. for ( var key in parameters ) {
  13380. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  13381. }
  13382. return data;
  13383. }
  13384. data.data = { attributes: {} };
  13385. var index = this.index;
  13386. if ( index !== null ) {
  13387. var array = Array.prototype.slice.call( index.array );
  13388. data.data.index = {
  13389. type: index.array.constructor.name,
  13390. array: array
  13391. };
  13392. }
  13393. var attributes = this.attributes;
  13394. for ( var key in attributes ) {
  13395. var attribute = attributes[ key ];
  13396. var array = Array.prototype.slice.call( attribute.array );
  13397. data.data.attributes[ key ] = {
  13398. itemSize: attribute.itemSize,
  13399. type: attribute.array.constructor.name,
  13400. array: array,
  13401. normalized: attribute.normalized
  13402. };
  13403. }
  13404. var groups = this.groups;
  13405. if ( groups.length > 0 ) {
  13406. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  13407. }
  13408. var boundingSphere = this.boundingSphere;
  13409. if ( boundingSphere !== null ) {
  13410. data.data.boundingSphere = {
  13411. center: boundingSphere.center.toArray(),
  13412. radius: boundingSphere.radius
  13413. };
  13414. }
  13415. return data;
  13416. },
  13417. clone: function () {
  13418. /*
  13419. // Handle primitives
  13420. var parameters = this.parameters;
  13421. if ( parameters !== undefined ) {
  13422. var values = [];
  13423. for ( var key in parameters ) {
  13424. values.push( parameters[ key ] );
  13425. }
  13426. var geometry = Object.create( this.constructor.prototype );
  13427. this.constructor.apply( geometry, values );
  13428. return geometry;
  13429. }
  13430. return new this.constructor().copy( this );
  13431. */
  13432. return new BufferGeometry().copy( this );
  13433. },
  13434. copy: function ( source ) {
  13435. var name, i, l;
  13436. // reset
  13437. this.index = null;
  13438. this.attributes = {};
  13439. this.morphAttributes = {};
  13440. this.groups = [];
  13441. this.boundingBox = null;
  13442. this.boundingSphere = null;
  13443. // name
  13444. this.name = source.name;
  13445. // index
  13446. var index = source.index;
  13447. if ( index !== null ) {
  13448. this.setIndex( index.clone() );
  13449. }
  13450. // attributes
  13451. var attributes = source.attributes;
  13452. for ( name in attributes ) {
  13453. var attribute = attributes[ name ];
  13454. this.addAttribute( name, attribute.clone() );
  13455. }
  13456. // morph attributes
  13457. var morphAttributes = source.morphAttributes;
  13458. for ( name in morphAttributes ) {
  13459. var array = [];
  13460. var morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  13461. for ( i = 0, l = morphAttribute.length; i < l; i ++ ) {
  13462. array.push( morphAttribute[ i ].clone() );
  13463. }
  13464. this.morphAttributes[ name ] = array;
  13465. }
  13466. // groups
  13467. var groups = source.groups;
  13468. for ( i = 0, l = groups.length; i < l; i ++ ) {
  13469. var group = groups[ i ];
  13470. this.addGroup( group.start, group.count, group.materialIndex );
  13471. }
  13472. // bounding box
  13473. var boundingBox = source.boundingBox;
  13474. if ( boundingBox !== null ) {
  13475. this.boundingBox = boundingBox.clone();
  13476. }
  13477. // bounding sphere
  13478. var boundingSphere = source.boundingSphere;
  13479. if ( boundingSphere !== null ) {
  13480. this.boundingSphere = boundingSphere.clone();
  13481. }
  13482. // draw range
  13483. this.drawRange.start = source.drawRange.start;
  13484. this.drawRange.count = source.drawRange.count;
  13485. return this;
  13486. },
  13487. dispose: function () {
  13488. this.dispatchEvent( { type: 'dispose' } );
  13489. }
  13490. };
  13491. BufferGeometry.MaxIndex = 65535;
  13492. Object.assign( BufferGeometry.prototype, EventDispatcher.prototype );
  13493. /**
  13494. * @author mrdoob / http://mrdoob.com/
  13495. * @author alteredq / http://alteredqualia.com/
  13496. * @author mikael emtinger / http://gomo.se/
  13497. * @author jonobr1 / http://jonobr1.com/
  13498. */
  13499. function Mesh( geometry, material ) {
  13500. Object3D.call( this );
  13501. this.type = 'Mesh';
  13502. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  13503. this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  13504. this.drawMode = TrianglesDrawMode;
  13505. this.updateMorphTargets();
  13506. }
  13507. Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13508. constructor: Mesh,
  13509. isMesh: true,
  13510. setDrawMode: function ( value ) {
  13511. this.drawMode = value;
  13512. },
  13513. copy: function ( source ) {
  13514. Object3D.prototype.copy.call( this, source );
  13515. this.drawMode = source.drawMode;
  13516. return this;
  13517. },
  13518. updateMorphTargets: function () {
  13519. var morphTargets = this.geometry.morphTargets;
  13520. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  13521. this.morphTargetInfluences = [];
  13522. this.morphTargetDictionary = {};
  13523. for ( var m = 0, ml = morphTargets.length; m < ml; m ++ ) {
  13524. this.morphTargetInfluences.push( 0 );
  13525. this.morphTargetDictionary[ morphTargets[ m ].name ] = m;
  13526. }
  13527. }
  13528. },
  13529. raycast: ( function () {
  13530. var inverseMatrix = new Matrix4();
  13531. var ray = new Ray();
  13532. var sphere = new Sphere();
  13533. var vA = new Vector3();
  13534. var vB = new Vector3();
  13535. var vC = new Vector3();
  13536. var tempA = new Vector3();
  13537. var tempB = new Vector3();
  13538. var tempC = new Vector3();
  13539. var uvA = new Vector2();
  13540. var uvB = new Vector2();
  13541. var uvC = new Vector2();
  13542. var barycoord = new Vector3();
  13543. var intersectionPoint = new Vector3();
  13544. var intersectionPointWorld = new Vector3();
  13545. function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) {
  13546. Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord );
  13547. uv1.multiplyScalar( barycoord.x );
  13548. uv2.multiplyScalar( barycoord.y );
  13549. uv3.multiplyScalar( barycoord.z );
  13550. uv1.add( uv2 ).add( uv3 );
  13551. return uv1.clone();
  13552. }
  13553. function checkIntersection( object, raycaster, ray, pA, pB, pC, point ) {
  13554. var intersect;
  13555. var material = object.material;
  13556. if ( material.side === BackSide ) {
  13557. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  13558. } else {
  13559. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  13560. }
  13561. if ( intersect === null ) return null;
  13562. intersectionPointWorld.copy( point );
  13563. intersectionPointWorld.applyMatrix4( object.matrixWorld );
  13564. var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld );
  13565. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  13566. return {
  13567. distance: distance,
  13568. point: intersectionPointWorld.clone(),
  13569. object: object
  13570. };
  13571. }
  13572. function checkBufferGeometryIntersection( object, raycaster, ray, position, uv, a, b, c ) {
  13573. vA.fromBufferAttribute( position, a );
  13574. vB.fromBufferAttribute( position, b );
  13575. vC.fromBufferAttribute( position, c );
  13576. var intersection = checkIntersection( object, raycaster, ray, vA, vB, vC, intersectionPoint );
  13577. if ( intersection ) {
  13578. if ( uv ) {
  13579. uvA.fromBufferAttribute( uv, a );
  13580. uvB.fromBufferAttribute( uv, b );
  13581. uvC.fromBufferAttribute( uv, c );
  13582. intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC );
  13583. }
  13584. intersection.face = new Face3( a, b, c, Triangle.normal( vA, vB, vC ) );
  13585. intersection.faceIndex = a;
  13586. }
  13587. return intersection;
  13588. }
  13589. return function raycast( raycaster, intersects ) {
  13590. var geometry = this.geometry;
  13591. var material = this.material;
  13592. var matrixWorld = this.matrixWorld;
  13593. if ( material === undefined ) return;
  13594. // Checking boundingSphere distance to ray
  13595. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  13596. sphere.copy( geometry.boundingSphere );
  13597. sphere.applyMatrix4( matrixWorld );
  13598. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  13599. //
  13600. inverseMatrix.getInverse( matrixWorld );
  13601. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  13602. // Check boundingBox before continuing
  13603. if ( geometry.boundingBox !== null ) {
  13604. if ( ray.intersectsBox( geometry.boundingBox ) === false ) return;
  13605. }
  13606. var intersection;
  13607. if ( geometry.isBufferGeometry ) {
  13608. var a, b, c;
  13609. var index = geometry.index;
  13610. var position = geometry.attributes.position;
  13611. var uv = geometry.attributes.uv;
  13612. var i, l;
  13613. if ( index !== null ) {
  13614. // indexed buffer geometry
  13615. for ( i = 0, l = index.count; i < l; i += 3 ) {
  13616. a = index.getX( i );
  13617. b = index.getX( i + 1 );
  13618. c = index.getX( i + 2 );
  13619. intersection = checkBufferGeometryIntersection( this, raycaster, ray, position, uv, a, b, c );
  13620. if ( intersection ) {
  13621. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics
  13622. intersects.push( intersection );
  13623. }
  13624. }
  13625. } else {
  13626. // non-indexed buffer geometry
  13627. for ( i = 0, l = position.count; i < l; i += 3 ) {
  13628. a = i;
  13629. b = i + 1;
  13630. c = i + 2;
  13631. intersection = checkBufferGeometryIntersection( this, raycaster, ray, position, uv, a, b, c );
  13632. if ( intersection ) {
  13633. intersection.index = a; // triangle number in positions buffer semantics
  13634. intersects.push( intersection );
  13635. }
  13636. }
  13637. }
  13638. } else if ( geometry.isGeometry ) {
  13639. var fvA, fvB, fvC;
  13640. var isFaceMaterial = ( material && material.isMultiMaterial );
  13641. var materials = isFaceMaterial === true ? material.materials : null;
  13642. var vertices = geometry.vertices;
  13643. var faces = geometry.faces;
  13644. var uvs;
  13645. var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  13646. if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;
  13647. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  13648. var face = faces[ f ];
  13649. var faceMaterial = isFaceMaterial === true ? materials[ face.materialIndex ] : material;
  13650. if ( faceMaterial === undefined ) continue;
  13651. fvA = vertices[ face.a ];
  13652. fvB = vertices[ face.b ];
  13653. fvC = vertices[ face.c ];
  13654. if ( faceMaterial.morphTargets === true ) {
  13655. var morphTargets = geometry.morphTargets;
  13656. var morphInfluences = this.morphTargetInfluences;
  13657. vA.set( 0, 0, 0 );
  13658. vB.set( 0, 0, 0 );
  13659. vC.set( 0, 0, 0 );
  13660. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  13661. var influence = morphInfluences[ t ];
  13662. if ( influence === 0 ) continue;
  13663. var targets = morphTargets[ t ].vertices;
  13664. vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence );
  13665. vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence );
  13666. vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence );
  13667. }
  13668. vA.add( fvA );
  13669. vB.add( fvB );
  13670. vC.add( fvC );
  13671. fvA = vA;
  13672. fvB = vB;
  13673. fvC = vC;
  13674. }
  13675. intersection = checkIntersection( this, raycaster, ray, fvA, fvB, fvC, intersectionPoint );
  13676. if ( intersection ) {
  13677. if ( uvs ) {
  13678. var uvs_f = uvs[ f ];
  13679. uvA.copy( uvs_f[ 0 ] );
  13680. uvB.copy( uvs_f[ 1 ] );
  13681. uvC.copy( uvs_f[ 2 ] );
  13682. intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC );
  13683. }
  13684. intersection.face = face;
  13685. intersection.faceIndex = f;
  13686. intersects.push( intersection );
  13687. }
  13688. }
  13689. }
  13690. };
  13691. }() ),
  13692. clone: function () {
  13693. return new this.constructor( this.geometry, this.material ).copy( this );
  13694. }
  13695. } );
  13696. /**
  13697. * @author mrdoob / http://mrdoob.com/
  13698. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  13699. */
  13700. function BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  13701. Geometry.call( this );
  13702. this.type = 'BoxGeometry';
  13703. this.parameters = {
  13704. width: width,
  13705. height: height,
  13706. depth: depth,
  13707. widthSegments: widthSegments,
  13708. heightSegments: heightSegments,
  13709. depthSegments: depthSegments
  13710. };
  13711. this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
  13712. this.mergeVertices();
  13713. }
  13714. BoxGeometry.prototype = Object.create( Geometry.prototype );
  13715. BoxGeometry.prototype.constructor = BoxGeometry;
  13716. /**
  13717. * @author Mugen87 / https://github.com/Mugen87
  13718. */
  13719. function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  13720. BufferGeometry.call( this );
  13721. this.type = 'BoxBufferGeometry';
  13722. this.parameters = {
  13723. width: width,
  13724. height: height,
  13725. depth: depth,
  13726. widthSegments: widthSegments,
  13727. heightSegments: heightSegments,
  13728. depthSegments: depthSegments
  13729. };
  13730. var scope = this;
  13731. // segments
  13732. widthSegments = Math.floor( widthSegments ) || 1;
  13733. heightSegments = Math.floor( heightSegments ) || 1;
  13734. depthSegments = Math.floor( depthSegments ) || 1;
  13735. // buffers
  13736. var indices = [];
  13737. var vertices = [];
  13738. var normals = [];
  13739. var uvs = [];
  13740. // helper variables
  13741. var numberOfVertices = 0;
  13742. var groupStart = 0;
  13743. // build each side of the box geometry
  13744. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  13745. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  13746. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  13747. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  13748. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  13749. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  13750. // build geometry
  13751. this.setIndex( indices );
  13752. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13753. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13754. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13755. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  13756. var segmentWidth = width / gridX;
  13757. var segmentHeight = height / gridY;
  13758. var widthHalf = width / 2;
  13759. var heightHalf = height / 2;
  13760. var depthHalf = depth / 2;
  13761. var gridX1 = gridX + 1;
  13762. var gridY1 = gridY + 1;
  13763. var vertexCounter = 0;
  13764. var groupCount = 0;
  13765. var ix, iy;
  13766. var vector = new Vector3();
  13767. // generate vertices, normals and uvs
  13768. for ( iy = 0; iy < gridY1; iy ++ ) {
  13769. var y = iy * segmentHeight - heightHalf;
  13770. for ( ix = 0; ix < gridX1; ix ++ ) {
  13771. var x = ix * segmentWidth - widthHalf;
  13772. // set values to correct vector component
  13773. vector[ u ] = x * udir;
  13774. vector[ v ] = y * vdir;
  13775. vector[ w ] = depthHalf;
  13776. // now apply vector to vertex buffer
  13777. vertices.push( vector.x, vector.y, vector.z );
  13778. // set values to correct vector component
  13779. vector[ u ] = 0;
  13780. vector[ v ] = 0;
  13781. vector[ w ] = depth > 0 ? 1 : - 1;
  13782. // now apply vector to normal buffer
  13783. normals.push( vector.x, vector.y, vector.z );
  13784. // uvs
  13785. uvs.push( ix / gridX );
  13786. uvs.push( 1 - ( iy / gridY ) );
  13787. // counters
  13788. vertexCounter += 1;
  13789. }
  13790. }
  13791. // indices
  13792. // 1. you need three indices to draw a single face
  13793. // 2. a single segment consists of two faces
  13794. // 3. so we need to generate six (2*3) indices per segment
  13795. for ( iy = 0; iy < gridY; iy ++ ) {
  13796. for ( ix = 0; ix < gridX; ix ++ ) {
  13797. var a = numberOfVertices + ix + gridX1 * iy;
  13798. var b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  13799. var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  13800. var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  13801. // faces
  13802. indices.push( a, b, d );
  13803. indices.push( b, c, d );
  13804. // increase counter
  13805. groupCount += 6;
  13806. }
  13807. }
  13808. // add a group to the geometry. this will ensure multi material support
  13809. scope.addGroup( groupStart, groupCount, materialIndex );
  13810. // calculate new start value for groups
  13811. groupStart += groupCount;
  13812. // update total number of vertices
  13813. numberOfVertices += vertexCounter;
  13814. }
  13815. }
  13816. BoxBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  13817. BoxBufferGeometry.prototype.constructor = BoxBufferGeometry;
  13818. /**
  13819. * @author mrdoob / http://mrdoob.com/
  13820. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  13821. */
  13822. function PlaneGeometry( width, height, widthSegments, heightSegments ) {
  13823. Geometry.call( this );
  13824. this.type = 'PlaneGeometry';
  13825. this.parameters = {
  13826. width: width,
  13827. height: height,
  13828. widthSegments: widthSegments,
  13829. heightSegments: heightSegments
  13830. };
  13831. this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  13832. }
  13833. PlaneGeometry.prototype = Object.create( Geometry.prototype );
  13834. PlaneGeometry.prototype.constructor = PlaneGeometry;
  13835. /**
  13836. * @author mrdoob / http://mrdoob.com/
  13837. * @author Mugen87 / https://github.com/Mugen87
  13838. *
  13839. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  13840. */
  13841. function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) {
  13842. BufferGeometry.call( this );
  13843. this.type = 'PlaneBufferGeometry';
  13844. this.parameters = {
  13845. width: width,
  13846. height: height,
  13847. widthSegments: widthSegments,
  13848. heightSegments: heightSegments
  13849. };
  13850. var width_half = width / 2;
  13851. var height_half = height / 2;
  13852. var gridX = Math.floor( widthSegments ) || 1;
  13853. var gridY = Math.floor( heightSegments ) || 1;
  13854. var gridX1 = gridX + 1;
  13855. var gridY1 = gridY + 1;
  13856. var segment_width = width / gridX;
  13857. var segment_height = height / gridY;
  13858. var ix, iy;
  13859. // buffers
  13860. var indices = [];
  13861. var vertices = [];
  13862. var normals = [];
  13863. var uvs = [];
  13864. // generate vertices, normals and uvs
  13865. for ( iy = 0; iy < gridY1; iy ++ ) {
  13866. var y = iy * segment_height - height_half;
  13867. for ( ix = 0; ix < gridX1; ix ++ ) {
  13868. var x = ix * segment_width - width_half;
  13869. vertices.push( x, - y, 0 );
  13870. normals.push( 0, 0, 1 );
  13871. uvs.push( ix / gridX );
  13872. uvs.push( 1 - ( iy / gridY ) );
  13873. }
  13874. }
  13875. // indices
  13876. for ( iy = 0; iy < gridY; iy ++ ) {
  13877. for ( ix = 0; ix < gridX; ix ++ ) {
  13878. var a = ix + gridX1 * iy;
  13879. var b = ix + gridX1 * ( iy + 1 );
  13880. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  13881. var d = ( ix + 1 ) + gridX1 * iy;
  13882. // faces
  13883. indices.push( a, b, d );
  13884. indices.push( b, c, d );
  13885. }
  13886. }
  13887. // build geometry
  13888. this.setIndex( indices );
  13889. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13890. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13891. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13892. }
  13893. PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  13894. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  13895. /**
  13896. * @author mrdoob / http://mrdoob.com/
  13897. * @author mikael emtinger / http://gomo.se/
  13898. * @author WestLangley / http://github.com/WestLangley
  13899. */
  13900. function Camera() {
  13901. Object3D.call( this );
  13902. this.type = 'Camera';
  13903. this.matrixWorldInverse = new Matrix4();
  13904. this.projectionMatrix = new Matrix4();
  13905. }
  13906. Camera.prototype = Object.create( Object3D.prototype );
  13907. Camera.prototype.constructor = Camera;
  13908. Camera.prototype.isCamera = true;
  13909. Camera.prototype.getWorldDirection = function () {
  13910. var quaternion = new Quaternion();
  13911. return function getWorldDirection( optionalTarget ) {
  13912. var result = optionalTarget || new Vector3();
  13913. this.getWorldQuaternion( quaternion );
  13914. return result.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  13915. };
  13916. }();
  13917. Camera.prototype.lookAt = function () {
  13918. // This routine does not support cameras with rotated and/or translated parent(s)
  13919. var m1 = new Matrix4();
  13920. return function lookAt( vector ) {
  13921. m1.lookAt( this.position, vector, this.up );
  13922. this.quaternion.setFromRotationMatrix( m1 );
  13923. };
  13924. }();
  13925. Camera.prototype.clone = function () {
  13926. return new this.constructor().copy( this );
  13927. };
  13928. Camera.prototype.copy = function ( source ) {
  13929. Object3D.prototype.copy.call( this, source );
  13930. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  13931. this.projectionMatrix.copy( source.projectionMatrix );
  13932. return this;
  13933. };
  13934. /**
  13935. * @author mrdoob / http://mrdoob.com/
  13936. * @author greggman / http://games.greggman.com/
  13937. * @author zz85 / http://www.lab4games.net/zz85/blog
  13938. * @author tschw
  13939. */
  13940. function PerspectiveCamera( fov, aspect, near, far ) {
  13941. Camera.call( this );
  13942. this.type = 'PerspectiveCamera';
  13943. this.fov = fov !== undefined ? fov : 50;
  13944. this.zoom = 1;
  13945. this.near = near !== undefined ? near : 0.1;
  13946. this.far = far !== undefined ? far : 2000;
  13947. this.focus = 10;
  13948. this.aspect = aspect !== undefined ? aspect : 1;
  13949. this.view = null;
  13950. this.filmGauge = 35; // width of the film (default in millimeters)
  13951. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  13952. this.updateProjectionMatrix();
  13953. }
  13954. PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  13955. constructor: PerspectiveCamera,
  13956. isPerspectiveCamera: true,
  13957. copy: function ( source ) {
  13958. Camera.prototype.copy.call( this, source );
  13959. this.fov = source.fov;
  13960. this.zoom = source.zoom;
  13961. this.near = source.near;
  13962. this.far = source.far;
  13963. this.focus = source.focus;
  13964. this.aspect = source.aspect;
  13965. this.view = source.view === null ? null : Object.assign( {}, source.view );
  13966. this.filmGauge = source.filmGauge;
  13967. this.filmOffset = source.filmOffset;
  13968. return this;
  13969. },
  13970. /**
  13971. * Sets the FOV by focal length in respect to the current .filmGauge.
  13972. *
  13973. * The default film gauge is 35, so that the focal length can be specified for
  13974. * a 35mm (full frame) camera.
  13975. *
  13976. * Values for focal length and film gauge must have the same unit.
  13977. */
  13978. setFocalLength: function ( focalLength ) {
  13979. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  13980. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  13981. this.fov = _Math.RAD2DEG * 2 * Math.atan( vExtentSlope );
  13982. this.updateProjectionMatrix();
  13983. },
  13984. /**
  13985. * Calculates the focal length from the current .fov and .filmGauge.
  13986. */
  13987. getFocalLength: function () {
  13988. var vExtentSlope = Math.tan( _Math.DEG2RAD * 0.5 * this.fov );
  13989. return 0.5 * this.getFilmHeight() / vExtentSlope;
  13990. },
  13991. getEffectiveFOV: function () {
  13992. return _Math.RAD2DEG * 2 * Math.atan(
  13993. Math.tan( _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom );
  13994. },
  13995. getFilmWidth: function () {
  13996. // film not completely covered in portrait format (aspect < 1)
  13997. return this.filmGauge * Math.min( this.aspect, 1 );
  13998. },
  13999. getFilmHeight: function () {
  14000. // film not completely covered in landscape format (aspect > 1)
  14001. return this.filmGauge / Math.max( this.aspect, 1 );
  14002. },
  14003. /**
  14004. * Sets an offset in a larger frustum. This is useful for multi-window or
  14005. * multi-monitor/multi-machine setups.
  14006. *
  14007. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  14008. * the monitors are in grid like this
  14009. *
  14010. * +---+---+---+
  14011. * | A | B | C |
  14012. * +---+---+---+
  14013. * | D | E | F |
  14014. * +---+---+---+
  14015. *
  14016. * then for each monitor you would call it like this
  14017. *
  14018. * var w = 1920;
  14019. * var h = 1080;
  14020. * var fullWidth = w * 3;
  14021. * var fullHeight = h * 2;
  14022. *
  14023. * --A--
  14024. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  14025. * --B--
  14026. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  14027. * --C--
  14028. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  14029. * --D--
  14030. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  14031. * --E--
  14032. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  14033. * --F--
  14034. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  14035. *
  14036. * Note there is no reason monitors have to be the same size or in a grid.
  14037. */
  14038. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  14039. this.aspect = fullWidth / fullHeight;
  14040. this.view = {
  14041. fullWidth: fullWidth,
  14042. fullHeight: fullHeight,
  14043. offsetX: x,
  14044. offsetY: y,
  14045. width: width,
  14046. height: height
  14047. };
  14048. this.updateProjectionMatrix();
  14049. },
  14050. clearViewOffset: function() {
  14051. this.view = null;
  14052. this.updateProjectionMatrix();
  14053. },
  14054. updateProjectionMatrix: function () {
  14055. var near = this.near,
  14056. top = near * Math.tan(
  14057. _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom,
  14058. height = 2 * top,
  14059. width = this.aspect * height,
  14060. left = - 0.5 * width,
  14061. view = this.view;
  14062. if ( view !== null ) {
  14063. var fullWidth = view.fullWidth,
  14064. fullHeight = view.fullHeight;
  14065. left += view.offsetX * width / fullWidth;
  14066. top -= view.offsetY * height / fullHeight;
  14067. width *= view.width / fullWidth;
  14068. height *= view.height / fullHeight;
  14069. }
  14070. var skew = this.filmOffset;
  14071. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  14072. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  14073. },
  14074. toJSON: function ( meta ) {
  14075. var data = Object3D.prototype.toJSON.call( this, meta );
  14076. data.object.fov = this.fov;
  14077. data.object.zoom = this.zoom;
  14078. data.object.near = this.near;
  14079. data.object.far = this.far;
  14080. data.object.focus = this.focus;
  14081. data.object.aspect = this.aspect;
  14082. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  14083. data.object.filmGauge = this.filmGauge;
  14084. data.object.filmOffset = this.filmOffset;
  14085. return data;
  14086. }
  14087. } );
  14088. /**
  14089. * @author alteredq / http://alteredqualia.com/
  14090. * @author arose / http://github.com/arose
  14091. */
  14092. function OrthographicCamera( left, right, top, bottom, near, far ) {
  14093. Camera.call( this );
  14094. this.type = 'OrthographicCamera';
  14095. this.zoom = 1;
  14096. this.view = null;
  14097. this.left = left;
  14098. this.right = right;
  14099. this.top = top;
  14100. this.bottom = bottom;
  14101. this.near = ( near !== undefined ) ? near : 0.1;
  14102. this.far = ( far !== undefined ) ? far : 2000;
  14103. this.updateProjectionMatrix();
  14104. }
  14105. OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  14106. constructor: OrthographicCamera,
  14107. isOrthographicCamera: true,
  14108. copy: function ( source ) {
  14109. Camera.prototype.copy.call( this, source );
  14110. this.left = source.left;
  14111. this.right = source.right;
  14112. this.top = source.top;
  14113. this.bottom = source.bottom;
  14114. this.near = source.near;
  14115. this.far = source.far;
  14116. this.zoom = source.zoom;
  14117. this.view = source.view === null ? null : Object.assign( {}, source.view );
  14118. return this;
  14119. },
  14120. setViewOffset: function( fullWidth, fullHeight, x, y, width, height ) {
  14121. this.view = {
  14122. fullWidth: fullWidth,
  14123. fullHeight: fullHeight,
  14124. offsetX: x,
  14125. offsetY: y,
  14126. width: width,
  14127. height: height
  14128. };
  14129. this.updateProjectionMatrix();
  14130. },
  14131. clearViewOffset: function() {
  14132. this.view = null;
  14133. this.updateProjectionMatrix();
  14134. },
  14135. updateProjectionMatrix: function () {
  14136. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  14137. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  14138. var cx = ( this.right + this.left ) / 2;
  14139. var cy = ( this.top + this.bottom ) / 2;
  14140. var left = cx - dx;
  14141. var right = cx + dx;
  14142. var top = cy + dy;
  14143. var bottom = cy - dy;
  14144. if ( this.view !== null ) {
  14145. var zoomW = this.zoom / ( this.view.width / this.view.fullWidth );
  14146. var zoomH = this.zoom / ( this.view.height / this.view.fullHeight );
  14147. var scaleW = ( this.right - this.left ) / this.view.width;
  14148. var scaleH = ( this.top - this.bottom ) / this.view.height;
  14149. left += scaleW * ( this.view.offsetX / zoomW );
  14150. right = left + scaleW * ( this.view.width / zoomW );
  14151. top -= scaleH * ( this.view.offsetY / zoomH );
  14152. bottom = top - scaleH * ( this.view.height / zoomH );
  14153. }
  14154. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  14155. },
  14156. toJSON: function ( meta ) {
  14157. var data = Object3D.prototype.toJSON.call( this, meta );
  14158. data.object.zoom = this.zoom;
  14159. data.object.left = this.left;
  14160. data.object.right = this.right;
  14161. data.object.top = this.top;
  14162. data.object.bottom = this.bottom;
  14163. data.object.near = this.near;
  14164. data.object.far = this.far;
  14165. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  14166. return data;
  14167. }
  14168. } );
  14169. /**
  14170. * @author mrdoob / http://mrdoob.com/
  14171. */
  14172. function WebGLIndexedBufferRenderer( gl, extensions, infoRender ) {
  14173. var mode;
  14174. function setMode( value ) {
  14175. mode = value;
  14176. }
  14177. var type, size;
  14178. function setIndex( index ) {
  14179. if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) {
  14180. type = gl.UNSIGNED_INT;
  14181. size = 4;
  14182. } else if ( index.array instanceof Uint16Array ) {
  14183. type = gl.UNSIGNED_SHORT;
  14184. size = 2;
  14185. } else {
  14186. type = gl.UNSIGNED_BYTE;
  14187. size = 1;
  14188. }
  14189. }
  14190. function render( start, count ) {
  14191. gl.drawElements( mode, count, type, start * size );
  14192. infoRender.calls ++;
  14193. infoRender.vertices += count;
  14194. if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3;
  14195. }
  14196. function renderInstances( geometry, start, count ) {
  14197. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  14198. if ( extension === null ) {
  14199. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  14200. return;
  14201. }
  14202. extension.drawElementsInstancedANGLE( mode, count, type, start * size, geometry.maxInstancedCount );
  14203. infoRender.calls ++;
  14204. infoRender.vertices += count * geometry.maxInstancedCount;
  14205. if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3;
  14206. }
  14207. return {
  14208. setMode: setMode,
  14209. setIndex: setIndex,
  14210. render: render,
  14211. renderInstances: renderInstances
  14212. };
  14213. }
  14214. /**
  14215. * @author mrdoob / http://mrdoob.com/
  14216. */
  14217. function WebGLBufferRenderer( gl, extensions, infoRender ) {
  14218. var mode;
  14219. function setMode( value ) {
  14220. mode = value;
  14221. }
  14222. function render( start, count ) {
  14223. gl.drawArrays( mode, start, count );
  14224. infoRender.calls ++;
  14225. infoRender.vertices += count;
  14226. if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3;
  14227. }
  14228. function renderInstances( geometry ) {
  14229. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  14230. if ( extension === null ) {
  14231. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  14232. return;
  14233. }
  14234. var position = geometry.attributes.position;
  14235. var count = 0;
  14236. if ( position.isInterleavedBufferAttribute ) {
  14237. count = position.data.count;
  14238. extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
  14239. } else {
  14240. count = position.count;
  14241. extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
  14242. }
  14243. infoRender.calls ++;
  14244. infoRender.vertices += count * geometry.maxInstancedCount;
  14245. if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3;
  14246. }
  14247. return {
  14248. setMode: setMode,
  14249. render: render,
  14250. renderInstances: renderInstances
  14251. };
  14252. }
  14253. /**
  14254. * @author mrdoob / http://mrdoob.com/
  14255. */
  14256. function WebGLLights() {
  14257. var lights = {};
  14258. return {
  14259. get: function ( light ) {
  14260. if ( lights[ light.id ] !== undefined ) {
  14261. return lights[ light.id ];
  14262. }
  14263. var uniforms;
  14264. switch ( light.type ) {
  14265. case 'DirectionalLight':
  14266. uniforms = {
  14267. direction: new Vector3(),
  14268. color: new Color(),
  14269. shadow: false,
  14270. shadowBias: 0,
  14271. shadowRadius: 1,
  14272. shadowMapSize: new Vector2()
  14273. };
  14274. break;
  14275. case 'SpotLight':
  14276. uniforms = {
  14277. position: new Vector3(),
  14278. direction: new Vector3(),
  14279. color: new Color(),
  14280. distance: 0,
  14281. coneCos: 0,
  14282. penumbraCos: 0,
  14283. decay: 0,
  14284. shadow: false,
  14285. shadowBias: 0,
  14286. shadowRadius: 1,
  14287. shadowMapSize: new Vector2()
  14288. };
  14289. break;
  14290. case 'PointLight':
  14291. uniforms = {
  14292. position: new Vector3(),
  14293. color: new Color(),
  14294. distance: 0,
  14295. decay: 0,
  14296. shadow: false,
  14297. shadowBias: 0,
  14298. shadowRadius: 1,
  14299. shadowMapSize: new Vector2()
  14300. };
  14301. break;
  14302. case 'HemisphereLight':
  14303. uniforms = {
  14304. direction: new Vector3(),
  14305. skyColor: new Color(),
  14306. groundColor: new Color()
  14307. };
  14308. break;
  14309. case 'RectAreaLight':
  14310. uniforms = {
  14311. color: new Color(),
  14312. position: new Vector3(),
  14313. halfWidth: new Vector3(),
  14314. halfHeight: new Vector3()
  14315. // TODO (abelnation): set RectAreaLight shadow uniforms
  14316. };
  14317. break;
  14318. }
  14319. lights[ light.id ] = uniforms;
  14320. return uniforms;
  14321. }
  14322. };
  14323. }
  14324. /**
  14325. * @author mrdoob / http://mrdoob.com/
  14326. */
  14327. function addLineNumbers( string ) {
  14328. var lines = string.split( '\n' );
  14329. for ( var i = 0; i < lines.length; i ++ ) {
  14330. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  14331. }
  14332. return lines.join( '\n' );
  14333. }
  14334. function WebGLShader( gl, type, string ) {
  14335. var shader = gl.createShader( type );
  14336. gl.shaderSource( shader, string );
  14337. gl.compileShader( shader );
  14338. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  14339. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  14340. }
  14341. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  14342. console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) );
  14343. }
  14344. // --enable-privileged-webgl-extension
  14345. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  14346. return shader;
  14347. }
  14348. /**
  14349. * @author mrdoob / http://mrdoob.com/
  14350. */
  14351. var programIdCount = 0;
  14352. function getEncodingComponents( encoding ) {
  14353. switch ( encoding ) {
  14354. case LinearEncoding:
  14355. return [ 'Linear','( value )' ];
  14356. case sRGBEncoding:
  14357. return [ 'sRGB','( value )' ];
  14358. case RGBEEncoding:
  14359. return [ 'RGBE','( value )' ];
  14360. case RGBM7Encoding:
  14361. return [ 'RGBM','( value, 7.0 )' ];
  14362. case RGBM16Encoding:
  14363. return [ 'RGBM','( value, 16.0 )' ];
  14364. case RGBDEncoding:
  14365. return [ 'RGBD','( value, 256.0 )' ];
  14366. case GammaEncoding:
  14367. return [ 'Gamma','( value, float( GAMMA_FACTOR ) )' ];
  14368. default:
  14369. throw new Error( 'unsupported encoding: ' + encoding );
  14370. }
  14371. }
  14372. function getTexelDecodingFunction( functionName, encoding ) {
  14373. var components = getEncodingComponents( encoding );
  14374. return "vec4 " + functionName + "( vec4 value ) { return " + components[ 0 ] + "ToLinear" + components[ 1 ] + "; }";
  14375. }
  14376. function getTexelEncodingFunction( functionName, encoding ) {
  14377. var components = getEncodingComponents( encoding );
  14378. return "vec4 " + functionName + "( vec4 value ) { return LinearTo" + components[ 0 ] + components[ 1 ] + "; }";
  14379. }
  14380. function getToneMappingFunction( functionName, toneMapping ) {
  14381. var toneMappingName;
  14382. switch ( toneMapping ) {
  14383. case LinearToneMapping:
  14384. toneMappingName = "Linear";
  14385. break;
  14386. case ReinhardToneMapping:
  14387. toneMappingName = "Reinhard";
  14388. break;
  14389. case Uncharted2ToneMapping:
  14390. toneMappingName = "Uncharted2";
  14391. break;
  14392. case CineonToneMapping:
  14393. toneMappingName = "OptimizedCineon";
  14394. break;
  14395. default:
  14396. throw new Error( 'unsupported toneMapping: ' + toneMapping );
  14397. }
  14398. return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }";
  14399. }
  14400. function generateExtensions( extensions, parameters, rendererExtensions ) {
  14401. extensions = extensions || {};
  14402. var chunks = [
  14403. ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  14404. ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '',
  14405. ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '',
  14406. ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  14407. ];
  14408. return chunks.filter( filterEmptyLine ).join( '\n' );
  14409. }
  14410. function generateDefines( defines ) {
  14411. var chunks = [];
  14412. for ( var name in defines ) {
  14413. var value = defines[ name ];
  14414. if ( value === false ) continue;
  14415. chunks.push( '#define ' + name + ' ' + value );
  14416. }
  14417. return chunks.join( '\n' );
  14418. }
  14419. function fetchAttributeLocations( gl, program, identifiers ) {
  14420. var attributes = {};
  14421. var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  14422. for ( var i = 0; i < n; i ++ ) {
  14423. var info = gl.getActiveAttrib( program, i );
  14424. var name = info.name;
  14425. // console.log("THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:", name, i );
  14426. attributes[ name ] = gl.getAttribLocation( program, name );
  14427. }
  14428. return attributes;
  14429. }
  14430. function filterEmptyLine( string ) {
  14431. return string !== '';
  14432. }
  14433. function replaceLightNums( string, parameters ) {
  14434. return string
  14435. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  14436. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  14437. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  14438. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  14439. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights );
  14440. }
  14441. function parseIncludes( string ) {
  14442. var pattern = /#include +<([\w\d.]+)>/g;
  14443. function replace( match, include ) {
  14444. var replace = ShaderChunk[ include ];
  14445. if ( replace === undefined ) {
  14446. throw new Error( 'Can not resolve #include <' + include + '>' );
  14447. }
  14448. return parseIncludes( replace );
  14449. }
  14450. return string.replace( pattern, replace );
  14451. }
  14452. function unrollLoops( string ) {
  14453. var pattern = /for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  14454. function replace( match, start, end, snippet ) {
  14455. var unroll = '';
  14456. for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) {
  14457. unroll += snippet.replace( /\[ i \]/g, '[ ' + i + ' ]' );
  14458. }
  14459. return unroll;
  14460. }
  14461. return string.replace( pattern, replace );
  14462. }
  14463. function WebGLProgram( renderer, code, material, parameters ) {
  14464. var gl = renderer.context;
  14465. var extensions = material.extensions;
  14466. var defines = material.defines;
  14467. var vertexShader = material.__webglShader.vertexShader;
  14468. var fragmentShader = material.__webglShader.fragmentShader;
  14469. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  14470. if ( parameters.shadowMapType === PCFShadowMap ) {
  14471. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  14472. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  14473. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  14474. }
  14475. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  14476. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  14477. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  14478. if ( parameters.envMap ) {
  14479. switch ( material.envMap.mapping ) {
  14480. case CubeReflectionMapping:
  14481. case CubeRefractionMapping:
  14482. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  14483. break;
  14484. case CubeUVReflectionMapping:
  14485. case CubeUVRefractionMapping:
  14486. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  14487. break;
  14488. case EquirectangularReflectionMapping:
  14489. case EquirectangularRefractionMapping:
  14490. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  14491. break;
  14492. case SphericalReflectionMapping:
  14493. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  14494. break;
  14495. }
  14496. switch ( material.envMap.mapping ) {
  14497. case CubeRefractionMapping:
  14498. case EquirectangularRefractionMapping:
  14499. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  14500. break;
  14501. }
  14502. switch ( material.combine ) {
  14503. case MultiplyOperation:
  14504. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  14505. break;
  14506. case MixOperation:
  14507. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  14508. break;
  14509. case AddOperation:
  14510. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  14511. break;
  14512. }
  14513. }
  14514. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  14515. // console.log( 'building new program ' );
  14516. //
  14517. var customExtensions = generateExtensions( extensions, parameters, renderer.extensions );
  14518. var customDefines = generateDefines( defines );
  14519. //
  14520. var program = gl.createProgram();
  14521. var prefixVertex, prefixFragment;
  14522. if ( material.isRawShaderMaterial ) {
  14523. prefixVertex = [
  14524. customDefines,
  14525. '\n'
  14526. ].filter( filterEmptyLine ).join( '\n' );
  14527. prefixFragment = [
  14528. customExtensions,
  14529. customDefines,
  14530. '\n'
  14531. ].filter( filterEmptyLine ).join( '\n' );
  14532. } else {
  14533. prefixVertex = [
  14534. 'precision ' + parameters.precision + ' float;',
  14535. 'precision ' + parameters.precision + ' int;',
  14536. '#define SHADER_NAME ' + material.__webglShader.name,
  14537. customDefines,
  14538. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  14539. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  14540. '#define MAX_BONES ' + parameters.maxBones,
  14541. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  14542. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  14543. parameters.map ? '#define USE_MAP' : '',
  14544. parameters.envMap ? '#define USE_ENVMAP' : '',
  14545. parameters.envMap ? '#define ' + envMapModeDefine : '',
  14546. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  14547. parameters.aoMap ? '#define USE_AOMAP' : '',
  14548. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  14549. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  14550. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  14551. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  14552. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  14553. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  14554. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  14555. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  14556. parameters.vertexColors ? '#define USE_COLOR' : '',
  14557. parameters.flatShading ? '#define FLAT_SHADED' : '',
  14558. parameters.skinning ? '#define USE_SKINNING' : '',
  14559. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  14560. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  14561. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  14562. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  14563. parameters.flipSided ? '#define FLIP_SIDED' : '',
  14564. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  14565. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  14566. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  14567. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  14568. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  14569. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  14570. 'uniform mat4 modelMatrix;',
  14571. 'uniform mat4 modelViewMatrix;',
  14572. 'uniform mat4 projectionMatrix;',
  14573. 'uniform mat4 viewMatrix;',
  14574. 'uniform mat3 normalMatrix;',
  14575. 'uniform vec3 cameraPosition;',
  14576. 'attribute vec3 position;',
  14577. 'attribute vec3 normal;',
  14578. 'attribute vec2 uv;',
  14579. '#ifdef USE_COLOR',
  14580. ' attribute vec3 color;',
  14581. '#endif',
  14582. '#ifdef USE_MORPHTARGETS',
  14583. ' attribute vec3 morphTarget0;',
  14584. ' attribute vec3 morphTarget1;',
  14585. ' attribute vec3 morphTarget2;',
  14586. ' attribute vec3 morphTarget3;',
  14587. ' #ifdef USE_MORPHNORMALS',
  14588. ' attribute vec3 morphNormal0;',
  14589. ' attribute vec3 morphNormal1;',
  14590. ' attribute vec3 morphNormal2;',
  14591. ' attribute vec3 morphNormal3;',
  14592. ' #else',
  14593. ' attribute vec3 morphTarget4;',
  14594. ' attribute vec3 morphTarget5;',
  14595. ' attribute vec3 morphTarget6;',
  14596. ' attribute vec3 morphTarget7;',
  14597. ' #endif',
  14598. '#endif',
  14599. '#ifdef USE_SKINNING',
  14600. ' attribute vec4 skinIndex;',
  14601. ' attribute vec4 skinWeight;',
  14602. '#endif',
  14603. '\n'
  14604. ].filter( filterEmptyLine ).join( '\n' );
  14605. prefixFragment = [
  14606. customExtensions,
  14607. 'precision ' + parameters.precision + ' float;',
  14608. 'precision ' + parameters.precision + ' int;',
  14609. '#define SHADER_NAME ' + material.__webglShader.name,
  14610. customDefines,
  14611. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '',
  14612. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  14613. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  14614. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  14615. parameters.map ? '#define USE_MAP' : '',
  14616. parameters.envMap ? '#define USE_ENVMAP' : '',
  14617. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  14618. parameters.envMap ? '#define ' + envMapModeDefine : '',
  14619. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  14620. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  14621. parameters.aoMap ? '#define USE_AOMAP' : '',
  14622. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  14623. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  14624. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  14625. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  14626. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  14627. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  14628. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  14629. parameters.vertexColors ? '#define USE_COLOR' : '',
  14630. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  14631. parameters.flatShading ? '#define FLAT_SHADED' : '',
  14632. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  14633. parameters.flipSided ? '#define FLIP_SIDED' : '',
  14634. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  14635. '#define UNION_CLIPPING_PLANES ' + (parameters.numClippingPlanes - parameters.numClipIntersection),
  14636. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  14637. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  14638. parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : '',
  14639. parameters.physicallyCorrectLights ? "#define PHYSICALLY_CORRECT_LIGHTS" : '',
  14640. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  14641. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  14642. parameters.envMap && renderer.extensions.get( 'EXT_shader_texture_lod' ) ? '#define TEXTURE_LOD_EXT' : '',
  14643. 'uniform mat4 viewMatrix;',
  14644. 'uniform vec3 cameraPosition;',
  14645. ( parameters.toneMapping !== NoToneMapping ) ? "#define TONE_MAPPING" : '',
  14646. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  14647. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( "toneMapping", parameters.toneMapping ) : '',
  14648. ( 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
  14649. parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  14650. parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  14651. parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  14652. parameters.outputEncoding ? getTexelEncodingFunction( "linearToOutputTexel", parameters.outputEncoding ) : '',
  14653. parameters.depthPacking ? "#define DEPTH_PACKING " + material.depthPacking : '',
  14654. '\n'
  14655. ].filter( filterEmptyLine ).join( '\n' );
  14656. }
  14657. vertexShader = parseIncludes( vertexShader, parameters );
  14658. vertexShader = replaceLightNums( vertexShader, parameters );
  14659. fragmentShader = parseIncludes( fragmentShader, parameters );
  14660. fragmentShader = replaceLightNums( fragmentShader, parameters );
  14661. if ( ! material.isShaderMaterial ) {
  14662. vertexShader = unrollLoops( vertexShader );
  14663. fragmentShader = unrollLoops( fragmentShader );
  14664. }
  14665. var vertexGlsl = prefixVertex + vertexShader;
  14666. var fragmentGlsl = prefixFragment + fragmentShader;
  14667. // console.log( '*VERTEX*', vertexGlsl );
  14668. // console.log( '*FRAGMENT*', fragmentGlsl );
  14669. var glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  14670. var glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  14671. gl.attachShader( program, glVertexShader );
  14672. gl.attachShader( program, glFragmentShader );
  14673. // Force a particular attribute to index 0.
  14674. if ( material.index0AttributeName !== undefined ) {
  14675. gl.bindAttribLocation( program, 0, material.index0AttributeName );
  14676. } else if ( parameters.morphTargets === true ) {
  14677. // programs with morphTargets displace position out of attribute 0
  14678. gl.bindAttribLocation( program, 0, 'position' );
  14679. }
  14680. gl.linkProgram( program );
  14681. var programLog = gl.getProgramInfoLog( program );
  14682. var vertexLog = gl.getShaderInfoLog( glVertexShader );
  14683. var fragmentLog = gl.getShaderInfoLog( glFragmentShader );
  14684. var runnable = true;
  14685. var haveDiagnostics = true;
  14686. // console.log( '**VERTEX**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) );
  14687. // console.log( '**FRAGMENT**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) );
  14688. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  14689. runnable = false;
  14690. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog );
  14691. } else if ( programLog !== '' ) {
  14692. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  14693. } else if ( vertexLog === '' || fragmentLog === '' ) {
  14694. haveDiagnostics = false;
  14695. }
  14696. if ( haveDiagnostics ) {
  14697. this.diagnostics = {
  14698. runnable: runnable,
  14699. material: material,
  14700. programLog: programLog,
  14701. vertexShader: {
  14702. log: vertexLog,
  14703. prefix: prefixVertex
  14704. },
  14705. fragmentShader: {
  14706. log: fragmentLog,
  14707. prefix: prefixFragment
  14708. }
  14709. };
  14710. }
  14711. // clean up
  14712. gl.deleteShader( glVertexShader );
  14713. gl.deleteShader( glFragmentShader );
  14714. // set up caching for uniform locations
  14715. var cachedUniforms;
  14716. this.getUniforms = function() {
  14717. if ( cachedUniforms === undefined ) {
  14718. cachedUniforms =
  14719. new WebGLUniforms( gl, program, renderer );
  14720. }
  14721. return cachedUniforms;
  14722. };
  14723. // set up caching for attribute locations
  14724. var cachedAttributes;
  14725. this.getAttributes = function() {
  14726. if ( cachedAttributes === undefined ) {
  14727. cachedAttributes = fetchAttributeLocations( gl, program );
  14728. }
  14729. return cachedAttributes;
  14730. };
  14731. // free resource
  14732. this.destroy = function() {
  14733. gl.deleteProgram( program );
  14734. this.program = undefined;
  14735. };
  14736. // DEPRECATED
  14737. Object.defineProperties( this, {
  14738. uniforms: {
  14739. get: function() {
  14740. console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' );
  14741. return this.getUniforms();
  14742. }
  14743. },
  14744. attributes: {
  14745. get: function() {
  14746. console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' );
  14747. return this.getAttributes();
  14748. }
  14749. }
  14750. } );
  14751. //
  14752. this.id = programIdCount ++;
  14753. this.code = code;
  14754. this.usedTimes = 1;
  14755. this.program = program;
  14756. this.vertexShader = glVertexShader;
  14757. this.fragmentShader = glFragmentShader;
  14758. return this;
  14759. }
  14760. /**
  14761. * @author mrdoob / http://mrdoob.com/
  14762. */
  14763. function WebGLPrograms( renderer, capabilities ) {
  14764. var programs = [];
  14765. var shaderIDs = {
  14766. MeshDepthMaterial: 'depth',
  14767. MeshNormalMaterial: 'normal',
  14768. MeshBasicMaterial: 'basic',
  14769. MeshLambertMaterial: 'lambert',
  14770. MeshPhongMaterial: 'phong',
  14771. MeshToonMaterial: 'phong',
  14772. MeshStandardMaterial: 'physical',
  14773. MeshPhysicalMaterial: 'physical',
  14774. LineBasicMaterial: 'basic',
  14775. LineDashedMaterial: 'dashed',
  14776. PointsMaterial: 'points'
  14777. };
  14778. var parameterNames = [
  14779. "precision", "supportsVertexTextures", "map", "mapEncoding", "envMap", "envMapMode", "envMapEncoding",
  14780. "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "displacementMap", "specularMap",
  14781. "roughnessMap", "metalnessMap", "gradientMap",
  14782. "alphaMap", "combine", "vertexColors", "fog", "useFog", "fogExp",
  14783. "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
  14784. "maxBones", "useVertexTexture", "morphTargets", "morphNormals",
  14785. "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha",
  14786. "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights",
  14787. "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights',
  14788. "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking"
  14789. ];
  14790. function allocateBones( object ) {
  14791. if ( capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture ) {
  14792. return 1024;
  14793. } else {
  14794. // default for when object is not specified
  14795. // ( for example when prebuilding shader to be used with multiple objects )
  14796. //
  14797. // - leave some extra space for other uniforms
  14798. // - limit here is ANGLE's 254 max uniform vectors
  14799. // (up to 54 should be safe)
  14800. var nVertexUniforms = capabilities.maxVertexUniforms;
  14801. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  14802. var maxBones = nVertexMatrices;
  14803. if ( object !== undefined && (object && object.isSkinnedMesh) ) {
  14804. maxBones = Math.min( object.skeleton.bones.length, maxBones );
  14805. if ( maxBones < object.skeleton.bones.length ) {
  14806. console.warn( 'WebGLRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' );
  14807. }
  14808. }
  14809. return maxBones;
  14810. }
  14811. }
  14812. function getTextureEncodingFromMap( map, gammaOverrideLinear ) {
  14813. var encoding;
  14814. if ( ! map ) {
  14815. encoding = LinearEncoding;
  14816. } else if ( map.isTexture ) {
  14817. encoding = map.encoding;
  14818. } else if ( map.isWebGLRenderTarget ) {
  14819. console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." );
  14820. encoding = map.texture.encoding;
  14821. }
  14822. // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  14823. if ( encoding === LinearEncoding && gammaOverrideLinear ) {
  14824. encoding = GammaEncoding;
  14825. }
  14826. return encoding;
  14827. }
  14828. this.getParameters = function ( material, lights, fog, nClipPlanes, nClipIntersection, object ) {
  14829. var shaderID = shaderIDs[ material.type ];
  14830. // heuristics to create shader parameters according to lights in the scene
  14831. // (not to blow over maxLights budget)
  14832. var maxBones = allocateBones( object );
  14833. var precision = renderer.getPrecision();
  14834. if ( material.precision !== null ) {
  14835. precision = capabilities.getMaxPrecision( material.precision );
  14836. if ( precision !== material.precision ) {
  14837. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  14838. }
  14839. }
  14840. var currentRenderTarget = renderer.getCurrentRenderTarget();
  14841. var parameters = {
  14842. shaderID: shaderID,
  14843. precision: precision,
  14844. supportsVertexTextures: capabilities.vertexTextures,
  14845. outputEncoding: getTextureEncodingFromMap( ( ! currentRenderTarget ) ? null : currentRenderTarget.texture, renderer.gammaOutput ),
  14846. map: !! material.map,
  14847. mapEncoding: getTextureEncodingFromMap( material.map, renderer.gammaInput ),
  14848. envMap: !! material.envMap,
  14849. envMapMode: material.envMap && material.envMap.mapping,
  14850. envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ),
  14851. envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === CubeUVReflectionMapping ) || ( material.envMap.mapping === CubeUVRefractionMapping ) ),
  14852. lightMap: !! material.lightMap,
  14853. aoMap: !! material.aoMap,
  14854. emissiveMap: !! material.emissiveMap,
  14855. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap, renderer.gammaInput ),
  14856. bumpMap: !! material.bumpMap,
  14857. normalMap: !! material.normalMap,
  14858. displacementMap: !! material.displacementMap,
  14859. roughnessMap: !! material.roughnessMap,
  14860. metalnessMap: !! material.metalnessMap,
  14861. specularMap: !! material.specularMap,
  14862. alphaMap: !! material.alphaMap,
  14863. gradientMap: !! material.gradientMap,
  14864. combine: material.combine,
  14865. vertexColors: material.vertexColors,
  14866. fog: !! fog,
  14867. useFog: material.fog,
  14868. fogExp: (fog && fog.isFogExp2),
  14869. flatShading: material.shading === FlatShading,
  14870. sizeAttenuation: material.sizeAttenuation,
  14871. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  14872. skinning: material.skinning,
  14873. maxBones: maxBones,
  14874. useVertexTexture: capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture,
  14875. morphTargets: material.morphTargets,
  14876. morphNormals: material.morphNormals,
  14877. maxMorphTargets: renderer.maxMorphTargets,
  14878. maxMorphNormals: renderer.maxMorphNormals,
  14879. numDirLights: lights.directional.length,
  14880. numPointLights: lights.point.length,
  14881. numSpotLights: lights.spot.length,
  14882. numRectAreaLights: lights.rectArea.length,
  14883. numHemiLights: lights.hemi.length,
  14884. numClippingPlanes: nClipPlanes,
  14885. numClipIntersection: nClipIntersection,
  14886. shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && lights.shadows.length > 0,
  14887. shadowMapType: renderer.shadowMap.type,
  14888. toneMapping: renderer.toneMapping,
  14889. physicallyCorrectLights: renderer.physicallyCorrectLights,
  14890. premultipliedAlpha: material.premultipliedAlpha,
  14891. alphaTest: material.alphaTest,
  14892. doubleSided: material.side === DoubleSide,
  14893. flipSided: material.side === BackSide,
  14894. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false
  14895. };
  14896. return parameters;
  14897. };
  14898. this.getProgramCode = function ( material, parameters ) {
  14899. var array = [];
  14900. if ( parameters.shaderID ) {
  14901. array.push( parameters.shaderID );
  14902. } else {
  14903. array.push( material.fragmentShader );
  14904. array.push( material.vertexShader );
  14905. }
  14906. if ( material.defines !== undefined ) {
  14907. for ( var name in material.defines ) {
  14908. array.push( name );
  14909. array.push( material.defines[ name ] );
  14910. }
  14911. }
  14912. for ( var i = 0; i < parameterNames.length; i ++ ) {
  14913. array.push( parameters[ parameterNames[ i ] ] );
  14914. }
  14915. return array.join();
  14916. };
  14917. this.acquireProgram = function ( material, parameters, code ) {
  14918. var program;
  14919. // Check if code has been already compiled
  14920. for ( var p = 0, pl = programs.length; p < pl; p ++ ) {
  14921. var programInfo = programs[ p ];
  14922. if ( programInfo.code === code ) {
  14923. program = programInfo;
  14924. ++ program.usedTimes;
  14925. break;
  14926. }
  14927. }
  14928. if ( program === undefined ) {
  14929. program = new WebGLProgram( renderer, code, material, parameters );
  14930. programs.push( program );
  14931. }
  14932. return program;
  14933. };
  14934. this.releaseProgram = function( program ) {
  14935. if ( -- program.usedTimes === 0 ) {
  14936. // Remove from unordered set
  14937. var i = programs.indexOf( program );
  14938. programs[ i ] = programs[ programs.length - 1 ];
  14939. programs.pop();
  14940. // Free WebGL resources
  14941. program.destroy();
  14942. }
  14943. };
  14944. // Exposed for resource monitoring & error feedback via renderer.info:
  14945. this.programs = programs;
  14946. }
  14947. /**
  14948. * @author mrdoob / http://mrdoob.com/
  14949. */
  14950. function WebGLGeometries( gl, properties, info ) {
  14951. var geometries = {};
  14952. function onGeometryDispose( event ) {
  14953. var geometry = event.target;
  14954. var buffergeometry = geometries[ geometry.id ];
  14955. if ( buffergeometry.index !== null ) {
  14956. deleteAttribute( buffergeometry.index );
  14957. }
  14958. deleteAttributes( buffergeometry.attributes );
  14959. geometry.removeEventListener( 'dispose', onGeometryDispose );
  14960. delete geometries[ geometry.id ];
  14961. // TODO
  14962. var property = properties.get( geometry );
  14963. if ( property.wireframe ) {
  14964. deleteAttribute( property.wireframe );
  14965. }
  14966. properties.delete( geometry );
  14967. var bufferproperty = properties.get( buffergeometry );
  14968. if ( bufferproperty.wireframe ) {
  14969. deleteAttribute( bufferproperty.wireframe );
  14970. }
  14971. properties.delete( buffergeometry );
  14972. //
  14973. info.memory.geometries --;
  14974. }
  14975. function getAttributeBuffer( attribute ) {
  14976. if ( attribute.isInterleavedBufferAttribute ) {
  14977. return properties.get( attribute.data ).__webglBuffer;
  14978. }
  14979. return properties.get( attribute ).__webglBuffer;
  14980. }
  14981. function deleteAttribute( attribute ) {
  14982. var buffer = getAttributeBuffer( attribute );
  14983. if ( buffer !== undefined ) {
  14984. gl.deleteBuffer( buffer );
  14985. removeAttributeBuffer( attribute );
  14986. }
  14987. }
  14988. function deleteAttributes( attributes ) {
  14989. for ( var name in attributes ) {
  14990. deleteAttribute( attributes[ name ] );
  14991. }
  14992. }
  14993. function removeAttributeBuffer( attribute ) {
  14994. if ( attribute.isInterleavedBufferAttribute ) {
  14995. properties.delete( attribute.data );
  14996. } else {
  14997. properties.delete( attribute );
  14998. }
  14999. }
  15000. return {
  15001. get: function ( object ) {
  15002. var geometry = object.geometry;
  15003. if ( geometries[ geometry.id ] !== undefined ) {
  15004. return geometries[ geometry.id ];
  15005. }
  15006. geometry.addEventListener( 'dispose', onGeometryDispose );
  15007. var buffergeometry;
  15008. if ( geometry.isBufferGeometry ) {
  15009. buffergeometry = geometry;
  15010. } else if ( geometry.isGeometry ) {
  15011. if ( geometry._bufferGeometry === undefined ) {
  15012. geometry._bufferGeometry = new BufferGeometry().setFromObject( object );
  15013. }
  15014. buffergeometry = geometry._bufferGeometry;
  15015. }
  15016. geometries[ geometry.id ] = buffergeometry;
  15017. info.memory.geometries ++;
  15018. return buffergeometry;
  15019. }
  15020. };
  15021. }
  15022. /**
  15023. * @author mrdoob / http://mrdoob.com/
  15024. */
  15025. function WebGLObjects( gl, properties, info ) {
  15026. var geometries = new WebGLGeometries( gl, properties, info );
  15027. //
  15028. function update( object ) {
  15029. // TODO: Avoid updating twice (when using shadowMap). Maybe add frame counter.
  15030. var geometry = geometries.get( object );
  15031. if ( object.geometry.isGeometry ) {
  15032. geometry.updateFromObject( object );
  15033. }
  15034. var index = geometry.index;
  15035. var attributes = geometry.attributes;
  15036. if ( index !== null ) {
  15037. updateAttribute( index, gl.ELEMENT_ARRAY_BUFFER );
  15038. }
  15039. for ( var name in attributes ) {
  15040. updateAttribute( attributes[ name ], gl.ARRAY_BUFFER );
  15041. }
  15042. // morph targets
  15043. var morphAttributes = geometry.morphAttributes;
  15044. for ( var name in morphAttributes ) {
  15045. var array = morphAttributes[ name ];
  15046. for ( var i = 0, l = array.length; i < l; i ++ ) {
  15047. updateAttribute( array[ i ], gl.ARRAY_BUFFER );
  15048. }
  15049. }
  15050. return geometry;
  15051. }
  15052. function updateAttribute( attribute, bufferType ) {
  15053. var data = ( attribute.isInterleavedBufferAttribute ) ? attribute.data : attribute;
  15054. var attributeProperties = properties.get( data );
  15055. if ( attributeProperties.__webglBuffer === undefined ) {
  15056. createBuffer( attributeProperties, data, bufferType );
  15057. } else if ( attributeProperties.version !== data.version ) {
  15058. updateBuffer( attributeProperties, data, bufferType );
  15059. }
  15060. }
  15061. function createBuffer( attributeProperties, data, bufferType ) {
  15062. attributeProperties.__webglBuffer = gl.createBuffer();
  15063. gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
  15064. var usage = data.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;
  15065. gl.bufferData( bufferType, data.array, usage );
  15066. var type = gl.FLOAT;
  15067. var array = data.array;
  15068. if ( array instanceof Float32Array ) {
  15069. type = gl.FLOAT;
  15070. } else if ( array instanceof Float64Array ) {
  15071. console.warn( "Unsupported data buffer format: Float64Array" );
  15072. } else if ( array instanceof Uint16Array ) {
  15073. type = gl.UNSIGNED_SHORT;
  15074. } else if ( array instanceof Int16Array ) {
  15075. type = gl.SHORT;
  15076. } else if ( array instanceof Uint32Array ) {
  15077. type = gl.UNSIGNED_INT;
  15078. } else if ( array instanceof Int32Array ) {
  15079. type = gl.INT;
  15080. } else if ( array instanceof Int8Array ) {
  15081. type = gl.BYTE;
  15082. } else if ( array instanceof Uint8Array ) {
  15083. type = gl.UNSIGNED_BYTE;
  15084. }
  15085. attributeProperties.bytesPerElement = array.BYTES_PER_ELEMENT;
  15086. attributeProperties.type = type;
  15087. attributeProperties.version = data.version;
  15088. data.onUploadCallback();
  15089. }
  15090. function updateBuffer( attributeProperties, data, bufferType ) {
  15091. gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
  15092. if ( data.dynamic === false ) {
  15093. gl.bufferData( bufferType, data.array, gl.STATIC_DRAW );
  15094. } else if ( data.updateRange.count === - 1 ) {
  15095. // Not using update ranges
  15096. gl.bufferSubData( bufferType, 0, data.array );
  15097. } else if ( data.updateRange.count === 0 ) {
  15098. 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.' );
  15099. } else {
  15100. gl.bufferSubData( bufferType, data.updateRange.offset * data.array.BYTES_PER_ELEMENT,
  15101. data.array.subarray( data.updateRange.offset, data.updateRange.offset + data.updateRange.count ) );
  15102. data.updateRange.count = 0; // reset range
  15103. }
  15104. attributeProperties.version = data.version;
  15105. }
  15106. function getAttributeBuffer( attribute ) {
  15107. if ( attribute.isInterleavedBufferAttribute ) {
  15108. return properties.get( attribute.data ).__webglBuffer;
  15109. }
  15110. return properties.get( attribute ).__webglBuffer;
  15111. }
  15112. function getAttributeProperties( attribute ) {
  15113. if ( attribute.isInterleavedBufferAttribute ) {
  15114. return properties.get( attribute.data );
  15115. }
  15116. return properties.get( attribute );
  15117. }
  15118. function getWireframeAttribute( geometry ) {
  15119. var property = properties.get( geometry );
  15120. if ( property.wireframe !== undefined ) {
  15121. return property.wireframe;
  15122. }
  15123. var indices = [];
  15124. var index = geometry.index;
  15125. var attributes = geometry.attributes;
  15126. // console.time( 'wireframe' );
  15127. if ( index !== null ) {
  15128. var array = index.array;
  15129. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  15130. var a = array[ i + 0 ];
  15131. var b = array[ i + 1 ];
  15132. var c = array[ i + 2 ];
  15133. indices.push( a, b, b, c, c, a );
  15134. }
  15135. } else {
  15136. var array = attributes.position.array;
  15137. for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  15138. var a = i + 0;
  15139. var b = i + 1;
  15140. var c = i + 2;
  15141. indices.push( a, b, b, c, c, a );
  15142. }
  15143. }
  15144. // console.timeEnd( 'wireframe' );
  15145. var attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  15146. updateAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  15147. property.wireframe = attribute;
  15148. return attribute;
  15149. }
  15150. return {
  15151. getAttributeBuffer: getAttributeBuffer,
  15152. getAttributeProperties: getAttributeProperties,
  15153. getWireframeAttribute: getWireframeAttribute,
  15154. update: update
  15155. };
  15156. }
  15157. /**
  15158. * @author mrdoob / http://mrdoob.com/
  15159. */
  15160. function WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, info ) {
  15161. var _infoMemory = info.memory;
  15162. var _isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof WebGL2RenderingContext );
  15163. //
  15164. function clampToMaxSize( image, maxSize ) {
  15165. if ( image.width > maxSize || image.height > maxSize ) {
  15166. // Warning: Scaling through the canvas will only work with images that use
  15167. // premultiplied alpha.
  15168. var scale = maxSize / Math.max( image.width, image.height );
  15169. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  15170. canvas.width = Math.floor( image.width * scale );
  15171. canvas.height = Math.floor( image.height * scale );
  15172. var context = canvas.getContext( '2d' );
  15173. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  15174. console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  15175. return canvas;
  15176. }
  15177. return image;
  15178. }
  15179. function isPowerOfTwo( image ) {
  15180. return _Math.isPowerOfTwo( image.width ) && _Math.isPowerOfTwo( image.height );
  15181. }
  15182. function makePowerOfTwo( image ) {
  15183. if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) {
  15184. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  15185. canvas.width = _Math.nearestPowerOfTwo( image.width );
  15186. canvas.height = _Math.nearestPowerOfTwo( image.height );
  15187. var context = canvas.getContext( '2d' );
  15188. context.drawImage( image, 0, 0, canvas.width, canvas.height );
  15189. console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  15190. return canvas;
  15191. }
  15192. return image;
  15193. }
  15194. function textureNeedsPowerOfTwo( texture ) {
  15195. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  15196. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  15197. }
  15198. // Fallback filters for non-power-of-2 textures
  15199. function filterFallback( f ) {
  15200. if ( f === NearestFilter || f === NearestMipMapNearestFilter || f === NearestMipMapLinearFilter ) {
  15201. return _gl.NEAREST;
  15202. }
  15203. return _gl.LINEAR;
  15204. }
  15205. //
  15206. function onTextureDispose( event ) {
  15207. var texture = event.target;
  15208. texture.removeEventListener( 'dispose', onTextureDispose );
  15209. deallocateTexture( texture );
  15210. _infoMemory.textures --;
  15211. }
  15212. function onRenderTargetDispose( event ) {
  15213. var renderTarget = event.target;
  15214. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  15215. deallocateRenderTarget( renderTarget );
  15216. _infoMemory.textures --;
  15217. }
  15218. //
  15219. function deallocateTexture( texture ) {
  15220. var textureProperties = properties.get( texture );
  15221. if ( texture.image && textureProperties.__image__webglTextureCube ) {
  15222. // cube texture
  15223. _gl.deleteTexture( textureProperties.__image__webglTextureCube );
  15224. } else {
  15225. // 2D texture
  15226. if ( textureProperties.__webglInit === undefined ) return;
  15227. _gl.deleteTexture( textureProperties.__webglTexture );
  15228. }
  15229. // remove all webgl properties
  15230. properties.delete( texture );
  15231. }
  15232. function deallocateRenderTarget( renderTarget ) {
  15233. var renderTargetProperties = properties.get( renderTarget );
  15234. var textureProperties = properties.get( renderTarget.texture );
  15235. if ( ! renderTarget ) return;
  15236. if ( textureProperties.__webglTexture !== undefined ) {
  15237. _gl.deleteTexture( textureProperties.__webglTexture );
  15238. }
  15239. if ( renderTarget.depthTexture ) {
  15240. renderTarget.depthTexture.dispose();
  15241. }
  15242. if ( renderTarget.isWebGLRenderTargetCube ) {
  15243. for ( var i = 0; i < 6; i ++ ) {
  15244. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  15245. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  15246. }
  15247. } else {
  15248. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  15249. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  15250. }
  15251. properties.delete( renderTarget.texture );
  15252. properties.delete( renderTarget );
  15253. }
  15254. //
  15255. function setTexture2D( texture, slot ) {
  15256. var textureProperties = properties.get( texture );
  15257. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  15258. var image = texture.image;
  15259. if ( image === undefined ) {
  15260. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture );
  15261. } else if ( image.complete === false ) {
  15262. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
  15263. } else {
  15264. uploadTexture( textureProperties, texture, slot );
  15265. return;
  15266. }
  15267. }
  15268. state.activeTexture( _gl.TEXTURE0 + slot );
  15269. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  15270. }
  15271. function setTextureCube( texture, slot ) {
  15272. var textureProperties = properties.get( texture );
  15273. if ( texture.image.length === 6 ) {
  15274. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  15275. if ( ! textureProperties.__image__webglTextureCube ) {
  15276. texture.addEventListener( 'dispose', onTextureDispose );
  15277. textureProperties.__image__webglTextureCube = _gl.createTexture();
  15278. _infoMemory.textures ++;
  15279. }
  15280. state.activeTexture( _gl.TEXTURE0 + slot );
  15281. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  15282. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15283. var isCompressed = ( texture && texture.isCompressedTexture );
  15284. var isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  15285. var cubeImage = [];
  15286. for ( var i = 0; i < 6; i ++ ) {
  15287. if ( ! isCompressed && ! isDataTexture ) {
  15288. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize );
  15289. } else {
  15290. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  15291. }
  15292. }
  15293. var image = cubeImage[ 0 ],
  15294. isPowerOfTwoImage = isPowerOfTwo( image ),
  15295. glFormat = paramThreeToGL( texture.format ),
  15296. glType = paramThreeToGL( texture.type );
  15297. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage );
  15298. for ( var i = 0; i < 6; i ++ ) {
  15299. if ( ! isCompressed ) {
  15300. if ( isDataTexture ) {
  15301. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  15302. } else {
  15303. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  15304. }
  15305. } else {
  15306. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  15307. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  15308. mipmap = mipmaps[ j ];
  15309. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  15310. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  15311. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15312. } else {
  15313. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()" );
  15314. }
  15315. } else {
  15316. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15317. }
  15318. }
  15319. }
  15320. }
  15321. if ( texture.generateMipmaps && isPowerOfTwoImage ) {
  15322. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15323. }
  15324. textureProperties.__version = texture.version;
  15325. if ( texture.onUpdate ) texture.onUpdate( texture );
  15326. } else {
  15327. state.activeTexture( _gl.TEXTURE0 + slot );
  15328. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  15329. }
  15330. }
  15331. }
  15332. function setTextureCubeDynamic( texture, slot ) {
  15333. state.activeTexture( _gl.TEXTURE0 + slot );
  15334. state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture );
  15335. }
  15336. function setTextureParameters( textureType, texture, isPowerOfTwoImage ) {
  15337. var extension;
  15338. if ( isPowerOfTwoImage ) {
  15339. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  15340. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  15341. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  15342. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  15343. } else {
  15344. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  15345. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  15346. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  15347. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture );
  15348. }
  15349. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  15350. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  15351. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  15352. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture );
  15353. }
  15354. }
  15355. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  15356. if ( extension ) {
  15357. if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  15358. if ( texture.type === HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return;
  15359. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  15360. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  15361. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  15362. }
  15363. }
  15364. }
  15365. function uploadTexture( textureProperties, texture, slot ) {
  15366. if ( textureProperties.__webglInit === undefined ) {
  15367. textureProperties.__webglInit = true;
  15368. texture.addEventListener( 'dispose', onTextureDispose );
  15369. textureProperties.__webglTexture = _gl.createTexture();
  15370. _infoMemory.textures ++;
  15371. }
  15372. state.activeTexture( _gl.TEXTURE0 + slot );
  15373. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  15374. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15375. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  15376. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  15377. var image = clampToMaxSize( texture.image, capabilities.maxTextureSize );
  15378. if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) {
  15379. image = makePowerOfTwo( image );
  15380. }
  15381. var isPowerOfTwoImage = isPowerOfTwo( image ),
  15382. glFormat = paramThreeToGL( texture.format ),
  15383. glType = paramThreeToGL( texture.type );
  15384. setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage );
  15385. var mipmap, mipmaps = texture.mipmaps;
  15386. if ( texture.isDepthTexture ) {
  15387. // populate depth texture with dummy data
  15388. var internalFormat = _gl.DEPTH_COMPONENT;
  15389. if ( texture.type === FloatType ) {
  15390. if ( !_isWebGL2 ) throw new Error('Float Depth Texture only supported in WebGL2.0');
  15391. internalFormat = _gl.DEPTH_COMPONENT32F;
  15392. } else if ( _isWebGL2 ) {
  15393. // WebGL 2.0 requires signed internalformat for glTexImage2D
  15394. internalFormat = _gl.DEPTH_COMPONENT16;
  15395. }
  15396. if ( texture.format === DepthFormat && internalFormat === _gl.DEPTH_COMPONENT ) {
  15397. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  15398. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  15399. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  15400. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  15401. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  15402. texture.type = UnsignedShortType;
  15403. glType = paramThreeToGL( texture.type );
  15404. }
  15405. }
  15406. // Depth stencil textures need the DEPTH_STENCIL internal format
  15407. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  15408. if ( texture.format === DepthStencilFormat ) {
  15409. internalFormat = _gl.DEPTH_STENCIL;
  15410. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  15411. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  15412. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  15413. if ( texture.type !== UnsignedInt248Type ) {
  15414. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  15415. texture.type = UnsignedInt248Type;
  15416. glType = paramThreeToGL( texture.type );
  15417. }
  15418. }
  15419. state.texImage2D( _gl.TEXTURE_2D, 0, internalFormat, image.width, image.height, 0, glFormat, glType, null );
  15420. } else if ( texture.isDataTexture ) {
  15421. // use manually created mipmaps if available
  15422. // if there are no manual mipmaps
  15423. // set 0 level mipmap and then use GL to generate other mipmap levels
  15424. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  15425. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15426. mipmap = mipmaps[ i ];
  15427. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15428. }
  15429. texture.generateMipmaps = false;
  15430. } else {
  15431. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  15432. }
  15433. } else if ( texture.isCompressedTexture ) {
  15434. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15435. mipmap = mipmaps[ i ];
  15436. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  15437. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  15438. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15439. } else {
  15440. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" );
  15441. }
  15442. } else {
  15443. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15444. }
  15445. }
  15446. } else {
  15447. // regular Texture (image, video, canvas)
  15448. // use manually created mipmaps if available
  15449. // if there are no manual mipmaps
  15450. // set 0 level mipmap and then use GL to generate other mipmap levels
  15451. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  15452. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15453. mipmap = mipmaps[ i ];
  15454. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  15455. }
  15456. texture.generateMipmaps = false;
  15457. } else {
  15458. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image );
  15459. }
  15460. }
  15461. if ( texture.generateMipmaps && isPowerOfTwoImage ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15462. textureProperties.__version = texture.version;
  15463. if ( texture.onUpdate ) texture.onUpdate( texture );
  15464. }
  15465. // Render targets
  15466. // Setup storage for target texture and bind it to correct framebuffer
  15467. function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {
  15468. var glFormat = paramThreeToGL( renderTarget.texture.format );
  15469. var glType = paramThreeToGL( renderTarget.texture.type );
  15470. state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15471. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15472. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  15473. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15474. }
  15475. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  15476. function setupRenderBufferStorage( renderbuffer, renderTarget ) {
  15477. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  15478. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15479. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  15480. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15481. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15482. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  15483. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15484. } else {
  15485. // FIXME: We don't support !depth !stencil
  15486. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  15487. }
  15488. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15489. }
  15490. // Setup resources for a Depth Texture for a FBO (needs an extension)
  15491. function setupDepthTexture( framebuffer, renderTarget ) {
  15492. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  15493. if ( isCube ) throw new Error('Depth Texture with cube render targets is not supported!');
  15494. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15495. if ( !( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  15496. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  15497. }
  15498. // upload an empty depth texture with framebuffer size
  15499. if ( !properties.get( renderTarget.depthTexture ).__webglTexture ||
  15500. renderTarget.depthTexture.image.width !== renderTarget.width ||
  15501. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  15502. renderTarget.depthTexture.image.width = renderTarget.width;
  15503. renderTarget.depthTexture.image.height = renderTarget.height;
  15504. renderTarget.depthTexture.needsUpdate = true;
  15505. }
  15506. setTexture2D( renderTarget.depthTexture, 0 );
  15507. var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  15508. if ( renderTarget.depthTexture.format === DepthFormat ) {
  15509. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  15510. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  15511. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  15512. } else {
  15513. throw new Error('Unknown depthTexture format')
  15514. }
  15515. }
  15516. // Setup GL resources for a non-texture depth buffer
  15517. function setupDepthRenderbuffer( renderTarget ) {
  15518. var renderTargetProperties = properties.get( renderTarget );
  15519. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  15520. if ( renderTarget.depthTexture ) {
  15521. if ( isCube ) throw new Error('target.depthTexture not supported in Cube render targets');
  15522. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  15523. } else {
  15524. if ( isCube ) {
  15525. renderTargetProperties.__webglDepthbuffer = [];
  15526. for ( var i = 0; i < 6; i ++ ) {
  15527. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  15528. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  15529. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );
  15530. }
  15531. } else {
  15532. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15533. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  15534. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );
  15535. }
  15536. }
  15537. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15538. }
  15539. // Set up GL resources for the render target
  15540. function setupRenderTarget( renderTarget ) {
  15541. var renderTargetProperties = properties.get( renderTarget );
  15542. var textureProperties = properties.get( renderTarget.texture );
  15543. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  15544. textureProperties.__webglTexture = _gl.createTexture();
  15545. _infoMemory.textures ++;
  15546. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  15547. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget );
  15548. // Setup framebuffer
  15549. if ( isCube ) {
  15550. renderTargetProperties.__webglFramebuffer = [];
  15551. for ( var i = 0; i < 6; i ++ ) {
  15552. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15553. }
  15554. } else {
  15555. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  15556. }
  15557. // Setup color buffer
  15558. if ( isCube ) {
  15559. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  15560. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo );
  15561. for ( var i = 0; i < 6; i ++ ) {
  15562. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  15563. }
  15564. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15565. state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15566. } else {
  15567. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  15568. setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo );
  15569. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
  15570. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15571. state.bindTexture( _gl.TEXTURE_2D, null );
  15572. }
  15573. // Setup depth and stencil buffers
  15574. if ( renderTarget.depthBuffer ) {
  15575. setupDepthRenderbuffer( renderTarget );
  15576. }
  15577. }
  15578. function updateRenderTargetMipmap( renderTarget ) {
  15579. var texture = renderTarget.texture;
  15580. if ( texture.generateMipmaps && isPowerOfTwo( renderTarget ) &&
  15581. texture.minFilter !== NearestFilter &&
  15582. texture.minFilter !== LinearFilter ) {
  15583. var target = (renderTarget && renderTarget.isWebGLRenderTargetCube) ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  15584. var webglTexture = properties.get( texture ).__webglTexture;
  15585. state.bindTexture( target, webglTexture );
  15586. _gl.generateMipmap( target );
  15587. state.bindTexture( target, null );
  15588. }
  15589. }
  15590. this.setTexture2D = setTexture2D;
  15591. this.setTextureCube = setTextureCube;
  15592. this.setTextureCubeDynamic = setTextureCubeDynamic;
  15593. this.setupRenderTarget = setupRenderTarget;
  15594. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  15595. }
  15596. /**
  15597. * @author fordacious / fordacious.github.io
  15598. */
  15599. function WebGLProperties() {
  15600. var properties = {};
  15601. return {
  15602. get: function ( object ) {
  15603. var uuid = object.uuid;
  15604. var map = properties[ uuid ];
  15605. if ( map === undefined ) {
  15606. map = {};
  15607. properties[ uuid ] = map;
  15608. }
  15609. return map;
  15610. },
  15611. delete: function ( object ) {
  15612. delete properties[ object.uuid ];
  15613. },
  15614. clear: function () {
  15615. properties = {};
  15616. }
  15617. };
  15618. }
  15619. /**
  15620. * @author mrdoob / http://mrdoob.com/
  15621. */
  15622. function WebGLState( gl, extensions, paramThreeToGL ) {
  15623. function ColorBuffer() {
  15624. var locked = false;
  15625. var color = new Vector4();
  15626. var currentColorMask = null;
  15627. var currentColorClear = new Vector4();
  15628. return {
  15629. setMask: function ( colorMask ) {
  15630. if ( currentColorMask !== colorMask && ! locked ) {
  15631. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  15632. currentColorMask = colorMask;
  15633. }
  15634. },
  15635. setLocked: function ( lock ) {
  15636. locked = lock;
  15637. },
  15638. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  15639. if ( premultipliedAlpha === true ) {
  15640. r *= a; g *= a; b *= a;
  15641. }
  15642. color.set( r, g, b, a );
  15643. if ( currentColorClear.equals( color ) === false ) {
  15644. gl.clearColor( r, g, b, a );
  15645. currentColorClear.copy( color );
  15646. }
  15647. },
  15648. reset: function () {
  15649. locked = false;
  15650. currentColorMask = null;
  15651. currentColorClear.set( 0, 0, 0, 1 );
  15652. }
  15653. };
  15654. }
  15655. function DepthBuffer() {
  15656. var locked = false;
  15657. var currentDepthMask = null;
  15658. var currentDepthFunc = null;
  15659. var currentDepthClear = null;
  15660. return {
  15661. setTest: function ( depthTest ) {
  15662. if ( depthTest ) {
  15663. enable( gl.DEPTH_TEST );
  15664. } else {
  15665. disable( gl.DEPTH_TEST );
  15666. }
  15667. },
  15668. setMask: function ( depthMask ) {
  15669. if ( currentDepthMask !== depthMask && ! locked ) {
  15670. gl.depthMask( depthMask );
  15671. currentDepthMask = depthMask;
  15672. }
  15673. },
  15674. setFunc: function ( depthFunc ) {
  15675. if ( currentDepthFunc !== depthFunc ) {
  15676. if ( depthFunc ) {
  15677. switch ( depthFunc ) {
  15678. case NeverDepth:
  15679. gl.depthFunc( gl.NEVER );
  15680. break;
  15681. case AlwaysDepth:
  15682. gl.depthFunc( gl.ALWAYS );
  15683. break;
  15684. case LessDepth:
  15685. gl.depthFunc( gl.LESS );
  15686. break;
  15687. case LessEqualDepth:
  15688. gl.depthFunc( gl.LEQUAL );
  15689. break;
  15690. case EqualDepth:
  15691. gl.depthFunc( gl.EQUAL );
  15692. break;
  15693. case GreaterEqualDepth:
  15694. gl.depthFunc( gl.GEQUAL );
  15695. break;
  15696. case GreaterDepth:
  15697. gl.depthFunc( gl.GREATER );
  15698. break;
  15699. case NotEqualDepth:
  15700. gl.depthFunc( gl.NOTEQUAL );
  15701. break;
  15702. default:
  15703. gl.depthFunc( gl.LEQUAL );
  15704. }
  15705. } else {
  15706. gl.depthFunc( gl.LEQUAL );
  15707. }
  15708. currentDepthFunc = depthFunc;
  15709. }
  15710. },
  15711. setLocked: function ( lock ) {
  15712. locked = lock;
  15713. },
  15714. setClear: function ( depth ) {
  15715. if ( currentDepthClear !== depth ) {
  15716. gl.clearDepth( depth );
  15717. currentDepthClear = depth;
  15718. }
  15719. },
  15720. reset: function () {
  15721. locked = false;
  15722. currentDepthMask = null;
  15723. currentDepthFunc = null;
  15724. currentDepthClear = null;
  15725. }
  15726. };
  15727. }
  15728. function StencilBuffer() {
  15729. var locked = false;
  15730. var currentStencilMask = null;
  15731. var currentStencilFunc = null;
  15732. var currentStencilRef = null;
  15733. var currentStencilFuncMask = null;
  15734. var currentStencilFail = null;
  15735. var currentStencilZFail = null;
  15736. var currentStencilZPass = null;
  15737. var currentStencilClear = null;
  15738. return {
  15739. setTest: function ( stencilTest ) {
  15740. if ( stencilTest ) {
  15741. enable( gl.STENCIL_TEST );
  15742. } else {
  15743. disable( gl.STENCIL_TEST );
  15744. }
  15745. },
  15746. setMask: function ( stencilMask ) {
  15747. if ( currentStencilMask !== stencilMask && ! locked ) {
  15748. gl.stencilMask( stencilMask );
  15749. currentStencilMask = stencilMask;
  15750. }
  15751. },
  15752. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  15753. if ( currentStencilFunc !== stencilFunc ||
  15754. currentStencilRef !== stencilRef ||
  15755. currentStencilFuncMask !== stencilMask ) {
  15756. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  15757. currentStencilFunc = stencilFunc;
  15758. currentStencilRef = stencilRef;
  15759. currentStencilFuncMask = stencilMask;
  15760. }
  15761. },
  15762. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  15763. if ( currentStencilFail !== stencilFail ||
  15764. currentStencilZFail !== stencilZFail ||
  15765. currentStencilZPass !== stencilZPass ) {
  15766. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  15767. currentStencilFail = stencilFail;
  15768. currentStencilZFail = stencilZFail;
  15769. currentStencilZPass = stencilZPass;
  15770. }
  15771. },
  15772. setLocked: function ( lock ) {
  15773. locked = lock;
  15774. },
  15775. setClear: function ( stencil ) {
  15776. if ( currentStencilClear !== stencil ) {
  15777. gl.clearStencil( stencil );
  15778. currentStencilClear = stencil;
  15779. }
  15780. },
  15781. reset: function () {
  15782. locked = false;
  15783. currentStencilMask = null;
  15784. currentStencilFunc = null;
  15785. currentStencilRef = null;
  15786. currentStencilFuncMask = null;
  15787. currentStencilFail = null;
  15788. currentStencilZFail = null;
  15789. currentStencilZPass = null;
  15790. currentStencilClear = null;
  15791. }
  15792. };
  15793. }
  15794. //
  15795. var colorBuffer = new ColorBuffer();
  15796. var depthBuffer = new DepthBuffer();
  15797. var stencilBuffer = new StencilBuffer();
  15798. var maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  15799. var newAttributes = new Uint8Array( maxVertexAttributes );
  15800. var enabledAttributes = new Uint8Array( maxVertexAttributes );
  15801. var attributeDivisors = new Uint8Array( maxVertexAttributes );
  15802. var capabilities = {};
  15803. var compressedTextureFormats = null;
  15804. var currentBlending = null;
  15805. var currentBlendEquation = null;
  15806. var currentBlendSrc = null;
  15807. var currentBlendDst = null;
  15808. var currentBlendEquationAlpha = null;
  15809. var currentBlendSrcAlpha = null;
  15810. var currentBlendDstAlpha = null;
  15811. var currentPremultipledAlpha = false;
  15812. var currentFlipSided = null;
  15813. var currentCullFace = null;
  15814. var currentLineWidth = null;
  15815. var currentPolygonOffsetFactor = null;
  15816. var currentPolygonOffsetUnits = null;
  15817. var currentScissorTest = null;
  15818. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  15819. var version = parseFloat( /^WebGL\ ([0-9])/.exec( gl.getParameter( gl.VERSION ) )[ 1 ] );
  15820. var lineWidthAvailable = parseFloat( version ) >= 1.0;
  15821. var currentTextureSlot = null;
  15822. var currentBoundTextures = {};
  15823. var currentScissor = new Vector4();
  15824. var currentViewport = new Vector4();
  15825. function createTexture( type, target, count ) {
  15826. var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  15827. var texture = gl.createTexture();
  15828. gl.bindTexture( type, texture );
  15829. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  15830. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  15831. for ( var i = 0; i < count; i ++ ) {
  15832. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  15833. }
  15834. return texture;
  15835. }
  15836. var emptyTextures = {};
  15837. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  15838. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  15839. //
  15840. function init() {
  15841. colorBuffer.setClear( 0, 0, 0, 1 );
  15842. depthBuffer.setClear( 1 );
  15843. stencilBuffer.setClear( 0 );
  15844. enable( gl.DEPTH_TEST );
  15845. setDepthFunc( LessEqualDepth );
  15846. setFlipSided( false );
  15847. setCullFace( CullFaceBack );
  15848. enable( gl.CULL_FACE );
  15849. enable( gl.BLEND );
  15850. setBlending( NormalBlending );
  15851. }
  15852. function initAttributes() {
  15853. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  15854. newAttributes[ i ] = 0;
  15855. }
  15856. }
  15857. function enableAttribute( attribute ) {
  15858. newAttributes[ attribute ] = 1;
  15859. if ( enabledAttributes[ attribute ] === 0 ) {
  15860. gl.enableVertexAttribArray( attribute );
  15861. enabledAttributes[ attribute ] = 1;
  15862. }
  15863. if ( attributeDivisors[ attribute ] !== 0 ) {
  15864. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  15865. extension.vertexAttribDivisorANGLE( attribute, 0 );
  15866. attributeDivisors[ attribute ] = 0;
  15867. }
  15868. }
  15869. function enableAttributeAndDivisor( attribute, meshPerAttribute, extension ) {
  15870. newAttributes[ attribute ] = 1;
  15871. if ( enabledAttributes[ attribute ] === 0 ) {
  15872. gl.enableVertexAttribArray( attribute );
  15873. enabledAttributes[ attribute ] = 1;
  15874. }
  15875. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  15876. extension.vertexAttribDivisorANGLE( attribute, meshPerAttribute );
  15877. attributeDivisors[ attribute ] = meshPerAttribute;
  15878. }
  15879. }
  15880. function disableUnusedAttributes() {
  15881. for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) {
  15882. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  15883. gl.disableVertexAttribArray( i );
  15884. enabledAttributes[ i ] = 0;
  15885. }
  15886. }
  15887. }
  15888. function enable( id ) {
  15889. if ( capabilities[ id ] !== true ) {
  15890. gl.enable( id );
  15891. capabilities[ id ] = true;
  15892. }
  15893. }
  15894. function disable( id ) {
  15895. if ( capabilities[ id ] !== false ) {
  15896. gl.disable( id );
  15897. capabilities[ id ] = false;
  15898. }
  15899. }
  15900. function getCompressedTextureFormats() {
  15901. if ( compressedTextureFormats === null ) {
  15902. compressedTextureFormats = [];
  15903. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) ||
  15904. extensions.get( 'WEBGL_compressed_texture_s3tc' ) ||
  15905. extensions.get( 'WEBGL_compressed_texture_etc1' ) ) {
  15906. var formats = gl.getParameter( gl.COMPRESSED_TEXTURE_FORMATS );
  15907. for ( var i = 0; i < formats.length; i ++ ) {
  15908. compressedTextureFormats.push( formats[ i ] );
  15909. }
  15910. }
  15911. }
  15912. return compressedTextureFormats;
  15913. }
  15914. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  15915. if ( blending !== NoBlending ) {
  15916. enable( gl.BLEND );
  15917. } else {
  15918. disable( gl.BLEND );
  15919. }
  15920. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  15921. if ( blending === AdditiveBlending ) {
  15922. if ( premultipliedAlpha ) {
  15923. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  15924. gl.blendFuncSeparate( gl.ONE, gl.ONE, gl.ONE, gl.ONE );
  15925. } else {
  15926. gl.blendEquation( gl.FUNC_ADD );
  15927. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  15928. }
  15929. } else if ( blending === SubtractiveBlending ) {
  15930. if ( premultipliedAlpha ) {
  15931. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  15932. gl.blendFuncSeparate( gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA );
  15933. } else {
  15934. gl.blendEquation( gl.FUNC_ADD );
  15935. gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR );
  15936. }
  15937. } else if ( blending === MultiplyBlending ) {
  15938. if ( premultipliedAlpha ) {
  15939. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  15940. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  15941. } else {
  15942. gl.blendEquation( gl.FUNC_ADD );
  15943. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  15944. }
  15945. } else {
  15946. if ( premultipliedAlpha ) {
  15947. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  15948. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  15949. } else {
  15950. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  15951. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  15952. }
  15953. }
  15954. currentBlending = blending;
  15955. currentPremultipledAlpha = premultipliedAlpha;
  15956. }
  15957. if ( blending === CustomBlending ) {
  15958. blendEquationAlpha = blendEquationAlpha || blendEquation;
  15959. blendSrcAlpha = blendSrcAlpha || blendSrc;
  15960. blendDstAlpha = blendDstAlpha || blendDst;
  15961. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  15962. gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) );
  15963. currentBlendEquation = blendEquation;
  15964. currentBlendEquationAlpha = blendEquationAlpha;
  15965. }
  15966. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  15967. gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) );
  15968. currentBlendSrc = blendSrc;
  15969. currentBlendDst = blendDst;
  15970. currentBlendSrcAlpha = blendSrcAlpha;
  15971. currentBlendDstAlpha = blendDstAlpha;
  15972. }
  15973. } else {
  15974. currentBlendEquation = null;
  15975. currentBlendSrc = null;
  15976. currentBlendDst = null;
  15977. currentBlendEquationAlpha = null;
  15978. currentBlendSrcAlpha = null;
  15979. currentBlendDstAlpha = null;
  15980. }
  15981. }
  15982. // TODO Deprecate
  15983. function setColorWrite( colorWrite ) {
  15984. colorBuffer.setMask( colorWrite );
  15985. }
  15986. function setDepthTest( depthTest ) {
  15987. depthBuffer.setTest( depthTest );
  15988. }
  15989. function setDepthWrite( depthWrite ) {
  15990. depthBuffer.setMask( depthWrite );
  15991. }
  15992. function setDepthFunc( depthFunc ) {
  15993. depthBuffer.setFunc( depthFunc );
  15994. }
  15995. function setStencilTest( stencilTest ) {
  15996. stencilBuffer.setTest( stencilTest );
  15997. }
  15998. function setStencilWrite( stencilWrite ) {
  15999. stencilBuffer.setMask( stencilWrite );
  16000. }
  16001. function setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  16002. stencilBuffer.setFunc( stencilFunc, stencilRef, stencilMask );
  16003. }
  16004. function setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  16005. stencilBuffer.setOp( stencilFail, stencilZFail, stencilZPass );
  16006. }
  16007. //
  16008. function setFlipSided( flipSided ) {
  16009. if ( currentFlipSided !== flipSided ) {
  16010. if ( flipSided ) {
  16011. gl.frontFace( gl.CW );
  16012. } else {
  16013. gl.frontFace( gl.CCW );
  16014. }
  16015. currentFlipSided = flipSided;
  16016. }
  16017. }
  16018. function setCullFace( cullFace ) {
  16019. if ( cullFace !== CullFaceNone ) {
  16020. enable( gl.CULL_FACE );
  16021. if ( cullFace !== currentCullFace ) {
  16022. if ( cullFace === CullFaceBack ) {
  16023. gl.cullFace( gl.BACK );
  16024. } else if ( cullFace === CullFaceFront ) {
  16025. gl.cullFace( gl.FRONT );
  16026. } else {
  16027. gl.cullFace( gl.FRONT_AND_BACK );
  16028. }
  16029. }
  16030. } else {
  16031. disable( gl.CULL_FACE );
  16032. }
  16033. currentCullFace = cullFace;
  16034. }
  16035. function setLineWidth( width ) {
  16036. if ( width !== currentLineWidth ) {
  16037. if ( lineWidthAvailable ) gl.lineWidth( width );
  16038. currentLineWidth = width;
  16039. }
  16040. }
  16041. function setPolygonOffset( polygonOffset, factor, units ) {
  16042. if ( polygonOffset ) {
  16043. enable( gl.POLYGON_OFFSET_FILL );
  16044. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  16045. gl.polygonOffset( factor, units );
  16046. currentPolygonOffsetFactor = factor;
  16047. currentPolygonOffsetUnits = units;
  16048. }
  16049. } else {
  16050. disable( gl.POLYGON_OFFSET_FILL );
  16051. }
  16052. }
  16053. function getScissorTest() {
  16054. return currentScissorTest;
  16055. }
  16056. function setScissorTest( scissorTest ) {
  16057. currentScissorTest = scissorTest;
  16058. if ( scissorTest ) {
  16059. enable( gl.SCISSOR_TEST );
  16060. } else {
  16061. disable( gl.SCISSOR_TEST );
  16062. }
  16063. }
  16064. // texture
  16065. function activeTexture( webglSlot ) {
  16066. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  16067. if ( currentTextureSlot !== webglSlot ) {
  16068. gl.activeTexture( webglSlot );
  16069. currentTextureSlot = webglSlot;
  16070. }
  16071. }
  16072. function bindTexture( webglType, webglTexture ) {
  16073. if ( currentTextureSlot === null ) {
  16074. activeTexture();
  16075. }
  16076. var boundTexture = currentBoundTextures[ currentTextureSlot ];
  16077. if ( boundTexture === undefined ) {
  16078. boundTexture = { type: undefined, texture: undefined };
  16079. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  16080. }
  16081. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  16082. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  16083. boundTexture.type = webglType;
  16084. boundTexture.texture = webglTexture;
  16085. }
  16086. }
  16087. function compressedTexImage2D() {
  16088. try {
  16089. gl.compressedTexImage2D.apply( gl, arguments );
  16090. } catch ( error ) {
  16091. console.error( error );
  16092. }
  16093. }
  16094. function texImage2D() {
  16095. try {
  16096. gl.texImage2D.apply( gl, arguments );
  16097. } catch ( error ) {
  16098. console.error( error );
  16099. }
  16100. }
  16101. //
  16102. function scissor( scissor ) {
  16103. if ( currentScissor.equals( scissor ) === false ) {
  16104. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  16105. currentScissor.copy( scissor );
  16106. }
  16107. }
  16108. function viewport( viewport ) {
  16109. if ( currentViewport.equals( viewport ) === false ) {
  16110. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  16111. currentViewport.copy( viewport );
  16112. }
  16113. }
  16114. //
  16115. function reset() {
  16116. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  16117. if ( enabledAttributes[ i ] === 1 ) {
  16118. gl.disableVertexAttribArray( i );
  16119. enabledAttributes[ i ] = 0;
  16120. }
  16121. }
  16122. capabilities = {};
  16123. compressedTextureFormats = null;
  16124. currentTextureSlot = null;
  16125. currentBoundTextures = {};
  16126. currentBlending = null;
  16127. currentFlipSided = null;
  16128. currentCullFace = null;
  16129. colorBuffer.reset();
  16130. depthBuffer.reset();
  16131. stencilBuffer.reset();
  16132. }
  16133. return {
  16134. buffers: {
  16135. color: colorBuffer,
  16136. depth: depthBuffer,
  16137. stencil: stencilBuffer
  16138. },
  16139. init: init,
  16140. initAttributes: initAttributes,
  16141. enableAttribute: enableAttribute,
  16142. enableAttributeAndDivisor: enableAttributeAndDivisor,
  16143. disableUnusedAttributes: disableUnusedAttributes,
  16144. enable: enable,
  16145. disable: disable,
  16146. getCompressedTextureFormats: getCompressedTextureFormats,
  16147. setBlending: setBlending,
  16148. setColorWrite: setColorWrite,
  16149. setDepthTest: setDepthTest,
  16150. setDepthWrite: setDepthWrite,
  16151. setDepthFunc: setDepthFunc,
  16152. setStencilTest: setStencilTest,
  16153. setStencilWrite: setStencilWrite,
  16154. setStencilFunc: setStencilFunc,
  16155. setStencilOp: setStencilOp,
  16156. setFlipSided: setFlipSided,
  16157. setCullFace: setCullFace,
  16158. setLineWidth: setLineWidth,
  16159. setPolygonOffset: setPolygonOffset,
  16160. getScissorTest: getScissorTest,
  16161. setScissorTest: setScissorTest,
  16162. activeTexture: activeTexture,
  16163. bindTexture: bindTexture,
  16164. compressedTexImage2D: compressedTexImage2D,
  16165. texImage2D: texImage2D,
  16166. scissor: scissor,
  16167. viewport: viewport,
  16168. reset: reset
  16169. };
  16170. }
  16171. /**
  16172. * @author mrdoob / http://mrdoob.com/
  16173. */
  16174. function WebGLCapabilities( gl, extensions, parameters ) {
  16175. var maxAnisotropy;
  16176. function getMaxAnisotropy() {
  16177. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  16178. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  16179. if ( extension !== null ) {
  16180. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  16181. } else {
  16182. maxAnisotropy = 0;
  16183. }
  16184. return maxAnisotropy;
  16185. }
  16186. function getMaxPrecision( precision ) {
  16187. if ( precision === 'highp' ) {
  16188. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  16189. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  16190. return 'highp';
  16191. }
  16192. precision = 'mediump';
  16193. }
  16194. if ( precision === 'mediump' ) {
  16195. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  16196. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  16197. return 'mediump';
  16198. }
  16199. }
  16200. return 'lowp';
  16201. }
  16202. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  16203. var maxPrecision = getMaxPrecision( precision );
  16204. if ( maxPrecision !== precision ) {
  16205. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  16206. precision = maxPrecision;
  16207. }
  16208. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true && !! extensions.get( 'EXT_frag_depth' );
  16209. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  16210. var maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  16211. var maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  16212. var maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  16213. var maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  16214. var maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  16215. var maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  16216. var maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  16217. var vertexTextures = maxVertexTextures > 0;
  16218. var floatFragmentTextures = !! extensions.get( 'OES_texture_float' );
  16219. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  16220. return {
  16221. getMaxAnisotropy: getMaxAnisotropy,
  16222. getMaxPrecision: getMaxPrecision,
  16223. precision: precision,
  16224. logarithmicDepthBuffer: logarithmicDepthBuffer,
  16225. maxTextures: maxTextures,
  16226. maxVertexTextures: maxVertexTextures,
  16227. maxTextureSize: maxTextureSize,
  16228. maxCubemapSize: maxCubemapSize,
  16229. maxAttributes: maxAttributes,
  16230. maxVertexUniforms: maxVertexUniforms,
  16231. maxVaryings: maxVaryings,
  16232. maxFragmentUniforms: maxFragmentUniforms,
  16233. vertexTextures: vertexTextures,
  16234. floatFragmentTextures: floatFragmentTextures,
  16235. floatVertexTextures: floatVertexTextures
  16236. };
  16237. }
  16238. /**
  16239. * @author mrdoob / http://mrdoob.com/
  16240. */
  16241. function WebGLExtensions( gl ) {
  16242. var extensions = {};
  16243. return {
  16244. get: function ( name ) {
  16245. if ( extensions[ name ] !== undefined ) {
  16246. return extensions[ name ];
  16247. }
  16248. var extension;
  16249. switch ( name ) {
  16250. case 'WEBGL_depth_texture':
  16251. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  16252. break;
  16253. case 'EXT_texture_filter_anisotropic':
  16254. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  16255. break;
  16256. case 'WEBGL_compressed_texture_s3tc':
  16257. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  16258. break;
  16259. case 'WEBGL_compressed_texture_pvrtc':
  16260. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  16261. break;
  16262. case 'WEBGL_compressed_texture_etc1':
  16263. extension = gl.getExtension( 'WEBGL_compressed_texture_etc1' );
  16264. break;
  16265. default:
  16266. extension = gl.getExtension( name );
  16267. }
  16268. if ( extension === null ) {
  16269. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  16270. }
  16271. extensions[ name ] = extension;
  16272. return extension;
  16273. }
  16274. };
  16275. }
  16276. /**
  16277. * @author tschw
  16278. */
  16279. function WebGLClipping() {
  16280. var scope = this,
  16281. globalState = null,
  16282. numGlobalPlanes = 0,
  16283. localClippingEnabled = false,
  16284. renderingShadows = false,
  16285. plane = new Plane(),
  16286. viewNormalMatrix = new Matrix3(),
  16287. uniform = { value: null, needsUpdate: false };
  16288. this.uniform = uniform;
  16289. this.numPlanes = 0;
  16290. this.numIntersection = 0;
  16291. this.init = function( planes, enableLocalClipping, camera ) {
  16292. var enabled =
  16293. planes.length !== 0 ||
  16294. enableLocalClipping ||
  16295. // enable state of previous frame - the clipping code has to
  16296. // run another frame in order to reset the state:
  16297. numGlobalPlanes !== 0 ||
  16298. localClippingEnabled;
  16299. localClippingEnabled = enableLocalClipping;
  16300. globalState = projectPlanes( planes, camera, 0 );
  16301. numGlobalPlanes = planes.length;
  16302. return enabled;
  16303. };
  16304. this.beginShadows = function() {
  16305. renderingShadows = true;
  16306. projectPlanes( null );
  16307. };
  16308. this.endShadows = function() {
  16309. renderingShadows = false;
  16310. resetGlobalState();
  16311. };
  16312. this.setState = function( planes, clipIntersection, clipShadows, camera, cache, fromCache ) {
  16313. if ( ! localClippingEnabled ||
  16314. planes === null || planes.length === 0 ||
  16315. renderingShadows && ! clipShadows ) {
  16316. // there's no local clipping
  16317. if ( renderingShadows ) {
  16318. // there's no global clipping
  16319. projectPlanes( null );
  16320. } else {
  16321. resetGlobalState();
  16322. }
  16323. } else {
  16324. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  16325. lGlobal = nGlobal * 4,
  16326. dstArray = cache.clippingState || null;
  16327. uniform.value = dstArray; // ensure unique state
  16328. dstArray = projectPlanes( planes, camera, lGlobal, fromCache );
  16329. for ( var i = 0; i !== lGlobal; ++ i ) {
  16330. dstArray[ i ] = globalState[ i ];
  16331. }
  16332. cache.clippingState = dstArray;
  16333. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  16334. this.numPlanes += nGlobal;
  16335. }
  16336. };
  16337. function resetGlobalState() {
  16338. if ( uniform.value !== globalState ) {
  16339. uniform.value = globalState;
  16340. uniform.needsUpdate = numGlobalPlanes > 0;
  16341. }
  16342. scope.numPlanes = numGlobalPlanes;
  16343. scope.numIntersection = 0;
  16344. }
  16345. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  16346. var nPlanes = planes !== null ? planes.length : 0,
  16347. dstArray = null;
  16348. if ( nPlanes !== 0 ) {
  16349. dstArray = uniform.value;
  16350. if ( skipTransform !== true || dstArray === null ) {
  16351. var flatSize = dstOffset + nPlanes * 4,
  16352. viewMatrix = camera.matrixWorldInverse;
  16353. viewNormalMatrix.getNormalMatrix( viewMatrix );
  16354. if ( dstArray === null || dstArray.length < flatSize ) {
  16355. dstArray = new Float32Array( flatSize );
  16356. }
  16357. for ( var i = 0, i4 = dstOffset;
  16358. i !== nPlanes; ++ i, i4 += 4 ) {
  16359. plane.copy( planes[ i ] ).
  16360. applyMatrix4( viewMatrix, viewNormalMatrix );
  16361. plane.normal.toArray( dstArray, i4 );
  16362. dstArray[ i4 + 3 ] = plane.constant;
  16363. }
  16364. }
  16365. uniform.value = dstArray;
  16366. uniform.needsUpdate = true;
  16367. }
  16368. scope.numPlanes = nPlanes;
  16369. return dstArray;
  16370. }
  16371. }
  16372. /**
  16373. * @author supereggbert / http://www.paulbrunt.co.uk/
  16374. * @author mrdoob / http://mrdoob.com/
  16375. * @author alteredq / http://alteredqualia.com/
  16376. * @author szimek / https://github.com/szimek/
  16377. * @author tschw
  16378. */
  16379. function WebGLRenderer( parameters ) {
  16380. console.log( 'THREE.WebGLRenderer', REVISION );
  16381. parameters = parameters || {};
  16382. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
  16383. _context = parameters.context !== undefined ? parameters.context : null,
  16384. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  16385. _depth = parameters.depth !== undefined ? parameters.depth : true,
  16386. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  16387. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  16388. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  16389. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false;
  16390. var lights = [];
  16391. var opaqueObjects = [];
  16392. var opaqueObjectsLastIndex = - 1;
  16393. var transparentObjects = [];
  16394. var transparentObjectsLastIndex = - 1;
  16395. var morphInfluences = new Float32Array( 8 );
  16396. var sprites = [];
  16397. var lensFlares = [];
  16398. // public properties
  16399. this.domElement = _canvas;
  16400. this.context = null;
  16401. // clearing
  16402. this.autoClear = true;
  16403. this.autoClearColor = true;
  16404. this.autoClearDepth = true;
  16405. this.autoClearStencil = true;
  16406. // scene graph
  16407. this.sortObjects = true;
  16408. // user-defined clipping
  16409. this.clippingPlanes = [];
  16410. this.localClippingEnabled = false;
  16411. // physically based shading
  16412. this.gammaFactor = 2.0; // for backwards compatibility
  16413. this.gammaInput = false;
  16414. this.gammaOutput = false;
  16415. // physical lights
  16416. this.physicallyCorrectLights = false;
  16417. // tone mapping
  16418. this.toneMapping = LinearToneMapping;
  16419. this.toneMappingExposure = 1.0;
  16420. this.toneMappingWhitePoint = 1.0;
  16421. // morphs
  16422. this.maxMorphTargets = 8;
  16423. this.maxMorphNormals = 4;
  16424. // internal properties
  16425. var _this = this,
  16426. // internal state cache
  16427. _currentProgram = null,
  16428. _currentRenderTarget = null,
  16429. _currentFramebuffer = null,
  16430. _currentMaterialId = - 1,
  16431. _currentGeometryProgram = '',
  16432. _currentCamera = null,
  16433. _currentScissor = new Vector4(),
  16434. _currentScissorTest = null,
  16435. _currentViewport = new Vector4(),
  16436. //
  16437. _usedTextureUnits = 0,
  16438. //
  16439. _clearColor = new Color( 0x000000 ),
  16440. _clearAlpha = 0,
  16441. _width = _canvas.width,
  16442. _height = _canvas.height,
  16443. _pixelRatio = 1,
  16444. _scissor = new Vector4( 0, 0, _width, _height ),
  16445. _scissorTest = false,
  16446. _viewport = new Vector4( 0, 0, _width, _height ),
  16447. // frustum
  16448. _frustum = new Frustum(),
  16449. // clipping
  16450. _clipping = new WebGLClipping(),
  16451. _clippingEnabled = false,
  16452. _localClippingEnabled = false,
  16453. _sphere = new Sphere(),
  16454. // camera matrices cache
  16455. _projScreenMatrix = new Matrix4(),
  16456. _vector3 = new Vector3(),
  16457. _matrix4 = new Matrix4(),
  16458. _matrix42 = new Matrix4(),
  16459. // light arrays cache
  16460. _lights = {
  16461. hash: '',
  16462. ambient: [ 0, 0, 0 ],
  16463. directional: [],
  16464. directionalShadowMap: [],
  16465. directionalShadowMatrix: [],
  16466. spot: [],
  16467. spotShadowMap: [],
  16468. spotShadowMatrix: [],
  16469. rectArea: [],
  16470. point: [],
  16471. pointShadowMap: [],
  16472. pointShadowMatrix: [],
  16473. hemi: [],
  16474. shadows: []
  16475. },
  16476. // info
  16477. _infoRender = {
  16478. calls: 0,
  16479. vertices: 0,
  16480. faces: 0,
  16481. points: 0
  16482. };
  16483. this.info = {
  16484. render: _infoRender,
  16485. memory: {
  16486. geometries: 0,
  16487. textures: 0
  16488. },
  16489. programs: null
  16490. };
  16491. // initialize
  16492. var _gl;
  16493. try {
  16494. var attributes = {
  16495. alpha: _alpha,
  16496. depth: _depth,
  16497. stencil: _stencil,
  16498. antialias: _antialias,
  16499. premultipliedAlpha: _premultipliedAlpha,
  16500. preserveDrawingBuffer: _preserveDrawingBuffer
  16501. };
  16502. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  16503. if ( _gl === null ) {
  16504. if ( _canvas.getContext( 'webgl' ) !== null ) {
  16505. throw 'Error creating WebGL context with your selected attributes.';
  16506. } else {
  16507. throw 'Error creating WebGL context.';
  16508. }
  16509. }
  16510. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  16511. if ( _gl.getShaderPrecisionFormat === undefined ) {
  16512. _gl.getShaderPrecisionFormat = function () {
  16513. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  16514. };
  16515. }
  16516. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  16517. } catch ( error ) {
  16518. console.error( 'THREE.WebGLRenderer: ' + error );
  16519. }
  16520. var extensions = new WebGLExtensions( _gl );
  16521. extensions.get( 'WEBGL_depth_texture' );
  16522. extensions.get( 'OES_texture_float' );
  16523. extensions.get( 'OES_texture_float_linear' );
  16524. extensions.get( 'OES_texture_half_float' );
  16525. extensions.get( 'OES_texture_half_float_linear' );
  16526. extensions.get( 'OES_standard_derivatives' );
  16527. extensions.get( 'ANGLE_instanced_arrays' );
  16528. if ( extensions.get( 'OES_element_index_uint' ) ) {
  16529. BufferGeometry.MaxIndex = 4294967296;
  16530. }
  16531. var capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  16532. var state = new WebGLState( _gl, extensions, paramThreeToGL );
  16533. var properties = new WebGLProperties();
  16534. var textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, this.info );
  16535. var objects = new WebGLObjects( _gl, properties, this.info );
  16536. var programCache = new WebGLPrograms( this, capabilities );
  16537. var lightCache = new WebGLLights();
  16538. this.info.programs = programCache.programs;
  16539. var bufferRenderer = new WebGLBufferRenderer( _gl, extensions, _infoRender );
  16540. var indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
  16541. //
  16542. var backgroundPlaneCamera, backgroundPlaneMesh;
  16543. var backgroundBoxCamera, backgroundBoxMesh;
  16544. //
  16545. function getTargetPixelRatio() {
  16546. return _currentRenderTarget === null ? _pixelRatio : 1;
  16547. }
  16548. function setDefaultGLState() {
  16549. state.init();
  16550. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  16551. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  16552. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  16553. }
  16554. function resetGLState() {
  16555. _currentProgram = null;
  16556. _currentCamera = null;
  16557. _currentGeometryProgram = '';
  16558. _currentMaterialId = - 1;
  16559. state.reset();
  16560. }
  16561. setDefaultGLState();
  16562. this.context = _gl;
  16563. this.capabilities = capabilities;
  16564. this.extensions = extensions;
  16565. this.properties = properties;
  16566. this.state = state;
  16567. // shadow map
  16568. var shadowMap = new WebGLShadowMap( this, _lights, objects, capabilities );
  16569. this.shadowMap = shadowMap;
  16570. // Plugins
  16571. var spritePlugin = new SpritePlugin( this, sprites );
  16572. var lensFlarePlugin = new LensFlarePlugin( this, lensFlares );
  16573. // API
  16574. this.getContext = function () {
  16575. return _gl;
  16576. };
  16577. this.getContextAttributes = function () {
  16578. return _gl.getContextAttributes();
  16579. };
  16580. this.forceContextLoss = function () {
  16581. extensions.get( 'WEBGL_lose_context' ).loseContext();
  16582. };
  16583. this.getMaxAnisotropy = function () {
  16584. return capabilities.getMaxAnisotropy();
  16585. };
  16586. this.getPrecision = function () {
  16587. return capabilities.precision;
  16588. };
  16589. this.getPixelRatio = function () {
  16590. return _pixelRatio;
  16591. };
  16592. this.setPixelRatio = function ( value ) {
  16593. if ( value === undefined ) return;
  16594. _pixelRatio = value;
  16595. this.setSize( _viewport.z, _viewport.w, false );
  16596. };
  16597. this.getSize = function () {
  16598. return {
  16599. width: _width,
  16600. height: _height
  16601. };
  16602. };
  16603. this.setSize = function ( width, height, updateStyle ) {
  16604. _width = width;
  16605. _height = height;
  16606. _canvas.width = width * _pixelRatio;
  16607. _canvas.height = height * _pixelRatio;
  16608. if ( updateStyle !== false ) {
  16609. _canvas.style.width = width + 'px';
  16610. _canvas.style.height = height + 'px';
  16611. }
  16612. this.setViewport( 0, 0, width, height );
  16613. };
  16614. this.setViewport = function ( x, y, width, height ) {
  16615. state.viewport( _viewport.set( x, y, width, height ) );
  16616. };
  16617. this.setScissor = function ( x, y, width, height ) {
  16618. state.scissor( _scissor.set( x, y, width, height ) );
  16619. };
  16620. this.setScissorTest = function ( boolean ) {
  16621. state.setScissorTest( _scissorTest = boolean );
  16622. };
  16623. // Clearing
  16624. this.getClearColor = function () {
  16625. return _clearColor;
  16626. };
  16627. this.setClearColor = function ( color, alpha ) {
  16628. _clearColor.set( color );
  16629. _clearAlpha = alpha !== undefined ? alpha : 1;
  16630. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  16631. };
  16632. this.getClearAlpha = function () {
  16633. return _clearAlpha;
  16634. };
  16635. this.setClearAlpha = function ( alpha ) {
  16636. _clearAlpha = alpha;
  16637. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  16638. };
  16639. this.clear = function ( color, depth, stencil ) {
  16640. var bits = 0;
  16641. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  16642. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  16643. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  16644. _gl.clear( bits );
  16645. };
  16646. this.clearColor = function () {
  16647. this.clear( true, false, false );
  16648. };
  16649. this.clearDepth = function () {
  16650. this.clear( false, true, false );
  16651. };
  16652. this.clearStencil = function () {
  16653. this.clear( false, false, true );
  16654. };
  16655. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  16656. this.setRenderTarget( renderTarget );
  16657. this.clear( color, depth, stencil );
  16658. };
  16659. // Reset
  16660. this.resetGLState = resetGLState;
  16661. this.dispose = function() {
  16662. transparentObjects = [];
  16663. transparentObjectsLastIndex = -1;
  16664. opaqueObjects = [];
  16665. opaqueObjectsLastIndex = -1;
  16666. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  16667. };
  16668. // Events
  16669. function onContextLost( event ) {
  16670. event.preventDefault();
  16671. resetGLState();
  16672. setDefaultGLState();
  16673. properties.clear();
  16674. }
  16675. function onMaterialDispose( event ) {
  16676. var material = event.target;
  16677. material.removeEventListener( 'dispose', onMaterialDispose );
  16678. deallocateMaterial( material );
  16679. }
  16680. // Buffer deallocation
  16681. function deallocateMaterial( material ) {
  16682. releaseMaterialProgramReference( material );
  16683. properties.delete( material );
  16684. }
  16685. function releaseMaterialProgramReference( material ) {
  16686. var programInfo = properties.get( material ).program;
  16687. material.program = undefined;
  16688. if ( programInfo !== undefined ) {
  16689. programCache.releaseProgram( programInfo );
  16690. }
  16691. }
  16692. // Buffer rendering
  16693. this.renderBufferImmediate = function ( object, program, material ) {
  16694. state.initAttributes();
  16695. var buffers = properties.get( object );
  16696. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  16697. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  16698. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  16699. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  16700. var attributes = program.getAttributes();
  16701. if ( object.hasPositions ) {
  16702. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  16703. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  16704. state.enableAttribute( attributes.position );
  16705. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  16706. }
  16707. if ( object.hasNormals ) {
  16708. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  16709. if ( ! material.isMeshPhongMaterial &&
  16710. ! material.isMeshStandardMaterial &&
  16711. ! material.isMeshNormalMaterial &&
  16712. material.shading === FlatShading ) {
  16713. for ( var i = 0, l = object.count * 3; i < l; i += 9 ) {
  16714. var array = object.normalArray;
  16715. var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3;
  16716. var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3;
  16717. var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3;
  16718. array[ i + 0 ] = nx;
  16719. array[ i + 1 ] = ny;
  16720. array[ i + 2 ] = nz;
  16721. array[ i + 3 ] = nx;
  16722. array[ i + 4 ] = ny;
  16723. array[ i + 5 ] = nz;
  16724. array[ i + 6 ] = nx;
  16725. array[ i + 7 ] = ny;
  16726. array[ i + 8 ] = nz;
  16727. }
  16728. }
  16729. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  16730. state.enableAttribute( attributes.normal );
  16731. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  16732. }
  16733. if ( object.hasUvs && material.map ) {
  16734. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  16735. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  16736. state.enableAttribute( attributes.uv );
  16737. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  16738. }
  16739. if ( object.hasColors && material.vertexColors !== NoColors ) {
  16740. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  16741. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  16742. state.enableAttribute( attributes.color );
  16743. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  16744. }
  16745. state.disableUnusedAttributes();
  16746. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  16747. object.count = 0;
  16748. };
  16749. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  16750. setMaterial( material );
  16751. var program = setProgram( camera, fog, material, object );
  16752. var updateBuffers = false;
  16753. var geometryProgram = geometry.id + '_' + program.id + '_' + material.wireframe;
  16754. if ( geometryProgram !== _currentGeometryProgram ) {
  16755. _currentGeometryProgram = geometryProgram;
  16756. updateBuffers = true;
  16757. }
  16758. // morph targets
  16759. var morphTargetInfluences = object.morphTargetInfluences;
  16760. if ( morphTargetInfluences !== undefined ) {
  16761. var activeInfluences = [];
  16762. for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) {
  16763. var influence = morphTargetInfluences[ i ];
  16764. activeInfluences.push( [ influence, i ] );
  16765. }
  16766. activeInfluences.sort( absNumericalSort );
  16767. if ( activeInfluences.length > 8 ) {
  16768. activeInfluences.length = 8;
  16769. }
  16770. var morphAttributes = geometry.morphAttributes;
  16771. for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) {
  16772. var influence = activeInfluences[ i ];
  16773. morphInfluences[ i ] = influence[ 0 ];
  16774. if ( influence[ 0 ] !== 0 ) {
  16775. var index = influence[ 1 ];
  16776. if ( material.morphTargets === true && morphAttributes.position ) geometry.addAttribute( 'morphTarget' + i, morphAttributes.position[ index ] );
  16777. if ( material.morphNormals === true && morphAttributes.normal ) geometry.addAttribute( 'morphNormal' + i, morphAttributes.normal[ index ] );
  16778. } else {
  16779. if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i );
  16780. if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i );
  16781. }
  16782. }
  16783. for ( var i = activeInfluences.length, il = morphInfluences.length; i < il; i ++ ) {
  16784. morphInfluences[ i ] = 0.0;
  16785. }
  16786. program.getUniforms().setValue(
  16787. _gl, 'morphTargetInfluences', morphInfluences );
  16788. updateBuffers = true;
  16789. }
  16790. //
  16791. var index = geometry.index;
  16792. var position = geometry.attributes.position;
  16793. var rangeFactor = 1;
  16794. if ( material.wireframe === true ) {
  16795. index = objects.getWireframeAttribute( geometry );
  16796. rangeFactor = 2;
  16797. }
  16798. var renderer;
  16799. if ( index !== null ) {
  16800. renderer = indexedBufferRenderer;
  16801. renderer.setIndex( index );
  16802. } else {
  16803. renderer = bufferRenderer;
  16804. }
  16805. if ( updateBuffers ) {
  16806. setupVertexAttributes( material, program, geometry );
  16807. if ( index !== null ) {
  16808. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, objects.getAttributeBuffer( index ) );
  16809. }
  16810. }
  16811. //
  16812. var dataCount = 0;
  16813. if ( index !== null ) {
  16814. dataCount = index.count;
  16815. } else if ( position !== undefined ) {
  16816. dataCount = position.count;
  16817. }
  16818. var rangeStart = geometry.drawRange.start * rangeFactor;
  16819. var rangeCount = geometry.drawRange.count * rangeFactor;
  16820. var groupStart = group !== null ? group.start * rangeFactor : 0;
  16821. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  16822. var drawStart = Math.max( rangeStart, groupStart );
  16823. var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  16824. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  16825. if ( drawCount === 0 ) return;
  16826. //
  16827. if ( object.isMesh ) {
  16828. if ( material.wireframe === true ) {
  16829. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  16830. renderer.setMode( _gl.LINES );
  16831. } else {
  16832. switch ( object.drawMode ) {
  16833. case TrianglesDrawMode:
  16834. renderer.setMode( _gl.TRIANGLES );
  16835. break;
  16836. case TriangleStripDrawMode:
  16837. renderer.setMode( _gl.TRIANGLE_STRIP );
  16838. break;
  16839. case TriangleFanDrawMode:
  16840. renderer.setMode( _gl.TRIANGLE_FAN );
  16841. break;
  16842. }
  16843. }
  16844. } else if ( object.isLine ) {
  16845. var lineWidth = material.linewidth;
  16846. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  16847. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  16848. if ( object.isLineSegments ) {
  16849. renderer.setMode( _gl.LINES );
  16850. } else {
  16851. renderer.setMode( _gl.LINE_STRIP );
  16852. }
  16853. } else if ( object.isPoints ) {
  16854. renderer.setMode( _gl.POINTS );
  16855. }
  16856. if ( geometry && geometry.isInstancedBufferGeometry ) {
  16857. if ( geometry.maxInstancedCount > 0 ) {
  16858. renderer.renderInstances( geometry, drawStart, drawCount );
  16859. }
  16860. } else {
  16861. renderer.render( drawStart, drawCount );
  16862. }
  16863. };
  16864. function setupVertexAttributes( material, program, geometry, startIndex ) {
  16865. var extension;
  16866. if ( geometry && geometry.isInstancedBufferGeometry ) {
  16867. extension = extensions.get( 'ANGLE_instanced_arrays' );
  16868. if ( extension === null ) {
  16869. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  16870. return;
  16871. }
  16872. }
  16873. if ( startIndex === undefined ) startIndex = 0;
  16874. state.initAttributes();
  16875. var geometryAttributes = geometry.attributes;
  16876. var programAttributes = program.getAttributes();
  16877. var materialDefaultAttributeValues = material.defaultAttributeValues;
  16878. for ( var name in programAttributes ) {
  16879. var programAttribute = programAttributes[ name ];
  16880. if ( programAttribute >= 0 ) {
  16881. var geometryAttribute = geometryAttributes[ name ];
  16882. if ( geometryAttribute !== undefined ) {
  16883. var normalized = geometryAttribute.normalized;
  16884. var size = geometryAttribute.itemSize;
  16885. var attributeProperties = objects.getAttributeProperties( geometryAttribute );
  16886. var buffer = attributeProperties.__webglBuffer;
  16887. var type = attributeProperties.type;
  16888. var bytesPerElement = attributeProperties.bytesPerElement;
  16889. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  16890. var data = geometryAttribute.data;
  16891. var stride = data.stride;
  16892. var offset = geometryAttribute.offset;
  16893. if ( data && data.isInstancedInterleavedBuffer ) {
  16894. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute, extension );
  16895. if ( geometry.maxInstancedCount === undefined ) {
  16896. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  16897. }
  16898. } else {
  16899. state.enableAttribute( programAttribute );
  16900. }
  16901. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  16902. _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, ( startIndex * stride + offset ) * bytesPerElement );
  16903. } else {
  16904. if ( geometryAttribute.isInstancedBufferAttribute ) {
  16905. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute, extension );
  16906. if ( geometry.maxInstancedCount === undefined ) {
  16907. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  16908. }
  16909. } else {
  16910. state.enableAttribute( programAttribute );
  16911. }
  16912. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  16913. _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * bytesPerElement );
  16914. }
  16915. } else if ( materialDefaultAttributeValues !== undefined ) {
  16916. var value = materialDefaultAttributeValues[ name ];
  16917. if ( value !== undefined ) {
  16918. switch ( value.length ) {
  16919. case 2:
  16920. _gl.vertexAttrib2fv( programAttribute, value );
  16921. break;
  16922. case 3:
  16923. _gl.vertexAttrib3fv( programAttribute, value );
  16924. break;
  16925. case 4:
  16926. _gl.vertexAttrib4fv( programAttribute, value );
  16927. break;
  16928. default:
  16929. _gl.vertexAttrib1fv( programAttribute, value );
  16930. }
  16931. }
  16932. }
  16933. }
  16934. }
  16935. state.disableUnusedAttributes();
  16936. }
  16937. // Sorting
  16938. function absNumericalSort( a, b ) {
  16939. return Math.abs( b[ 0 ] ) - Math.abs( a[ 0 ] );
  16940. }
  16941. function painterSortStable( a, b ) {
  16942. if ( a.object.renderOrder !== b.object.renderOrder ) {
  16943. return a.object.renderOrder - b.object.renderOrder;
  16944. } else if ( a.material.program && b.material.program && a.material.program !== b.material.program ) {
  16945. return a.material.program.id - b.material.program.id;
  16946. } else if ( a.material.id !== b.material.id ) {
  16947. return a.material.id - b.material.id;
  16948. } else if ( a.z !== b.z ) {
  16949. return a.z - b.z;
  16950. } else {
  16951. return a.id - b.id;
  16952. }
  16953. }
  16954. function reversePainterSortStable( a, b ) {
  16955. if ( a.object.renderOrder !== b.object.renderOrder ) {
  16956. return a.object.renderOrder - b.object.renderOrder;
  16957. } if ( a.z !== b.z ) {
  16958. return b.z - a.z;
  16959. } else {
  16960. return a.id - b.id;
  16961. }
  16962. }
  16963. // Rendering
  16964. this.render = function ( scene, camera, renderTarget, forceClear ) {
  16965. if ( camera !== undefined && camera.isCamera !== true ) {
  16966. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  16967. return;
  16968. }
  16969. // reset caching for this frame
  16970. _currentGeometryProgram = '';
  16971. _currentMaterialId = - 1;
  16972. _currentCamera = null;
  16973. // update scene graph
  16974. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  16975. // update camera matrices and frustum
  16976. if ( camera.parent === null ) camera.updateMatrixWorld();
  16977. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  16978. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  16979. _frustum.setFromMatrix( _projScreenMatrix );
  16980. lights.length = 0;
  16981. opaqueObjectsLastIndex = - 1;
  16982. transparentObjectsLastIndex = - 1;
  16983. sprites.length = 0;
  16984. lensFlares.length = 0;
  16985. _localClippingEnabled = this.localClippingEnabled;
  16986. _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  16987. projectObject( scene, camera );
  16988. opaqueObjects.length = opaqueObjectsLastIndex + 1;
  16989. transparentObjects.length = transparentObjectsLastIndex + 1;
  16990. if ( _this.sortObjects === true ) {
  16991. opaqueObjects.sort( painterSortStable );
  16992. transparentObjects.sort( reversePainterSortStable );
  16993. }
  16994. //
  16995. if ( _clippingEnabled ) _clipping.beginShadows();
  16996. setupShadows( lights );
  16997. shadowMap.render( scene, camera );
  16998. setupLights( lights, camera );
  16999. if ( _clippingEnabled ) _clipping.endShadows();
  17000. //
  17001. _infoRender.calls = 0;
  17002. _infoRender.vertices = 0;
  17003. _infoRender.faces = 0;
  17004. _infoRender.points = 0;
  17005. if ( renderTarget === undefined ) {
  17006. renderTarget = null;
  17007. }
  17008. this.setRenderTarget( renderTarget );
  17009. //
  17010. var background = scene.background;
  17011. if ( background === null ) {
  17012. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  17013. } else if ( background && background.isColor ) {
  17014. state.buffers.color.setClear( background.r, background.g, background.b, 1, _premultipliedAlpha );
  17015. forceClear = true;
  17016. }
  17017. if ( this.autoClear || forceClear ) {
  17018. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  17019. }
  17020. if ( background && background.isCubeTexture ) {
  17021. if ( backgroundBoxCamera === undefined ) {
  17022. backgroundBoxCamera = new PerspectiveCamera();
  17023. backgroundBoxMesh = new Mesh(
  17024. new BoxBufferGeometry( 5, 5, 5 ),
  17025. new ShaderMaterial( {
  17026. uniforms: ShaderLib.cube.uniforms,
  17027. vertexShader: ShaderLib.cube.vertexShader,
  17028. fragmentShader: ShaderLib.cube.fragmentShader,
  17029. side: BackSide,
  17030. depthTest: false,
  17031. depthWrite: false,
  17032. fog: false
  17033. } )
  17034. );
  17035. }
  17036. backgroundBoxCamera.projectionMatrix.copy( camera.projectionMatrix );
  17037. backgroundBoxCamera.matrixWorld.extractRotation( camera.matrixWorld );
  17038. backgroundBoxCamera.matrixWorldInverse.getInverse( backgroundBoxCamera.matrixWorld );
  17039. backgroundBoxMesh.material.uniforms[ "tCube" ].value = background;
  17040. backgroundBoxMesh.modelViewMatrix.multiplyMatrices( backgroundBoxCamera.matrixWorldInverse, backgroundBoxMesh.matrixWorld );
  17041. objects.update( backgroundBoxMesh );
  17042. _this.renderBufferDirect( backgroundBoxCamera, null, backgroundBoxMesh.geometry, backgroundBoxMesh.material, backgroundBoxMesh, null );
  17043. } else if ( background && background.isTexture ) {
  17044. if ( backgroundPlaneCamera === undefined ) {
  17045. backgroundPlaneCamera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  17046. backgroundPlaneMesh = new Mesh(
  17047. new PlaneBufferGeometry( 2, 2 ),
  17048. new MeshBasicMaterial( { depthTest: false, depthWrite: false, fog: false } )
  17049. );
  17050. }
  17051. backgroundPlaneMesh.material.map = background;
  17052. objects.update( backgroundPlaneMesh );
  17053. _this.renderBufferDirect( backgroundPlaneCamera, null, backgroundPlaneMesh.geometry, backgroundPlaneMesh.material, backgroundPlaneMesh, null );
  17054. }
  17055. //
  17056. if ( scene.overrideMaterial ) {
  17057. var overrideMaterial = scene.overrideMaterial;
  17058. renderObjects( opaqueObjects, scene, camera, overrideMaterial );
  17059. renderObjects( transparentObjects, scene, camera, overrideMaterial );
  17060. } else {
  17061. // opaque pass (front-to-back order)
  17062. state.setBlending( NoBlending );
  17063. renderObjects( opaqueObjects, scene, camera );
  17064. // transparent pass (back-to-front order)
  17065. renderObjects( transparentObjects, scene, camera );
  17066. }
  17067. // custom render plugins (post pass)
  17068. spritePlugin.render( scene, camera );
  17069. lensFlarePlugin.render( scene, camera, _currentViewport );
  17070. // Generate mipmap if we're using any kind of mipmap filtering
  17071. if ( renderTarget ) {
  17072. textures.updateRenderTargetMipmap( renderTarget );
  17073. }
  17074. // Ensure depth buffer writing is enabled so it can be cleared on next render
  17075. state.setDepthTest( true );
  17076. state.setDepthWrite( true );
  17077. state.setColorWrite( true );
  17078. // _gl.finish();
  17079. };
  17080. function pushRenderItem( object, geometry, material, z, group ) {
  17081. var array, index;
  17082. // allocate the next position in the appropriate array
  17083. if ( material.transparent ) {
  17084. array = transparentObjects;
  17085. index = ++ transparentObjectsLastIndex;
  17086. } else {
  17087. array = opaqueObjects;
  17088. index = ++ opaqueObjectsLastIndex;
  17089. }
  17090. // recycle existing render item or grow the array
  17091. var renderItem = array[ index ];
  17092. if ( renderItem !== undefined ) {
  17093. renderItem.id = object.id;
  17094. renderItem.object = object;
  17095. renderItem.geometry = geometry;
  17096. renderItem.material = material;
  17097. renderItem.z = _vector3.z;
  17098. renderItem.group = group;
  17099. } else {
  17100. renderItem = {
  17101. id: object.id,
  17102. object: object,
  17103. geometry: geometry,
  17104. material: material,
  17105. z: _vector3.z,
  17106. group: group
  17107. };
  17108. // assert( index === array.length );
  17109. array.push( renderItem );
  17110. }
  17111. }
  17112. // TODO Duplicated code (Frustum)
  17113. function isObjectViewable( object ) {
  17114. var geometry = object.geometry;
  17115. if ( geometry.boundingSphere === null )
  17116. geometry.computeBoundingSphere();
  17117. _sphere.copy( geometry.boundingSphere ).
  17118. applyMatrix4( object.matrixWorld );
  17119. return isSphereViewable( _sphere );
  17120. }
  17121. function isSpriteViewable( sprite ) {
  17122. _sphere.center.set( 0, 0, 0 );
  17123. _sphere.radius = 0.7071067811865476;
  17124. _sphere.applyMatrix4( sprite.matrixWorld );
  17125. return isSphereViewable( _sphere );
  17126. }
  17127. function isSphereViewable( sphere ) {
  17128. if ( ! _frustum.intersectsSphere( sphere ) ) return false;
  17129. var numPlanes = _clipping.numPlanes;
  17130. if ( numPlanes === 0 ) return true;
  17131. var planes = _this.clippingPlanes,
  17132. center = sphere.center,
  17133. negRad = - sphere.radius,
  17134. i = 0;
  17135. do {
  17136. // out when deeper than radius in the negative halfspace
  17137. if ( planes[ i ].distanceToPoint( center ) < negRad ) return false;
  17138. } while ( ++ i !== numPlanes );
  17139. return true;
  17140. }
  17141. function projectObject( object, camera ) {
  17142. if ( object.visible === false ) return;
  17143. var visible = ( object.layers.mask & camera.layers.mask ) !== 0;
  17144. if ( visible ) {
  17145. if ( object.isLight ) {
  17146. lights.push( object );
  17147. } else if ( object.isSprite ) {
  17148. if ( object.frustumCulled === false || isSpriteViewable( object ) === true ) {
  17149. sprites.push( object );
  17150. }
  17151. } else if ( object.isLensFlare ) {
  17152. lensFlares.push( object );
  17153. } else if ( object.isImmediateRenderObject ) {
  17154. if ( _this.sortObjects === true ) {
  17155. _vector3.setFromMatrixPosition( object.matrixWorld );
  17156. _vector3.applyMatrix4( _projScreenMatrix );
  17157. }
  17158. pushRenderItem( object, null, object.material, _vector3.z, null );
  17159. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  17160. if ( object.isSkinnedMesh ) {
  17161. object.skeleton.update();
  17162. }
  17163. if ( object.frustumCulled === false || isObjectViewable( object ) === true ) {
  17164. var material = object.material;
  17165. if ( material.visible === true ) {
  17166. if ( _this.sortObjects === true ) {
  17167. _vector3.setFromMatrixPosition( object.matrixWorld );
  17168. _vector3.applyMatrix4( _projScreenMatrix );
  17169. }
  17170. var geometry = objects.update( object );
  17171. if ( material.isMultiMaterial ) {
  17172. var groups = geometry.groups;
  17173. var materials = material.materials;
  17174. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  17175. var group = groups[ i ];
  17176. var groupMaterial = materials[ group.materialIndex ];
  17177. if ( groupMaterial.visible === true ) {
  17178. pushRenderItem( object, geometry, groupMaterial, _vector3.z, group );
  17179. }
  17180. }
  17181. } else {
  17182. pushRenderItem( object, geometry, material, _vector3.z, null );
  17183. }
  17184. }
  17185. }
  17186. }
  17187. }
  17188. var children = object.children;
  17189. for ( var i = 0, l = children.length; i < l; i ++ ) {
  17190. projectObject( children[ i ], camera );
  17191. }
  17192. }
  17193. function renderObjects( renderList, scene, camera, overrideMaterial ) {
  17194. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  17195. var renderItem = renderList[ i ];
  17196. var object = renderItem.object;
  17197. var geometry = renderItem.geometry;
  17198. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  17199. var group = renderItem.group;
  17200. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  17201. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  17202. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  17203. if ( object.isImmediateRenderObject ) {
  17204. setMaterial( material );
  17205. var program = setProgram( camera, scene.fog, material, object );
  17206. _currentGeometryProgram = '';
  17207. object.render( function ( object ) {
  17208. _this.renderBufferImmediate( object, program, material );
  17209. } );
  17210. } else {
  17211. _this.renderBufferDirect( camera, scene.fog, geometry, material, object, group );
  17212. }
  17213. object.onAfterRender( _this, scene, camera, geometry, material, group );
  17214. }
  17215. }
  17216. function initMaterial( material, fog, object ) {
  17217. var materialProperties = properties.get( material );
  17218. var parameters = programCache.getParameters(
  17219. material, _lights, fog, _clipping.numPlanes, _clipping.numIntersection, object );
  17220. var code = programCache.getProgramCode( material, parameters );
  17221. var program = materialProperties.program;
  17222. var programChange = true;
  17223. if ( program === undefined ) {
  17224. // new material
  17225. material.addEventListener( 'dispose', onMaterialDispose );
  17226. } else if ( program.code !== code ) {
  17227. // changed glsl or parameters
  17228. releaseMaterialProgramReference( material );
  17229. } else if ( parameters.shaderID !== undefined ) {
  17230. // same glsl and uniform list
  17231. return;
  17232. } else {
  17233. // only rebuild uniform list
  17234. programChange = false;
  17235. }
  17236. if ( programChange ) {
  17237. if ( parameters.shaderID ) {
  17238. var shader = ShaderLib[ parameters.shaderID ];
  17239. materialProperties.__webglShader = {
  17240. name: material.type,
  17241. uniforms: UniformsUtils.clone( shader.uniforms ),
  17242. vertexShader: shader.vertexShader,
  17243. fragmentShader: shader.fragmentShader
  17244. };
  17245. } else {
  17246. materialProperties.__webglShader = {
  17247. name: material.type,
  17248. uniforms: material.uniforms,
  17249. vertexShader: material.vertexShader,
  17250. fragmentShader: material.fragmentShader
  17251. };
  17252. }
  17253. material.__webglShader = materialProperties.__webglShader;
  17254. program = programCache.acquireProgram( material, parameters, code );
  17255. materialProperties.program = program;
  17256. material.program = program;
  17257. }
  17258. var attributes = program.getAttributes();
  17259. if ( material.morphTargets ) {
  17260. material.numSupportedMorphTargets = 0;
  17261. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  17262. if ( attributes[ 'morphTarget' + i ] >= 0 ) {
  17263. material.numSupportedMorphTargets ++;
  17264. }
  17265. }
  17266. }
  17267. if ( material.morphNormals ) {
  17268. material.numSupportedMorphNormals = 0;
  17269. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  17270. if ( attributes[ 'morphNormal' + i ] >= 0 ) {
  17271. material.numSupportedMorphNormals ++;
  17272. }
  17273. }
  17274. }
  17275. var uniforms = materialProperties.__webglShader.uniforms;
  17276. if ( ! material.isShaderMaterial &&
  17277. ! material.isRawShaderMaterial ||
  17278. material.clipping === true ) {
  17279. materialProperties.numClippingPlanes = _clipping.numPlanes;
  17280. materialProperties.numIntersection = _clipping.numIntersection;
  17281. uniforms.clippingPlanes = _clipping.uniform;
  17282. }
  17283. materialProperties.fog = fog;
  17284. // store the light setup it was created for
  17285. materialProperties.lightsHash = _lights.hash;
  17286. if ( material.lights ) {
  17287. // wire up the material to this renderer's lighting state
  17288. uniforms.ambientLightColor.value = _lights.ambient;
  17289. uniforms.directionalLights.value = _lights.directional;
  17290. uniforms.spotLights.value = _lights.spot;
  17291. uniforms.rectAreaLights.value = _lights.rectArea;
  17292. uniforms.pointLights.value = _lights.point;
  17293. uniforms.hemisphereLights.value = _lights.hemi;
  17294. uniforms.directionalShadowMap.value = _lights.directionalShadowMap;
  17295. uniforms.directionalShadowMatrix.value = _lights.directionalShadowMatrix;
  17296. uniforms.spotShadowMap.value = _lights.spotShadowMap;
  17297. uniforms.spotShadowMatrix.value = _lights.spotShadowMatrix;
  17298. uniforms.pointShadowMap.value = _lights.pointShadowMap;
  17299. uniforms.pointShadowMatrix.value = _lights.pointShadowMatrix;
  17300. // TODO (abelnation): add area lights shadow info to uniforms
  17301. }
  17302. var progUniforms = materialProperties.program.getUniforms(),
  17303. uniformsList =
  17304. WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  17305. materialProperties.uniformsList = uniformsList;
  17306. }
  17307. function setMaterial( material ) {
  17308. material.side === DoubleSide
  17309. ? state.disable( _gl.CULL_FACE )
  17310. : state.enable( _gl.CULL_FACE );
  17311. state.setFlipSided( material.side === BackSide );
  17312. material.transparent === true
  17313. ? state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha )
  17314. : state.setBlending( NoBlending );
  17315. state.setDepthFunc( material.depthFunc );
  17316. state.setDepthTest( material.depthTest );
  17317. state.setDepthWrite( material.depthWrite );
  17318. state.setColorWrite( material.colorWrite );
  17319. state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  17320. }
  17321. function setProgram( camera, fog, material, object ) {
  17322. _usedTextureUnits = 0;
  17323. var materialProperties = properties.get( material );
  17324. if ( _clippingEnabled ) {
  17325. if ( _localClippingEnabled || camera !== _currentCamera ) {
  17326. var useCache =
  17327. camera === _currentCamera &&
  17328. material.id === _currentMaterialId;
  17329. // we might want to call this function with some ClippingGroup
  17330. // object instead of the material, once it becomes feasible
  17331. // (#8465, #8379)
  17332. _clipping.setState(
  17333. material.clippingPlanes, material.clipIntersection, material.clipShadows,
  17334. camera, materialProperties, useCache );
  17335. }
  17336. }
  17337. if ( material.needsUpdate === false ) {
  17338. if ( materialProperties.program === undefined ) {
  17339. material.needsUpdate = true;
  17340. } else if ( material.fog && materialProperties.fog !== fog ) {
  17341. material.needsUpdate = true;
  17342. } else if ( material.lights && materialProperties.lightsHash !== _lights.hash ) {
  17343. material.needsUpdate = true;
  17344. } else if ( materialProperties.numClippingPlanes !== undefined &&
  17345. ( materialProperties.numClippingPlanes !== _clipping.numPlanes ||
  17346. materialProperties.numIntersection !== _clipping.numIntersection ) ) {
  17347. material.needsUpdate = true;
  17348. }
  17349. }
  17350. if ( material.needsUpdate ) {
  17351. initMaterial( material, fog, object );
  17352. material.needsUpdate = false;
  17353. }
  17354. var refreshProgram = false;
  17355. var refreshMaterial = false;
  17356. var refreshLights = false;
  17357. var program = materialProperties.program,
  17358. p_uniforms = program.getUniforms(),
  17359. m_uniforms = materialProperties.__webglShader.uniforms;
  17360. if ( program.id !== _currentProgram ) {
  17361. _gl.useProgram( program.program );
  17362. _currentProgram = program.id;
  17363. refreshProgram = true;
  17364. refreshMaterial = true;
  17365. refreshLights = true;
  17366. }
  17367. if ( material.id !== _currentMaterialId ) {
  17368. _currentMaterialId = material.id;
  17369. refreshMaterial = true;
  17370. }
  17371. if ( refreshProgram || camera !== _currentCamera ) {
  17372. p_uniforms.set( _gl, camera, 'projectionMatrix' );
  17373. if ( capabilities.logarithmicDepthBuffer ) {
  17374. p_uniforms.setValue( _gl, 'logDepthBufFC',
  17375. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  17376. }
  17377. if ( camera !== _currentCamera ) {
  17378. _currentCamera = camera;
  17379. // lighting uniforms depend on the camera so enforce an update
  17380. // now, in case this material supports lights - or later, when
  17381. // the next material that does gets activated:
  17382. refreshMaterial = true; // set to true on material change
  17383. refreshLights = true; // remains set until update done
  17384. }
  17385. // load material specific uniforms
  17386. // (shader material also gets them for the sake of genericity)
  17387. if ( material.isShaderMaterial ||
  17388. material.isMeshPhongMaterial ||
  17389. material.isMeshStandardMaterial ||
  17390. material.envMap ) {
  17391. var uCamPos = p_uniforms.map.cameraPosition;
  17392. if ( uCamPos !== undefined ) {
  17393. uCamPos.setValue( _gl,
  17394. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  17395. }
  17396. }
  17397. if ( material.isMeshPhongMaterial ||
  17398. material.isMeshLambertMaterial ||
  17399. material.isMeshBasicMaterial ||
  17400. material.isMeshStandardMaterial ||
  17401. material.isShaderMaterial ||
  17402. material.skinning ) {
  17403. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  17404. }
  17405. p_uniforms.set( _gl, _this, 'toneMappingExposure' );
  17406. p_uniforms.set( _gl, _this, 'toneMappingWhitePoint' );
  17407. }
  17408. // skinning uniforms must be set even if material didn't change
  17409. // auto-setting of texture unit for bone texture must go before other textures
  17410. // not sure why, but otherwise weird things happen
  17411. if ( material.skinning ) {
  17412. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  17413. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  17414. var skeleton = object.skeleton;
  17415. if ( skeleton ) {
  17416. if ( capabilities.floatVertexTextures && skeleton.useVertexTexture ) {
  17417. p_uniforms.set( _gl, skeleton, 'boneTexture' );
  17418. p_uniforms.set( _gl, skeleton, 'boneTextureWidth' );
  17419. p_uniforms.set( _gl, skeleton, 'boneTextureHeight' );
  17420. } else {
  17421. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  17422. }
  17423. }
  17424. }
  17425. if ( refreshMaterial ) {
  17426. if ( material.lights ) {
  17427. // the current material requires lighting info
  17428. // note: all lighting uniforms are always set correctly
  17429. // they simply reference the renderer's state for their
  17430. // values
  17431. //
  17432. // use the current material's .needsUpdate flags to set
  17433. // the GL state when required
  17434. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  17435. }
  17436. // refresh uniforms common to several materials
  17437. if ( fog && material.fog ) {
  17438. refreshUniformsFog( m_uniforms, fog );
  17439. }
  17440. if ( material.isMeshBasicMaterial ||
  17441. material.isMeshLambertMaterial ||
  17442. material.isMeshPhongMaterial ||
  17443. material.isMeshStandardMaterial ||
  17444. material.isMeshNormalMaterial ||
  17445. material.isMeshDepthMaterial ) {
  17446. refreshUniformsCommon( m_uniforms, material );
  17447. }
  17448. // refresh single material specific uniforms
  17449. if ( material.isLineBasicMaterial ) {
  17450. refreshUniformsLine( m_uniforms, material );
  17451. } else if ( material.isLineDashedMaterial ) {
  17452. refreshUniformsLine( m_uniforms, material );
  17453. refreshUniformsDash( m_uniforms, material );
  17454. } else if ( material.isPointsMaterial ) {
  17455. refreshUniformsPoints( m_uniforms, material );
  17456. } else if ( material.isMeshLambertMaterial ) {
  17457. refreshUniformsLambert( m_uniforms, material );
  17458. } else if ( material.isMeshToonMaterial ) {
  17459. refreshUniformsToon( m_uniforms, material );
  17460. } else if ( material.isMeshPhongMaterial ) {
  17461. refreshUniformsPhong( m_uniforms, material );
  17462. } else if ( material.isMeshPhysicalMaterial ) {
  17463. refreshUniformsPhysical( m_uniforms, material );
  17464. } else if ( material.isMeshStandardMaterial ) {
  17465. refreshUniformsStandard( m_uniforms, material );
  17466. } else if ( material.isMeshDepthMaterial ) {
  17467. if ( material.displacementMap ) {
  17468. m_uniforms.displacementMap.value = material.displacementMap;
  17469. m_uniforms.displacementScale.value = material.displacementScale;
  17470. m_uniforms.displacementBias.value = material.displacementBias;
  17471. }
  17472. } else if ( material.isMeshNormalMaterial ) {
  17473. refreshUniformsNormal( m_uniforms, material );
  17474. }
  17475. // RectAreaLight Texture
  17476. // TODO (mrdoob): Find a nicer implementation
  17477. if ( m_uniforms.ltcMat !== undefined ) m_uniforms.ltcMat.value = THREE.UniformsLib.LTC_MAT_TEXTURE;
  17478. if ( m_uniforms.ltcMag !== undefined ) m_uniforms.ltcMag.value = THREE.UniformsLib.LTC_MAG_TEXTURE;
  17479. WebGLUniforms.upload(
  17480. _gl, materialProperties.uniformsList, m_uniforms, _this );
  17481. }
  17482. // common matrices
  17483. p_uniforms.set( _gl, object, 'modelViewMatrix' );
  17484. p_uniforms.set( _gl, object, 'normalMatrix' );
  17485. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  17486. return program;
  17487. }
  17488. // Uniforms (refresh uniforms objects)
  17489. function refreshUniformsCommon( uniforms, material ) {
  17490. uniforms.opacity.value = material.opacity;
  17491. uniforms.diffuse.value = material.color;
  17492. if ( material.emissive ) {
  17493. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  17494. }
  17495. uniforms.map.value = material.map;
  17496. uniforms.specularMap.value = material.specularMap;
  17497. uniforms.alphaMap.value = material.alphaMap;
  17498. if ( material.lightMap ) {
  17499. uniforms.lightMap.value = material.lightMap;
  17500. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  17501. }
  17502. if ( material.aoMap ) {
  17503. uniforms.aoMap.value = material.aoMap;
  17504. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  17505. }
  17506. // uv repeat and offset setting priorities
  17507. // 1. color map
  17508. // 2. specular map
  17509. // 3. normal map
  17510. // 4. bump map
  17511. // 5. alpha map
  17512. // 6. emissive map
  17513. var uvScaleMap;
  17514. if ( material.map ) {
  17515. uvScaleMap = material.map;
  17516. } else if ( material.specularMap ) {
  17517. uvScaleMap = material.specularMap;
  17518. } else if ( material.displacementMap ) {
  17519. uvScaleMap = material.displacementMap;
  17520. } else if ( material.normalMap ) {
  17521. uvScaleMap = material.normalMap;
  17522. } else if ( material.bumpMap ) {
  17523. uvScaleMap = material.bumpMap;
  17524. } else if ( material.roughnessMap ) {
  17525. uvScaleMap = material.roughnessMap;
  17526. } else if ( material.metalnessMap ) {
  17527. uvScaleMap = material.metalnessMap;
  17528. } else if ( material.alphaMap ) {
  17529. uvScaleMap = material.alphaMap;
  17530. } else if ( material.emissiveMap ) {
  17531. uvScaleMap = material.emissiveMap;
  17532. }
  17533. if ( uvScaleMap !== undefined ) {
  17534. // backwards compatibility
  17535. if ( uvScaleMap.isWebGLRenderTarget ) {
  17536. uvScaleMap = uvScaleMap.texture;
  17537. }
  17538. var offset = uvScaleMap.offset;
  17539. var repeat = uvScaleMap.repeat;
  17540. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  17541. }
  17542. uniforms.envMap.value = material.envMap;
  17543. // don't flip CubeTexture envMaps, flip everything else:
  17544. // WebGLRenderTargetCube will be flipped for backwards compatibility
  17545. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  17546. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  17547. uniforms.flipEnvMap.value = ( ! ( material.envMap && material.envMap.isCubeTexture ) ) ? 1 : - 1;
  17548. uniforms.reflectivity.value = material.reflectivity;
  17549. uniforms.refractionRatio.value = material.refractionRatio;
  17550. }
  17551. function refreshUniformsLine( uniforms, material ) {
  17552. uniforms.diffuse.value = material.color;
  17553. uniforms.opacity.value = material.opacity;
  17554. }
  17555. function refreshUniformsDash( uniforms, material ) {
  17556. uniforms.dashSize.value = material.dashSize;
  17557. uniforms.totalSize.value = material.dashSize + material.gapSize;
  17558. uniforms.scale.value = material.scale;
  17559. }
  17560. function refreshUniformsPoints( uniforms, material ) {
  17561. uniforms.diffuse.value = material.color;
  17562. uniforms.opacity.value = material.opacity;
  17563. uniforms.size.value = material.size * _pixelRatio;
  17564. uniforms.scale.value = _height * 0.5;
  17565. uniforms.map.value = material.map;
  17566. if ( material.map !== null ) {
  17567. var offset = material.map.offset;
  17568. var repeat = material.map.repeat;
  17569. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  17570. }
  17571. }
  17572. function refreshUniformsFog( uniforms, fog ) {
  17573. uniforms.fogColor.value = fog.color;
  17574. if ( fog.isFog ) {
  17575. uniforms.fogNear.value = fog.near;
  17576. uniforms.fogFar.value = fog.far;
  17577. } else if ( fog.isFogExp2 ) {
  17578. uniforms.fogDensity.value = fog.density;
  17579. }
  17580. }
  17581. function refreshUniformsLambert( uniforms, material ) {
  17582. if ( material.emissiveMap ) {
  17583. uniforms.emissiveMap.value = material.emissiveMap;
  17584. }
  17585. }
  17586. function refreshUniformsPhong( uniforms, material ) {
  17587. uniforms.specular.value = material.specular;
  17588. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  17589. if ( material.emissiveMap ) {
  17590. uniforms.emissiveMap.value = material.emissiveMap;
  17591. }
  17592. if ( material.bumpMap ) {
  17593. uniforms.bumpMap.value = material.bumpMap;
  17594. uniforms.bumpScale.value = material.bumpScale;
  17595. }
  17596. if ( material.normalMap ) {
  17597. uniforms.normalMap.value = material.normalMap;
  17598. uniforms.normalScale.value.copy( material.normalScale );
  17599. }
  17600. if ( material.displacementMap ) {
  17601. uniforms.displacementMap.value = material.displacementMap;
  17602. uniforms.displacementScale.value = material.displacementScale;
  17603. uniforms.displacementBias.value = material.displacementBias;
  17604. }
  17605. }
  17606. function refreshUniformsToon( uniforms, material ) {
  17607. refreshUniformsPhong( uniforms, material );
  17608. if ( material.gradientMap ) {
  17609. uniforms.gradientMap.value = material.gradientMap;
  17610. }
  17611. }
  17612. function refreshUniformsStandard( uniforms, material ) {
  17613. uniforms.roughness.value = material.roughness;
  17614. uniforms.metalness.value = material.metalness;
  17615. if ( material.roughnessMap ) {
  17616. uniforms.roughnessMap.value = material.roughnessMap;
  17617. }
  17618. if ( material.metalnessMap ) {
  17619. uniforms.metalnessMap.value = material.metalnessMap;
  17620. }
  17621. if ( material.emissiveMap ) {
  17622. uniforms.emissiveMap.value = material.emissiveMap;
  17623. }
  17624. if ( material.bumpMap ) {
  17625. uniforms.bumpMap.value = material.bumpMap;
  17626. uniforms.bumpScale.value = material.bumpScale;
  17627. }
  17628. if ( material.normalMap ) {
  17629. uniforms.normalMap.value = material.normalMap;
  17630. uniforms.normalScale.value.copy( material.normalScale );
  17631. }
  17632. if ( material.displacementMap ) {
  17633. uniforms.displacementMap.value = material.displacementMap;
  17634. uniforms.displacementScale.value = material.displacementScale;
  17635. uniforms.displacementBias.value = material.displacementBias;
  17636. }
  17637. if ( material.envMap ) {
  17638. //uniforms.envMap.value = material.envMap; // part of uniforms common
  17639. uniforms.envMapIntensity.value = material.envMapIntensity;
  17640. }
  17641. }
  17642. function refreshUniformsPhysical( uniforms, material ) {
  17643. uniforms.clearCoat.value = material.clearCoat;
  17644. uniforms.clearCoatRoughness.value = material.clearCoatRoughness;
  17645. refreshUniformsStandard( uniforms, material );
  17646. }
  17647. function refreshUniformsNormal( uniforms, material ) {
  17648. if ( material.bumpMap ) {
  17649. uniforms.bumpMap.value = material.bumpMap;
  17650. uniforms.bumpScale.value = material.bumpScale;
  17651. }
  17652. if ( material.normalMap ) {
  17653. uniforms.normalMap.value = material.normalMap;
  17654. uniforms.normalScale.value.copy( material.normalScale );
  17655. }
  17656. if ( material.displacementMap ) {
  17657. uniforms.displacementMap.value = material.displacementMap;
  17658. uniforms.displacementScale.value = material.displacementScale;
  17659. uniforms.displacementBias.value = material.displacementBias;
  17660. }
  17661. }
  17662. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  17663. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  17664. uniforms.ambientLightColor.needsUpdate = value;
  17665. uniforms.directionalLights.needsUpdate = value;
  17666. uniforms.pointLights.needsUpdate = value;
  17667. uniforms.spotLights.needsUpdate = value;
  17668. uniforms.rectAreaLights.needsUpdate = value;
  17669. uniforms.hemisphereLights.needsUpdate = value;
  17670. }
  17671. // Lighting
  17672. function setupShadows( lights ) {
  17673. var lightShadowsLength = 0;
  17674. for ( var i = 0, l = lights.length; i < l; i ++ ) {
  17675. var light = lights[ i ];
  17676. if ( light.castShadow ) {
  17677. _lights.shadows[ lightShadowsLength ++ ] = light;
  17678. }
  17679. }
  17680. _lights.shadows.length = lightShadowsLength;
  17681. }
  17682. function setupLights( lights, camera ) {
  17683. var l, ll, light,
  17684. r = 0, g = 0, b = 0,
  17685. color,
  17686. intensity,
  17687. distance,
  17688. shadowMap,
  17689. viewMatrix = camera.matrixWorldInverse,
  17690. directionalLength = 0,
  17691. pointLength = 0,
  17692. spotLength = 0,
  17693. rectAreaLength = 0,
  17694. hemiLength = 0;
  17695. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  17696. light = lights[ l ];
  17697. color = light.color;
  17698. intensity = light.intensity;
  17699. distance = light.distance;
  17700. shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  17701. if ( light.isAmbientLight ) {
  17702. r += color.r * intensity;
  17703. g += color.g * intensity;
  17704. b += color.b * intensity;
  17705. } else if ( light.isDirectionalLight ) {
  17706. var uniforms = lightCache.get( light );
  17707. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  17708. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  17709. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  17710. uniforms.direction.sub( _vector3 );
  17711. uniforms.direction.transformDirection( viewMatrix );
  17712. uniforms.shadow = light.castShadow;
  17713. if ( light.castShadow ) {
  17714. uniforms.shadowBias = light.shadow.bias;
  17715. uniforms.shadowRadius = light.shadow.radius;
  17716. uniforms.shadowMapSize = light.shadow.mapSize;
  17717. }
  17718. _lights.directionalShadowMap[ directionalLength ] = shadowMap;
  17719. _lights.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  17720. _lights.directional[ directionalLength ++ ] = uniforms;
  17721. } else if ( light.isSpotLight ) {
  17722. var uniforms = lightCache.get( light );
  17723. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  17724. uniforms.position.applyMatrix4( viewMatrix );
  17725. uniforms.color.copy( color ).multiplyScalar( intensity );
  17726. uniforms.distance = distance;
  17727. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  17728. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  17729. uniforms.direction.sub( _vector3 );
  17730. uniforms.direction.transformDirection( viewMatrix );
  17731. uniforms.coneCos = Math.cos( light.angle );
  17732. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  17733. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  17734. uniforms.shadow = light.castShadow;
  17735. if ( light.castShadow ) {
  17736. uniforms.shadowBias = light.shadow.bias;
  17737. uniforms.shadowRadius = light.shadow.radius;
  17738. uniforms.shadowMapSize = light.shadow.mapSize;
  17739. }
  17740. _lights.spotShadowMap[ spotLength ] = shadowMap;
  17741. _lights.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  17742. _lights.spot[ spotLength ++ ] = uniforms;
  17743. } else if ( light.isRectAreaLight ) {
  17744. var uniforms = lightCache.get( light );
  17745. // (a) intensity controls irradiance of entire light
  17746. uniforms.color
  17747. .copy( color )
  17748. .multiplyScalar( intensity / ( light.width * light.height ) );
  17749. // (b) intensity controls the radiance per light area
  17750. // uniforms.color.copy( color ).multiplyScalar( intensity );
  17751. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  17752. uniforms.position.applyMatrix4( viewMatrix );
  17753. // extract local rotation of light to derive width/height half vectors
  17754. _matrix42.identity();
  17755. _matrix4.copy( light.matrixWorld );
  17756. _matrix4.premultiply( viewMatrix );
  17757. _matrix42.extractRotation( _matrix4 );
  17758. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  17759. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  17760. uniforms.halfWidth.applyMatrix4( _matrix42 );
  17761. uniforms.halfHeight.applyMatrix4( _matrix42 );
  17762. // TODO (abelnation): RectAreaLight distance?
  17763. // uniforms.distance = distance;
  17764. _lights.rectArea[ rectAreaLength ++ ] = uniforms;
  17765. } else if ( light.isPointLight ) {
  17766. var uniforms = lightCache.get( light );
  17767. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  17768. uniforms.position.applyMatrix4( viewMatrix );
  17769. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  17770. uniforms.distance = light.distance;
  17771. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  17772. uniforms.shadow = light.castShadow;
  17773. if ( light.castShadow ) {
  17774. uniforms.shadowBias = light.shadow.bias;
  17775. uniforms.shadowRadius = light.shadow.radius;
  17776. uniforms.shadowMapSize = light.shadow.mapSize;
  17777. }
  17778. _lights.pointShadowMap[ pointLength ] = shadowMap;
  17779. if ( _lights.pointShadowMatrix[ pointLength ] === undefined ) {
  17780. _lights.pointShadowMatrix[ pointLength ] = new Matrix4();
  17781. }
  17782. // for point lights we set the shadow matrix to be a translation-only matrix
  17783. // equal to inverse of the light's position
  17784. _vector3.setFromMatrixPosition( light.matrixWorld ).negate();
  17785. _lights.pointShadowMatrix[ pointLength ].identity().setPosition( _vector3 );
  17786. _lights.point[ pointLength ++ ] = uniforms;
  17787. } else if ( light.isHemisphereLight ) {
  17788. var uniforms = lightCache.get( light );
  17789. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  17790. uniforms.direction.transformDirection( viewMatrix );
  17791. uniforms.direction.normalize();
  17792. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  17793. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  17794. _lights.hemi[ hemiLength ++ ] = uniforms;
  17795. }
  17796. }
  17797. _lights.ambient[ 0 ] = r;
  17798. _lights.ambient[ 1 ] = g;
  17799. _lights.ambient[ 2 ] = b;
  17800. _lights.directional.length = directionalLength;
  17801. _lights.spot.length = spotLength;
  17802. _lights.rectArea.length = rectAreaLength;
  17803. _lights.point.length = pointLength;
  17804. _lights.hemi.length = hemiLength;
  17805. // TODO (sam-g-steel) why aren't we using join
  17806. _lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + rectAreaLength + ',' + hemiLength + ',' + _lights.shadows.length;
  17807. }
  17808. // GL state setting
  17809. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  17810. state.setCullFace( cullFace );
  17811. state.setFlipSided( frontFaceDirection === FrontFaceDirectionCW );
  17812. };
  17813. // Textures
  17814. function allocTextureUnit() {
  17815. var textureUnit = _usedTextureUnits;
  17816. if ( textureUnit >= capabilities.maxTextures ) {
  17817. console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  17818. }
  17819. _usedTextureUnits += 1;
  17820. return textureUnit;
  17821. }
  17822. this.allocTextureUnit = allocTextureUnit;
  17823. // this.setTexture2D = setTexture2D;
  17824. this.setTexture2D = ( function() {
  17825. var warned = false;
  17826. // backwards compatibility: peel texture.texture
  17827. return function setTexture2D( texture, slot ) {
  17828. if ( texture && texture.isWebGLRenderTarget ) {
  17829. if ( ! warned ) {
  17830. console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." );
  17831. warned = true;
  17832. }
  17833. texture = texture.texture;
  17834. }
  17835. textures.setTexture2D( texture, slot );
  17836. };
  17837. }() );
  17838. this.setTexture = ( function() {
  17839. var warned = false;
  17840. return function setTexture( texture, slot ) {
  17841. if ( ! warned ) {
  17842. console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." );
  17843. warned = true;
  17844. }
  17845. textures.setTexture2D( texture, slot );
  17846. };
  17847. }() );
  17848. this.setTextureCube = ( function() {
  17849. var warned = false;
  17850. return function setTextureCube( texture, slot ) {
  17851. // backwards compatibility: peel texture.texture
  17852. if ( texture && texture.isWebGLRenderTargetCube ) {
  17853. if ( ! warned ) {
  17854. console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
  17855. warned = true;
  17856. }
  17857. texture = texture.texture;
  17858. }
  17859. // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  17860. // TODO: unify these code paths
  17861. if ( ( texture && texture.isCubeTexture ) ||
  17862. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  17863. // CompressedTexture can have Array in image :/
  17864. // this function alone should take care of cube textures
  17865. textures.setTextureCube( texture, slot );
  17866. } else {
  17867. // assumed: texture property of THREE.WebGLRenderTargetCube
  17868. textures.setTextureCubeDynamic( texture, slot );
  17869. }
  17870. };
  17871. }() );
  17872. this.getCurrentRenderTarget = function() {
  17873. return _currentRenderTarget;
  17874. };
  17875. this.setRenderTarget = function ( renderTarget ) {
  17876. _currentRenderTarget = renderTarget;
  17877. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  17878. textures.setupRenderTarget( renderTarget );
  17879. }
  17880. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  17881. var framebuffer;
  17882. if ( renderTarget ) {
  17883. var renderTargetProperties = properties.get( renderTarget );
  17884. if ( isCube ) {
  17885. framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ];
  17886. } else {
  17887. framebuffer = renderTargetProperties.__webglFramebuffer;
  17888. }
  17889. _currentScissor.copy( renderTarget.scissor );
  17890. _currentScissorTest = renderTarget.scissorTest;
  17891. _currentViewport.copy( renderTarget.viewport );
  17892. } else {
  17893. framebuffer = null;
  17894. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
  17895. _currentScissorTest = _scissorTest;
  17896. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
  17897. }
  17898. if ( _currentFramebuffer !== framebuffer ) {
  17899. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  17900. _currentFramebuffer = framebuffer;
  17901. }
  17902. state.scissor( _currentScissor );
  17903. state.setScissorTest( _currentScissorTest );
  17904. state.viewport( _currentViewport );
  17905. if ( isCube ) {
  17906. var textureProperties = properties.get( renderTarget.texture );
  17907. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel );
  17908. }
  17909. };
  17910. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  17911. if ( ( renderTarget && renderTarget.isWebGLRenderTarget ) === false ) {
  17912. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  17913. return;
  17914. }
  17915. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  17916. if ( framebuffer ) {
  17917. var restore = false;
  17918. if ( framebuffer !== _currentFramebuffer ) {
  17919. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  17920. restore = true;
  17921. }
  17922. try {
  17923. var texture = renderTarget.texture;
  17924. var textureFormat = texture.format;
  17925. var textureType = texture.type;
  17926. if ( textureFormat !== RGBAFormat && paramThreeToGL( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  17927. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  17928. return;
  17929. }
  17930. if ( textureType !== UnsignedByteType && paramThreeToGL( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // IE11, Edge and Chrome Mac < 52 (#9513)
  17931. ! ( textureType === FloatType && ( extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  17932. ! ( textureType === HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
  17933. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  17934. return;
  17935. }
  17936. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  17937. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  17938. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  17939. _gl.readPixels( x, y, width, height, paramThreeToGL( textureFormat ), paramThreeToGL( textureType ), buffer );
  17940. }
  17941. } else {
  17942. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  17943. }
  17944. } finally {
  17945. if ( restore ) {
  17946. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  17947. }
  17948. }
  17949. }
  17950. };
  17951. // Map three.js constants to WebGL constants
  17952. function paramThreeToGL( p ) {
  17953. var extension;
  17954. if ( p === RepeatWrapping ) return _gl.REPEAT;
  17955. if ( p === ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  17956. if ( p === MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  17957. if ( p === NearestFilter ) return _gl.NEAREST;
  17958. if ( p === NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  17959. if ( p === NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  17960. if ( p === LinearFilter ) return _gl.LINEAR;
  17961. if ( p === LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  17962. if ( p === LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  17963. if ( p === UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  17964. if ( p === UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  17965. if ( p === UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  17966. if ( p === UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  17967. if ( p === ByteType ) return _gl.BYTE;
  17968. if ( p === ShortType ) return _gl.SHORT;
  17969. if ( p === UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  17970. if ( p === IntType ) return _gl.INT;
  17971. if ( p === UnsignedIntType ) return _gl.UNSIGNED_INT;
  17972. if ( p === FloatType ) return _gl.FLOAT;
  17973. if ( p === HalfFloatType ) {
  17974. extension = extensions.get( 'OES_texture_half_float' );
  17975. if ( extension !== null ) return extension.HALF_FLOAT_OES;
  17976. }
  17977. if ( p === AlphaFormat ) return _gl.ALPHA;
  17978. if ( p === RGBFormat ) return _gl.RGB;
  17979. if ( p === RGBAFormat ) return _gl.RGBA;
  17980. if ( p === LuminanceFormat ) return _gl.LUMINANCE;
  17981. if ( p === LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  17982. if ( p === DepthFormat ) return _gl.DEPTH_COMPONENT;
  17983. if ( p === DepthStencilFormat ) return _gl.DEPTH_STENCIL;
  17984. if ( p === AddEquation ) return _gl.FUNC_ADD;
  17985. if ( p === SubtractEquation ) return _gl.FUNC_SUBTRACT;
  17986. if ( p === ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  17987. if ( p === ZeroFactor ) return _gl.ZERO;
  17988. if ( p === OneFactor ) return _gl.ONE;
  17989. if ( p === SrcColorFactor ) return _gl.SRC_COLOR;
  17990. if ( p === OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  17991. if ( p === SrcAlphaFactor ) return _gl.SRC_ALPHA;
  17992. if ( p === OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  17993. if ( p === DstAlphaFactor ) return _gl.DST_ALPHA;
  17994. if ( p === OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  17995. if ( p === DstColorFactor ) return _gl.DST_COLOR;
  17996. if ( p === OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  17997. if ( p === SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  17998. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  17999. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  18000. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  18001. if ( extension !== null ) {
  18002. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  18003. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  18004. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  18005. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  18006. }
  18007. }
  18008. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  18009. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  18010. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  18011. if ( extension !== null ) {
  18012. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  18013. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  18014. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  18015. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  18016. }
  18017. }
  18018. if ( p === RGB_ETC1_Format ) {
  18019. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  18020. if ( extension !== null ) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  18021. }
  18022. if ( p === MinEquation || p === MaxEquation ) {
  18023. extension = extensions.get( 'EXT_blend_minmax' );
  18024. if ( extension !== null ) {
  18025. if ( p === MinEquation ) return extension.MIN_EXT;
  18026. if ( p === MaxEquation ) return extension.MAX_EXT;
  18027. }
  18028. }
  18029. if ( p === UnsignedInt248Type ) {
  18030. extension = extensions.get( 'WEBGL_depth_texture' );
  18031. if ( extension !== null ) return extension.UNSIGNED_INT_24_8_WEBGL;
  18032. }
  18033. return 0;
  18034. }
  18035. }
  18036. /**
  18037. * @author mrdoob / http://mrdoob.com/
  18038. * @author alteredq / http://alteredqualia.com/
  18039. */
  18040. function FogExp2 ( color, density ) {
  18041. this.name = '';
  18042. this.color = new Color( color );
  18043. this.density = ( density !== undefined ) ? density : 0.00025;
  18044. }
  18045. FogExp2.prototype.isFogExp2 = true;
  18046. FogExp2.prototype.clone = function () {
  18047. return new FogExp2( this.color.getHex(), this.density );
  18048. };
  18049. FogExp2.prototype.toJSON = function ( meta ) {
  18050. return {
  18051. type: 'FogExp2',
  18052. color: this.color.getHex(),
  18053. density: this.density
  18054. };
  18055. };
  18056. /**
  18057. * @author mrdoob / http://mrdoob.com/
  18058. * @author alteredq / http://alteredqualia.com/
  18059. */
  18060. function Fog ( color, near, far ) {
  18061. this.name = '';
  18062. this.color = new Color( color );
  18063. this.near = ( near !== undefined ) ? near : 1;
  18064. this.far = ( far !== undefined ) ? far : 1000;
  18065. }
  18066. Fog.prototype.isFog = true;
  18067. Fog.prototype.clone = function () {
  18068. return new Fog( this.color.getHex(), this.near, this.far );
  18069. };
  18070. Fog.prototype.toJSON = function ( meta ) {
  18071. return {
  18072. type: 'Fog',
  18073. color: this.color.getHex(),
  18074. near: this.near,
  18075. far: this.far
  18076. };
  18077. };
  18078. /**
  18079. * @author mrdoob / http://mrdoob.com/
  18080. */
  18081. function Scene () {
  18082. Object3D.call( this );
  18083. this.type = 'Scene';
  18084. this.background = null;
  18085. this.fog = null;
  18086. this.overrideMaterial = null;
  18087. this.autoUpdate = true; // checked by the renderer
  18088. }
  18089. Scene.prototype = Object.create( Object3D.prototype );
  18090. Scene.prototype.constructor = Scene;
  18091. Scene.prototype.copy = function ( source, recursive ) {
  18092. Object3D.prototype.copy.call( this, source, recursive );
  18093. if ( source.background !== null ) this.background = source.background.clone();
  18094. if ( source.fog !== null ) this.fog = source.fog.clone();
  18095. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  18096. this.autoUpdate = source.autoUpdate;
  18097. this.matrixAutoUpdate = source.matrixAutoUpdate;
  18098. return this;
  18099. };
  18100. Scene.prototype.toJSON = function ( meta ) {
  18101. var data = Object3D.prototype.toJSON.call( this, meta );
  18102. if ( this.background !== null ) data.object.background = this.background.toJSON( meta );
  18103. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  18104. return data;
  18105. };
  18106. /**
  18107. * @author mikael emtinger / http://gomo.se/
  18108. * @author alteredq / http://alteredqualia.com/
  18109. */
  18110. function LensFlare( texture, size, distance, blending, color ) {
  18111. Object3D.call( this );
  18112. this.lensFlares = [];
  18113. this.positionScreen = new Vector3();
  18114. this.customUpdateCallback = undefined;
  18115. if ( texture !== undefined ) {
  18116. this.add( texture, size, distance, blending, color );
  18117. }
  18118. }
  18119. LensFlare.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18120. constructor: LensFlare,
  18121. isLensFlare: true,
  18122. copy: function ( source ) {
  18123. Object3D.prototype.copy.call( this, source );
  18124. this.positionScreen.copy( source.positionScreen );
  18125. this.customUpdateCallback = source.customUpdateCallback;
  18126. for ( var i = 0, l = source.lensFlares.length; i < l; i ++ ) {
  18127. this.lensFlares.push( source.lensFlares[ i ] );
  18128. }
  18129. return this;
  18130. },
  18131. add: function ( texture, size, distance, blending, color, opacity ) {
  18132. if ( size === undefined ) size = - 1;
  18133. if ( distance === undefined ) distance = 0;
  18134. if ( opacity === undefined ) opacity = 1;
  18135. if ( color === undefined ) color = new Color( 0xffffff );
  18136. if ( blending === undefined ) blending = NormalBlending;
  18137. distance = Math.min( distance, Math.max( 0, distance ) );
  18138. this.lensFlares.push( {
  18139. texture: texture, // THREE.Texture
  18140. size: size, // size in pixels (-1 = use texture.width)
  18141. distance: distance, // distance (0-1) from light source (0=at light source)
  18142. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is in front z = 1 is back
  18143. scale: 1, // scale
  18144. rotation: 0, // rotation
  18145. opacity: opacity, // opacity
  18146. color: color, // color
  18147. blending: blending // blending
  18148. } );
  18149. },
  18150. /*
  18151. * Update lens flares update positions on all flares based on the screen position
  18152. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  18153. */
  18154. updateLensFlares: function () {
  18155. var f, fl = this.lensFlares.length;
  18156. var flare;
  18157. var vecX = - this.positionScreen.x * 2;
  18158. var vecY = - this.positionScreen.y * 2;
  18159. for ( f = 0; f < fl; f ++ ) {
  18160. flare = this.lensFlares[ f ];
  18161. flare.x = this.positionScreen.x + vecX * flare.distance;
  18162. flare.y = this.positionScreen.y + vecY * flare.distance;
  18163. flare.wantedRotation = flare.x * Math.PI * 0.25;
  18164. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  18165. }
  18166. }
  18167. } );
  18168. /**
  18169. * @author alteredq / http://alteredqualia.com/
  18170. *
  18171. * parameters = {
  18172. * color: <hex>,
  18173. * opacity: <float>,
  18174. * map: new THREE.Texture( <Image> ),
  18175. *
  18176. * uvOffset: new THREE.Vector2(),
  18177. * uvScale: new THREE.Vector2()
  18178. * }
  18179. */
  18180. function SpriteMaterial( parameters ) {
  18181. Material.call( this );
  18182. this.type = 'SpriteMaterial';
  18183. this.color = new Color( 0xffffff );
  18184. this.map = null;
  18185. this.rotation = 0;
  18186. this.fog = false;
  18187. this.lights = false;
  18188. this.setValues( parameters );
  18189. }
  18190. SpriteMaterial.prototype = Object.create( Material.prototype );
  18191. SpriteMaterial.prototype.constructor = SpriteMaterial;
  18192. SpriteMaterial.prototype.copy = function ( source ) {
  18193. Material.prototype.copy.call( this, source );
  18194. this.color.copy( source.color );
  18195. this.map = source.map;
  18196. this.rotation = source.rotation;
  18197. return this;
  18198. };
  18199. /**
  18200. * @author mikael emtinger / http://gomo.se/
  18201. * @author alteredq / http://alteredqualia.com/
  18202. */
  18203. function Sprite( material ) {
  18204. Object3D.call( this );
  18205. this.type = 'Sprite';
  18206. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  18207. }
  18208. Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18209. constructor: Sprite,
  18210. isSprite: true,
  18211. raycast: ( function () {
  18212. var matrixPosition = new Vector3();
  18213. return function raycast( raycaster, intersects ) {
  18214. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  18215. var distanceSq = raycaster.ray.distanceSqToPoint( matrixPosition );
  18216. var guessSizeSq = this.scale.x * this.scale.y / 4;
  18217. if ( distanceSq > guessSizeSq ) {
  18218. return;
  18219. }
  18220. intersects.push( {
  18221. distance: Math.sqrt( distanceSq ),
  18222. point: this.position,
  18223. face: null,
  18224. object: this
  18225. } );
  18226. };
  18227. }() ),
  18228. clone: function () {
  18229. return new this.constructor( this.material ).copy( this );
  18230. }
  18231. } );
  18232. /**
  18233. * @author mikael emtinger / http://gomo.se/
  18234. * @author alteredq / http://alteredqualia.com/
  18235. * @author mrdoob / http://mrdoob.com/
  18236. */
  18237. function LOD() {
  18238. Object3D.call( this );
  18239. this.type = 'LOD';
  18240. Object.defineProperties( this, {
  18241. levels: {
  18242. enumerable: true,
  18243. value: []
  18244. }
  18245. } );
  18246. }
  18247. LOD.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18248. constructor: LOD,
  18249. copy: function ( source ) {
  18250. Object3D.prototype.copy.call( this, source, false );
  18251. var levels = source.levels;
  18252. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  18253. var level = levels[ i ];
  18254. this.addLevel( level.object.clone(), level.distance );
  18255. }
  18256. return this;
  18257. },
  18258. addLevel: function ( object, distance ) {
  18259. if ( distance === undefined ) distance = 0;
  18260. distance = Math.abs( distance );
  18261. var levels = this.levels;
  18262. for ( var l = 0; l < levels.length; l ++ ) {
  18263. if ( distance < levels[ l ].distance ) {
  18264. break;
  18265. }
  18266. }
  18267. levels.splice( l, 0, { distance: distance, object: object } );
  18268. this.add( object );
  18269. },
  18270. getObjectForDistance: function ( distance ) {
  18271. var levels = this.levels;
  18272. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  18273. if ( distance < levels[ i ].distance ) {
  18274. break;
  18275. }
  18276. }
  18277. return levels[ i - 1 ].object;
  18278. },
  18279. raycast: ( function () {
  18280. var matrixPosition = new Vector3();
  18281. return function raycast( raycaster, intersects ) {
  18282. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  18283. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  18284. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  18285. };
  18286. }() ),
  18287. update: function () {
  18288. var v1 = new Vector3();
  18289. var v2 = new Vector3();
  18290. return function update( camera ) {
  18291. var levels = this.levels;
  18292. if ( levels.length > 1 ) {
  18293. v1.setFromMatrixPosition( camera.matrixWorld );
  18294. v2.setFromMatrixPosition( this.matrixWorld );
  18295. var distance = v1.distanceTo( v2 );
  18296. levels[ 0 ].object.visible = true;
  18297. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  18298. if ( distance >= levels[ i ].distance ) {
  18299. levels[ i - 1 ].object.visible = false;
  18300. levels[ i ].object.visible = true;
  18301. } else {
  18302. break;
  18303. }
  18304. }
  18305. for ( ; i < l; i ++ ) {
  18306. levels[ i ].object.visible = false;
  18307. }
  18308. }
  18309. };
  18310. }(),
  18311. toJSON: function ( meta ) {
  18312. var data = Object3D.prototype.toJSON.call( this, meta );
  18313. data.object.levels = [];
  18314. var levels = this.levels;
  18315. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  18316. var level = levels[ i ];
  18317. data.object.levels.push( {
  18318. object: level.object.uuid,
  18319. distance: level.distance
  18320. } );
  18321. }
  18322. return data;
  18323. }
  18324. } );
  18325. /**
  18326. * @author mikael emtinger / http://gomo.se/
  18327. * @author alteredq / http://alteredqualia.com/
  18328. * @author michael guerrero / http://realitymeltdown.com
  18329. * @author ikerr / http://verold.com
  18330. */
  18331. function Skeleton( bones, boneInverses, useVertexTexture ) {
  18332. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  18333. this.identityMatrix = new Matrix4();
  18334. // copy the bone array
  18335. bones = bones || [];
  18336. this.bones = bones.slice( 0 );
  18337. // create a bone texture or an array of floats
  18338. if ( this.useVertexTexture ) {
  18339. // layout (1 matrix = 4 pixels)
  18340. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18341. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18342. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18343. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18344. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18345. var size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  18346. size = _Math.nextPowerOfTwo( Math.ceil( size ) );
  18347. size = Math.max( size, 4 );
  18348. this.boneTextureWidth = size;
  18349. this.boneTextureHeight = size;
  18350. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  18351. this.boneTexture = new DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, RGBAFormat, FloatType );
  18352. } else {
  18353. this.boneMatrices = new Float32Array( 16 * this.bones.length );
  18354. }
  18355. // use the supplied bone inverses or calculate the inverses
  18356. if ( boneInverses === undefined ) {
  18357. this.calculateInverses();
  18358. } else {
  18359. if ( this.bones.length === boneInverses.length ) {
  18360. this.boneInverses = boneInverses.slice( 0 );
  18361. } else {
  18362. console.warn( 'THREE.Skeleton bonInverses is the wrong length.' );
  18363. this.boneInverses = [];
  18364. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  18365. this.boneInverses.push( new Matrix4() );
  18366. }
  18367. }
  18368. }
  18369. }
  18370. Object.assign( Skeleton.prototype, {
  18371. calculateInverses: function () {
  18372. this.boneInverses = [];
  18373. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  18374. var inverse = new Matrix4();
  18375. if ( this.bones[ b ] ) {
  18376. inverse.getInverse( this.bones[ b ].matrixWorld );
  18377. }
  18378. this.boneInverses.push( inverse );
  18379. }
  18380. },
  18381. pose: function () {
  18382. var bone;
  18383. // recover the bind-time world matrices
  18384. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  18385. bone = this.bones[ b ];
  18386. if ( bone ) {
  18387. bone.matrixWorld.getInverse( this.boneInverses[ b ] );
  18388. }
  18389. }
  18390. // compute the local matrices, positions, rotations and scales
  18391. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  18392. bone = this.bones[ b ];
  18393. if ( bone ) {
  18394. if ( bone.parent && bone.parent.isBone ) {
  18395. bone.matrix.getInverse( bone.parent.matrixWorld );
  18396. bone.matrix.multiply( bone.matrixWorld );
  18397. } else {
  18398. bone.matrix.copy( bone.matrixWorld );
  18399. }
  18400. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18401. }
  18402. }
  18403. },
  18404. update: ( function () {
  18405. var offsetMatrix = new Matrix4();
  18406. return function update() {
  18407. // flatten bone matrices to array
  18408. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  18409. // compute the offset between the current and the original transform
  18410. var matrix = this.bones[ b ] ? this.bones[ b ].matrixWorld : this.identityMatrix;
  18411. offsetMatrix.multiplyMatrices( matrix, this.boneInverses[ b ] );
  18412. offsetMatrix.toArray( this.boneMatrices, b * 16 );
  18413. }
  18414. if ( this.useVertexTexture ) {
  18415. this.boneTexture.needsUpdate = true;
  18416. }
  18417. };
  18418. } )(),
  18419. clone: function () {
  18420. return new Skeleton( this.bones, this.boneInverses, this.useVertexTexture );
  18421. }
  18422. } );
  18423. /**
  18424. * @author mikael emtinger / http://gomo.se/
  18425. * @author alteredq / http://alteredqualia.com/
  18426. * @author ikerr / http://verold.com
  18427. */
  18428. function Bone() {
  18429. Object3D.call( this );
  18430. this.type = 'Bone';
  18431. }
  18432. Bone.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18433. constructor: Bone,
  18434. isBone: true
  18435. } );
  18436. /**
  18437. * @author mikael emtinger / http://gomo.se/
  18438. * @author alteredq / http://alteredqualia.com/
  18439. * @author ikerr / http://verold.com
  18440. */
  18441. function SkinnedMesh( geometry, material, useVertexTexture ) {
  18442. Mesh.call( this, geometry, material );
  18443. this.type = 'SkinnedMesh';
  18444. this.bindMode = "attached";
  18445. this.bindMatrix = new Matrix4();
  18446. this.bindMatrixInverse = new Matrix4();
  18447. // init bones
  18448. // TODO: remove bone creation as there is no reason (other than
  18449. // convenience) for THREE.SkinnedMesh to do this.
  18450. var bones = [];
  18451. if ( this.geometry && this.geometry.bones !== undefined ) {
  18452. var bone, gbone;
  18453. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  18454. gbone = this.geometry.bones[ b ];
  18455. bone = new Bone();
  18456. bones.push( bone );
  18457. bone.name = gbone.name;
  18458. bone.position.fromArray( gbone.pos );
  18459. bone.quaternion.fromArray( gbone.rotq );
  18460. if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl );
  18461. }
  18462. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  18463. gbone = this.geometry.bones[ b ];
  18464. if ( gbone.parent !== - 1 && gbone.parent !== null &&
  18465. bones[ gbone.parent ] !== undefined ) {
  18466. bones[ gbone.parent ].add( bones[ b ] );
  18467. } else {
  18468. this.add( bones[ b ] );
  18469. }
  18470. }
  18471. }
  18472. this.normalizeSkinWeights();
  18473. this.updateMatrixWorld( true );
  18474. this.bind( new Skeleton( bones, undefined, useVertexTexture ), this.matrixWorld );
  18475. }
  18476. SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  18477. constructor: SkinnedMesh,
  18478. isSkinnedMesh: true,
  18479. bind: function( skeleton, bindMatrix ) {
  18480. this.skeleton = skeleton;
  18481. if ( bindMatrix === undefined ) {
  18482. this.updateMatrixWorld( true );
  18483. this.skeleton.calculateInverses();
  18484. bindMatrix = this.matrixWorld;
  18485. }
  18486. this.bindMatrix.copy( bindMatrix );
  18487. this.bindMatrixInverse.getInverse( bindMatrix );
  18488. },
  18489. pose: function () {
  18490. this.skeleton.pose();
  18491. },
  18492. normalizeSkinWeights: function () {
  18493. if ( this.geometry && this.geometry.isGeometry ) {
  18494. for ( var i = 0; i < this.geometry.skinWeights.length; i ++ ) {
  18495. var sw = this.geometry.skinWeights[ i ];
  18496. var scale = 1.0 / sw.lengthManhattan();
  18497. if ( scale !== Infinity ) {
  18498. sw.multiplyScalar( scale );
  18499. } else {
  18500. sw.set( 1, 0, 0, 0 ); // do something reasonable
  18501. }
  18502. }
  18503. } else if ( this.geometry && this.geometry.isBufferGeometry ) {
  18504. var vec = new Vector4();
  18505. var skinWeight = this.geometry.attributes.skinWeight;
  18506. for ( var i = 0; i < skinWeight.count; i ++ ) {
  18507. vec.x = skinWeight.getX( i );
  18508. vec.y = skinWeight.getY( i );
  18509. vec.z = skinWeight.getZ( i );
  18510. vec.w = skinWeight.getW( i );
  18511. var scale = 1.0 / vec.lengthManhattan();
  18512. if ( scale !== Infinity ) {
  18513. vec.multiplyScalar( scale );
  18514. } else {
  18515. vec.set( 1, 0, 0, 0 ); // do something reasonable
  18516. }
  18517. skinWeight.setXYZW( i, vec.x, vec.y, vec.z, vec.w );
  18518. }
  18519. }
  18520. },
  18521. updateMatrixWorld: function( force ) {
  18522. Mesh.prototype.updateMatrixWorld.call( this, true );
  18523. if ( this.bindMode === "attached" ) {
  18524. this.bindMatrixInverse.getInverse( this.matrixWorld );
  18525. } else if ( this.bindMode === "detached" ) {
  18526. this.bindMatrixInverse.getInverse( this.bindMatrix );
  18527. } else {
  18528. console.warn( 'THREE.SkinnedMesh unrecognized bindMode: ' + this.bindMode );
  18529. }
  18530. },
  18531. clone: function() {
  18532. return new this.constructor( this.geometry, this.material, this.skeleton.useVertexTexture ).copy( this );
  18533. }
  18534. } );
  18535. /**
  18536. * @author mrdoob / http://mrdoob.com/
  18537. * @author alteredq / http://alteredqualia.com/
  18538. *
  18539. * parameters = {
  18540. * color: <hex>,
  18541. * opacity: <float>,
  18542. *
  18543. * linewidth: <float>,
  18544. * linecap: "round",
  18545. * linejoin: "round"
  18546. * }
  18547. */
  18548. function LineBasicMaterial( parameters ) {
  18549. Material.call( this );
  18550. this.type = 'LineBasicMaterial';
  18551. this.color = new Color( 0xffffff );
  18552. this.linewidth = 1;
  18553. this.linecap = 'round';
  18554. this.linejoin = 'round';
  18555. this.lights = false;
  18556. this.setValues( parameters );
  18557. }
  18558. LineBasicMaterial.prototype = Object.create( Material.prototype );
  18559. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  18560. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  18561. LineBasicMaterial.prototype.copy = function ( source ) {
  18562. Material.prototype.copy.call( this, source );
  18563. this.color.copy( source.color );
  18564. this.linewidth = source.linewidth;
  18565. this.linecap = source.linecap;
  18566. this.linejoin = source.linejoin;
  18567. return this;
  18568. };
  18569. /**
  18570. * @author mrdoob / http://mrdoob.com/
  18571. */
  18572. function Line( geometry, material, mode ) {
  18573. if ( mode === 1 ) {
  18574. console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' );
  18575. return new LineSegments( geometry, material );
  18576. }
  18577. Object3D.call( this );
  18578. this.type = 'Line';
  18579. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  18580. this.material = material !== undefined ? material : new LineBasicMaterial( { color: Math.random() * 0xffffff } );
  18581. }
  18582. Line.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18583. constructor: Line,
  18584. isLine: true,
  18585. raycast: ( function () {
  18586. var inverseMatrix = new Matrix4();
  18587. var ray = new Ray();
  18588. var sphere = new Sphere();
  18589. return function raycast( raycaster, intersects ) {
  18590. var precision = raycaster.linePrecision;
  18591. var precisionSq = precision * precision;
  18592. var geometry = this.geometry;
  18593. var matrixWorld = this.matrixWorld;
  18594. // Checking boundingSphere distance to ray
  18595. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18596. sphere.copy( geometry.boundingSphere );
  18597. sphere.applyMatrix4( matrixWorld );
  18598. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  18599. //
  18600. inverseMatrix.getInverse( matrixWorld );
  18601. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  18602. var vStart = new Vector3();
  18603. var vEnd = new Vector3();
  18604. var interSegment = new Vector3();
  18605. var interRay = new Vector3();
  18606. var step = (this && this.isLineSegments) ? 2 : 1;
  18607. if ( geometry.isBufferGeometry ) {
  18608. var index = geometry.index;
  18609. var attributes = geometry.attributes;
  18610. var positions = attributes.position.array;
  18611. if ( index !== null ) {
  18612. var indices = index.array;
  18613. for ( var i = 0, l = indices.length - 1; i < l; i += step ) {
  18614. var a = indices[ i ];
  18615. var b = indices[ i + 1 ];
  18616. vStart.fromArray( positions, a * 3 );
  18617. vEnd.fromArray( positions, b * 3 );
  18618. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  18619. if ( distSq > precisionSq ) continue;
  18620. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18621. var distance = raycaster.ray.origin.distanceTo( interRay );
  18622. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18623. intersects.push( {
  18624. distance: distance,
  18625. // What do we want? intersection point on the ray or on the segment??
  18626. // point: raycaster.ray.at( distance ),
  18627. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18628. index: i,
  18629. face: null,
  18630. faceIndex: null,
  18631. object: this
  18632. } );
  18633. }
  18634. } else {
  18635. for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) {
  18636. vStart.fromArray( positions, 3 * i );
  18637. vEnd.fromArray( positions, 3 * i + 3 );
  18638. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  18639. if ( distSq > precisionSq ) continue;
  18640. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18641. var distance = raycaster.ray.origin.distanceTo( interRay );
  18642. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18643. intersects.push( {
  18644. distance: distance,
  18645. // What do we want? intersection point on the ray or on the segment??
  18646. // point: raycaster.ray.at( distance ),
  18647. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18648. index: i,
  18649. face: null,
  18650. faceIndex: null,
  18651. object: this
  18652. } );
  18653. }
  18654. }
  18655. } else if ( geometry.isGeometry ) {
  18656. var vertices = geometry.vertices;
  18657. var nbVertices = vertices.length;
  18658. for ( var i = 0; i < nbVertices - 1; i += step ) {
  18659. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  18660. if ( distSq > precisionSq ) continue;
  18661. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18662. var distance = raycaster.ray.origin.distanceTo( interRay );
  18663. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18664. intersects.push( {
  18665. distance: distance,
  18666. // What do we want? intersection point on the ray or on the segment??
  18667. // point: raycaster.ray.at( distance ),
  18668. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18669. index: i,
  18670. face: null,
  18671. faceIndex: null,
  18672. object: this
  18673. } );
  18674. }
  18675. }
  18676. };
  18677. }() ),
  18678. clone: function () {
  18679. return new this.constructor( this.geometry, this.material ).copy( this );
  18680. }
  18681. } );
  18682. /**
  18683. * @author mrdoob / http://mrdoob.com/
  18684. */
  18685. function LineSegments( geometry, material ) {
  18686. Line.call( this, geometry, material );
  18687. this.type = 'LineSegments';
  18688. }
  18689. LineSegments.prototype = Object.assign( Object.create( Line.prototype ), {
  18690. constructor: LineSegments,
  18691. isLineSegments: true
  18692. } );
  18693. /**
  18694. * @author mrdoob / http://mrdoob.com/
  18695. * @author alteredq / http://alteredqualia.com/
  18696. *
  18697. * parameters = {
  18698. * color: <hex>,
  18699. * opacity: <float>,
  18700. * map: new THREE.Texture( <Image> ),
  18701. *
  18702. * size: <float>,
  18703. * sizeAttenuation: <bool>
  18704. * }
  18705. */
  18706. function PointsMaterial( parameters ) {
  18707. Material.call( this );
  18708. this.type = 'PointsMaterial';
  18709. this.color = new Color( 0xffffff );
  18710. this.map = null;
  18711. this.size = 1;
  18712. this.sizeAttenuation = true;
  18713. this.lights = false;
  18714. this.setValues( parameters );
  18715. }
  18716. PointsMaterial.prototype = Object.create( Material.prototype );
  18717. PointsMaterial.prototype.constructor = PointsMaterial;
  18718. PointsMaterial.prototype.isPointsMaterial = true;
  18719. PointsMaterial.prototype.copy = function ( source ) {
  18720. Material.prototype.copy.call( this, source );
  18721. this.color.copy( source.color );
  18722. this.map = source.map;
  18723. this.size = source.size;
  18724. this.sizeAttenuation = source.sizeAttenuation;
  18725. return this;
  18726. };
  18727. /**
  18728. * @author alteredq / http://alteredqualia.com/
  18729. */
  18730. function Points( geometry, material ) {
  18731. Object3D.call( this );
  18732. this.type = 'Points';
  18733. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  18734. this.material = material !== undefined ? material : new PointsMaterial( { color: Math.random() * 0xffffff } );
  18735. }
  18736. Points.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18737. constructor: Points,
  18738. isPoints: true,
  18739. raycast: ( function () {
  18740. var inverseMatrix = new Matrix4();
  18741. var ray = new Ray();
  18742. var sphere = new Sphere();
  18743. return function raycast( raycaster, intersects ) {
  18744. var object = this;
  18745. var geometry = this.geometry;
  18746. var matrixWorld = this.matrixWorld;
  18747. var threshold = raycaster.params.Points.threshold;
  18748. // Checking boundingSphere distance to ray
  18749. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18750. sphere.copy( geometry.boundingSphere );
  18751. sphere.applyMatrix4( matrixWorld );
  18752. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  18753. //
  18754. inverseMatrix.getInverse( matrixWorld );
  18755. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  18756. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  18757. var localThresholdSq = localThreshold * localThreshold;
  18758. var position = new Vector3();
  18759. function testPoint( point, index ) {
  18760. var rayPointDistanceSq = ray.distanceSqToPoint( point );
  18761. if ( rayPointDistanceSq < localThresholdSq ) {
  18762. var intersectPoint = ray.closestPointToPoint( point );
  18763. intersectPoint.applyMatrix4( matrixWorld );
  18764. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  18765. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18766. intersects.push( {
  18767. distance: distance,
  18768. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  18769. point: intersectPoint.clone(),
  18770. index: index,
  18771. face: null,
  18772. object: object
  18773. } );
  18774. }
  18775. }
  18776. if ( geometry.isBufferGeometry ) {
  18777. var index = geometry.index;
  18778. var attributes = geometry.attributes;
  18779. var positions = attributes.position.array;
  18780. if ( index !== null ) {
  18781. var indices = index.array;
  18782. for ( var i = 0, il = indices.length; i < il; i ++ ) {
  18783. var a = indices[ i ];
  18784. position.fromArray( positions, a * 3 );
  18785. testPoint( position, a );
  18786. }
  18787. } else {
  18788. for ( var i = 0, l = positions.length / 3; i < l; i ++ ) {
  18789. position.fromArray( positions, i * 3 );
  18790. testPoint( position, i );
  18791. }
  18792. }
  18793. } else {
  18794. var vertices = geometry.vertices;
  18795. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  18796. testPoint( vertices[ i ], i );
  18797. }
  18798. }
  18799. };
  18800. }() ),
  18801. clone: function () {
  18802. return new this.constructor( this.geometry, this.material ).copy( this );
  18803. }
  18804. } );
  18805. /**
  18806. * @author mrdoob / http://mrdoob.com/
  18807. */
  18808. function Group() {
  18809. Object3D.call( this );
  18810. this.type = 'Group';
  18811. }
  18812. Group.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18813. constructor: Group
  18814. } );
  18815. /**
  18816. * @author mrdoob / http://mrdoob.com/
  18817. */
  18818. function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  18819. Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  18820. this.generateMipmaps = false;
  18821. var scope = this;
  18822. function update() {
  18823. requestAnimationFrame( update );
  18824. if ( video.readyState >= video.HAVE_CURRENT_DATA ) {
  18825. scope.needsUpdate = true;
  18826. }
  18827. }
  18828. update();
  18829. }
  18830. VideoTexture.prototype = Object.create( Texture.prototype );
  18831. VideoTexture.prototype.constructor = VideoTexture;
  18832. /**
  18833. * @author alteredq / http://alteredqualia.com/
  18834. */
  18835. function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  18836. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  18837. this.image = { width: width, height: height };
  18838. this.mipmaps = mipmaps;
  18839. // no flipping for cube textures
  18840. // (also flipping doesn't work for compressed textures )
  18841. this.flipY = false;
  18842. // can't generate mipmaps for compressed textures
  18843. // mips must be embedded in DDS files
  18844. this.generateMipmaps = false;
  18845. }
  18846. CompressedTexture.prototype = Object.create( Texture.prototype );
  18847. CompressedTexture.prototype.constructor = CompressedTexture;
  18848. CompressedTexture.prototype.isCompressedTexture = true;
  18849. /**
  18850. * @author mrdoob / http://mrdoob.com/
  18851. */
  18852. function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  18853. Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  18854. this.needsUpdate = true;
  18855. }
  18856. CanvasTexture.prototype = Object.create( Texture.prototype );
  18857. CanvasTexture.prototype.constructor = CanvasTexture;
  18858. /**
  18859. * @author Matt DesLauriers / @mattdesl
  18860. * @author atix / arthursilber.de
  18861. */
  18862. function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  18863. format = format !== undefined ? format : DepthFormat;
  18864. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  18865. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' )
  18866. }
  18867. if ( type === undefined && format === DepthFormat ) type = UnsignedShortType;
  18868. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  18869. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  18870. this.image = { width: width, height: height };
  18871. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  18872. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  18873. this.flipY = false;
  18874. this.generateMipmaps = false;
  18875. }
  18876. DepthTexture.prototype = Object.create( Texture.prototype );
  18877. DepthTexture.prototype.constructor = DepthTexture;
  18878. DepthTexture.prototype.isDepthTexture = true;
  18879. /**
  18880. * @author mrdoob / http://mrdoob.com/
  18881. * @author Mugen87 / https://github.com/Mugen87
  18882. */
  18883. function WireframeGeometry( geometry ) {
  18884. BufferGeometry.call( this );
  18885. this.type = 'WireframeGeometry';
  18886. // buffer
  18887. var vertices = [];
  18888. // helper variables
  18889. var i, j, l, o, ol;
  18890. var edge = [ 0, 0 ], edges = {}, e;
  18891. var key, keys = [ 'a', 'b', 'c' ];
  18892. var vertex;
  18893. // different logic for Geometry and BufferGeometry
  18894. if ( geometry && geometry.isGeometry ) {
  18895. // create a data structure that contains all edges without duplicates
  18896. var faces = geometry.faces;
  18897. for ( i = 0, l = faces.length; i < l; i ++ ) {
  18898. var face = faces[ i ];
  18899. for ( j = 0; j < 3; j ++ ) {
  18900. edge[ 0 ] = face[ keys[ j ] ];
  18901. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  18902. edge.sort( sortFunction ); // sorting prevents duplicates
  18903. key = edge.toString();
  18904. if ( edges[ key ] === undefined ) {
  18905. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  18906. }
  18907. }
  18908. }
  18909. // generate vertices
  18910. for ( key in edges ) {
  18911. e = edges[ key ];
  18912. vertex = geometry.vertices[ e.index1 ];
  18913. vertices.push( vertex.x, vertex.y, vertex.z );
  18914. vertex = geometry.vertices[ e.index2 ];
  18915. vertices.push( vertex.x, vertex.y, vertex.z );
  18916. }
  18917. } else if ( geometry && geometry.isBufferGeometry ) {
  18918. var position, indices, groups;
  18919. var group, start, count;
  18920. var index1, index2;
  18921. vertex = new Vector3();
  18922. if ( geometry.index !== null ) {
  18923. // indexed BufferGeometry
  18924. position = geometry.attributes.position;
  18925. indices = geometry.index;
  18926. groups = geometry.groups;
  18927. if ( groups.length === 0 ) {
  18928. geometry.addGroup( 0, indices.count );
  18929. }
  18930. // create a data structure that contains all eges without duplicates
  18931. for ( o = 0, ol = groups.length; o < ol; ++ o ) {
  18932. group = groups[ o ];
  18933. start = group.start;
  18934. count = group.count;
  18935. for ( i = start, l = ( start + count ); i < l; i += 3 ) {
  18936. for ( j = 0; j < 3; j ++ ) {
  18937. edge[ 0 ] = indices.getX( i + j );
  18938. edge[ 1 ] = indices.getX( i + ( j + 1 ) % 3 );
  18939. edge.sort( sortFunction ); // sorting prevents duplicates
  18940. key = edge.toString();
  18941. if ( edges[ key ] === undefined ) {
  18942. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  18943. }
  18944. }
  18945. }
  18946. }
  18947. // generate vertices
  18948. for ( key in edges ) {
  18949. e = edges[ key ];
  18950. vertex.fromBufferAttribute( position, e.index1 );
  18951. vertices.push( vertex.x, vertex.y, vertex.z );
  18952. vertex.fromBufferAttribute( position, e.index2 );
  18953. vertices.push( vertex.x, vertex.y, vertex.z );
  18954. }
  18955. } else {
  18956. // non-indexed BufferGeometry
  18957. position = geometry.attributes.position;
  18958. for ( i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  18959. for ( j = 0; j < 3; j ++ ) {
  18960. // three edges per triangle, an edge is represented as (index1, index2)
  18961. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  18962. index1 = 3 * i + j;
  18963. vertex.fromBufferAttribute( position, index1 );
  18964. vertices.push( vertex.x, vertex.y, vertex.z );
  18965. index2 = 3 * i + ( ( j + 1 ) % 3 );
  18966. vertex.fromBufferAttribute( position, index2 );
  18967. vertices.push( vertex.x, vertex.y, vertex.z );
  18968. }
  18969. }
  18970. }
  18971. }
  18972. // build geometry
  18973. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18974. // custom array sort function
  18975. function sortFunction( a, b ) {
  18976. return a - b;
  18977. }
  18978. }
  18979. WireframeGeometry.prototype = Object.create( BufferGeometry.prototype );
  18980. WireframeGeometry.prototype.constructor = WireframeGeometry;
  18981. /**
  18982. * @author zz85 / https://github.com/zz85
  18983. *
  18984. * Parametric Surfaces Geometry
  18985. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  18986. */
  18987. function ParametricGeometry( func, slices, stacks ) {
  18988. Geometry.call( this );
  18989. this.type = 'ParametricGeometry';
  18990. this.parameters = {
  18991. func: func,
  18992. slices: slices,
  18993. stacks: stacks
  18994. };
  18995. this.fromBufferGeometry( new ParametricBufferGeometry( func, slices, stacks ) );
  18996. this.mergeVertices();
  18997. }
  18998. ParametricGeometry.prototype = Object.create( Geometry.prototype );
  18999. ParametricGeometry.prototype.constructor = ParametricGeometry;
  19000. /**
  19001. * @author Mugen87 / https://github.com/Mugen87
  19002. *
  19003. * Parametric Surfaces Geometry
  19004. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  19005. */
  19006. function ParametricBufferGeometry( func, slices, stacks ) {
  19007. BufferGeometry.call( this );
  19008. this.type = 'ParametricBufferGeometry';
  19009. this.parameters = {
  19010. func: func,
  19011. slices: slices,
  19012. stacks: stacks
  19013. };
  19014. // buffers
  19015. var indices = [];
  19016. var vertices = [];
  19017. var uvs = [];
  19018. var i, j;
  19019. // generate vertices and uvs
  19020. var sliceCount = slices + 1;
  19021. for ( i = 0; i <= stacks; i ++ ) {
  19022. var v = i / stacks;
  19023. for ( j = 0; j <= slices; j ++ ) {
  19024. var u = j / slices;
  19025. var p = func( u, v );
  19026. vertices.push( p.x, p.y, p.z );
  19027. uvs.push( u, v );
  19028. }
  19029. }
  19030. // generate indices
  19031. for ( i = 0; i < stacks; i ++ ) {
  19032. for ( j = 0; j < slices; j ++ ) {
  19033. var a = i * sliceCount + j;
  19034. var b = i * sliceCount + j + 1;
  19035. var c = ( i + 1 ) * sliceCount + j + 1;
  19036. var d = ( i + 1 ) * sliceCount + j;
  19037. // faces one and two
  19038. indices.push( a, b, d );
  19039. indices.push( b, c, d );
  19040. }
  19041. }
  19042. // build geometry
  19043. this.setIndex( indices );
  19044. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19045. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19046. // generate normals
  19047. this.computeVertexNormals();
  19048. }
  19049. ParametricBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  19050. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  19051. /**
  19052. * @author clockworkgeek / https://github.com/clockworkgeek
  19053. * @author timothypratley / https://github.com/timothypratley
  19054. * @author WestLangley / http://github.com/WestLangley
  19055. */
  19056. function PolyhedronGeometry( vertices, indices, radius, detail ) {
  19057. Geometry.call( this );
  19058. this.type = 'PolyhedronGeometry';
  19059. this.parameters = {
  19060. vertices: vertices,
  19061. indices: indices,
  19062. radius: radius,
  19063. detail: detail
  19064. };
  19065. this.fromBufferGeometry( new PolyhedronBufferGeometry( vertices, indices, radius, detail ) );
  19066. this.mergeVertices();
  19067. }
  19068. PolyhedronGeometry.prototype = Object.create( Geometry.prototype );
  19069. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry;
  19070. /**
  19071. * @author Mugen87 / https://github.com/Mugen87
  19072. */
  19073. function PolyhedronBufferGeometry( vertices, indices, radius, detail ) {
  19074. BufferGeometry.call( this );
  19075. this.type = 'PolyhedronBufferGeometry';
  19076. this.parameters = {
  19077. vertices: vertices,
  19078. indices: indices,
  19079. radius: radius,
  19080. detail: detail
  19081. };
  19082. radius = radius || 1;
  19083. detail = detail || 0;
  19084. // default buffer data
  19085. var vertexBuffer = [];
  19086. var uvBuffer = [];
  19087. // the subdivision creates the vertex buffer data
  19088. subdivide( detail );
  19089. // all vertices should lie on a conceptual sphere with a given radius
  19090. appplyRadius( radius );
  19091. // finally, create the uv data
  19092. generateUVs();
  19093. // build non-indexed geometry
  19094. this.addAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  19095. this.addAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  19096. this.addAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  19097. this.normalizeNormals();
  19098. // helper functions
  19099. function subdivide( detail ) {
  19100. var a = new Vector3();
  19101. var b = new Vector3();
  19102. var c = new Vector3();
  19103. // iterate over all faces and apply a subdivison with the given detail value
  19104. for ( var i = 0; i < indices.length; i += 3 ) {
  19105. // get the vertices of the face
  19106. getVertexByIndex( indices[ i + 0 ], a );
  19107. getVertexByIndex( indices[ i + 1 ], b );
  19108. getVertexByIndex( indices[ i + 2 ], c );
  19109. // perform subdivision
  19110. subdivideFace( a, b, c, detail );
  19111. }
  19112. }
  19113. function subdivideFace( a, b, c, detail ) {
  19114. var cols = Math.pow( 2, detail );
  19115. // we use this multidimensional array as a data structure for creating the subdivision
  19116. var v = [];
  19117. var i, j;
  19118. // construct all of the vertices for this subdivision
  19119. for ( i = 0; i <= cols; i ++ ) {
  19120. v[ i ] = [];
  19121. var aj = a.clone().lerp( c, i / cols );
  19122. var bj = b.clone().lerp( c, i / cols );
  19123. var rows = cols - i;
  19124. for ( j = 0; j <= rows; j ++ ) {
  19125. if ( j === 0 && i === cols ) {
  19126. v[ i ][ j ] = aj;
  19127. } else {
  19128. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  19129. }
  19130. }
  19131. }
  19132. // construct all of the faces
  19133. for ( i = 0; i < cols; i ++ ) {
  19134. for ( j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  19135. var k = Math.floor( j / 2 );
  19136. if ( j % 2 === 0 ) {
  19137. pushVertex( v[ i ][ k + 1 ] );
  19138. pushVertex( v[ i + 1 ][ k ] );
  19139. pushVertex( v[ i ][ k ] );
  19140. } else {
  19141. pushVertex( v[ i ][ k + 1 ] );
  19142. pushVertex( v[ i + 1 ][ k + 1 ] );
  19143. pushVertex( v[ i + 1 ][ k ] );
  19144. }
  19145. }
  19146. }
  19147. }
  19148. function appplyRadius( radius ) {
  19149. var vertex = new Vector3();
  19150. // iterate over the entire buffer and apply the radius to each vertex
  19151. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  19152. vertex.x = vertexBuffer[ i + 0 ];
  19153. vertex.y = vertexBuffer[ i + 1 ];
  19154. vertex.z = vertexBuffer[ i + 2 ];
  19155. vertex.normalize().multiplyScalar( radius );
  19156. vertexBuffer[ i + 0 ] = vertex.x;
  19157. vertexBuffer[ i + 1 ] = vertex.y;
  19158. vertexBuffer[ i + 2 ] = vertex.z;
  19159. }
  19160. }
  19161. function generateUVs() {
  19162. var vertex = new Vector3();
  19163. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  19164. vertex.x = vertexBuffer[ i + 0 ];
  19165. vertex.y = vertexBuffer[ i + 1 ];
  19166. vertex.z = vertexBuffer[ i + 2 ];
  19167. var u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  19168. var v = inclination( vertex ) / Math.PI + 0.5;
  19169. uvBuffer.push( u, 1 - v );
  19170. }
  19171. correctUVs();
  19172. correctSeam();
  19173. }
  19174. function correctSeam() {
  19175. // handle case when face straddles the seam, see #3269
  19176. for ( var i = 0; i < uvBuffer.length; i += 6 ) {
  19177. // uv data of a single face
  19178. var x0 = uvBuffer[ i + 0 ];
  19179. var x1 = uvBuffer[ i + 2 ];
  19180. var x2 = uvBuffer[ i + 4 ];
  19181. var max = Math.max( x0, x1, x2 );
  19182. var min = Math.min( x0, x1, x2 );
  19183. // 0.9 is somewhat arbitrary
  19184. if ( max > 0.9 && min < 0.1 ) {
  19185. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  19186. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  19187. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  19188. }
  19189. }
  19190. }
  19191. function pushVertex( vertex ) {
  19192. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  19193. }
  19194. function getVertexByIndex( index, vertex ) {
  19195. var stride = index * 3;
  19196. vertex.x = vertices[ stride + 0 ];
  19197. vertex.y = vertices[ stride + 1 ];
  19198. vertex.z = vertices[ stride + 2 ];
  19199. }
  19200. function correctUVs() {
  19201. var a = new Vector3();
  19202. var b = new Vector3();
  19203. var c = new Vector3();
  19204. var centroid = new Vector3();
  19205. var uvA = new Vector2();
  19206. var uvB = new Vector2();
  19207. var uvC = new Vector2();
  19208. for ( var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  19209. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  19210. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  19211. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  19212. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  19213. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  19214. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  19215. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  19216. var azi = azimuth( centroid );
  19217. correctUV( uvA, j + 0, a, azi );
  19218. correctUV( uvB, j + 2, b, azi );
  19219. correctUV( uvC, j + 4, c, azi );
  19220. }
  19221. }
  19222. function correctUV( uv, stride, vector, azimuth ) {
  19223. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  19224. uvBuffer[ stride ] = uv.x - 1;
  19225. }
  19226. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  19227. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  19228. }
  19229. }
  19230. // Angle around the Y axis, counter-clockwise when looking from above.
  19231. function azimuth( vector ) {
  19232. return Math.atan2( vector.z, - vector.x );
  19233. }
  19234. // Angle above the XZ plane.
  19235. function inclination( vector ) {
  19236. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19237. }
  19238. }
  19239. PolyhedronBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  19240. PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;
  19241. /**
  19242. * @author timothypratley / https://github.com/timothypratley
  19243. */
  19244. function TetrahedronGeometry( radius, detail ) {
  19245. Geometry.call( this );
  19246. this.type = 'TetrahedronGeometry';
  19247. this.parameters = {
  19248. radius: radius,
  19249. detail: detail
  19250. };
  19251. this.fromBufferGeometry( new TetrahedronBufferGeometry( radius, detail ) );
  19252. this.mergeVertices();
  19253. }
  19254. TetrahedronGeometry.prototype = Object.create( Geometry.prototype );
  19255. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry;
  19256. /**
  19257. * @author Mugen87 / https://github.com/Mugen87
  19258. */
  19259. function TetrahedronBufferGeometry( radius, detail ) {
  19260. var vertices = [
  19261. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  19262. ];
  19263. var indices = [
  19264. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  19265. ];
  19266. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  19267. this.type = 'TetrahedronBufferGeometry';
  19268. this.parameters = {
  19269. radius: radius,
  19270. detail: detail
  19271. };
  19272. }
  19273. TetrahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  19274. TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;
  19275. /**
  19276. * @author timothypratley / https://github.com/timothypratley
  19277. */
  19278. function OctahedronGeometry( radius, detail ) {
  19279. Geometry.call( this );
  19280. this.type = 'OctahedronGeometry';
  19281. this.parameters = {
  19282. radius: radius,
  19283. detail: detail
  19284. };
  19285. this.fromBufferGeometry( new OctahedronBufferGeometry( radius, detail ) );
  19286. this.mergeVertices();
  19287. }
  19288. OctahedronGeometry.prototype = Object.create( Geometry.prototype );
  19289. OctahedronGeometry.prototype.constructor = OctahedronGeometry;
  19290. /**
  19291. * @author Mugen87 / https://github.com/Mugen87
  19292. */
  19293. function OctahedronBufferGeometry( radius, detail ) {
  19294. var vertices = [
  19295. 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  19296. ];
  19297. var indices = [
  19298. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  19299. ];
  19300. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  19301. this.type = 'OctahedronBufferGeometry';
  19302. this.parameters = {
  19303. radius: radius,
  19304. detail: detail
  19305. };
  19306. }
  19307. OctahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  19308. OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;
  19309. /**
  19310. * @author timothypratley / https://github.com/timothypratley
  19311. */
  19312. function IcosahedronGeometry( radius, detail ) {
  19313. Geometry.call( this );
  19314. this.type = 'IcosahedronGeometry';
  19315. this.parameters = {
  19316. radius: radius,
  19317. detail: detail
  19318. };
  19319. this.fromBufferGeometry( new IcosahedronBufferGeometry( radius, detail ) );
  19320. this.mergeVertices();
  19321. }
  19322. IcosahedronGeometry.prototype = Object.create( Geometry.prototype );
  19323. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry;
  19324. /**
  19325. * @author Mugen87 / https://github.com/Mugen87
  19326. */
  19327. function IcosahedronBufferGeometry( radius, detail ) {
  19328. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19329. var vertices = [
  19330. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  19331. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  19332. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  19333. ];
  19334. var indices = [
  19335. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  19336. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  19337. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  19338. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  19339. ];
  19340. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  19341. this.type = 'IcosahedronBufferGeometry';
  19342. this.parameters = {
  19343. radius: radius,
  19344. detail: detail
  19345. };
  19346. }
  19347. IcosahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  19348. IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;
  19349. /**
  19350. * @author Abe Pazos / https://hamoid.com
  19351. */
  19352. function DodecahedronGeometry( radius, detail ) {
  19353. Geometry.call( this );
  19354. this.type = 'DodecahedronGeometry';
  19355. this.parameters = {
  19356. radius: radius,
  19357. detail: detail
  19358. };
  19359. this.fromBufferGeometry( new DodecahedronBufferGeometry( radius, detail ) );
  19360. this.mergeVertices();
  19361. }
  19362. DodecahedronGeometry.prototype = Object.create( Geometry.prototype );
  19363. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry;
  19364. /**
  19365. * @author Mugen87 / https://github.com/Mugen87
  19366. */
  19367. function DodecahedronBufferGeometry( radius, detail ) {
  19368. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19369. var r = 1 / t;
  19370. var vertices = [
  19371. // (±1, ±1, ±1)
  19372. - 1, - 1, - 1, - 1, - 1, 1,
  19373. - 1, 1, - 1, - 1, 1, 1,
  19374. 1, - 1, - 1, 1, - 1, 1,
  19375. 1, 1, - 1, 1, 1, 1,
  19376. // (0, ±1/φ, ±φ)
  19377. 0, - r, - t, 0, - r, t,
  19378. 0, r, - t, 0, r, t,
  19379. // (±1/φ, ±φ, 0)
  19380. - r, - t, 0, - r, t, 0,
  19381. r, - t, 0, r, t, 0,
  19382. // (±φ, 0, ±1/φ)
  19383. - t, 0, - r, t, 0, - r,
  19384. - t, 0, r, t, 0, r
  19385. ];
  19386. var indices = [
  19387. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  19388. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  19389. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  19390. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  19391. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  19392. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  19393. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  19394. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  19395. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  19396. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  19397. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  19398. 1, 12, 14, 1, 14, 5, 1, 5, 9
  19399. ];
  19400. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  19401. this.type = 'DodecahedronBufferGeometry';
  19402. this.parameters = {
  19403. radius: radius,
  19404. detail: detail
  19405. };
  19406. }
  19407. DodecahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  19408. DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;
  19409. /**
  19410. * @author oosmoxiecode / https://github.com/oosmoxiecode
  19411. * @author WestLangley / https://github.com/WestLangley
  19412. * @author zz85 / https://github.com/zz85
  19413. * @author miningold / https://github.com/miningold
  19414. * @author jonobr1 / https://github.com/jonobr1
  19415. *
  19416. * Creates a tube which extrudes along a 3d spline.
  19417. */
  19418. function TubeGeometry( path, tubularSegments, radius, radialSegments, closed, taper ) {
  19419. Geometry.call( this );
  19420. this.type = 'TubeGeometry';
  19421. this.parameters = {
  19422. path: path,
  19423. tubularSegments: tubularSegments,
  19424. radius: radius,
  19425. radialSegments: radialSegments,
  19426. closed: closed
  19427. };
  19428. if ( taper !== undefined ) console.warn( 'THREE.TubeGeometry: taper has been removed.' );
  19429. var bufferGeometry = new TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed );
  19430. // expose internals
  19431. this.tangents = bufferGeometry.tangents;
  19432. this.normals = bufferGeometry.normals;
  19433. this.binormals = bufferGeometry.binormals;
  19434. // create geometry
  19435. this.fromBufferGeometry( bufferGeometry );
  19436. this.mergeVertices();
  19437. }
  19438. TubeGeometry.prototype = Object.create( Geometry.prototype );
  19439. TubeGeometry.prototype.constructor = TubeGeometry;
  19440. /**
  19441. * @author Mugen87 / https://github.com/Mugen87
  19442. */
  19443. function TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed ) {
  19444. BufferGeometry.call( this );
  19445. this.type = 'TubeBufferGeometry';
  19446. this.parameters = {
  19447. path: path,
  19448. tubularSegments: tubularSegments,
  19449. radius: radius,
  19450. radialSegments: radialSegments,
  19451. closed: closed
  19452. };
  19453. tubularSegments = tubularSegments || 64;
  19454. radius = radius || 1;
  19455. radialSegments = radialSegments || 8;
  19456. closed = closed || false;
  19457. var frames = path.computeFrenetFrames( tubularSegments, closed );
  19458. // expose internals
  19459. this.tangents = frames.tangents;
  19460. this.normals = frames.normals;
  19461. this.binormals = frames.binormals;
  19462. // helper variables
  19463. var vertex = new Vector3();
  19464. var normal = new Vector3();
  19465. var uv = new Vector2();
  19466. var i, j;
  19467. // buffer
  19468. var vertices = [];
  19469. var normals = [];
  19470. var uvs = [];
  19471. var indices = [];
  19472. // create buffer data
  19473. generateBufferData();
  19474. // build geometry
  19475. this.setIndex( indices );
  19476. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19477. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19478. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19479. // functions
  19480. function generateBufferData() {
  19481. for ( i = 0; i < tubularSegments; i ++ ) {
  19482. generateSegment( i );
  19483. }
  19484. // if the geometry is not closed, generate the last row of vertices and normals
  19485. // at the regular position on the given path
  19486. //
  19487. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  19488. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  19489. // uvs are generated in a separate function.
  19490. // this makes it easy compute correct values for closed geometries
  19491. generateUVs();
  19492. // finally create faces
  19493. generateIndices();
  19494. }
  19495. function generateSegment( i ) {
  19496. // we use getPointAt to sample evenly distributed points from the given path
  19497. var P = path.getPointAt( i / tubularSegments );
  19498. // retrieve corresponding normal and binormal
  19499. var N = frames.normals[ i ];
  19500. var B = frames.binormals[ i ];
  19501. // generate normals and vertices for the current segment
  19502. for ( j = 0; j <= radialSegments; j ++ ) {
  19503. var v = j / radialSegments * Math.PI * 2;
  19504. var sin = Math.sin( v );
  19505. var cos = - Math.cos( v );
  19506. // normal
  19507. normal.x = ( cos * N.x + sin * B.x );
  19508. normal.y = ( cos * N.y + sin * B.y );
  19509. normal.z = ( cos * N.z + sin * B.z );
  19510. normal.normalize();
  19511. normals.push( normal.x, normal.y, normal.z );
  19512. // vertex
  19513. vertex.x = P.x + radius * normal.x;
  19514. vertex.y = P.y + radius * normal.y;
  19515. vertex.z = P.z + radius * normal.z;
  19516. vertices.push( vertex.x, vertex.y, vertex.z );
  19517. }
  19518. }
  19519. function generateIndices() {
  19520. for ( j = 1; j <= tubularSegments; j ++ ) {
  19521. for ( i = 1; i <= radialSegments; i ++ ) {
  19522. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  19523. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  19524. var c = ( radialSegments + 1 ) * j + i;
  19525. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  19526. // faces
  19527. indices.push( a, b, d );
  19528. indices.push( b, c, d );
  19529. }
  19530. }
  19531. }
  19532. function generateUVs() {
  19533. for ( i = 0; i <= tubularSegments; i ++ ) {
  19534. for ( j = 0; j <= radialSegments; j ++ ) {
  19535. uv.x = i / tubularSegments;
  19536. uv.y = j / radialSegments;
  19537. uvs.push( uv.x, uv.y );
  19538. }
  19539. }
  19540. }
  19541. }
  19542. TubeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  19543. TubeBufferGeometry.prototype.constructor = TubeBufferGeometry;
  19544. /**
  19545. * @author oosmoxiecode
  19546. */
  19547. function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {
  19548. Geometry.call( this );
  19549. this.type = 'TorusKnotGeometry';
  19550. this.parameters = {
  19551. radius: radius,
  19552. tube: tube,
  19553. tubularSegments: tubularSegments,
  19554. radialSegments: radialSegments,
  19555. p: p,
  19556. q: q
  19557. };
  19558. if ( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' );
  19559. this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
  19560. this.mergeVertices();
  19561. }
  19562. TorusKnotGeometry.prototype = Object.create( Geometry.prototype );
  19563. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry;
  19564. /**
  19565. * @author Mugen87 / https://github.com/Mugen87
  19566. * see: http://www.blackpawn.com/texts/pqtorus/
  19567. */
  19568. function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) {
  19569. BufferGeometry.call( this );
  19570. this.type = 'TorusKnotBufferGeometry';
  19571. this.parameters = {
  19572. radius: radius,
  19573. tube: tube,
  19574. tubularSegments: tubularSegments,
  19575. radialSegments: radialSegments,
  19576. p: p,
  19577. q: q
  19578. };
  19579. radius = radius || 100;
  19580. tube = tube || 40;
  19581. tubularSegments = Math.floor( tubularSegments ) || 64;
  19582. radialSegments = Math.floor( radialSegments ) || 8;
  19583. p = p || 2;
  19584. q = q || 3;
  19585. // buffers
  19586. var indices = [];
  19587. var vertices = [];
  19588. var normals = [];
  19589. var uvs = [];
  19590. // helper variables
  19591. var i, j;
  19592. var vertex = new Vector3();
  19593. var normal = new Vector3();
  19594. var uv = new Vector2();
  19595. var P1 = new Vector3();
  19596. var P2 = new Vector3();
  19597. var B = new Vector3();
  19598. var T = new Vector3();
  19599. var N = new Vector3();
  19600. // generate vertices, normals and uvs
  19601. for ( i = 0; i <= tubularSegments; ++ i ) {
  19602. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  19603. var u = i / tubularSegments * p * Math.PI * 2;
  19604. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  19605. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  19606. calculatePositionOnCurve( u, p, q, radius, P1 );
  19607. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  19608. // calculate orthonormal basis
  19609. T.subVectors( P2, P1 );
  19610. N.addVectors( P2, P1 );
  19611. B.crossVectors( T, N );
  19612. N.crossVectors( B, T );
  19613. // normalize B, N. T can be ignored, we don't use it
  19614. B.normalize();
  19615. N.normalize();
  19616. for ( j = 0; j <= radialSegments; ++ j ) {
  19617. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  19618. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  19619. var v = j / radialSegments * Math.PI * 2;
  19620. var cx = - tube * Math.cos( v );
  19621. var cy = tube * Math.sin( v );
  19622. // now calculate the final vertex position.
  19623. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  19624. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  19625. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  19626. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  19627. vertices.push( vertex.x, vertex.y, vertex.z );
  19628. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  19629. normal.subVectors( vertex, P1 ).normalize();
  19630. normals.push( normal.x, normal.y, normal.z );
  19631. // uv
  19632. uvs.push( i / tubularSegments );
  19633. uvs.push( j / radialSegments );
  19634. }
  19635. }
  19636. // generate indices
  19637. for ( j = 1; j <= tubularSegments; j ++ ) {
  19638. for ( i = 1; i <= radialSegments; i ++ ) {
  19639. // indices
  19640. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  19641. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  19642. var c = ( radialSegments + 1 ) * j + i;
  19643. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  19644. // faces
  19645. indices.push( a, b, d );
  19646. indices.push( b, c, d );
  19647. }
  19648. }
  19649. // build geometry
  19650. this.setIndex( indices );
  19651. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19652. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19653. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19654. // this function calculates the current position on the torus curve
  19655. function calculatePositionOnCurve( u, p, q, radius, position ) {
  19656. var cu = Math.cos( u );
  19657. var su = Math.sin( u );
  19658. var quOverP = q / p * u;
  19659. var cs = Math.cos( quOverP );
  19660. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  19661. position.y = radius * ( 2 + cs ) * su * 0.5;
  19662. position.z = radius * Math.sin( quOverP ) * 0.5;
  19663. }
  19664. }
  19665. TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  19666. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  19667. /**
  19668. * @author oosmoxiecode
  19669. * @author mrdoob / http://mrdoob.com/
  19670. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19671. */
  19672. function TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  19673. Geometry.call( this );
  19674. this.type = 'TorusGeometry';
  19675. this.parameters = {
  19676. radius: radius,
  19677. tube: tube,
  19678. radialSegments: radialSegments,
  19679. tubularSegments: tubularSegments,
  19680. arc: arc
  19681. };
  19682. this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) );
  19683. }
  19684. TorusGeometry.prototype = Object.create( Geometry.prototype );
  19685. TorusGeometry.prototype.constructor = TorusGeometry;
  19686. /**
  19687. * @author Mugen87 / https://github.com/Mugen87
  19688. */
  19689. function TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  19690. BufferGeometry.call( this );
  19691. this.type = 'TorusBufferGeometry';
  19692. this.parameters = {
  19693. radius: radius,
  19694. tube: tube,
  19695. radialSegments: radialSegments,
  19696. tubularSegments: tubularSegments,
  19697. arc: arc
  19698. };
  19699. radius = radius || 100;
  19700. tube = tube || 40;
  19701. radialSegments = Math.floor( radialSegments ) || 8;
  19702. tubularSegments = Math.floor( tubularSegments ) || 6;
  19703. arc = arc || Math.PI * 2;
  19704. // buffers
  19705. var indices = [];
  19706. var vertices = [];
  19707. var normals = [];
  19708. var uvs = [];
  19709. // helper variables
  19710. var center = new Vector3();
  19711. var vertex = new Vector3();
  19712. var normal = new Vector3();
  19713. var j, i;
  19714. // generate vertices, normals and uvs
  19715. for ( j = 0; j <= radialSegments; j ++ ) {
  19716. for ( i = 0; i <= tubularSegments; i ++ ) {
  19717. var u = i / tubularSegments * arc;
  19718. var v = j / radialSegments * Math.PI * 2;
  19719. // vertex
  19720. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  19721. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  19722. vertex.z = tube * Math.sin( v );
  19723. vertices.push( vertex.x, vertex.y, vertex.z );
  19724. // normal
  19725. center.x = radius * Math.cos( u );
  19726. center.y = radius * Math.sin( u );
  19727. normal.subVectors( vertex, center ).normalize();
  19728. normals.push( normal.x, normal.y, normal.z );
  19729. // uv
  19730. uvs.push( i / tubularSegments );
  19731. uvs.push( j / radialSegments );
  19732. }
  19733. }
  19734. // generate indices
  19735. for ( j = 1; j <= radialSegments; j ++ ) {
  19736. for ( i = 1; i <= tubularSegments; i ++ ) {
  19737. // indices
  19738. var a = ( tubularSegments + 1 ) * j + i - 1;
  19739. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19740. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  19741. var d = ( tubularSegments + 1 ) * j + i;
  19742. // faces
  19743. indices.push( a, b, d );
  19744. indices.push( b, c, d );
  19745. }
  19746. }
  19747. // build geometry
  19748. this.setIndex( indices );
  19749. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19750. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19751. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19752. }
  19753. TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  19754. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  19755. /**
  19756. * @author zz85 / http://www.lab4games.net/zz85/blog
  19757. */
  19758. var ShapeUtils = {
  19759. // calculate area of the contour polygon
  19760. area: function ( contour ) {
  19761. var n = contour.length;
  19762. var a = 0.0;
  19763. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  19764. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  19765. }
  19766. return a * 0.5;
  19767. },
  19768. triangulate: ( function () {
  19769. /**
  19770. * This code is a quick port of code written in C++ which was submitted to
  19771. * flipcode.com by John W. Ratcliff // July 22, 2000
  19772. * See original code and more information here:
  19773. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  19774. *
  19775. * ported to actionscript by Zevan Rosser
  19776. * www.actionsnippet.com
  19777. *
  19778. * ported to javascript by Joshua Koo
  19779. * http://www.lab4games.net/zz85/blog
  19780. *
  19781. */
  19782. function snip( contour, u, v, w, n, verts ) {
  19783. var p;
  19784. var ax, ay, bx, by;
  19785. var cx, cy, px, py;
  19786. ax = contour[ verts[ u ] ].x;
  19787. ay = contour[ verts[ u ] ].y;
  19788. bx = contour[ verts[ v ] ].x;
  19789. by = contour[ verts[ v ] ].y;
  19790. cx = contour[ verts[ w ] ].x;
  19791. cy = contour[ verts[ w ] ].y;
  19792. if ( ( bx - ax ) * ( cy - ay ) - ( by - ay ) * ( cx - ax ) <= 0 ) return false;
  19793. var aX, aY, bX, bY, cX, cY;
  19794. var apx, apy, bpx, bpy, cpx, cpy;
  19795. var cCROSSap, bCROSScp, aCROSSbp;
  19796. aX = cx - bx; aY = cy - by;
  19797. bX = ax - cx; bY = ay - cy;
  19798. cX = bx - ax; cY = by - ay;
  19799. for ( p = 0; p < n; p ++ ) {
  19800. px = contour[ verts[ p ] ].x;
  19801. py = contour[ verts[ p ] ].y;
  19802. if ( ( ( px === ax ) && ( py === ay ) ) ||
  19803. ( ( px === bx ) && ( py === by ) ) ||
  19804. ( ( px === cx ) && ( py === cy ) ) ) continue;
  19805. apx = px - ax; apy = py - ay;
  19806. bpx = px - bx; bpy = py - by;
  19807. cpx = px - cx; cpy = py - cy;
  19808. // see if p is inside triangle abc
  19809. aCROSSbp = aX * bpy - aY * bpx;
  19810. cCROSSap = cX * apy - cY * apx;
  19811. bCROSScp = bX * cpy - bY * cpx;
  19812. if ( ( aCROSSbp >= - Number.EPSILON ) && ( bCROSScp >= - Number.EPSILON ) && ( cCROSSap >= - Number.EPSILON ) ) return false;
  19813. }
  19814. return true;
  19815. }
  19816. // takes in an contour array and returns
  19817. return function triangulate( contour, indices ) {
  19818. var n = contour.length;
  19819. if ( n < 3 ) return null;
  19820. var result = [],
  19821. verts = [],
  19822. vertIndices = [];
  19823. /* we want a counter-clockwise polygon in verts */
  19824. var u, v, w;
  19825. if ( ShapeUtils.area( contour ) > 0.0 ) {
  19826. for ( v = 0; v < n; v ++ ) verts[ v ] = v;
  19827. } else {
  19828. for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v;
  19829. }
  19830. var nv = n;
  19831. /* remove nv - 2 vertices, creating 1 triangle every time */
  19832. var count = 2 * nv; /* error detection */
  19833. for ( v = nv - 1; nv > 2; ) {
  19834. /* if we loop, it is probably a non-simple polygon */
  19835. if ( ( count -- ) <= 0 ) {
  19836. //** Triangulate: ERROR - probable bad polygon!
  19837. //throw ( "Warning, unable to triangulate polygon!" );
  19838. //return null;
  19839. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  19840. console.warn( 'THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()' );
  19841. if ( indices ) return vertIndices;
  19842. return result;
  19843. }
  19844. /* three consecutive vertices in current polygon, <u,v,w> */
  19845. u = v; if ( nv <= u ) u = 0; /* previous */
  19846. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  19847. w = v + 1; if ( nv <= w ) w = 0; /* next */
  19848. if ( snip( contour, u, v, w, nv, verts ) ) {
  19849. var a, b, c, s, t;
  19850. /* true names of the vertices */
  19851. a = verts[ u ];
  19852. b = verts[ v ];
  19853. c = verts[ w ];
  19854. /* output Triangle */
  19855. result.push( [ contour[ a ],
  19856. contour[ b ],
  19857. contour[ c ] ] );
  19858. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  19859. /* remove v from the remaining polygon */
  19860. for ( s = v, t = v + 1; t < nv; s ++, t ++ ) {
  19861. verts[ s ] = verts[ t ];
  19862. }
  19863. nv --;
  19864. /* reset error detection counter */
  19865. count = 2 * nv;
  19866. }
  19867. }
  19868. if ( indices ) return vertIndices;
  19869. return result;
  19870. }
  19871. } )(),
  19872. triangulateShape: function ( contour, holes ) {
  19873. function removeDupEndPts(points) {
  19874. var l = points.length;
  19875. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  19876. points.pop();
  19877. }
  19878. }
  19879. removeDupEndPts( contour );
  19880. holes.forEach( removeDupEndPts );
  19881. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  19882. // inOtherPt needs to be collinear to the inSegment
  19883. if ( inSegPt1.x !== inSegPt2.x ) {
  19884. if ( inSegPt1.x < inSegPt2.x ) {
  19885. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  19886. } else {
  19887. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  19888. }
  19889. } else {
  19890. if ( inSegPt1.y < inSegPt2.y ) {
  19891. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  19892. } else {
  19893. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  19894. }
  19895. }
  19896. }
  19897. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  19898. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  19899. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  19900. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  19901. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  19902. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  19903. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  19904. if ( Math.abs( limit ) > Number.EPSILON ) {
  19905. // not parallel
  19906. var perpSeg2;
  19907. if ( limit > 0 ) {
  19908. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  19909. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  19910. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  19911. } else {
  19912. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  19913. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  19914. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  19915. }
  19916. // i.e. to reduce rounding errors
  19917. // intersection at endpoint of segment#1?
  19918. if ( perpSeg2 === 0 ) {
  19919. if ( ( inExcludeAdjacentSegs ) &&
  19920. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  19921. return [ inSeg1Pt1 ];
  19922. }
  19923. if ( perpSeg2 === limit ) {
  19924. if ( ( inExcludeAdjacentSegs ) &&
  19925. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  19926. return [ inSeg1Pt2 ];
  19927. }
  19928. // intersection at endpoint of segment#2?
  19929. if ( perpSeg1 === 0 ) return [ inSeg2Pt1 ];
  19930. if ( perpSeg1 === limit ) return [ inSeg2Pt2 ];
  19931. // return real intersection point
  19932. var factorSeg1 = perpSeg2 / limit;
  19933. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  19934. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  19935. } else {
  19936. // parallel or collinear
  19937. if ( ( perpSeg1 !== 0 ) ||
  19938. ( seg2dy * seg1seg2dx !== seg2dx * seg1seg2dy ) ) return [];
  19939. // they are collinear or degenerate
  19940. var seg1Pt = ( ( seg1dx === 0 ) && ( seg1dy === 0 ) ); // segment1 is just a point?
  19941. var seg2Pt = ( ( seg2dx === 0 ) && ( seg2dy === 0 ) ); // segment2 is just a point?
  19942. // both segments are points
  19943. if ( seg1Pt && seg2Pt ) {
  19944. if ( ( inSeg1Pt1.x !== inSeg2Pt1.x ) ||
  19945. ( inSeg1Pt1.y !== inSeg2Pt1.y ) ) return []; // they are distinct points
  19946. return [ inSeg1Pt1 ]; // they are the same point
  19947. }
  19948. // segment#1 is a single point
  19949. if ( seg1Pt ) {
  19950. if ( ! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  19951. return [ inSeg1Pt1 ];
  19952. }
  19953. // segment#2 is a single point
  19954. if ( seg2Pt ) {
  19955. if ( ! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  19956. return [ inSeg2Pt1 ];
  19957. }
  19958. // they are collinear segments, which might overlap
  19959. var seg1min, seg1max, seg1minVal, seg1maxVal;
  19960. var seg2min, seg2max, seg2minVal, seg2maxVal;
  19961. if ( seg1dx !== 0 ) {
  19962. // the segments are NOT on a vertical line
  19963. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  19964. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  19965. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  19966. } else {
  19967. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  19968. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  19969. }
  19970. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  19971. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  19972. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  19973. } else {
  19974. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  19975. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  19976. }
  19977. } else {
  19978. // the segments are on a vertical line
  19979. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  19980. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  19981. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  19982. } else {
  19983. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  19984. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  19985. }
  19986. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  19987. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  19988. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  19989. } else {
  19990. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  19991. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  19992. }
  19993. }
  19994. if ( seg1minVal <= seg2minVal ) {
  19995. if ( seg1maxVal < seg2minVal ) return [];
  19996. if ( seg1maxVal === seg2minVal ) {
  19997. if ( inExcludeAdjacentSegs ) return [];
  19998. return [ seg2min ];
  19999. }
  20000. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  20001. return [ seg2min, seg2max ];
  20002. } else {
  20003. if ( seg1minVal > seg2maxVal ) return [];
  20004. if ( seg1minVal === seg2maxVal ) {
  20005. if ( inExcludeAdjacentSegs ) return [];
  20006. return [ seg1min ];
  20007. }
  20008. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  20009. return [ seg1min, seg2max ];
  20010. }
  20011. }
  20012. }
  20013. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  20014. // The order of legs is important
  20015. // translation of all points, so that Vertex is at (0,0)
  20016. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  20017. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  20018. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  20019. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  20020. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  20021. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  20022. if ( Math.abs( from2toAngle ) > Number.EPSILON ) {
  20023. // angle != 180 deg.
  20024. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  20025. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  20026. if ( from2toAngle > 0 ) {
  20027. // main angle < 180 deg.
  20028. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  20029. } else {
  20030. // main angle > 180 deg.
  20031. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  20032. }
  20033. } else {
  20034. // angle == 180 deg.
  20035. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  20036. return ( from2otherAngle > 0 );
  20037. }
  20038. }
  20039. function removeHoles( contour, holes ) {
  20040. var shape = contour.concat(); // work on this shape
  20041. var hole;
  20042. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  20043. // Check if hole point lies within angle around shape point
  20044. var lastShapeIdx = shape.length - 1;
  20045. var prevShapeIdx = inShapeIdx - 1;
  20046. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  20047. var nextShapeIdx = inShapeIdx + 1;
  20048. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  20049. var insideAngle = isPointInsideAngle( shape[ inShapeIdx ], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[ inHoleIdx ] );
  20050. if ( ! insideAngle ) {
  20051. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  20052. return false;
  20053. }
  20054. // Check if shape point lies within angle around hole point
  20055. var lastHoleIdx = hole.length - 1;
  20056. var prevHoleIdx = inHoleIdx - 1;
  20057. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  20058. var nextHoleIdx = inHoleIdx + 1;
  20059. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  20060. insideAngle = isPointInsideAngle( hole[ inHoleIdx ], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[ inShapeIdx ] );
  20061. if ( ! insideAngle ) {
  20062. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  20063. return false;
  20064. }
  20065. return true;
  20066. }
  20067. function intersectsShapeEdge( inShapePt, inHolePt ) {
  20068. // checks for intersections with shape edges
  20069. var sIdx, nextIdx, intersection;
  20070. for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) {
  20071. nextIdx = sIdx + 1; nextIdx %= shape.length;
  20072. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[ sIdx ], shape[ nextIdx ], true );
  20073. if ( intersection.length > 0 ) return true;
  20074. }
  20075. return false;
  20076. }
  20077. var indepHoles = [];
  20078. function intersectsHoleEdge( inShapePt, inHolePt ) {
  20079. // checks for intersections with hole edges
  20080. var ihIdx, chkHole,
  20081. hIdx, nextIdx, intersection;
  20082. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) {
  20083. chkHole = holes[ indepHoles[ ihIdx ]];
  20084. for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) {
  20085. nextIdx = hIdx + 1; nextIdx %= chkHole.length;
  20086. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[ hIdx ], chkHole[ nextIdx ], true );
  20087. if ( intersection.length > 0 ) return true;
  20088. }
  20089. }
  20090. return false;
  20091. }
  20092. var holeIndex, shapeIndex,
  20093. shapePt, holePt,
  20094. holeIdx, cutKey, failedCuts = [],
  20095. tmpShape1, tmpShape2,
  20096. tmpHole1, tmpHole2;
  20097. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  20098. indepHoles.push( h );
  20099. }
  20100. var minShapeIndex = 0;
  20101. var counter = indepHoles.length * 2;
  20102. while ( indepHoles.length > 0 ) {
  20103. counter --;
  20104. if ( counter < 0 ) {
  20105. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  20106. break;
  20107. }
  20108. // search for shape-vertex and hole-vertex,
  20109. // which can be connected without intersections
  20110. for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) {
  20111. shapePt = shape[ shapeIndex ];
  20112. holeIndex = - 1;
  20113. // search for hole which can be reached without intersections
  20114. for ( var h = 0; h < indepHoles.length; h ++ ) {
  20115. holeIdx = indepHoles[ h ];
  20116. // prevent multiple checks
  20117. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  20118. if ( failedCuts[ cutKey ] !== undefined ) continue;
  20119. hole = holes[ holeIdx ];
  20120. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  20121. holePt = hole[ h2 ];
  20122. if ( ! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  20123. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  20124. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  20125. holeIndex = h2;
  20126. indepHoles.splice( h, 1 );
  20127. tmpShape1 = shape.slice( 0, shapeIndex + 1 );
  20128. tmpShape2 = shape.slice( shapeIndex );
  20129. tmpHole1 = hole.slice( holeIndex );
  20130. tmpHole2 = hole.slice( 0, holeIndex + 1 );
  20131. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  20132. minShapeIndex = shapeIndex;
  20133. // Debug only, to show the selected cuts
  20134. // glob_CutLines.push( [ shapePt, holePt ] );
  20135. break;
  20136. }
  20137. if ( holeIndex >= 0 ) break; // hole-vertex found
  20138. failedCuts[ cutKey ] = true; // remember failure
  20139. }
  20140. if ( holeIndex >= 0 ) break; // hole-vertex found
  20141. }
  20142. }
  20143. return shape; /* shape with no holes */
  20144. }
  20145. var i, il, f, face,
  20146. key, index,
  20147. allPointsMap = {};
  20148. // 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.
  20149. var allpoints = contour.concat();
  20150. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  20151. Array.prototype.push.apply( allpoints, holes[ h ] );
  20152. }
  20153. //console.log( "allpoints",allpoints, allpoints.length );
  20154. // prepare all points map
  20155. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  20156. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  20157. if ( allPointsMap[ key ] !== undefined ) {
  20158. console.warn( "THREE.ShapeUtils: Duplicate point", key, i );
  20159. }
  20160. allPointsMap[ key ] = i;
  20161. }
  20162. // remove holes by cutting paths to holes and adding them to the shape
  20163. var shapeWithoutHoles = removeHoles( contour, holes );
  20164. var triangles = ShapeUtils.triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  20165. //console.log( "triangles",triangles, triangles.length );
  20166. // check all face vertices against all points map
  20167. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  20168. face = triangles[ i ];
  20169. for ( f = 0; f < 3; f ++ ) {
  20170. key = face[ f ].x + ":" + face[ f ].y;
  20171. index = allPointsMap[ key ];
  20172. if ( index !== undefined ) {
  20173. face[ f ] = index;
  20174. }
  20175. }
  20176. }
  20177. return triangles.concat();
  20178. },
  20179. isClockWise: function ( pts ) {
  20180. return ShapeUtils.area( pts ) < 0;
  20181. }
  20182. };
  20183. /**
  20184. * @author zz85 / http://www.lab4games.net/zz85/blog
  20185. *
  20186. * Creates extruded geometry from a path shape.
  20187. *
  20188. * parameters = {
  20189. *
  20190. * curveSegments: <int>, // number of points on the curves
  20191. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  20192. * amount: <int>, // Depth to extrude the shape
  20193. *
  20194. * bevelEnabled: <bool>, // turn on bevel
  20195. * bevelThickness: <float>, // how deep into the original shape bevel goes
  20196. * bevelSize: <float>, // how far from shape outline is bevel
  20197. * bevelSegments: <int>, // number of bevel layers
  20198. *
  20199. * extrudePath: <THREE.Curve> // curve to extrude shape along
  20200. * frames: <Object> // containing arrays of tangents, normals, binormals
  20201. *
  20202. * uvGenerator: <Object> // object that provides UV generator functions
  20203. *
  20204. * }
  20205. **/
  20206. function ExtrudeGeometry( shapes, options ) {
  20207. if ( typeof( shapes ) === "undefined" ) {
  20208. shapes = [];
  20209. return;
  20210. }
  20211. Geometry.call( this );
  20212. this.type = 'ExtrudeGeometry';
  20213. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  20214. this.addShapeList( shapes, options );
  20215. this.computeFaceNormals();
  20216. // can't really use automatic vertex normals
  20217. // as then front and back sides get smoothed too
  20218. // should do separate smoothing just for sides
  20219. //this.computeVertexNormals();
  20220. //console.log( "took", ( Date.now() - startTime ) );
  20221. }
  20222. ExtrudeGeometry.prototype = Object.create( Geometry.prototype );
  20223. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  20224. ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  20225. var sl = shapes.length;
  20226. for ( var s = 0; s < sl; s ++ ) {
  20227. var shape = shapes[ s ];
  20228. this.addShape( shape, options );
  20229. }
  20230. };
  20231. ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  20232. var amount = options.amount !== undefined ? options.amount : 100;
  20233. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  20234. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  20235. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  20236. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  20237. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  20238. var steps = options.steps !== undefined ? options.steps : 1;
  20239. var extrudePath = options.extrudePath;
  20240. var extrudePts, extrudeByPath = false;
  20241. // Use default WorldUVGenerator if no UV generators are specified.
  20242. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : ExtrudeGeometry.WorldUVGenerator;
  20243. var splineTube, binormal, normal, position2;
  20244. if ( extrudePath ) {
  20245. extrudePts = extrudePath.getSpacedPoints( steps );
  20246. extrudeByPath = true;
  20247. bevelEnabled = false; // bevels not supported for path extrusion
  20248. // SETUP TNB variables
  20249. // TODO1 - have a .isClosed in spline?
  20250. splineTube = options.frames !== undefined ? options.frames : extrudePath.computeFrenetFrames( steps, false );
  20251. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  20252. binormal = new Vector3();
  20253. normal = new Vector3();
  20254. position2 = new Vector3();
  20255. }
  20256. // Safeguards if bevels are not enabled
  20257. if ( ! bevelEnabled ) {
  20258. bevelSegments = 0;
  20259. bevelThickness = 0;
  20260. bevelSize = 0;
  20261. }
  20262. // Variables initialization
  20263. var ahole, h, hl; // looping of holes
  20264. var scope = this;
  20265. var shapesOffset = this.vertices.length;
  20266. var shapePoints = shape.extractPoints( curveSegments );
  20267. var vertices = shapePoints.shape;
  20268. var holes = shapePoints.holes;
  20269. var reverse = ! ShapeUtils.isClockWise( vertices );
  20270. if ( reverse ) {
  20271. vertices = vertices.reverse();
  20272. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  20273. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  20274. ahole = holes[ h ];
  20275. if ( ShapeUtils.isClockWise( ahole ) ) {
  20276. holes[ h ] = ahole.reverse();
  20277. }
  20278. }
  20279. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  20280. }
  20281. var faces = ShapeUtils.triangulateShape( vertices, holes );
  20282. /* Vertices */
  20283. var contour = vertices; // vertices has all points but contour has only points of circumference
  20284. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  20285. ahole = holes[ h ];
  20286. vertices = vertices.concat( ahole );
  20287. }
  20288. function scalePt2( pt, vec, size ) {
  20289. if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" );
  20290. return vec.clone().multiplyScalar( size ).add( pt );
  20291. }
  20292. var b, bs, t, z,
  20293. vert, vlen = vertices.length,
  20294. face, flen = faces.length;
  20295. // Find directions for point movement
  20296. function getBevelVec( inPt, inPrev, inNext ) {
  20297. // computes for inPt the corresponding point inPt' on a new contour
  20298. // shifted by 1 unit (length of normalized vector) to the left
  20299. // if we walk along contour clockwise, this new contour is outside the old one
  20300. //
  20301. // inPt' is the intersection of the two lines parallel to the two
  20302. // adjacent edges of inPt at a distance of 1 unit on the left side.
  20303. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  20304. // good reading for geometry algorithms (here: line-line intersection)
  20305. // http://geomalgorithms.com/a05-_intersect-1.html
  20306. var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y;
  20307. var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y;
  20308. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  20309. // check for collinear edges
  20310. var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  20311. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  20312. // not collinear
  20313. // length of vectors for normalizing
  20314. var v_prev_len = Math.sqrt( v_prev_lensq );
  20315. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  20316. // shift adjacent points by unit vectors to the left
  20317. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  20318. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  20319. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  20320. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  20321. // scaling factor for v_prev to intersection point
  20322. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  20323. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  20324. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  20325. // vector from inPt to intersection point
  20326. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  20327. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  20328. // Don't normalize!, otherwise sharp corners become ugly
  20329. // but prevent crazy spikes
  20330. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  20331. if ( v_trans_lensq <= 2 ) {
  20332. return new Vector2( v_trans_x, v_trans_y );
  20333. } else {
  20334. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  20335. }
  20336. } else {
  20337. // handle special case of collinear edges
  20338. var direction_eq = false; // assumes: opposite
  20339. if ( v_prev_x > Number.EPSILON ) {
  20340. if ( v_next_x > Number.EPSILON ) {
  20341. direction_eq = true;
  20342. }
  20343. } else {
  20344. if ( v_prev_x < - Number.EPSILON ) {
  20345. if ( v_next_x < - Number.EPSILON ) {
  20346. direction_eq = true;
  20347. }
  20348. } else {
  20349. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  20350. direction_eq = true;
  20351. }
  20352. }
  20353. }
  20354. if ( direction_eq ) {
  20355. // console.log("Warning: lines are a straight sequence");
  20356. v_trans_x = - v_prev_y;
  20357. v_trans_y = v_prev_x;
  20358. shrink_by = Math.sqrt( v_prev_lensq );
  20359. } else {
  20360. // console.log("Warning: lines are a straight spike");
  20361. v_trans_x = v_prev_x;
  20362. v_trans_y = v_prev_y;
  20363. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  20364. }
  20365. }
  20366. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  20367. }
  20368. var contourMovements = [];
  20369. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  20370. if ( j === il ) j = 0;
  20371. if ( k === il ) k = 0;
  20372. // (j)---(i)---(k)
  20373. // console.log('i,j,k', i, j , k)
  20374. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  20375. }
  20376. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  20377. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  20378. ahole = holes[ h ];
  20379. oneHoleMovements = [];
  20380. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  20381. if ( j === il ) j = 0;
  20382. if ( k === il ) k = 0;
  20383. // (j)---(i)---(k)
  20384. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  20385. }
  20386. holesMovements.push( oneHoleMovements );
  20387. verticesMovements = verticesMovements.concat( oneHoleMovements );
  20388. }
  20389. // Loop bevelSegments, 1 for the front, 1 for the back
  20390. for ( b = 0; b < bevelSegments; b ++ ) {
  20391. //for ( b = bevelSegments; b > 0; b -- ) {
  20392. t = b / bevelSegments;
  20393. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  20394. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  20395. // contract shape
  20396. for ( i = 0, il = contour.length; i < il; i ++ ) {
  20397. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  20398. v( vert.x, vert.y, - z );
  20399. }
  20400. // expand holes
  20401. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  20402. ahole = holes[ h ];
  20403. oneHoleMovements = holesMovements[ h ];
  20404. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  20405. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  20406. v( vert.x, vert.y, - z );
  20407. }
  20408. }
  20409. }
  20410. bs = bevelSize;
  20411. // Back facing vertices
  20412. for ( i = 0; i < vlen; i ++ ) {
  20413. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  20414. if ( ! extrudeByPath ) {
  20415. v( vert.x, vert.y, 0 );
  20416. } else {
  20417. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  20418. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  20419. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  20420. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  20421. v( position2.x, position2.y, position2.z );
  20422. }
  20423. }
  20424. // Add stepped vertices...
  20425. // Including front facing vertices
  20426. var s;
  20427. for ( s = 1; s <= steps; s ++ ) {
  20428. for ( i = 0; i < vlen; i ++ ) {
  20429. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  20430. if ( ! extrudeByPath ) {
  20431. v( vert.x, vert.y, amount / steps * s );
  20432. } else {
  20433. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  20434. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  20435. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  20436. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  20437. v( position2.x, position2.y, position2.z );
  20438. }
  20439. }
  20440. }
  20441. // Add bevel segments planes
  20442. //for ( b = 1; b <= bevelSegments; b ++ ) {
  20443. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  20444. t = b / bevelSegments;
  20445. z = bevelThickness * Math.cos ( t * Math.PI / 2 );
  20446. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  20447. // contract shape
  20448. for ( i = 0, il = contour.length; i < il; i ++ ) {
  20449. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  20450. v( vert.x, vert.y, amount + z );
  20451. }
  20452. // expand holes
  20453. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  20454. ahole = holes[ h ];
  20455. oneHoleMovements = holesMovements[ h ];
  20456. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  20457. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  20458. if ( ! extrudeByPath ) {
  20459. v( vert.x, vert.y, amount + z );
  20460. } else {
  20461. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  20462. }
  20463. }
  20464. }
  20465. }
  20466. /* Faces */
  20467. // Top and bottom faces
  20468. buildLidFaces();
  20469. // Sides faces
  20470. buildSideFaces();
  20471. ///// Internal functions
  20472. function buildLidFaces() {
  20473. if ( bevelEnabled ) {
  20474. var layer = 0; // steps + 1
  20475. var offset = vlen * layer;
  20476. // Bottom faces
  20477. for ( i = 0; i < flen; i ++ ) {
  20478. face = faces[ i ];
  20479. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  20480. }
  20481. layer = steps + bevelSegments * 2;
  20482. offset = vlen * layer;
  20483. // Top faces
  20484. for ( i = 0; i < flen; i ++ ) {
  20485. face = faces[ i ];
  20486. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  20487. }
  20488. } else {
  20489. // Bottom faces
  20490. for ( i = 0; i < flen; i ++ ) {
  20491. face = faces[ i ];
  20492. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  20493. }
  20494. // Top faces
  20495. for ( i = 0; i < flen; i ++ ) {
  20496. face = faces[ i ];
  20497. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  20498. }
  20499. }
  20500. }
  20501. // Create faces for the z-sides of the shape
  20502. function buildSideFaces() {
  20503. var layeroffset = 0;
  20504. sidewalls( contour, layeroffset );
  20505. layeroffset += contour.length;
  20506. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  20507. ahole = holes[ h ];
  20508. sidewalls( ahole, layeroffset );
  20509. //, true
  20510. layeroffset += ahole.length;
  20511. }
  20512. }
  20513. function sidewalls( contour, layeroffset ) {
  20514. var j, k;
  20515. i = contour.length;
  20516. while ( -- i >= 0 ) {
  20517. j = i;
  20518. k = i - 1;
  20519. if ( k < 0 ) k = contour.length - 1;
  20520. //console.log('b', i,j, i-1, k,vertices.length);
  20521. var s = 0, sl = steps + bevelSegments * 2;
  20522. for ( s = 0; s < sl; s ++ ) {
  20523. var slen1 = vlen * s;
  20524. var slen2 = vlen * ( s + 1 );
  20525. var a = layeroffset + j + slen1,
  20526. b = layeroffset + k + slen1,
  20527. c = layeroffset + k + slen2,
  20528. d = layeroffset + j + slen2;
  20529. f4( a, b, c, d, contour, s, sl, j, k );
  20530. }
  20531. }
  20532. }
  20533. function v( x, y, z ) {
  20534. scope.vertices.push( new Vector3( x, y, z ) );
  20535. }
  20536. function f3( a, b, c ) {
  20537. a += shapesOffset;
  20538. b += shapesOffset;
  20539. c += shapesOffset;
  20540. scope.faces.push( new Face3( a, b, c, null, null, 0 ) );
  20541. var uvs = uvgen.generateTopUV( scope, a, b, c );
  20542. scope.faceVertexUvs[ 0 ].push( uvs );
  20543. }
  20544. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  20545. a += shapesOffset;
  20546. b += shapesOffset;
  20547. c += shapesOffset;
  20548. d += shapesOffset;
  20549. scope.faces.push( new Face3( a, b, d, null, null, 1 ) );
  20550. scope.faces.push( new Face3( b, c, d, null, null, 1 ) );
  20551. var uvs = uvgen.generateSideWallUV( scope, a, b, c, d );
  20552. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  20553. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  20554. }
  20555. };
  20556. ExtrudeGeometry.WorldUVGenerator = {
  20557. generateTopUV: function ( geometry, indexA, indexB, indexC ) {
  20558. var vertices = geometry.vertices;
  20559. var a = vertices[ indexA ];
  20560. var b = vertices[ indexB ];
  20561. var c = vertices[ indexC ];
  20562. return [
  20563. new Vector2( a.x, a.y ),
  20564. new Vector2( b.x, b.y ),
  20565. new Vector2( c.x, c.y )
  20566. ];
  20567. },
  20568. generateSideWallUV: function ( geometry, indexA, indexB, indexC, indexD ) {
  20569. var vertices = geometry.vertices;
  20570. var a = vertices[ indexA ];
  20571. var b = vertices[ indexB ];
  20572. var c = vertices[ indexC ];
  20573. var d = vertices[ indexD ];
  20574. if ( Math.abs( a.y - b.y ) < 0.01 ) {
  20575. return [
  20576. new Vector2( a.x, 1 - a.z ),
  20577. new Vector2( b.x, 1 - b.z ),
  20578. new Vector2( c.x, 1 - c.z ),
  20579. new Vector2( d.x, 1 - d.z )
  20580. ];
  20581. } else {
  20582. return [
  20583. new Vector2( a.y, 1 - a.z ),
  20584. new Vector2( b.y, 1 - b.z ),
  20585. new Vector2( c.y, 1 - c.z ),
  20586. new Vector2( d.y, 1 - d.z )
  20587. ];
  20588. }
  20589. }
  20590. };
  20591. /**
  20592. * @author zz85 / http://www.lab4games.net/zz85/blog
  20593. * @author alteredq / http://alteredqualia.com/
  20594. *
  20595. * Text = 3D Text
  20596. *
  20597. * parameters = {
  20598. * font: <THREE.Font>, // font
  20599. *
  20600. * size: <float>, // size of the text
  20601. * height: <float>, // thickness to extrude text
  20602. * curveSegments: <int>, // number of points on the curves
  20603. *
  20604. * bevelEnabled: <bool>, // turn on bevel
  20605. * bevelThickness: <float>, // how deep into text bevel goes
  20606. * bevelSize: <float> // how far from text outline is bevel
  20607. * }
  20608. */
  20609. function TextGeometry( text, parameters ) {
  20610. parameters = parameters || {};
  20611. var font = parameters.font;
  20612. if ( ( font && font.isFont ) === false ) {
  20613. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  20614. return new Geometry();
  20615. }
  20616. var shapes = font.generateShapes( text, parameters.size, parameters.curveSegments );
  20617. // translate parameters to ExtrudeGeometry API
  20618. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  20619. // defaults
  20620. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  20621. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  20622. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  20623. ExtrudeGeometry.call( this, shapes, parameters );
  20624. this.type = 'TextGeometry';
  20625. }
  20626. TextGeometry.prototype = Object.create( ExtrudeGeometry.prototype );
  20627. TextGeometry.prototype.constructor = TextGeometry;
  20628. /**
  20629. * @author mrdoob / http://mrdoob.com/
  20630. */
  20631. function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  20632. Geometry.call( this );
  20633. this.type = 'SphereGeometry';
  20634. this.parameters = {
  20635. radius: radius,
  20636. widthSegments: widthSegments,
  20637. heightSegments: heightSegments,
  20638. phiStart: phiStart,
  20639. phiLength: phiLength,
  20640. thetaStart: thetaStart,
  20641. thetaLength: thetaLength
  20642. };
  20643. this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  20644. }
  20645. SphereGeometry.prototype = Object.create( Geometry.prototype );
  20646. SphereGeometry.prototype.constructor = SphereGeometry;
  20647. /**
  20648. * @author benaadams / https://twitter.com/ben_a_adams
  20649. * @author Mugen87 / https://github.com/Mugen87
  20650. */
  20651. function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  20652. BufferGeometry.call( this );
  20653. this.type = 'SphereBufferGeometry';
  20654. this.parameters = {
  20655. radius: radius,
  20656. widthSegments: widthSegments,
  20657. heightSegments: heightSegments,
  20658. phiStart: phiStart,
  20659. phiLength: phiLength,
  20660. thetaStart: thetaStart,
  20661. thetaLength: thetaLength
  20662. };
  20663. radius = radius || 50;
  20664. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  20665. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  20666. phiStart = phiStart !== undefined ? phiStart : 0;
  20667. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  20668. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  20669. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  20670. var thetaEnd = thetaStart + thetaLength;
  20671. var ix, iy;
  20672. var index = 0;
  20673. var grid = [];
  20674. var vertex = new Vector3();
  20675. var normal = new Vector3();
  20676. // buffers
  20677. var indices = [];
  20678. var vertices = [];
  20679. var normals = [];
  20680. var uvs = [];
  20681. // generate vertices, normals and uvs
  20682. for ( iy = 0; iy <= heightSegments; iy ++ ) {
  20683. var verticesRow = [];
  20684. var v = iy / heightSegments;
  20685. for ( ix = 0; ix <= widthSegments; ix ++ ) {
  20686. var u = ix / widthSegments;
  20687. // vertex
  20688. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  20689. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  20690. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  20691. vertices.push( vertex.x, vertex.y, vertex.z );
  20692. // normal
  20693. normal.set( vertex.x, vertex.y, vertex.z ).normalize();
  20694. normals.push( normal.x, normal.y, normal.z );
  20695. // uv
  20696. uvs.push( u, 1 - v );
  20697. verticesRow.push( index ++ );
  20698. }
  20699. grid.push( verticesRow );
  20700. }
  20701. // indices
  20702. for ( iy = 0; iy < heightSegments; iy ++ ) {
  20703. for ( ix = 0; ix < widthSegments; ix ++ ) {
  20704. var a = grid[ iy ][ ix + 1 ];
  20705. var b = grid[ iy ][ ix ];
  20706. var c = grid[ iy + 1 ][ ix ];
  20707. var d = grid[ iy + 1 ][ ix + 1 ];
  20708. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  20709. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  20710. }
  20711. }
  20712. // build geometry
  20713. this.setIndex( indices );
  20714. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20715. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20716. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20717. }
  20718. SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  20719. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  20720. /**
  20721. * @author Kaleb Murphy
  20722. */
  20723. function RingGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  20724. Geometry.call( this );
  20725. this.type = 'RingGeometry';
  20726. this.parameters = {
  20727. innerRadius: innerRadius,
  20728. outerRadius: outerRadius,
  20729. thetaSegments: thetaSegments,
  20730. phiSegments: phiSegments,
  20731. thetaStart: thetaStart,
  20732. thetaLength: thetaLength
  20733. };
  20734. this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) );
  20735. }
  20736. RingGeometry.prototype = Object.create( Geometry.prototype );
  20737. RingGeometry.prototype.constructor = RingGeometry;
  20738. /**
  20739. * @author Mugen87 / https://github.com/Mugen87
  20740. */
  20741. function RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  20742. BufferGeometry.call( this );
  20743. this.type = 'RingBufferGeometry';
  20744. this.parameters = {
  20745. innerRadius: innerRadius,
  20746. outerRadius: outerRadius,
  20747. thetaSegments: thetaSegments,
  20748. phiSegments: phiSegments,
  20749. thetaStart: thetaStart,
  20750. thetaLength: thetaLength
  20751. };
  20752. innerRadius = innerRadius || 20;
  20753. outerRadius = outerRadius || 50;
  20754. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  20755. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  20756. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  20757. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1;
  20758. // buffers
  20759. var indices = [];
  20760. var vertices = [];
  20761. var normals = [];
  20762. var uvs = [];
  20763. // some helper variables
  20764. var segment;
  20765. var radius = innerRadius;
  20766. var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  20767. var vertex = new Vector3();
  20768. var uv = new Vector2();
  20769. var j, i;
  20770. // generate vertices, normals and uvs
  20771. for ( j = 0; j <= phiSegments; j ++ ) {
  20772. for ( i = 0; i <= thetaSegments; i ++ ) {
  20773. // values are generate from the inside of the ring to the outside
  20774. segment = thetaStart + i / thetaSegments * thetaLength;
  20775. // vertex
  20776. vertex.x = radius * Math.cos( segment );
  20777. vertex.y = radius * Math.sin( segment );
  20778. vertices.push( vertex.x, vertex.y, vertex.z );
  20779. // normal
  20780. normals.push( 0, 0, 1 );
  20781. // uv
  20782. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  20783. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  20784. uvs.push( uv.x, uv.y );
  20785. }
  20786. // increase the radius for next row of vertices
  20787. radius += radiusStep;
  20788. }
  20789. // indices
  20790. for ( j = 0; j < phiSegments; j ++ ) {
  20791. var thetaSegmentLevel = j * ( thetaSegments + 1 );
  20792. for ( i = 0; i < thetaSegments; i ++ ) {
  20793. segment = i + thetaSegmentLevel;
  20794. var a = segment;
  20795. var b = segment + thetaSegments + 1;
  20796. var c = segment + thetaSegments + 2;
  20797. var d = segment + 1;
  20798. // faces
  20799. indices.push( a, b, d );
  20800. indices.push( b, c, d );
  20801. }
  20802. }
  20803. // build geometry
  20804. this.setIndex( indices );
  20805. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20806. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20807. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20808. }
  20809. RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  20810. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  20811. /**
  20812. * @author astrodud / http://astrodud.isgreat.org/
  20813. * @author zz85 / https://github.com/zz85
  20814. * @author bhouston / http://clara.io
  20815. */
  20816. // points - to create a closed torus, one must use a set of points
  20817. // like so: [ a, b, c, d, a ], see first is the same as last.
  20818. // segments - the number of circumference segments to create
  20819. // phiStart - the starting radian
  20820. // phiLength - the radian (0 to 2PI) range of the lathed section
  20821. // 2PI is a closed lathe, less than 2PI is a portion.
  20822. function LatheGeometry( points, segments, phiStart, phiLength ) {
  20823. Geometry.call( this );
  20824. this.type = 'LatheGeometry';
  20825. this.parameters = {
  20826. points: points,
  20827. segments: segments,
  20828. phiStart: phiStart,
  20829. phiLength: phiLength
  20830. };
  20831. this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) );
  20832. this.mergeVertices();
  20833. }
  20834. LatheGeometry.prototype = Object.create( Geometry.prototype );
  20835. LatheGeometry.prototype.constructor = LatheGeometry;
  20836. /**
  20837. * @author Mugen87 / https://github.com/Mugen87
  20838. */
  20839. function LatheBufferGeometry( points, segments, phiStart, phiLength ) {
  20840. BufferGeometry.call( this );
  20841. this.type = 'LatheBufferGeometry';
  20842. this.parameters = {
  20843. points: points,
  20844. segments: segments,
  20845. phiStart: phiStart,
  20846. phiLength: phiLength
  20847. };
  20848. segments = Math.floor( segments ) || 12;
  20849. phiStart = phiStart || 0;
  20850. phiLength = phiLength || Math.PI * 2;
  20851. // clamp phiLength so it's in range of [ 0, 2PI ]
  20852. phiLength = _Math.clamp( phiLength, 0, Math.PI * 2 );
  20853. // buffers
  20854. var indices = [];
  20855. var vertices = [];
  20856. var uvs = [];
  20857. // helper variables
  20858. var base;
  20859. var inverseSegments = 1.0 / segments;
  20860. var vertex = new Vector3();
  20861. var uv = new Vector2();
  20862. var i, j;
  20863. // generate vertices and uvs
  20864. for ( i = 0; i <= segments; i ++ ) {
  20865. var phi = phiStart + i * inverseSegments * phiLength;
  20866. var sin = Math.sin( phi );
  20867. var cos = Math.cos( phi );
  20868. for ( j = 0; j <= ( points.length - 1 ); j ++ ) {
  20869. // vertex
  20870. vertex.x = points[ j ].x * sin;
  20871. vertex.y = points[ j ].y;
  20872. vertex.z = points[ j ].x * cos;
  20873. vertices.push( vertex.x, vertex.y, vertex.z );
  20874. // uv
  20875. uv.x = i / segments;
  20876. uv.y = j / ( points.length - 1 );
  20877. uvs.push( uv.x, uv.y );
  20878. }
  20879. }
  20880. // indices
  20881. for ( i = 0; i < segments; i ++ ) {
  20882. for ( j = 0; j < ( points.length - 1 ); j ++ ) {
  20883. base = j + i * points.length;
  20884. var a = base;
  20885. var b = base + points.length;
  20886. var c = base + points.length + 1;
  20887. var d = base + 1;
  20888. // faces
  20889. indices.push( a, b, d );
  20890. indices.push( b, c, d );
  20891. }
  20892. }
  20893. // build geometry
  20894. this.setIndex( indices );
  20895. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20896. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20897. // generate normals
  20898. this.computeVertexNormals();
  20899. // if the geometry is closed, we need to average the normals along the seam.
  20900. // because the corresponding vertices are identical (but still have different UVs).
  20901. if ( phiLength === Math.PI * 2 ) {
  20902. var normals = this.attributes.normal.array;
  20903. var n1 = new Vector3();
  20904. var n2 = new Vector3();
  20905. var n = new Vector3();
  20906. // this is the buffer offset for the last line of vertices
  20907. base = segments * points.length * 3;
  20908. for ( i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  20909. // select the normal of the vertex in the first line
  20910. n1.x = normals[ j + 0 ];
  20911. n1.y = normals[ j + 1 ];
  20912. n1.z = normals[ j + 2 ];
  20913. // select the normal of the vertex in the last line
  20914. n2.x = normals[ base + j + 0 ];
  20915. n2.y = normals[ base + j + 1 ];
  20916. n2.z = normals[ base + j + 2 ];
  20917. // average normals
  20918. n.addVectors( n1, n2 ).normalize();
  20919. // assign the new values to both normals
  20920. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  20921. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  20922. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  20923. }
  20924. }
  20925. }
  20926. LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  20927. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  20928. /**
  20929. * @author jonobr1 / http://jonobr1.com
  20930. */
  20931. function ShapeGeometry( shapes, curveSegments ) {
  20932. Geometry.call( this );
  20933. this.type = 'ShapeGeometry';
  20934. if ( typeof curveSegments === 'object' ) {
  20935. console.warn( 'THREE.ShapeGeometry: Options parameter has been removed.' );
  20936. curveSegments = curveSegments.curveSegments;
  20937. }
  20938. this.parameters = {
  20939. shapes: shapes,
  20940. curveSegments: curveSegments
  20941. };
  20942. this.fromBufferGeometry( new ShapeBufferGeometry( shapes, curveSegments ) );
  20943. this.mergeVertices();
  20944. }
  20945. ShapeGeometry.prototype = Object.create( Geometry.prototype );
  20946. ShapeGeometry.prototype.constructor = ShapeGeometry;
  20947. /**
  20948. * @author Mugen87 / https://github.com/Mugen87
  20949. */
  20950. function ShapeBufferGeometry( shapes, curveSegments ) {
  20951. BufferGeometry.call( this );
  20952. this.type = 'ShapeBufferGeometry';
  20953. this.parameters = {
  20954. shapes: shapes,
  20955. curveSegments: curveSegments
  20956. };
  20957. curveSegments = curveSegments || 12;
  20958. // buffers
  20959. var indices = [];
  20960. var vertices = [];
  20961. var normals = [];
  20962. var uvs = [];
  20963. // helper variables
  20964. var groupStart = 0;
  20965. var groupCount = 0;
  20966. // allow single and array values for "shapes" parameter
  20967. if ( Array.isArray( shapes ) === false ) {
  20968. addShape( shapes );
  20969. } else {
  20970. for ( var i = 0; i < shapes.length; i ++ ) {
  20971. addShape( shapes[ i ] );
  20972. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  20973. groupStart += groupCount;
  20974. groupCount = 0;
  20975. }
  20976. }
  20977. // build geometry
  20978. this.setIndex( indices );
  20979. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20980. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20981. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20982. // helper functions
  20983. function addShape( shape ) {
  20984. var i, l, shapeHole;
  20985. var indexOffset = vertices.length / 3;
  20986. var points = shape.extractPoints( curveSegments );
  20987. var shapeVertices = points.shape;
  20988. var shapeHoles = points.holes;
  20989. // check direction of vertices
  20990. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  20991. shapeVertices = shapeVertices.reverse();
  20992. // also check if holes are in the opposite direction
  20993. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  20994. shapeHole = shapeHoles[ i ];
  20995. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  20996. shapeHoles[ i ] = shapeHole.reverse();
  20997. }
  20998. }
  20999. }
  21000. var faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  21001. // join vertices of inner and outer paths to a single array
  21002. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21003. shapeHole = shapeHoles[ i ];
  21004. shapeVertices = shapeVertices.concat( shapeHole );
  21005. }
  21006. // vertices, normals, uvs
  21007. for ( i = 0, l = shapeVertices.length; i < l; i ++ ) {
  21008. var vertex = shapeVertices[ i ];
  21009. vertices.push( vertex.x, vertex.y, 0 );
  21010. normals.push( 0, 0, 1 );
  21011. uvs.push( vertex.x, vertex.y ); // world uvs
  21012. }
  21013. // incides
  21014. for ( i = 0, l = faces.length; i < l; i ++ ) {
  21015. var face = faces[ i ];
  21016. var a = face[ 0 ] + indexOffset;
  21017. var b = face[ 1 ] + indexOffset;
  21018. var c = face[ 2 ] + indexOffset;
  21019. indices.push( a, b, c );
  21020. groupCount += 3;
  21021. }
  21022. }
  21023. }
  21024. ShapeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21025. ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;
  21026. /**
  21027. * @author WestLangley / http://github.com/WestLangley
  21028. * @author Mugen87 / https://github.com/Mugen87
  21029. */
  21030. function EdgesGeometry( geometry, thresholdAngle ) {
  21031. BufferGeometry.call( this );
  21032. this.type = 'EdgesGeometry';
  21033. this.parameters = {
  21034. thresholdAngle: thresholdAngle
  21035. };
  21036. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  21037. // buffer
  21038. var vertices = [];
  21039. // helper variables
  21040. var thresholdDot = Math.cos( _Math.DEG2RAD * thresholdAngle );
  21041. var edge = [ 0, 0 ], edges = {};
  21042. var key, keys = [ 'a', 'b', 'c' ];
  21043. // prepare source geometry
  21044. var geometry2;
  21045. if ( geometry.isBufferGeometry ) {
  21046. geometry2 = new Geometry();
  21047. geometry2.fromBufferGeometry( geometry );
  21048. } else {
  21049. geometry2 = geometry.clone();
  21050. }
  21051. geometry2.mergeVertices();
  21052. geometry2.computeFaceNormals();
  21053. var sourceVertices = geometry2.vertices;
  21054. var faces = geometry2.faces;
  21055. // now create a data structure where each entry represents an edge with its adjoining faces
  21056. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21057. var face = faces[ i ];
  21058. for ( var j = 0; j < 3; j ++ ) {
  21059. edge[ 0 ] = face[ keys[ j ] ];
  21060. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  21061. edge.sort( sortFunction );
  21062. key = edge.toString();
  21063. if ( edges[ key ] === undefined ) {
  21064. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ], face1: i, face2: undefined };
  21065. } else {
  21066. edges[ key ].face2 = i;
  21067. }
  21068. }
  21069. }
  21070. // generate vertices
  21071. for ( key in edges ) {
  21072. var e = edges[ key ];
  21073. // an edge is only rendered if the angle (in degrees) between the face normals of the adjoining faces exceeds this value. default = 1 degree.
  21074. if ( e.face2 === undefined || faces[ e.face1 ].normal.dot( faces[ e.face2 ].normal ) <= thresholdDot ) {
  21075. var vertex = sourceVertices[ e.index1 ];
  21076. vertices.push( vertex.x, vertex.y, vertex.z );
  21077. vertex = sourceVertices[ e.index2 ];
  21078. vertices.push( vertex.x, vertex.y, vertex.z );
  21079. }
  21080. }
  21081. // build geometry
  21082. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21083. // custom array sort function
  21084. function sortFunction( a, b ) {
  21085. return a - b;
  21086. }
  21087. }
  21088. EdgesGeometry.prototype = Object.create( BufferGeometry.prototype );
  21089. EdgesGeometry.prototype.constructor = EdgesGeometry;
  21090. /**
  21091. * @author mrdoob / http://mrdoob.com/
  21092. */
  21093. function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  21094. Geometry.call( this );
  21095. this.type = 'CylinderGeometry';
  21096. this.parameters = {
  21097. radiusTop: radiusTop,
  21098. radiusBottom: radiusBottom,
  21099. height: height,
  21100. radialSegments: radialSegments,
  21101. heightSegments: heightSegments,
  21102. openEnded: openEnded,
  21103. thetaStart: thetaStart,
  21104. thetaLength: thetaLength
  21105. };
  21106. this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
  21107. this.mergeVertices();
  21108. }
  21109. CylinderGeometry.prototype = Object.create( Geometry.prototype );
  21110. CylinderGeometry.prototype.constructor = CylinderGeometry;
  21111. /**
  21112. * @author Mugen87 / https://github.com/Mugen87
  21113. */
  21114. function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  21115. BufferGeometry.call( this );
  21116. this.type = 'CylinderBufferGeometry';
  21117. this.parameters = {
  21118. radiusTop: radiusTop,
  21119. radiusBottom: radiusBottom,
  21120. height: height,
  21121. radialSegments: radialSegments,
  21122. heightSegments: heightSegments,
  21123. openEnded: openEnded,
  21124. thetaStart: thetaStart,
  21125. thetaLength: thetaLength
  21126. };
  21127. var scope = this;
  21128. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  21129. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  21130. height = height !== undefined ? height : 100;
  21131. radialSegments = Math.floor( radialSegments ) || 8;
  21132. heightSegments = Math.floor( heightSegments ) || 1;
  21133. openEnded = openEnded !== undefined ? openEnded : false;
  21134. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  21135. thetaLength = thetaLength !== undefined ? thetaLength : 2.0 * Math.PI;
  21136. // buffers
  21137. var indices = [];
  21138. var vertices = [];
  21139. var normals = [];
  21140. var uvs = [];
  21141. // helper variables
  21142. var index = 0;
  21143. var indexOffset = 0;
  21144. var indexArray = [];
  21145. var halfHeight = height / 2;
  21146. var groupStart = 0;
  21147. // generate geometry
  21148. generateTorso();
  21149. if ( openEnded === false ) {
  21150. if ( radiusTop > 0 ) generateCap( true );
  21151. if ( radiusBottom > 0 ) generateCap( false );
  21152. }
  21153. // build geometry
  21154. this.setIndex( indices );
  21155. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21156. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21157. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21158. function generateTorso() {
  21159. var x, y;
  21160. var normal = new Vector3();
  21161. var vertex = new Vector3();
  21162. var groupCount = 0;
  21163. // this will be used to calculate the normal
  21164. var slope = ( radiusBottom - radiusTop ) / height;
  21165. // generate vertices, normals and uvs
  21166. for ( y = 0; y <= heightSegments; y ++ ) {
  21167. var indexRow = [];
  21168. var v = y / heightSegments;
  21169. // calculate the radius of the current row
  21170. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  21171. for ( x = 0; x <= radialSegments; x ++ ) {
  21172. var u = x / radialSegments;
  21173. var theta = u * thetaLength + thetaStart;
  21174. var sinTheta = Math.sin( theta );
  21175. var cosTheta = Math.cos( theta );
  21176. // vertex
  21177. vertex.x = radius * sinTheta;
  21178. vertex.y = - v * height + halfHeight;
  21179. vertex.z = radius * cosTheta;
  21180. vertices.push( vertex.x, vertex.y, vertex.z );
  21181. // normal
  21182. normal.set( sinTheta, slope, cosTheta ).normalize();
  21183. normals.push( normal.x, normal.y, normal.z );
  21184. // uv
  21185. uvs.push( u, 1 - v );
  21186. // save index of vertex in respective row
  21187. indexRow.push( index ++ );
  21188. }
  21189. // now save vertices of the row in our index array
  21190. indexArray.push( indexRow );
  21191. }
  21192. // generate indices
  21193. for ( x = 0; x < radialSegments; x ++ ) {
  21194. for ( y = 0; y < heightSegments; y ++ ) {
  21195. // we use the index array to access the correct indices
  21196. var a = indexArray[ y ][ x ];
  21197. var b = indexArray[ y + 1 ][ x ];
  21198. var c = indexArray[ y + 1 ][ x + 1 ];
  21199. var d = indexArray[ y ][ x + 1 ];
  21200. // faces
  21201. indices.push( a, b, d );
  21202. indices.push( b, c, d );
  21203. // update group counter
  21204. groupCount += 6;
  21205. }
  21206. }
  21207. // add a group to the geometry. this will ensure multi material support
  21208. scope.addGroup( groupStart, groupCount, 0 );
  21209. // calculate new start value for groups
  21210. groupStart += groupCount;
  21211. }
  21212. function generateCap( top ) {
  21213. var x, centerIndexStart, centerIndexEnd;
  21214. var uv = new Vector2();
  21215. var vertex = new Vector3();
  21216. var groupCount = 0;
  21217. var radius = ( top === true ) ? radiusTop : radiusBottom;
  21218. var sign = ( top === true ) ? 1 : - 1;
  21219. // save the index of the first center vertex
  21220. centerIndexStart = index;
  21221. // first we generate the center vertex data of the cap.
  21222. // because the geometry needs one set of uvs per face,
  21223. // we must generate a center vertex per face/segment
  21224. for ( x = 1; x <= radialSegments; x ++ ) {
  21225. // vertex
  21226. vertices.push( 0, halfHeight * sign, 0 );
  21227. // normal
  21228. normals.push( 0, sign, 0 );
  21229. // uv
  21230. uvs.push( 0.5, 0.5 );
  21231. // increase index
  21232. index ++;
  21233. }
  21234. // save the index of the last center vertex
  21235. centerIndexEnd = index;
  21236. // now we generate the surrounding vertices, normals and uvs
  21237. for ( x = 0; x <= radialSegments; x ++ ) {
  21238. var u = x / radialSegments;
  21239. var theta = u * thetaLength + thetaStart;
  21240. var cosTheta = Math.cos( theta );
  21241. var sinTheta = Math.sin( theta );
  21242. // vertex
  21243. vertex.x = radius * sinTheta;
  21244. vertex.y = halfHeight * sign;
  21245. vertex.z = radius * cosTheta;
  21246. vertices.push( vertex.x, vertex.y, vertex.z );
  21247. // normal
  21248. normals.push( 0, sign, 0 );
  21249. // uv
  21250. uv.x = ( cosTheta * 0.5 ) + 0.5;
  21251. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  21252. uvs.push( uv.x, uv.y );
  21253. // increase index
  21254. index ++;
  21255. }
  21256. // generate indices
  21257. for ( x = 0; x < radialSegments; x ++ ) {
  21258. var c = centerIndexStart + x;
  21259. var i = centerIndexEnd + x;
  21260. if ( top === true ) {
  21261. // face top
  21262. indices.push( i, i + 1, c );
  21263. } else {
  21264. // face bottom
  21265. indices.push( i + 1, i, c );
  21266. }
  21267. groupCount += 3;
  21268. }
  21269. // add a group to the geometry. this will ensure multi material support
  21270. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  21271. // calculate new start value for groups
  21272. groupStart += groupCount;
  21273. }
  21274. }
  21275. CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21276. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  21277. /**
  21278. * @author abelnation / http://github.com/abelnation
  21279. */
  21280. function ConeGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  21281. CylinderGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  21282. this.type = 'ConeGeometry';
  21283. this.parameters = {
  21284. radius: radius,
  21285. height: height,
  21286. radialSegments: radialSegments,
  21287. heightSegments: heightSegments,
  21288. openEnded: openEnded,
  21289. thetaStart: thetaStart,
  21290. thetaLength: thetaLength
  21291. };
  21292. }
  21293. ConeGeometry.prototype = Object.create( CylinderGeometry.prototype );
  21294. ConeGeometry.prototype.constructor = ConeGeometry;
  21295. /**
  21296. * @author: abelnation / http://github.com/abelnation
  21297. */
  21298. function ConeBufferGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  21299. CylinderBufferGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  21300. this.type = 'ConeBufferGeometry';
  21301. this.parameters = {
  21302. radius: radius,
  21303. height: height,
  21304. radialSegments: radialSegments,
  21305. heightSegments: heightSegments,
  21306. openEnded: openEnded,
  21307. thetaStart: thetaStart,
  21308. thetaLength: thetaLength
  21309. };
  21310. }
  21311. ConeBufferGeometry.prototype = Object.create( CylinderBufferGeometry.prototype );
  21312. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  21313. /**
  21314. * @author hughes
  21315. */
  21316. function CircleGeometry( radius, segments, thetaStart, thetaLength ) {
  21317. Geometry.call( this );
  21318. this.type = 'CircleGeometry';
  21319. this.parameters = {
  21320. radius: radius,
  21321. segments: segments,
  21322. thetaStart: thetaStart,
  21323. thetaLength: thetaLength
  21324. };
  21325. this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  21326. }
  21327. CircleGeometry.prototype = Object.create( Geometry.prototype );
  21328. CircleGeometry.prototype.constructor = CircleGeometry;
  21329. /**
  21330. * @author benaadams / https://twitter.com/ben_a_adams
  21331. * @author Mugen87 / https://github.com/Mugen87
  21332. */
  21333. function CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) {
  21334. BufferGeometry.call( this );
  21335. this.type = 'CircleBufferGeometry';
  21336. this.parameters = {
  21337. radius: radius,
  21338. segments: segments,
  21339. thetaStart: thetaStart,
  21340. thetaLength: thetaLength
  21341. };
  21342. radius = radius || 50;
  21343. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  21344. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  21345. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  21346. // buffers
  21347. var indices = [];
  21348. var vertices = [];
  21349. var normals = [];
  21350. var uvs = [];
  21351. // helper variables
  21352. var i, s;
  21353. var vertex = new Vector3();
  21354. var uv = new Vector2();
  21355. // center point
  21356. vertices.push( 0, 0, 0 );
  21357. normals.push( 0, 0, 1 );
  21358. uvs.push( 0.5, 0.5 );
  21359. for ( s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  21360. var segment = thetaStart + s / segments * thetaLength;
  21361. // vertex
  21362. vertex.x = radius * Math.cos( segment );
  21363. vertex.y = radius * Math.sin( segment );
  21364. vertices.push( vertex.x, vertex.y, vertex.z );
  21365. // normal
  21366. normals.push( 0, 0, 1 );
  21367. // uvs
  21368. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  21369. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  21370. uvs.push( uv.x, uv.y );
  21371. }
  21372. // indices
  21373. for ( i = 1; i <= segments; i ++ ) {
  21374. indices.push( i, i + 1, 0 );
  21375. }
  21376. // build geometry
  21377. this.setIndex( indices );
  21378. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21379. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21380. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21381. }
  21382. CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21383. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  21384. var Geometries = Object.freeze({
  21385. WireframeGeometry: WireframeGeometry,
  21386. ParametricGeometry: ParametricGeometry,
  21387. ParametricBufferGeometry: ParametricBufferGeometry,
  21388. TetrahedronGeometry: TetrahedronGeometry,
  21389. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  21390. OctahedronGeometry: OctahedronGeometry,
  21391. OctahedronBufferGeometry: OctahedronBufferGeometry,
  21392. IcosahedronGeometry: IcosahedronGeometry,
  21393. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  21394. DodecahedronGeometry: DodecahedronGeometry,
  21395. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  21396. PolyhedronGeometry: PolyhedronGeometry,
  21397. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  21398. TubeGeometry: TubeGeometry,
  21399. TubeBufferGeometry: TubeBufferGeometry,
  21400. TorusKnotGeometry: TorusKnotGeometry,
  21401. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  21402. TorusGeometry: TorusGeometry,
  21403. TorusBufferGeometry: TorusBufferGeometry,
  21404. TextGeometry: TextGeometry,
  21405. SphereGeometry: SphereGeometry,
  21406. SphereBufferGeometry: SphereBufferGeometry,
  21407. RingGeometry: RingGeometry,
  21408. RingBufferGeometry: RingBufferGeometry,
  21409. PlaneGeometry: PlaneGeometry,
  21410. PlaneBufferGeometry: PlaneBufferGeometry,
  21411. LatheGeometry: LatheGeometry,
  21412. LatheBufferGeometry: LatheBufferGeometry,
  21413. ShapeGeometry: ShapeGeometry,
  21414. ShapeBufferGeometry: ShapeBufferGeometry,
  21415. ExtrudeGeometry: ExtrudeGeometry,
  21416. EdgesGeometry: EdgesGeometry,
  21417. ConeGeometry: ConeGeometry,
  21418. ConeBufferGeometry: ConeBufferGeometry,
  21419. CylinderGeometry: CylinderGeometry,
  21420. CylinderBufferGeometry: CylinderBufferGeometry,
  21421. CircleGeometry: CircleGeometry,
  21422. CircleBufferGeometry: CircleBufferGeometry,
  21423. BoxGeometry: BoxGeometry,
  21424. BoxBufferGeometry: BoxBufferGeometry
  21425. });
  21426. /**
  21427. * @author mrdoob / http://mrdoob.com/
  21428. */
  21429. function ShadowMaterial() {
  21430. ShaderMaterial.call( this, {
  21431. uniforms: UniformsUtils.merge( [
  21432. UniformsLib.lights,
  21433. {
  21434. opacity: { value: 1.0 }
  21435. }
  21436. ] ),
  21437. vertexShader: ShaderChunk[ 'shadow_vert' ],
  21438. fragmentShader: ShaderChunk[ 'shadow_frag' ]
  21439. } );
  21440. this.lights = true;
  21441. this.transparent = true;
  21442. Object.defineProperties( this, {
  21443. opacity: {
  21444. enumerable: true,
  21445. get: function () {
  21446. return this.uniforms.opacity.value;
  21447. },
  21448. set: function ( value ) {
  21449. this.uniforms.opacity.value = value;
  21450. }
  21451. }
  21452. } );
  21453. }
  21454. ShadowMaterial.prototype = Object.create( ShaderMaterial.prototype );
  21455. ShadowMaterial.prototype.constructor = ShadowMaterial;
  21456. ShadowMaterial.prototype.isShadowMaterial = true;
  21457. /**
  21458. * @author mrdoob / http://mrdoob.com/
  21459. */
  21460. function RawShaderMaterial( parameters ) {
  21461. ShaderMaterial.call( this, parameters );
  21462. this.type = 'RawShaderMaterial';
  21463. }
  21464. RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype );
  21465. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  21466. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  21467. /**
  21468. * @author mrdoob / http://mrdoob.com/
  21469. */
  21470. function MultiMaterial( materials ) {
  21471. this.uuid = _Math.generateUUID();
  21472. this.type = 'MultiMaterial';
  21473. this.materials = Array.isArray( materials ) ? materials : [];
  21474. this.visible = true;
  21475. }
  21476. MultiMaterial.prototype = {
  21477. constructor: MultiMaterial,
  21478. isMultiMaterial: true,
  21479. toJSON: function ( meta ) {
  21480. var output = {
  21481. metadata: {
  21482. version: 4.2,
  21483. type: 'material',
  21484. generator: 'MaterialExporter'
  21485. },
  21486. uuid: this.uuid,
  21487. type: this.type,
  21488. materials: []
  21489. };
  21490. var materials = this.materials;
  21491. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  21492. var material = materials[ i ].toJSON( meta );
  21493. delete material.metadata;
  21494. output.materials.push( material );
  21495. }
  21496. output.visible = this.visible;
  21497. return output;
  21498. },
  21499. clone: function () {
  21500. var material = new this.constructor();
  21501. for ( var i = 0; i < this.materials.length; i ++ ) {
  21502. material.materials.push( this.materials[ i ].clone() );
  21503. }
  21504. material.visible = this.visible;
  21505. return material;
  21506. }
  21507. };
  21508. /**
  21509. * @author WestLangley / http://github.com/WestLangley
  21510. *
  21511. * parameters = {
  21512. * color: <hex>,
  21513. * roughness: <float>,
  21514. * metalness: <float>,
  21515. * opacity: <float>,
  21516. *
  21517. * map: new THREE.Texture( <Image> ),
  21518. *
  21519. * lightMap: new THREE.Texture( <Image> ),
  21520. * lightMapIntensity: <float>
  21521. *
  21522. * aoMap: new THREE.Texture( <Image> ),
  21523. * aoMapIntensity: <float>
  21524. *
  21525. * emissive: <hex>,
  21526. * emissiveIntensity: <float>
  21527. * emissiveMap: new THREE.Texture( <Image> ),
  21528. *
  21529. * bumpMap: new THREE.Texture( <Image> ),
  21530. * bumpScale: <float>,
  21531. *
  21532. * normalMap: new THREE.Texture( <Image> ),
  21533. * normalScale: <Vector2>,
  21534. *
  21535. * displacementMap: new THREE.Texture( <Image> ),
  21536. * displacementScale: <float>,
  21537. * displacementBias: <float>,
  21538. *
  21539. * roughnessMap: new THREE.Texture( <Image> ),
  21540. *
  21541. * metalnessMap: new THREE.Texture( <Image> ),
  21542. *
  21543. * alphaMap: new THREE.Texture( <Image> ),
  21544. *
  21545. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  21546. * envMapIntensity: <float>
  21547. *
  21548. * refractionRatio: <float>,
  21549. *
  21550. * wireframe: <boolean>,
  21551. * wireframeLinewidth: <float>,
  21552. *
  21553. * skinning: <bool>,
  21554. * morphTargets: <bool>,
  21555. * morphNormals: <bool>
  21556. * }
  21557. */
  21558. function MeshStandardMaterial( parameters ) {
  21559. Material.call( this );
  21560. this.defines = { 'STANDARD': '' };
  21561. this.type = 'MeshStandardMaterial';
  21562. this.color = new Color( 0xffffff ); // diffuse
  21563. this.roughness = 0.5;
  21564. this.metalness = 0.5;
  21565. this.map = null;
  21566. this.lightMap = null;
  21567. this.lightMapIntensity = 1.0;
  21568. this.aoMap = null;
  21569. this.aoMapIntensity = 1.0;
  21570. this.emissive = new Color( 0x000000 );
  21571. this.emissiveIntensity = 1.0;
  21572. this.emissiveMap = null;
  21573. this.bumpMap = null;
  21574. this.bumpScale = 1;
  21575. this.normalMap = null;
  21576. this.normalScale = new Vector2( 1, 1 );
  21577. this.displacementMap = null;
  21578. this.displacementScale = 1;
  21579. this.displacementBias = 0;
  21580. this.roughnessMap = null;
  21581. this.metalnessMap = null;
  21582. this.alphaMap = null;
  21583. this.envMap = null;
  21584. this.envMapIntensity = 1.0;
  21585. this.refractionRatio = 0.98;
  21586. this.wireframe = false;
  21587. this.wireframeLinewidth = 1;
  21588. this.wireframeLinecap = 'round';
  21589. this.wireframeLinejoin = 'round';
  21590. this.skinning = false;
  21591. this.morphTargets = false;
  21592. this.morphNormals = false;
  21593. this.setValues( parameters );
  21594. }
  21595. MeshStandardMaterial.prototype = Object.create( Material.prototype );
  21596. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  21597. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  21598. MeshStandardMaterial.prototype.copy = function ( source ) {
  21599. Material.prototype.copy.call( this, source );
  21600. this.defines = { 'STANDARD': '' };
  21601. this.color.copy( source.color );
  21602. this.roughness = source.roughness;
  21603. this.metalness = source.metalness;
  21604. this.map = source.map;
  21605. this.lightMap = source.lightMap;
  21606. this.lightMapIntensity = source.lightMapIntensity;
  21607. this.aoMap = source.aoMap;
  21608. this.aoMapIntensity = source.aoMapIntensity;
  21609. this.emissive.copy( source.emissive );
  21610. this.emissiveMap = source.emissiveMap;
  21611. this.emissiveIntensity = source.emissiveIntensity;
  21612. this.bumpMap = source.bumpMap;
  21613. this.bumpScale = source.bumpScale;
  21614. this.normalMap = source.normalMap;
  21615. this.normalScale.copy( source.normalScale );
  21616. this.displacementMap = source.displacementMap;
  21617. this.displacementScale = source.displacementScale;
  21618. this.displacementBias = source.displacementBias;
  21619. this.roughnessMap = source.roughnessMap;
  21620. this.metalnessMap = source.metalnessMap;
  21621. this.alphaMap = source.alphaMap;
  21622. this.envMap = source.envMap;
  21623. this.envMapIntensity = source.envMapIntensity;
  21624. this.refractionRatio = source.refractionRatio;
  21625. this.wireframe = source.wireframe;
  21626. this.wireframeLinewidth = source.wireframeLinewidth;
  21627. this.wireframeLinecap = source.wireframeLinecap;
  21628. this.wireframeLinejoin = source.wireframeLinejoin;
  21629. this.skinning = source.skinning;
  21630. this.morphTargets = source.morphTargets;
  21631. this.morphNormals = source.morphNormals;
  21632. return this;
  21633. };
  21634. /**
  21635. * @author WestLangley / http://github.com/WestLangley
  21636. *
  21637. * parameters = {
  21638. * reflectivity: <float>
  21639. * }
  21640. */
  21641. function MeshPhysicalMaterial( parameters ) {
  21642. MeshStandardMaterial.call( this );
  21643. this.defines = { 'PHYSICAL': '' };
  21644. this.type = 'MeshPhysicalMaterial';
  21645. this.reflectivity = 0.5; // maps to F0 = 0.04
  21646. this.clearCoat = 0.0;
  21647. this.clearCoatRoughness = 0.0;
  21648. this.setValues( parameters );
  21649. }
  21650. MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
  21651. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  21652. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  21653. MeshPhysicalMaterial.prototype.copy = function ( source ) {
  21654. MeshStandardMaterial.prototype.copy.call( this, source );
  21655. this.defines = { 'PHYSICAL': '' };
  21656. this.reflectivity = source.reflectivity;
  21657. this.clearCoat = source.clearCoat;
  21658. this.clearCoatRoughness = source.clearCoatRoughness;
  21659. return this;
  21660. };
  21661. /**
  21662. * @author mrdoob / http://mrdoob.com/
  21663. * @author alteredq / http://alteredqualia.com/
  21664. *
  21665. * parameters = {
  21666. * color: <hex>,
  21667. * specular: <hex>,
  21668. * shininess: <float>,
  21669. * opacity: <float>,
  21670. *
  21671. * map: new THREE.Texture( <Image> ),
  21672. *
  21673. * lightMap: new THREE.Texture( <Image> ),
  21674. * lightMapIntensity: <float>
  21675. *
  21676. * aoMap: new THREE.Texture( <Image> ),
  21677. * aoMapIntensity: <float>
  21678. *
  21679. * emissive: <hex>,
  21680. * emissiveIntensity: <float>
  21681. * emissiveMap: new THREE.Texture( <Image> ),
  21682. *
  21683. * bumpMap: new THREE.Texture( <Image> ),
  21684. * bumpScale: <float>,
  21685. *
  21686. * normalMap: new THREE.Texture( <Image> ),
  21687. * normalScale: <Vector2>,
  21688. *
  21689. * displacementMap: new THREE.Texture( <Image> ),
  21690. * displacementScale: <float>,
  21691. * displacementBias: <float>,
  21692. *
  21693. * specularMap: new THREE.Texture( <Image> ),
  21694. *
  21695. * alphaMap: new THREE.Texture( <Image> ),
  21696. *
  21697. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  21698. * combine: THREE.Multiply,
  21699. * reflectivity: <float>,
  21700. * refractionRatio: <float>,
  21701. *
  21702. * wireframe: <boolean>,
  21703. * wireframeLinewidth: <float>,
  21704. *
  21705. * skinning: <bool>,
  21706. * morphTargets: <bool>,
  21707. * morphNormals: <bool>
  21708. * }
  21709. */
  21710. function MeshPhongMaterial( parameters ) {
  21711. Material.call( this );
  21712. this.type = 'MeshPhongMaterial';
  21713. this.color = new Color( 0xffffff ); // diffuse
  21714. this.specular = new Color( 0x111111 );
  21715. this.shininess = 30;
  21716. this.map = null;
  21717. this.lightMap = null;
  21718. this.lightMapIntensity = 1.0;
  21719. this.aoMap = null;
  21720. this.aoMapIntensity = 1.0;
  21721. this.emissive = new Color( 0x000000 );
  21722. this.emissiveIntensity = 1.0;
  21723. this.emissiveMap = null;
  21724. this.bumpMap = null;
  21725. this.bumpScale = 1;
  21726. this.normalMap = null;
  21727. this.normalScale = new Vector2( 1, 1 );
  21728. this.displacementMap = null;
  21729. this.displacementScale = 1;
  21730. this.displacementBias = 0;
  21731. this.specularMap = null;
  21732. this.alphaMap = null;
  21733. this.envMap = null;
  21734. this.combine = MultiplyOperation;
  21735. this.reflectivity = 1;
  21736. this.refractionRatio = 0.98;
  21737. this.wireframe = false;
  21738. this.wireframeLinewidth = 1;
  21739. this.wireframeLinecap = 'round';
  21740. this.wireframeLinejoin = 'round';
  21741. this.skinning = false;
  21742. this.morphTargets = false;
  21743. this.morphNormals = false;
  21744. this.setValues( parameters );
  21745. }
  21746. MeshPhongMaterial.prototype = Object.create( Material.prototype );
  21747. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  21748. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  21749. MeshPhongMaterial.prototype.copy = function ( source ) {
  21750. Material.prototype.copy.call( this, source );
  21751. this.color.copy( source.color );
  21752. this.specular.copy( source.specular );
  21753. this.shininess = source.shininess;
  21754. this.map = source.map;
  21755. this.lightMap = source.lightMap;
  21756. this.lightMapIntensity = source.lightMapIntensity;
  21757. this.aoMap = source.aoMap;
  21758. this.aoMapIntensity = source.aoMapIntensity;
  21759. this.emissive.copy( source.emissive );
  21760. this.emissiveMap = source.emissiveMap;
  21761. this.emissiveIntensity = source.emissiveIntensity;
  21762. this.bumpMap = source.bumpMap;
  21763. this.bumpScale = source.bumpScale;
  21764. this.normalMap = source.normalMap;
  21765. this.normalScale.copy( source.normalScale );
  21766. this.displacementMap = source.displacementMap;
  21767. this.displacementScale = source.displacementScale;
  21768. this.displacementBias = source.displacementBias;
  21769. this.specularMap = source.specularMap;
  21770. this.alphaMap = source.alphaMap;
  21771. this.envMap = source.envMap;
  21772. this.combine = source.combine;
  21773. this.reflectivity = source.reflectivity;
  21774. this.refractionRatio = source.refractionRatio;
  21775. this.wireframe = source.wireframe;
  21776. this.wireframeLinewidth = source.wireframeLinewidth;
  21777. this.wireframeLinecap = source.wireframeLinecap;
  21778. this.wireframeLinejoin = source.wireframeLinejoin;
  21779. this.skinning = source.skinning;
  21780. this.morphTargets = source.morphTargets;
  21781. this.morphNormals = source.morphNormals;
  21782. return this;
  21783. };
  21784. /**
  21785. * @author takahirox / http://github.com/takahirox
  21786. *
  21787. * parameters = {
  21788. * gradientMap: new THREE.Texture( <Image> )
  21789. * }
  21790. */
  21791. function MeshToonMaterial( parameters ) {
  21792. MeshPhongMaterial.call( this );
  21793. this.defines = { 'TOON': '' };
  21794. this.type = 'MeshToonMaterial';
  21795. this.gradientMap = null;
  21796. this.setValues( parameters );
  21797. }
  21798. MeshToonMaterial.prototype = Object.create( MeshPhongMaterial.prototype );
  21799. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  21800. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  21801. MeshToonMaterial.prototype.copy = function ( source ) {
  21802. MeshPhongMaterial.prototype.copy.call( this, source );
  21803. this.gradientMap = source.gradientMap;
  21804. return this;
  21805. };
  21806. /**
  21807. * @author mrdoob / http://mrdoob.com/
  21808. * @author WestLangley / http://github.com/WestLangley
  21809. *
  21810. * parameters = {
  21811. * opacity: <float>,
  21812. *
  21813. * bumpMap: new THREE.Texture( <Image> ),
  21814. * bumpScale: <float>,
  21815. *
  21816. * normalMap: new THREE.Texture( <Image> ),
  21817. * normalScale: <Vector2>,
  21818. *
  21819. * displacementMap: new THREE.Texture( <Image> ),
  21820. * displacementScale: <float>,
  21821. * displacementBias: <float>,
  21822. *
  21823. * wireframe: <boolean>,
  21824. * wireframeLinewidth: <float>
  21825. *
  21826. * skinning: <bool>,
  21827. * morphTargets: <bool>,
  21828. * morphNormals: <bool>
  21829. * }
  21830. */
  21831. function MeshNormalMaterial( parameters ) {
  21832. Material.call( this, parameters );
  21833. this.type = 'MeshNormalMaterial';
  21834. this.bumpMap = null;
  21835. this.bumpScale = 1;
  21836. this.normalMap = null;
  21837. this.normalScale = new Vector2( 1, 1 );
  21838. this.displacementMap = null;
  21839. this.displacementScale = 1;
  21840. this.displacementBias = 0;
  21841. this.wireframe = false;
  21842. this.wireframeLinewidth = 1;
  21843. this.fog = false;
  21844. this.lights = false;
  21845. this.skinning = false;
  21846. this.morphTargets = false;
  21847. this.morphNormals = false;
  21848. this.setValues( parameters );
  21849. }
  21850. MeshNormalMaterial.prototype = Object.create( Material.prototype );
  21851. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  21852. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  21853. MeshNormalMaterial.prototype.copy = function ( source ) {
  21854. Material.prototype.copy.call( this, source );
  21855. this.bumpMap = source.bumpMap;
  21856. this.bumpScale = source.bumpScale;
  21857. this.normalMap = source.normalMap;
  21858. this.normalScale.copy( source.normalScale );
  21859. this.displacementMap = source.displacementMap;
  21860. this.displacementScale = source.displacementScale;
  21861. this.displacementBias = source.displacementBias;
  21862. this.wireframe = source.wireframe;
  21863. this.wireframeLinewidth = source.wireframeLinewidth;
  21864. this.skinning = source.skinning;
  21865. this.morphTargets = source.morphTargets;
  21866. this.morphNormals = source.morphNormals;
  21867. return this;
  21868. };
  21869. /**
  21870. * @author mrdoob / http://mrdoob.com/
  21871. * @author alteredq / http://alteredqualia.com/
  21872. *
  21873. * parameters = {
  21874. * color: <hex>,
  21875. * opacity: <float>,
  21876. *
  21877. * map: new THREE.Texture( <Image> ),
  21878. *
  21879. * lightMap: new THREE.Texture( <Image> ),
  21880. * lightMapIntensity: <float>
  21881. *
  21882. * aoMap: new THREE.Texture( <Image> ),
  21883. * aoMapIntensity: <float>
  21884. *
  21885. * emissive: <hex>,
  21886. * emissiveIntensity: <float>
  21887. * emissiveMap: new THREE.Texture( <Image> ),
  21888. *
  21889. * specularMap: new THREE.Texture( <Image> ),
  21890. *
  21891. * alphaMap: new THREE.Texture( <Image> ),
  21892. *
  21893. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  21894. * combine: THREE.Multiply,
  21895. * reflectivity: <float>,
  21896. * refractionRatio: <float>,
  21897. *
  21898. * wireframe: <boolean>,
  21899. * wireframeLinewidth: <float>,
  21900. *
  21901. * skinning: <bool>,
  21902. * morphTargets: <bool>,
  21903. * morphNormals: <bool>
  21904. * }
  21905. */
  21906. function MeshLambertMaterial( parameters ) {
  21907. Material.call( this );
  21908. this.type = 'MeshLambertMaterial';
  21909. this.color = new Color( 0xffffff ); // diffuse
  21910. this.map = null;
  21911. this.lightMap = null;
  21912. this.lightMapIntensity = 1.0;
  21913. this.aoMap = null;
  21914. this.aoMapIntensity = 1.0;
  21915. this.emissive = new Color( 0x000000 );
  21916. this.emissiveIntensity = 1.0;
  21917. this.emissiveMap = null;
  21918. this.specularMap = null;
  21919. this.alphaMap = null;
  21920. this.envMap = null;
  21921. this.combine = MultiplyOperation;
  21922. this.reflectivity = 1;
  21923. this.refractionRatio = 0.98;
  21924. this.wireframe = false;
  21925. this.wireframeLinewidth = 1;
  21926. this.wireframeLinecap = 'round';
  21927. this.wireframeLinejoin = 'round';
  21928. this.skinning = false;
  21929. this.morphTargets = false;
  21930. this.morphNormals = false;
  21931. this.setValues( parameters );
  21932. }
  21933. MeshLambertMaterial.prototype = Object.create( Material.prototype );
  21934. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  21935. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  21936. MeshLambertMaterial.prototype.copy = function ( source ) {
  21937. Material.prototype.copy.call( this, source );
  21938. this.color.copy( source.color );
  21939. this.map = source.map;
  21940. this.lightMap = source.lightMap;
  21941. this.lightMapIntensity = source.lightMapIntensity;
  21942. this.aoMap = source.aoMap;
  21943. this.aoMapIntensity = source.aoMapIntensity;
  21944. this.emissive.copy( source.emissive );
  21945. this.emissiveMap = source.emissiveMap;
  21946. this.emissiveIntensity = source.emissiveIntensity;
  21947. this.specularMap = source.specularMap;
  21948. this.alphaMap = source.alphaMap;
  21949. this.envMap = source.envMap;
  21950. this.combine = source.combine;
  21951. this.reflectivity = source.reflectivity;
  21952. this.refractionRatio = source.refractionRatio;
  21953. this.wireframe = source.wireframe;
  21954. this.wireframeLinewidth = source.wireframeLinewidth;
  21955. this.wireframeLinecap = source.wireframeLinecap;
  21956. this.wireframeLinejoin = source.wireframeLinejoin;
  21957. this.skinning = source.skinning;
  21958. this.morphTargets = source.morphTargets;
  21959. this.morphNormals = source.morphNormals;
  21960. return this;
  21961. };
  21962. /**
  21963. * @author alteredq / http://alteredqualia.com/
  21964. *
  21965. * parameters = {
  21966. * color: <hex>,
  21967. * opacity: <float>,
  21968. *
  21969. * linewidth: <float>,
  21970. *
  21971. * scale: <float>,
  21972. * dashSize: <float>,
  21973. * gapSize: <float>
  21974. * }
  21975. */
  21976. function LineDashedMaterial( parameters ) {
  21977. Material.call( this );
  21978. this.type = 'LineDashedMaterial';
  21979. this.color = new Color( 0xffffff );
  21980. this.linewidth = 1;
  21981. this.scale = 1;
  21982. this.dashSize = 3;
  21983. this.gapSize = 1;
  21984. this.lights = false;
  21985. this.setValues( parameters );
  21986. }
  21987. LineDashedMaterial.prototype = Object.create( Material.prototype );
  21988. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  21989. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  21990. LineDashedMaterial.prototype.copy = function ( source ) {
  21991. Material.prototype.copy.call( this, source );
  21992. this.color.copy( source.color );
  21993. this.linewidth = source.linewidth;
  21994. this.scale = source.scale;
  21995. this.dashSize = source.dashSize;
  21996. this.gapSize = source.gapSize;
  21997. return this;
  21998. };
  21999. var Materials = Object.freeze({
  22000. ShadowMaterial: ShadowMaterial,
  22001. SpriteMaterial: SpriteMaterial,
  22002. RawShaderMaterial: RawShaderMaterial,
  22003. ShaderMaterial: ShaderMaterial,
  22004. PointsMaterial: PointsMaterial,
  22005. MultiMaterial: MultiMaterial,
  22006. MeshPhysicalMaterial: MeshPhysicalMaterial,
  22007. MeshStandardMaterial: MeshStandardMaterial,
  22008. MeshPhongMaterial: MeshPhongMaterial,
  22009. MeshToonMaterial: MeshToonMaterial,
  22010. MeshNormalMaterial: MeshNormalMaterial,
  22011. MeshLambertMaterial: MeshLambertMaterial,
  22012. MeshDepthMaterial: MeshDepthMaterial,
  22013. MeshBasicMaterial: MeshBasicMaterial,
  22014. LineDashedMaterial: LineDashedMaterial,
  22015. LineBasicMaterial: LineBasicMaterial,
  22016. Material: Material
  22017. });
  22018. /**
  22019. * @author mrdoob / http://mrdoob.com/
  22020. */
  22021. var Cache = {
  22022. enabled: false,
  22023. files: {},
  22024. add: function ( key, file ) {
  22025. if ( this.enabled === false ) return;
  22026. // console.log( 'THREE.Cache', 'Adding key:', key );
  22027. this.files[ key ] = file;
  22028. },
  22029. get: function ( key ) {
  22030. if ( this.enabled === false ) return;
  22031. // console.log( 'THREE.Cache', 'Checking key:', key );
  22032. return this.files[ key ];
  22033. },
  22034. remove: function ( key ) {
  22035. delete this.files[ key ];
  22036. },
  22037. clear: function () {
  22038. this.files = {};
  22039. }
  22040. };
  22041. /**
  22042. * @author mrdoob / http://mrdoob.com/
  22043. */
  22044. function LoadingManager( onLoad, onProgress, onError ) {
  22045. var scope = this;
  22046. var isLoading = false, itemsLoaded = 0, itemsTotal = 0;
  22047. this.onStart = undefined;
  22048. this.onLoad = onLoad;
  22049. this.onProgress = onProgress;
  22050. this.onError = onError;
  22051. this.itemStart = function ( url ) {
  22052. itemsTotal ++;
  22053. if ( isLoading === false ) {
  22054. if ( scope.onStart !== undefined ) {
  22055. scope.onStart( url, itemsLoaded, itemsTotal );
  22056. }
  22057. }
  22058. isLoading = true;
  22059. };
  22060. this.itemEnd = function ( url ) {
  22061. itemsLoaded ++;
  22062. if ( scope.onProgress !== undefined ) {
  22063. scope.onProgress( url, itemsLoaded, itemsTotal );
  22064. }
  22065. if ( itemsLoaded === itemsTotal ) {
  22066. isLoading = false;
  22067. if ( scope.onLoad !== undefined ) {
  22068. scope.onLoad();
  22069. }
  22070. }
  22071. };
  22072. this.itemError = function ( url ) {
  22073. if ( scope.onError !== undefined ) {
  22074. scope.onError( url );
  22075. }
  22076. };
  22077. }
  22078. var DefaultLoadingManager = new LoadingManager();
  22079. /**
  22080. * @author mrdoob / http://mrdoob.com/
  22081. */
  22082. function FileLoader( manager ) {
  22083. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  22084. }
  22085. Object.assign( FileLoader.prototype, {
  22086. load: function ( url, onLoad, onProgress, onError ) {
  22087. if ( url === undefined ) url = '';
  22088. if ( this.path !== undefined ) url = this.path + url;
  22089. var scope = this;
  22090. var cached = Cache.get( url );
  22091. if ( cached !== undefined ) {
  22092. scope.manager.itemStart( url );
  22093. setTimeout( function () {
  22094. if ( onLoad ) onLoad( cached );
  22095. scope.manager.itemEnd( url );
  22096. }, 0 );
  22097. return cached;
  22098. }
  22099. // Check for data: URI
  22100. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  22101. var dataUriRegexResult = url.match( dataUriRegex );
  22102. // Safari can not handle Data URIs through XMLHttpRequest so process manually
  22103. if ( dataUriRegexResult ) {
  22104. var mimeType = dataUriRegexResult[ 1 ];
  22105. var isBase64 = !! dataUriRegexResult[ 2 ];
  22106. var data = dataUriRegexResult[ 3 ];
  22107. data = window.decodeURIComponent( data );
  22108. if ( isBase64 ) data = window.atob( data );
  22109. try {
  22110. var response;
  22111. var responseType = ( this.responseType || '' ).toLowerCase();
  22112. switch ( responseType ) {
  22113. case 'arraybuffer':
  22114. case 'blob':
  22115. response = new ArrayBuffer( data.length );
  22116. var view = new Uint8Array( response );
  22117. for ( var i = 0; i < data.length; i ++ ) {
  22118. view[ i ] = data.charCodeAt( i );
  22119. }
  22120. if ( responseType === 'blob' ) {
  22121. response = new Blob( [ response ], { type: mimeType } );
  22122. }
  22123. break;
  22124. case 'document':
  22125. var parser = new DOMParser();
  22126. response = parser.parseFromString( data, mimeType );
  22127. break;
  22128. case 'json':
  22129. response = JSON.parse( data );
  22130. break;
  22131. default: // 'text' or other
  22132. response = data;
  22133. break;
  22134. }
  22135. // Wait for next browser tick
  22136. window.setTimeout( function () {
  22137. if ( onLoad ) onLoad( response );
  22138. scope.manager.itemEnd( url );
  22139. }, 0 );
  22140. } catch ( error ) {
  22141. // Wait for next browser tick
  22142. window.setTimeout( function () {
  22143. if ( onError ) onError( error );
  22144. scope.manager.itemError( url );
  22145. }, 0 );
  22146. }
  22147. } else {
  22148. var request = new XMLHttpRequest();
  22149. request.open( 'GET', url, true );
  22150. request.addEventListener( 'load', function ( event ) {
  22151. var response = event.target.response;
  22152. Cache.add( url, response );
  22153. if ( this.status === 200 ) {
  22154. if ( onLoad ) onLoad( response );
  22155. scope.manager.itemEnd( url );
  22156. } else if ( this.status === 0 ) {
  22157. // Some browsers return HTTP Status 0 when using non-http protocol
  22158. // e.g. 'file://' or 'data://'. Handle as success.
  22159. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  22160. if ( onLoad ) onLoad( response );
  22161. scope.manager.itemEnd( url );
  22162. } else {
  22163. if ( onError ) onError( event );
  22164. scope.manager.itemError( url );
  22165. }
  22166. }, false );
  22167. if ( onProgress !== undefined ) {
  22168. request.addEventListener( 'progress', function ( event ) {
  22169. onProgress( event );
  22170. }, false );
  22171. }
  22172. request.addEventListener( 'error', function ( event ) {
  22173. if ( onError ) onError( event );
  22174. scope.manager.itemError( url );
  22175. }, false );
  22176. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  22177. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  22178. if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );
  22179. request.send( null );
  22180. }
  22181. scope.manager.itemStart( url );
  22182. return request;
  22183. },
  22184. setPath: function ( value ) {
  22185. this.path = value;
  22186. return this;
  22187. },
  22188. setResponseType: function ( value ) {
  22189. this.responseType = value;
  22190. return this;
  22191. },
  22192. setWithCredentials: function ( value ) {
  22193. this.withCredentials = value;
  22194. return this;
  22195. },
  22196. setMimeType: function ( value ) {
  22197. this.mimeType = value;
  22198. return this;
  22199. }
  22200. } );
  22201. /**
  22202. * @author mrdoob / http://mrdoob.com/
  22203. *
  22204. * Abstract Base class to block based textures loader (dds, pvr, ...)
  22205. */
  22206. function CompressedTextureLoader( manager ) {
  22207. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  22208. // override in sub classes
  22209. this._parser = null;
  22210. }
  22211. Object.assign( CompressedTextureLoader.prototype, {
  22212. load: function ( url, onLoad, onProgress, onError ) {
  22213. var scope = this;
  22214. var images = [];
  22215. var texture = new CompressedTexture();
  22216. texture.image = images;
  22217. var loader = new FileLoader( this.manager );
  22218. loader.setPath( this.path );
  22219. loader.setResponseType( 'arraybuffer' );
  22220. function loadTexture( i ) {
  22221. loader.load( url[ i ], function ( buffer ) {
  22222. var texDatas = scope._parser( buffer, true );
  22223. images[ i ] = {
  22224. width: texDatas.width,
  22225. height: texDatas.height,
  22226. format: texDatas.format,
  22227. mipmaps: texDatas.mipmaps
  22228. };
  22229. loaded += 1;
  22230. if ( loaded === 6 ) {
  22231. if ( texDatas.mipmapCount === 1 )
  22232. texture.minFilter = LinearFilter;
  22233. texture.format = texDatas.format;
  22234. texture.needsUpdate = true;
  22235. if ( onLoad ) onLoad( texture );
  22236. }
  22237. }, onProgress, onError );
  22238. }
  22239. if ( Array.isArray( url ) ) {
  22240. var loaded = 0;
  22241. for ( var i = 0, il = url.length; i < il; ++ i ) {
  22242. loadTexture( i );
  22243. }
  22244. } else {
  22245. // compressed cubemap texture stored in a single DDS file
  22246. loader.load( url, function ( buffer ) {
  22247. var texDatas = scope._parser( buffer, true );
  22248. if ( texDatas.isCubemap ) {
  22249. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  22250. for ( var f = 0; f < faces; f ++ ) {
  22251. images[ f ] = { mipmaps : [] };
  22252. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  22253. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  22254. images[ f ].format = texDatas.format;
  22255. images[ f ].width = texDatas.width;
  22256. images[ f ].height = texDatas.height;
  22257. }
  22258. }
  22259. } else {
  22260. texture.image.width = texDatas.width;
  22261. texture.image.height = texDatas.height;
  22262. texture.mipmaps = texDatas.mipmaps;
  22263. }
  22264. if ( texDatas.mipmapCount === 1 ) {
  22265. texture.minFilter = LinearFilter;
  22266. }
  22267. texture.format = texDatas.format;
  22268. texture.needsUpdate = true;
  22269. if ( onLoad ) onLoad( texture );
  22270. }, onProgress, onError );
  22271. }
  22272. return texture;
  22273. },
  22274. setPath: function ( value ) {
  22275. this.path = value;
  22276. return this;
  22277. }
  22278. } );
  22279. /**
  22280. * @author Nikos M. / https://github.com/foo123/
  22281. *
  22282. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  22283. */
  22284. function DataTextureLoader( manager ) {
  22285. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  22286. // override in sub classes
  22287. this._parser = null;
  22288. }
  22289. Object.assign( DataTextureLoader.prototype, {
  22290. load: function ( url, onLoad, onProgress, onError ) {
  22291. var scope = this;
  22292. var texture = new DataTexture();
  22293. var loader = new FileLoader( this.manager );
  22294. loader.setResponseType( 'arraybuffer' );
  22295. loader.load( url, function ( buffer ) {
  22296. var texData = scope._parser( buffer );
  22297. if ( ! texData ) return;
  22298. if ( undefined !== texData.image ) {
  22299. texture.image = texData.image;
  22300. } else if ( undefined !== texData.data ) {
  22301. texture.image.width = texData.width;
  22302. texture.image.height = texData.height;
  22303. texture.image.data = texData.data;
  22304. }
  22305. texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : ClampToEdgeWrapping;
  22306. texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : ClampToEdgeWrapping;
  22307. texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : LinearFilter;
  22308. texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : LinearMipMapLinearFilter;
  22309. texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1;
  22310. if ( undefined !== texData.format ) {
  22311. texture.format = texData.format;
  22312. }
  22313. if ( undefined !== texData.type ) {
  22314. texture.type = texData.type;
  22315. }
  22316. if ( undefined !== texData.mipmaps ) {
  22317. texture.mipmaps = texData.mipmaps;
  22318. }
  22319. if ( 1 === texData.mipmapCount ) {
  22320. texture.minFilter = LinearFilter;
  22321. }
  22322. texture.needsUpdate = true;
  22323. if ( onLoad ) onLoad( texture, texData );
  22324. }, onProgress, onError );
  22325. return texture;
  22326. }
  22327. } );
  22328. /**
  22329. * @author mrdoob / http://mrdoob.com/
  22330. */
  22331. function ImageLoader( manager ) {
  22332. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  22333. }
  22334. Object.assign( ImageLoader.prototype, {
  22335. load: function ( url, onLoad, onProgress, onError ) {
  22336. if ( url === undefined ) url = '';
  22337. if ( this.path !== undefined ) url = this.path + url;
  22338. var scope = this;
  22339. var cached = Cache.get( url );
  22340. if ( cached !== undefined ) {
  22341. scope.manager.itemStart( url );
  22342. setTimeout( function () {
  22343. if ( onLoad ) onLoad( cached );
  22344. scope.manager.itemEnd( url );
  22345. }, 0 );
  22346. return cached;
  22347. }
  22348. var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  22349. image.addEventListener( 'load', function () {
  22350. Cache.add( url, this );
  22351. if ( onLoad ) onLoad( this );
  22352. scope.manager.itemEnd( url );
  22353. }, false );
  22354. /*
  22355. image.addEventListener( 'progress', function ( event ) {
  22356. if ( onProgress ) onProgress( event );
  22357. }, false );
  22358. */
  22359. image.addEventListener( 'error', function ( event ) {
  22360. if ( onError ) onError( event );
  22361. scope.manager.itemError( url );
  22362. }, false );
  22363. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  22364. scope.manager.itemStart( url );
  22365. image.src = url;
  22366. return image;
  22367. },
  22368. setCrossOrigin: function ( value ) {
  22369. this.crossOrigin = value;
  22370. return this;
  22371. },
  22372. setPath: function ( value ) {
  22373. this.path = value;
  22374. return this;
  22375. }
  22376. } );
  22377. /**
  22378. * @author mrdoob / http://mrdoob.com/
  22379. */
  22380. function CubeTextureLoader( manager ) {
  22381. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  22382. }
  22383. Object.assign( CubeTextureLoader.prototype, {
  22384. load: function ( urls, onLoad, onProgress, onError ) {
  22385. var texture = new CubeTexture();
  22386. var loader = new ImageLoader( this.manager );
  22387. loader.setCrossOrigin( this.crossOrigin );
  22388. loader.setPath( this.path );
  22389. var loaded = 0;
  22390. function loadTexture( i ) {
  22391. loader.load( urls[ i ], function ( image ) {
  22392. texture.images[ i ] = image;
  22393. loaded ++;
  22394. if ( loaded === 6 ) {
  22395. texture.needsUpdate = true;
  22396. if ( onLoad ) onLoad( texture );
  22397. }
  22398. }, undefined, onError );
  22399. }
  22400. for ( var i = 0; i < urls.length; ++ i ) {
  22401. loadTexture( i );
  22402. }
  22403. return texture;
  22404. },
  22405. setCrossOrigin: function ( value ) {
  22406. this.crossOrigin = value;
  22407. return this;
  22408. },
  22409. setPath: function ( value ) {
  22410. this.path = value;
  22411. return this;
  22412. }
  22413. } );
  22414. /**
  22415. * @author mrdoob / http://mrdoob.com/
  22416. */
  22417. function TextureLoader( manager ) {
  22418. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  22419. }
  22420. Object.assign( TextureLoader.prototype, {
  22421. load: function ( url, onLoad, onProgress, onError ) {
  22422. var texture = new Texture();
  22423. var loader = new ImageLoader( this.manager );
  22424. loader.setCrossOrigin( this.crossOrigin );
  22425. loader.setPath( this.path );
  22426. loader.load( url, function ( image ) {
  22427. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  22428. var isJPEG = url.search( /\.(jpg|jpeg)$/ ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  22429. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  22430. texture.image = image;
  22431. texture.needsUpdate = true;
  22432. if ( onLoad !== undefined ) {
  22433. onLoad( texture );
  22434. }
  22435. }, onProgress, onError );
  22436. return texture;
  22437. },
  22438. setCrossOrigin: function ( value ) {
  22439. this.crossOrigin = value;
  22440. return this;
  22441. },
  22442. setPath: function ( value ) {
  22443. this.path = value;
  22444. return this;
  22445. }
  22446. } );
  22447. /**
  22448. * @author mrdoob / http://mrdoob.com/
  22449. * @author alteredq / http://alteredqualia.com/
  22450. */
  22451. function Light( color, intensity ) {
  22452. Object3D.call( this );
  22453. this.type = 'Light';
  22454. this.color = new Color( color );
  22455. this.intensity = intensity !== undefined ? intensity : 1;
  22456. this.receiveShadow = undefined;
  22457. }
  22458. Light.prototype = Object.assign( Object.create( Object3D.prototype ), {
  22459. constructor: Light,
  22460. isLight: true,
  22461. copy: function ( source ) {
  22462. Object3D.prototype.copy.call( this, source );
  22463. this.color.copy( source.color );
  22464. this.intensity = source.intensity;
  22465. return this;
  22466. },
  22467. toJSON: function ( meta ) {
  22468. var data = Object3D.prototype.toJSON.call( this, meta );
  22469. data.object.color = this.color.getHex();
  22470. data.object.intensity = this.intensity;
  22471. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  22472. if ( this.distance !== undefined ) data.object.distance = this.distance;
  22473. if ( this.angle !== undefined ) data.object.angle = this.angle;
  22474. if ( this.decay !== undefined ) data.object.decay = this.decay;
  22475. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  22476. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  22477. return data;
  22478. }
  22479. } );
  22480. /**
  22481. * @author alteredq / http://alteredqualia.com/
  22482. */
  22483. function HemisphereLight( skyColor, groundColor, intensity ) {
  22484. Light.call( this, skyColor, intensity );
  22485. this.type = 'HemisphereLight';
  22486. this.castShadow = undefined;
  22487. this.position.copy( Object3D.DefaultUp );
  22488. this.updateMatrix();
  22489. this.groundColor = new Color( groundColor );
  22490. }
  22491. HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), {
  22492. constructor: HemisphereLight,
  22493. isHemisphereLight: true,
  22494. copy: function ( source ) {
  22495. Light.prototype.copy.call( this, source );
  22496. this.groundColor.copy( source.groundColor );
  22497. return this;
  22498. }
  22499. } );
  22500. /**
  22501. * @author mrdoob / http://mrdoob.com/
  22502. */
  22503. function LightShadow( camera ) {
  22504. this.camera = camera;
  22505. this.bias = 0;
  22506. this.radius = 1;
  22507. this.mapSize = new Vector2( 512, 512 );
  22508. this.map = null;
  22509. this.matrix = new Matrix4();
  22510. }
  22511. Object.assign( LightShadow.prototype, {
  22512. copy: function ( source ) {
  22513. this.camera = source.camera.clone();
  22514. this.bias = source.bias;
  22515. this.radius = source.radius;
  22516. this.mapSize.copy( source.mapSize );
  22517. return this;
  22518. },
  22519. clone: function () {
  22520. return new this.constructor().copy( this );
  22521. },
  22522. toJSON: function () {
  22523. var object = {};
  22524. if ( this.bias !== 0 ) object.bias = this.bias;
  22525. if ( this.radius !== 1 ) object.radius = this.radius;
  22526. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  22527. object.camera = this.camera.toJSON( false ).object;
  22528. delete object.camera.matrix;
  22529. return object;
  22530. }
  22531. } );
  22532. /**
  22533. * @author mrdoob / http://mrdoob.com/
  22534. */
  22535. function SpotLightShadow() {
  22536. LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  22537. }
  22538. SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  22539. constructor: SpotLightShadow,
  22540. isSpotLightShadow: true,
  22541. update: function ( light ) {
  22542. var fov = _Math.RAD2DEG * 2 * light.angle;
  22543. var aspect = this.mapSize.width / this.mapSize.height;
  22544. var far = light.distance || 500;
  22545. var camera = this.camera;
  22546. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  22547. camera.fov = fov;
  22548. camera.aspect = aspect;
  22549. camera.far = far;
  22550. camera.updateProjectionMatrix();
  22551. }
  22552. }
  22553. } );
  22554. /**
  22555. * @author alteredq / http://alteredqualia.com/
  22556. */
  22557. function SpotLight( color, intensity, distance, angle, penumbra, decay ) {
  22558. Light.call( this, color, intensity );
  22559. this.type = 'SpotLight';
  22560. this.position.copy( Object3D.DefaultUp );
  22561. this.updateMatrix();
  22562. this.target = new Object3D();
  22563. Object.defineProperty( this, 'power', {
  22564. get: function () {
  22565. // intensity = power per solid angle.
  22566. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  22567. return this.intensity * Math.PI;
  22568. },
  22569. set: function ( power ) {
  22570. // intensity = power per solid angle.
  22571. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  22572. this.intensity = power / Math.PI;
  22573. }
  22574. } );
  22575. this.distance = ( distance !== undefined ) ? distance : 0;
  22576. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  22577. this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;
  22578. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  22579. this.shadow = new SpotLightShadow();
  22580. }
  22581. SpotLight.prototype = Object.assign( Object.create( Light.prototype ), {
  22582. constructor: SpotLight,
  22583. isSpotLight: true,
  22584. copy: function ( source ) {
  22585. Light.prototype.copy.call( this, source );
  22586. this.distance = source.distance;
  22587. this.angle = source.angle;
  22588. this.penumbra = source.penumbra;
  22589. this.decay = source.decay;
  22590. this.target = source.target.clone();
  22591. this.shadow = source.shadow.clone();
  22592. return this;
  22593. }
  22594. } );
  22595. /**
  22596. * @author mrdoob / http://mrdoob.com/
  22597. */
  22598. function PointLight( color, intensity, distance, decay ) {
  22599. Light.call( this, color, intensity );
  22600. this.type = 'PointLight';
  22601. Object.defineProperty( this, 'power', {
  22602. get: function () {
  22603. // intensity = power per solid angle.
  22604. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  22605. return this.intensity * 4 * Math.PI;
  22606. },
  22607. set: function ( power ) {
  22608. // intensity = power per solid angle.
  22609. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  22610. this.intensity = power / ( 4 * Math.PI );
  22611. }
  22612. } );
  22613. this.distance = ( distance !== undefined ) ? distance : 0;
  22614. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  22615. this.shadow = new LightShadow( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  22616. }
  22617. PointLight.prototype = Object.assign( Object.create( Light.prototype ), {
  22618. constructor: PointLight,
  22619. isPointLight: true,
  22620. copy: function ( source ) {
  22621. Light.prototype.copy.call( this, source );
  22622. this.distance = source.distance;
  22623. this.decay = source.decay;
  22624. this.shadow = source.shadow.clone();
  22625. return this;
  22626. }
  22627. } );
  22628. /**
  22629. * @author mrdoob / http://mrdoob.com/
  22630. */
  22631. function DirectionalLightShadow( ) {
  22632. LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  22633. }
  22634. DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  22635. constructor: DirectionalLightShadow
  22636. } );
  22637. /**
  22638. * @author mrdoob / http://mrdoob.com/
  22639. * @author alteredq / http://alteredqualia.com/
  22640. */
  22641. function DirectionalLight( color, intensity ) {
  22642. Light.call( this, color, intensity );
  22643. this.type = 'DirectionalLight';
  22644. this.position.copy( Object3D.DefaultUp );
  22645. this.updateMatrix();
  22646. this.target = new Object3D();
  22647. this.shadow = new DirectionalLightShadow();
  22648. }
  22649. DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), {
  22650. constructor: DirectionalLight,
  22651. isDirectionalLight: true,
  22652. copy: function ( source ) {
  22653. Light.prototype.copy.call( this, source );
  22654. this.target = source.target.clone();
  22655. this.shadow = source.shadow.clone();
  22656. return this;
  22657. }
  22658. } );
  22659. /**
  22660. * @author mrdoob / http://mrdoob.com/
  22661. */
  22662. function AmbientLight( color, intensity ) {
  22663. Light.call( this, color, intensity );
  22664. this.type = 'AmbientLight';
  22665. this.castShadow = undefined;
  22666. }
  22667. AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {
  22668. constructor: AmbientLight,
  22669. isAmbientLight: true
  22670. } );
  22671. /**
  22672. * @author tschw
  22673. * @author Ben Houston / http://clara.io/
  22674. * @author David Sarno / http://lighthaus.us/
  22675. */
  22676. var AnimationUtils = {
  22677. // same as Array.prototype.slice, but also works on typed arrays
  22678. arraySlice: function( array, from, to ) {
  22679. if ( AnimationUtils.isTypedArray( array ) ) {
  22680. return new array.constructor( array.subarray( from, to ) );
  22681. }
  22682. return array.slice( from, to );
  22683. },
  22684. // converts an array to a specific type
  22685. convertArray: function( array, type, forceClone ) {
  22686. if ( ! array || // let 'undefined' and 'null' pass
  22687. ! forceClone && array.constructor === type ) return array;
  22688. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  22689. return new type( array ); // create typed array
  22690. }
  22691. return Array.prototype.slice.call( array ); // create Array
  22692. },
  22693. isTypedArray: function( object ) {
  22694. return ArrayBuffer.isView( object ) &&
  22695. ! ( object instanceof DataView );
  22696. },
  22697. // returns an array by which times and values can be sorted
  22698. getKeyframeOrder: function( times ) {
  22699. function compareTime( i, j ) {
  22700. return times[ i ] - times[ j ];
  22701. }
  22702. var n = times.length;
  22703. var result = new Array( n );
  22704. for ( var i = 0; i !== n; ++ i ) result[ i ] = i;
  22705. result.sort( compareTime );
  22706. return result;
  22707. },
  22708. // uses the array previously returned by 'getKeyframeOrder' to sort data
  22709. sortedArray: function( values, stride, order ) {
  22710. var nValues = values.length;
  22711. var result = new values.constructor( nValues );
  22712. for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  22713. var srcOffset = order[ i ] * stride;
  22714. for ( var j = 0; j !== stride; ++ j ) {
  22715. result[ dstOffset ++ ] = values[ srcOffset + j ];
  22716. }
  22717. }
  22718. return result;
  22719. },
  22720. // function for parsing AOS keyframe formats
  22721. flattenJSON: function( jsonKeys, times, values, valuePropertyName ) {
  22722. var i = 1, key = jsonKeys[ 0 ];
  22723. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  22724. key = jsonKeys[ i ++ ];
  22725. }
  22726. if ( key === undefined ) return; // no data
  22727. var value = key[ valuePropertyName ];
  22728. if ( value === undefined ) return; // no data
  22729. if ( Array.isArray( value ) ) {
  22730. do {
  22731. value = key[ valuePropertyName ];
  22732. if ( value !== undefined ) {
  22733. times.push( key.time );
  22734. values.push.apply( values, value ); // push all elements
  22735. }
  22736. key = jsonKeys[ i ++ ];
  22737. } while ( key !== undefined );
  22738. } else if ( value.toArray !== undefined ) {
  22739. // ...assume THREE.Math-ish
  22740. do {
  22741. value = key[ valuePropertyName ];
  22742. if ( value !== undefined ) {
  22743. times.push( key.time );
  22744. value.toArray( values, values.length );
  22745. }
  22746. key = jsonKeys[ i ++ ];
  22747. } while ( key !== undefined );
  22748. } else {
  22749. // otherwise push as-is
  22750. do {
  22751. value = key[ valuePropertyName ];
  22752. if ( value !== undefined ) {
  22753. times.push( key.time );
  22754. values.push( value );
  22755. }
  22756. key = jsonKeys[ i ++ ];
  22757. } while ( key !== undefined );
  22758. }
  22759. }
  22760. };
  22761. /**
  22762. * Abstract base class of interpolants over parametric samples.
  22763. *
  22764. * The parameter domain is one dimensional, typically the time or a path
  22765. * along a curve defined by the data.
  22766. *
  22767. * The sample values can have any dimensionality and derived classes may
  22768. * apply special interpretations to the data.
  22769. *
  22770. * This class provides the interval seek in a Template Method, deferring
  22771. * the actual interpolation to derived classes.
  22772. *
  22773. * Time complexity is O(1) for linear access crossing at most two points
  22774. * and O(log N) for random access, where N is the number of positions.
  22775. *
  22776. * References:
  22777. *
  22778. * http://www.oodesign.com/template-method-pattern.html
  22779. *
  22780. * @author tschw
  22781. */
  22782. function Interpolant(
  22783. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22784. this.parameterPositions = parameterPositions;
  22785. this._cachedIndex = 0;
  22786. this.resultBuffer = resultBuffer !== undefined ?
  22787. resultBuffer : new sampleValues.constructor( sampleSize );
  22788. this.sampleValues = sampleValues;
  22789. this.valueSize = sampleSize;
  22790. }
  22791. Interpolant.prototype = {
  22792. constructor: Interpolant,
  22793. evaluate: function( t ) {
  22794. var pp = this.parameterPositions,
  22795. i1 = this._cachedIndex,
  22796. t1 = pp[ i1 ],
  22797. t0 = pp[ i1 - 1 ];
  22798. validate_interval: {
  22799. seek: {
  22800. var right;
  22801. linear_scan: {
  22802. //- See http://jsperf.com/comparison-to-undefined/3
  22803. //- slower code:
  22804. //-
  22805. //- if ( t >= t1 || t1 === undefined ) {
  22806. forward_scan: if ( ! ( t < t1 ) ) {
  22807. for ( var giveUpAt = i1 + 2; ;) {
  22808. if ( t1 === undefined ) {
  22809. if ( t < t0 ) break forward_scan;
  22810. // after end
  22811. i1 = pp.length;
  22812. this._cachedIndex = i1;
  22813. return this.afterEnd_( i1 - 1, t, t0 );
  22814. }
  22815. if ( i1 === giveUpAt ) break; // this loop
  22816. t0 = t1;
  22817. t1 = pp[ ++ i1 ];
  22818. if ( t < t1 ) {
  22819. // we have arrived at the sought interval
  22820. break seek;
  22821. }
  22822. }
  22823. // prepare binary search on the right side of the index
  22824. right = pp.length;
  22825. break linear_scan;
  22826. }
  22827. //- slower code:
  22828. //- if ( t < t0 || t0 === undefined ) {
  22829. if ( ! ( t >= t0 ) ) {
  22830. // looping?
  22831. var t1global = pp[ 1 ];
  22832. if ( t < t1global ) {
  22833. i1 = 2; // + 1, using the scan for the details
  22834. t0 = t1global;
  22835. }
  22836. // linear reverse scan
  22837. for ( var giveUpAt = i1 - 2; ;) {
  22838. if ( t0 === undefined ) {
  22839. // before start
  22840. this._cachedIndex = 0;
  22841. return this.beforeStart_( 0, t, t1 );
  22842. }
  22843. if ( i1 === giveUpAt ) break; // this loop
  22844. t1 = t0;
  22845. t0 = pp[ -- i1 - 1 ];
  22846. if ( t >= t0 ) {
  22847. // we have arrived at the sought interval
  22848. break seek;
  22849. }
  22850. }
  22851. // prepare binary search on the left side of the index
  22852. right = i1;
  22853. i1 = 0;
  22854. break linear_scan;
  22855. }
  22856. // the interval is valid
  22857. break validate_interval;
  22858. } // linear scan
  22859. // binary search
  22860. while ( i1 < right ) {
  22861. var mid = ( i1 + right ) >>> 1;
  22862. if ( t < pp[ mid ] ) {
  22863. right = mid;
  22864. } else {
  22865. i1 = mid + 1;
  22866. }
  22867. }
  22868. t1 = pp[ i1 ];
  22869. t0 = pp[ i1 - 1 ];
  22870. // check boundary cases, again
  22871. if ( t0 === undefined ) {
  22872. this._cachedIndex = 0;
  22873. return this.beforeStart_( 0, t, t1 );
  22874. }
  22875. if ( t1 === undefined ) {
  22876. i1 = pp.length;
  22877. this._cachedIndex = i1;
  22878. return this.afterEnd_( i1 - 1, t0, t );
  22879. }
  22880. } // seek
  22881. this._cachedIndex = i1;
  22882. this.intervalChanged_( i1, t0, t1 );
  22883. } // validate_interval
  22884. return this.interpolate_( i1, t0, t, t1 );
  22885. },
  22886. settings: null, // optional, subclass-specific settings structure
  22887. // Note: The indirection allows central control of many interpolants.
  22888. // --- Protected interface
  22889. DefaultSettings_: {},
  22890. getSettings_: function() {
  22891. return this.settings || this.DefaultSettings_;
  22892. },
  22893. copySampleValue_: function( index ) {
  22894. // copies a sample value to the result buffer
  22895. var result = this.resultBuffer,
  22896. values = this.sampleValues,
  22897. stride = this.valueSize,
  22898. offset = index * stride;
  22899. for ( var i = 0; i !== stride; ++ i ) {
  22900. result[ i ] = values[ offset + i ];
  22901. }
  22902. return result;
  22903. },
  22904. // Template methods for derived classes:
  22905. interpolate_: function( i1, t0, t, t1 ) {
  22906. throw new Error( "call to abstract method" );
  22907. // implementations shall return this.resultBuffer
  22908. },
  22909. intervalChanged_: function( i1, t0, t1 ) {
  22910. // empty
  22911. }
  22912. };
  22913. Object.assign( Interpolant.prototype, {
  22914. beforeStart_: //( 0, t, t0 ), returns this.resultBuffer
  22915. Interpolant.prototype.copySampleValue_,
  22916. afterEnd_: //( N-1, tN-1, t ), returns this.resultBuffer
  22917. Interpolant.prototype.copySampleValue_
  22918. } );
  22919. /**
  22920. * Fast and simple cubic spline interpolant.
  22921. *
  22922. * It was derived from a Hermitian construction setting the first derivative
  22923. * at each sample position to the linear slope between neighboring positions
  22924. * over their parameter interval.
  22925. *
  22926. * @author tschw
  22927. */
  22928. function CubicInterpolant(
  22929. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22930. Interpolant.call(
  22931. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  22932. this._weightPrev = -0;
  22933. this._offsetPrev = -0;
  22934. this._weightNext = -0;
  22935. this._offsetNext = -0;
  22936. }
  22937. CubicInterpolant.prototype =
  22938. Object.assign( Object.create( Interpolant.prototype ), {
  22939. constructor: CubicInterpolant,
  22940. DefaultSettings_: {
  22941. endingStart: ZeroCurvatureEnding,
  22942. endingEnd: ZeroCurvatureEnding
  22943. },
  22944. intervalChanged_: function( i1, t0, t1 ) {
  22945. var pp = this.parameterPositions,
  22946. iPrev = i1 - 2,
  22947. iNext = i1 + 1,
  22948. tPrev = pp[ iPrev ],
  22949. tNext = pp[ iNext ];
  22950. if ( tPrev === undefined ) {
  22951. switch ( this.getSettings_().endingStart ) {
  22952. case ZeroSlopeEnding:
  22953. // f'(t0) = 0
  22954. iPrev = i1;
  22955. tPrev = 2 * t0 - t1;
  22956. break;
  22957. case WrapAroundEnding:
  22958. // use the other end of the curve
  22959. iPrev = pp.length - 2;
  22960. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  22961. break;
  22962. default: // ZeroCurvatureEnding
  22963. // f''(t0) = 0 a.k.a. Natural Spline
  22964. iPrev = i1;
  22965. tPrev = t1;
  22966. }
  22967. }
  22968. if ( tNext === undefined ) {
  22969. switch ( this.getSettings_().endingEnd ) {
  22970. case ZeroSlopeEnding:
  22971. // f'(tN) = 0
  22972. iNext = i1;
  22973. tNext = 2 * t1 - t0;
  22974. break;
  22975. case WrapAroundEnding:
  22976. // use the other end of the curve
  22977. iNext = 1;
  22978. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  22979. break;
  22980. default: // ZeroCurvatureEnding
  22981. // f''(tN) = 0, a.k.a. Natural Spline
  22982. iNext = i1 - 1;
  22983. tNext = t0;
  22984. }
  22985. }
  22986. var halfDt = ( t1 - t0 ) * 0.5,
  22987. stride = this.valueSize;
  22988. this._weightPrev = halfDt / ( t0 - tPrev );
  22989. this._weightNext = halfDt / ( tNext - t1 );
  22990. this._offsetPrev = iPrev * stride;
  22991. this._offsetNext = iNext * stride;
  22992. },
  22993. interpolate_: function( i1, t0, t, t1 ) {
  22994. var result = this.resultBuffer,
  22995. values = this.sampleValues,
  22996. stride = this.valueSize,
  22997. o1 = i1 * stride, o0 = o1 - stride,
  22998. oP = this._offsetPrev, oN = this._offsetNext,
  22999. wP = this._weightPrev, wN = this._weightNext,
  23000. p = ( t - t0 ) / ( t1 - t0 ),
  23001. pp = p * p,
  23002. ppp = pp * p;
  23003. // evaluate polynomials
  23004. var sP = - wP * ppp + 2 * wP * pp - wP * p;
  23005. var s0 = ( 1 + wP ) * ppp + (-1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  23006. var s1 = (-1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  23007. var sN = wN * ppp - wN * pp;
  23008. // combine data linearly
  23009. for ( var i = 0; i !== stride; ++ i ) {
  23010. result[ i ] =
  23011. sP * values[ oP + i ] +
  23012. s0 * values[ o0 + i ] +
  23013. s1 * values[ o1 + i ] +
  23014. sN * values[ oN + i ];
  23015. }
  23016. return result;
  23017. }
  23018. } );
  23019. /**
  23020. * @author tschw
  23021. */
  23022. function LinearInterpolant(
  23023. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23024. Interpolant.call(
  23025. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  23026. }
  23027. LinearInterpolant.prototype =
  23028. Object.assign( Object.create( Interpolant.prototype ), {
  23029. constructor: LinearInterpolant,
  23030. interpolate_: function( i1, t0, t, t1 ) {
  23031. var result = this.resultBuffer,
  23032. values = this.sampleValues,
  23033. stride = this.valueSize,
  23034. offset1 = i1 * stride,
  23035. offset0 = offset1 - stride,
  23036. weight1 = ( t - t0 ) / ( t1 - t0 ),
  23037. weight0 = 1 - weight1;
  23038. for ( var i = 0; i !== stride; ++ i ) {
  23039. result[ i ] =
  23040. values[ offset0 + i ] * weight0 +
  23041. values[ offset1 + i ] * weight1;
  23042. }
  23043. return result;
  23044. }
  23045. } );
  23046. /**
  23047. *
  23048. * Interpolant that evaluates to the sample value at the position preceeding
  23049. * the parameter.
  23050. *
  23051. * @author tschw
  23052. */
  23053. function DiscreteInterpolant(
  23054. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23055. Interpolant.call(
  23056. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  23057. }
  23058. DiscreteInterpolant.prototype =
  23059. Object.assign( Object.create( Interpolant.prototype ), {
  23060. constructor: DiscreteInterpolant,
  23061. interpolate_: function( i1, t0, t, t1 ) {
  23062. return this.copySampleValue_( i1 - 1 );
  23063. }
  23064. } );
  23065. var KeyframeTrackPrototype;
  23066. KeyframeTrackPrototype = {
  23067. TimeBufferType: Float32Array,
  23068. ValueBufferType: Float32Array,
  23069. DefaultInterpolation: InterpolateLinear,
  23070. InterpolantFactoryMethodDiscrete: function ( result ) {
  23071. return new DiscreteInterpolant(
  23072. this.times, this.values, this.getValueSize(), result );
  23073. },
  23074. InterpolantFactoryMethodLinear: function ( result ) {
  23075. return new LinearInterpolant(
  23076. this.times, this.values, this.getValueSize(), result );
  23077. },
  23078. InterpolantFactoryMethodSmooth: function ( result ) {
  23079. return new CubicInterpolant(
  23080. this.times, this.values, this.getValueSize(), result );
  23081. },
  23082. setInterpolation: function ( interpolation ) {
  23083. var factoryMethod;
  23084. switch ( interpolation ) {
  23085. case InterpolateDiscrete:
  23086. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  23087. break;
  23088. case InterpolateLinear:
  23089. factoryMethod = this.InterpolantFactoryMethodLinear;
  23090. break;
  23091. case InterpolateSmooth:
  23092. factoryMethod = this.InterpolantFactoryMethodSmooth;
  23093. break;
  23094. }
  23095. if ( factoryMethod === undefined ) {
  23096. var message = "unsupported interpolation for " +
  23097. this.ValueTypeName + " keyframe track named " + this.name;
  23098. if ( this.createInterpolant === undefined ) {
  23099. // fall back to default, unless the default itself is messed up
  23100. if ( interpolation !== this.DefaultInterpolation ) {
  23101. this.setInterpolation( this.DefaultInterpolation );
  23102. } else {
  23103. throw new Error( message ); // fatal, in this case
  23104. }
  23105. }
  23106. console.warn( message );
  23107. return;
  23108. }
  23109. this.createInterpolant = factoryMethod;
  23110. },
  23111. getInterpolation: function () {
  23112. switch ( this.createInterpolant ) {
  23113. case this.InterpolantFactoryMethodDiscrete:
  23114. return InterpolateDiscrete;
  23115. case this.InterpolantFactoryMethodLinear:
  23116. return InterpolateLinear;
  23117. case this.InterpolantFactoryMethodSmooth:
  23118. return InterpolateSmooth;
  23119. }
  23120. },
  23121. getValueSize: function () {
  23122. return this.values.length / this.times.length;
  23123. },
  23124. // move all keyframes either forwards or backwards in time
  23125. shift: function ( timeOffset ) {
  23126. if ( timeOffset !== 0.0 ) {
  23127. var times = this.times;
  23128. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  23129. times[ i ] += timeOffset;
  23130. }
  23131. }
  23132. return this;
  23133. },
  23134. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  23135. scale: function ( timeScale ) {
  23136. if ( timeScale !== 1.0 ) {
  23137. var times = this.times;
  23138. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  23139. times[ i ] *= timeScale;
  23140. }
  23141. }
  23142. return this;
  23143. },
  23144. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  23145. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  23146. trim: function ( startTime, endTime ) {
  23147. var times = this.times,
  23148. nKeys = times.length,
  23149. from = 0,
  23150. to = nKeys - 1;
  23151. while ( from !== nKeys && times[ from ] < startTime ) ++ from;
  23152. while ( to !== - 1 && times[ to ] > endTime ) -- to;
  23153. ++ to; // inclusive -> exclusive bound
  23154. if ( from !== 0 || to !== nKeys ) {
  23155. // empty tracks are forbidden, so keep at least one keyframe
  23156. if ( from >= to ) to = Math.max( to, 1 ), from = to - 1;
  23157. var stride = this.getValueSize();
  23158. this.times = AnimationUtils.arraySlice( times, from, to );
  23159. this.values = AnimationUtils.
  23160. arraySlice( this.values, from * stride, to * stride );
  23161. }
  23162. return this;
  23163. },
  23164. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  23165. validate: function () {
  23166. var valid = true;
  23167. var valueSize = this.getValueSize();
  23168. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  23169. console.error( "invalid value size in track", this );
  23170. valid = false;
  23171. }
  23172. var times = this.times,
  23173. values = this.values,
  23174. nKeys = times.length;
  23175. if ( nKeys === 0 ) {
  23176. console.error( "track is empty", this );
  23177. valid = false;
  23178. }
  23179. var prevTime = null;
  23180. for ( var i = 0; i !== nKeys; i ++ ) {
  23181. var currTime = times[ i ];
  23182. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  23183. console.error( "time is not a valid number", this, i, currTime );
  23184. valid = false;
  23185. break;
  23186. }
  23187. if ( prevTime !== null && prevTime > currTime ) {
  23188. console.error( "out of order keys", this, i, currTime, prevTime );
  23189. valid = false;
  23190. break;
  23191. }
  23192. prevTime = currTime;
  23193. }
  23194. if ( values !== undefined ) {
  23195. if ( AnimationUtils.isTypedArray( values ) ) {
  23196. for ( var i = 0, n = values.length; i !== n; ++ i ) {
  23197. var value = values[ i ];
  23198. if ( isNaN( value ) ) {
  23199. console.error( "value is not a valid number", this, i, value );
  23200. valid = false;
  23201. break;
  23202. }
  23203. }
  23204. }
  23205. }
  23206. return valid;
  23207. },
  23208. // removes equivalent sequential keys as common in morph target sequences
  23209. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  23210. optimize: function () {
  23211. var times = this.times,
  23212. values = this.values,
  23213. stride = this.getValueSize(),
  23214. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  23215. writeIndex = 1,
  23216. lastIndex = times.length - 1;
  23217. for ( var i = 1; i < lastIndex; ++ i ) {
  23218. var keep = false;
  23219. var time = times[ i ];
  23220. var timeNext = times[ i + 1 ];
  23221. // remove adjacent keyframes scheduled at the same time
  23222. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  23223. if ( ! smoothInterpolation ) {
  23224. // remove unnecessary keyframes same as their neighbors
  23225. var offset = i * stride,
  23226. offsetP = offset - stride,
  23227. offsetN = offset + stride;
  23228. for ( var j = 0; j !== stride; ++ j ) {
  23229. var value = values[ offset + j ];
  23230. if ( value !== values[ offsetP + j ] ||
  23231. value !== values[ offsetN + j ] ) {
  23232. keep = true;
  23233. break;
  23234. }
  23235. }
  23236. } else keep = true;
  23237. }
  23238. // in-place compaction
  23239. if ( keep ) {
  23240. if ( i !== writeIndex ) {
  23241. times[ writeIndex ] = times[ i ];
  23242. var readOffset = i * stride,
  23243. writeOffset = writeIndex * stride;
  23244. for ( var j = 0; j !== stride; ++ j )
  23245. values[ writeOffset + j ] = values[ readOffset + j ];
  23246. }
  23247. ++ writeIndex;
  23248. }
  23249. }
  23250. // flush last keyframe (compaction looks ahead)
  23251. if ( lastIndex > 0 ) {
  23252. times[ writeIndex ] = times[ lastIndex ];
  23253. for ( var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j )
  23254. values[ writeOffset + j ] = values[ readOffset + j ];
  23255. ++ writeIndex;
  23256. }
  23257. if ( writeIndex !== times.length ) {
  23258. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  23259. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  23260. }
  23261. return this;
  23262. }
  23263. };
  23264. function KeyframeTrackConstructor( name, times, values, interpolation ) {
  23265. if( name === undefined ) throw new Error( "track name is undefined" );
  23266. if( times === undefined || times.length === 0 ) {
  23267. throw new Error( "no keyframes in track named " + name );
  23268. }
  23269. this.name = name;
  23270. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  23271. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  23272. this.setInterpolation( interpolation || this.DefaultInterpolation );
  23273. this.validate();
  23274. this.optimize();
  23275. }
  23276. /**
  23277. *
  23278. * A Track of vectored keyframe values.
  23279. *
  23280. *
  23281. * @author Ben Houston / http://clara.io/
  23282. * @author David Sarno / http://lighthaus.us/
  23283. * @author tschw
  23284. */
  23285. function VectorKeyframeTrack( name, times, values, interpolation ) {
  23286. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  23287. }
  23288. VectorKeyframeTrack.prototype =
  23289. Object.assign( Object.create( KeyframeTrackPrototype ), {
  23290. constructor: VectorKeyframeTrack,
  23291. ValueTypeName: 'vector'
  23292. // ValueBufferType is inherited
  23293. // DefaultInterpolation is inherited
  23294. } );
  23295. /**
  23296. * Spherical linear unit quaternion interpolant.
  23297. *
  23298. * @author tschw
  23299. */
  23300. function QuaternionLinearInterpolant(
  23301. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23302. Interpolant.call(
  23303. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  23304. }
  23305. QuaternionLinearInterpolant.prototype =
  23306. Object.assign( Object.create( Interpolant.prototype ), {
  23307. constructor: QuaternionLinearInterpolant,
  23308. interpolate_: function( i1, t0, t, t1 ) {
  23309. var result = this.resultBuffer,
  23310. values = this.sampleValues,
  23311. stride = this.valueSize,
  23312. offset = i1 * stride,
  23313. alpha = ( t - t0 ) / ( t1 - t0 );
  23314. for ( var end = offset + stride; offset !== end; offset += 4 ) {
  23315. Quaternion.slerpFlat( result, 0,
  23316. values, offset - stride, values, offset, alpha );
  23317. }
  23318. return result;
  23319. }
  23320. } );
  23321. /**
  23322. *
  23323. * A Track of quaternion keyframe values.
  23324. *
  23325. * @author Ben Houston / http://clara.io/
  23326. * @author David Sarno / http://lighthaus.us/
  23327. * @author tschw
  23328. */
  23329. function QuaternionKeyframeTrack( name, times, values, interpolation ) {
  23330. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  23331. }
  23332. QuaternionKeyframeTrack.prototype =
  23333. Object.assign( Object.create( KeyframeTrackPrototype ), {
  23334. constructor: QuaternionKeyframeTrack,
  23335. ValueTypeName: 'quaternion',
  23336. // ValueBufferType is inherited
  23337. DefaultInterpolation: InterpolateLinear,
  23338. InterpolantFactoryMethodLinear: function( result ) {
  23339. return new QuaternionLinearInterpolant(
  23340. this.times, this.values, this.getValueSize(), result );
  23341. },
  23342. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  23343. } );
  23344. /**
  23345. *
  23346. * A Track of numeric keyframe values.
  23347. *
  23348. * @author Ben Houston / http://clara.io/
  23349. * @author David Sarno / http://lighthaus.us/
  23350. * @author tschw
  23351. */
  23352. function NumberKeyframeTrack( name, times, values, interpolation ) {
  23353. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  23354. }
  23355. NumberKeyframeTrack.prototype =
  23356. Object.assign( Object.create( KeyframeTrackPrototype ), {
  23357. constructor: NumberKeyframeTrack,
  23358. ValueTypeName: 'number'
  23359. // ValueBufferType is inherited
  23360. // DefaultInterpolation is inherited
  23361. } );
  23362. /**
  23363. *
  23364. * A Track that interpolates Strings
  23365. *
  23366. *
  23367. * @author Ben Houston / http://clara.io/
  23368. * @author David Sarno / http://lighthaus.us/
  23369. * @author tschw
  23370. */
  23371. function StringKeyframeTrack( name, times, values, interpolation ) {
  23372. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  23373. }
  23374. StringKeyframeTrack.prototype =
  23375. Object.assign( Object.create( KeyframeTrackPrototype ), {
  23376. constructor: StringKeyframeTrack,
  23377. ValueTypeName: 'string',
  23378. ValueBufferType: Array,
  23379. DefaultInterpolation: InterpolateDiscrete,
  23380. InterpolantFactoryMethodLinear: undefined,
  23381. InterpolantFactoryMethodSmooth: undefined
  23382. } );
  23383. /**
  23384. *
  23385. * A Track of Boolean keyframe values.
  23386. *
  23387. *
  23388. * @author Ben Houston / http://clara.io/
  23389. * @author David Sarno / http://lighthaus.us/
  23390. * @author tschw
  23391. */
  23392. function BooleanKeyframeTrack( name, times, values ) {
  23393. KeyframeTrackConstructor.call( this, name, times, values );
  23394. }
  23395. BooleanKeyframeTrack.prototype =
  23396. Object.assign( Object.create( KeyframeTrackPrototype ), {
  23397. constructor: BooleanKeyframeTrack,
  23398. ValueTypeName: 'bool',
  23399. ValueBufferType: Array,
  23400. DefaultInterpolation: InterpolateDiscrete,
  23401. InterpolantFactoryMethodLinear: undefined,
  23402. InterpolantFactoryMethodSmooth: undefined
  23403. // Note: Actually this track could have a optimized / compressed
  23404. // representation of a single value and a custom interpolant that
  23405. // computes "firstValue ^ isOdd( index )".
  23406. } );
  23407. /**
  23408. *
  23409. * A Track of keyframe values that represent color.
  23410. *
  23411. *
  23412. * @author Ben Houston / http://clara.io/
  23413. * @author David Sarno / http://lighthaus.us/
  23414. * @author tschw
  23415. */
  23416. function ColorKeyframeTrack( name, times, values, interpolation ) {
  23417. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  23418. }
  23419. ColorKeyframeTrack.prototype =
  23420. Object.assign( Object.create( KeyframeTrackPrototype ), {
  23421. constructor: ColorKeyframeTrack,
  23422. ValueTypeName: 'color'
  23423. // ValueBufferType is inherited
  23424. // DefaultInterpolation is inherited
  23425. // Note: Very basic implementation and nothing special yet.
  23426. // However, this is the place for color space parameterization.
  23427. } );
  23428. /**
  23429. *
  23430. * A timed sequence of keyframes for a specific property.
  23431. *
  23432. *
  23433. * @author Ben Houston / http://clara.io/
  23434. * @author David Sarno / http://lighthaus.us/
  23435. * @author tschw
  23436. */
  23437. function KeyframeTrack( name, times, values, interpolation ) {
  23438. KeyframeTrackConstructor.apply( this, arguments );
  23439. }
  23440. KeyframeTrack.prototype = KeyframeTrackPrototype;
  23441. KeyframeTrackPrototype.constructor = KeyframeTrack;
  23442. // Static methods:
  23443. Object.assign( KeyframeTrack, {
  23444. // Serialization (in static context, because of constructor invocation
  23445. // and automatic invocation of .toJSON):
  23446. parse: function( json ) {
  23447. if( json.type === undefined ) {
  23448. throw new Error( "track type undefined, can not parse" );
  23449. }
  23450. var trackType = KeyframeTrack._getTrackTypeForValueTypeName( json.type );
  23451. if ( json.times === undefined ) {
  23452. var times = [], values = [];
  23453. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  23454. json.times = times;
  23455. json.values = values;
  23456. }
  23457. // derived classes can define a static parse method
  23458. if ( trackType.parse !== undefined ) {
  23459. return trackType.parse( json );
  23460. } else {
  23461. // by default, we asssume a constructor compatible with the base
  23462. return new trackType(
  23463. json.name, json.times, json.values, json.interpolation );
  23464. }
  23465. },
  23466. toJSON: function( track ) {
  23467. var trackType = track.constructor;
  23468. var json;
  23469. // derived classes can define a static toJSON method
  23470. if ( trackType.toJSON !== undefined ) {
  23471. json = trackType.toJSON( track );
  23472. } else {
  23473. // by default, we assume the data can be serialized as-is
  23474. json = {
  23475. 'name': track.name,
  23476. 'times': AnimationUtils.convertArray( track.times, Array ),
  23477. 'values': AnimationUtils.convertArray( track.values, Array )
  23478. };
  23479. var interpolation = track.getInterpolation();
  23480. if ( interpolation !== track.DefaultInterpolation ) {
  23481. json.interpolation = interpolation;
  23482. }
  23483. }
  23484. json.type = track.ValueTypeName; // mandatory
  23485. return json;
  23486. },
  23487. _getTrackTypeForValueTypeName: function( typeName ) {
  23488. switch( typeName.toLowerCase() ) {
  23489. case "scalar":
  23490. case "double":
  23491. case "float":
  23492. case "number":
  23493. case "integer":
  23494. return NumberKeyframeTrack;
  23495. case "vector":
  23496. case "vector2":
  23497. case "vector3":
  23498. case "vector4":
  23499. return VectorKeyframeTrack;
  23500. case "color":
  23501. return ColorKeyframeTrack;
  23502. case "quaternion":
  23503. return QuaternionKeyframeTrack;
  23504. case "bool":
  23505. case "boolean":
  23506. return BooleanKeyframeTrack;
  23507. case "string":
  23508. return StringKeyframeTrack;
  23509. }
  23510. throw new Error( "Unsupported typeName: " + typeName );
  23511. }
  23512. } );
  23513. /**
  23514. *
  23515. * Reusable set of Tracks that represent an animation.
  23516. *
  23517. * @author Ben Houston / http://clara.io/
  23518. * @author David Sarno / http://lighthaus.us/
  23519. */
  23520. function AnimationClip( name, duration, tracks ) {
  23521. this.name = name;
  23522. this.tracks = tracks;
  23523. this.duration = ( duration !== undefined ) ? duration : -1;
  23524. this.uuid = _Math.generateUUID();
  23525. // this means it should figure out its duration by scanning the tracks
  23526. if ( this.duration < 0 ) {
  23527. this.resetDuration();
  23528. }
  23529. this.optimize();
  23530. }
  23531. AnimationClip.prototype = {
  23532. constructor: AnimationClip,
  23533. resetDuration: function() {
  23534. var tracks = this.tracks,
  23535. duration = 0;
  23536. for ( var i = 0, n = tracks.length; i !== n; ++ i ) {
  23537. var track = this.tracks[ i ];
  23538. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  23539. }
  23540. this.duration = duration;
  23541. },
  23542. trim: function() {
  23543. for ( var i = 0; i < this.tracks.length; i ++ ) {
  23544. this.tracks[ i ].trim( 0, this.duration );
  23545. }
  23546. return this;
  23547. },
  23548. optimize: function() {
  23549. for ( var i = 0; i < this.tracks.length; i ++ ) {
  23550. this.tracks[ i ].optimize();
  23551. }
  23552. return this;
  23553. }
  23554. };
  23555. // Static methods:
  23556. Object.assign( AnimationClip, {
  23557. parse: function( json ) {
  23558. var tracks = [],
  23559. jsonTracks = json.tracks,
  23560. frameTime = 1.0 / ( json.fps || 1.0 );
  23561. for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  23562. tracks.push( KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) );
  23563. }
  23564. return new AnimationClip( json.name, json.duration, tracks );
  23565. },
  23566. toJSON: function( clip ) {
  23567. var tracks = [],
  23568. clipTracks = clip.tracks;
  23569. var json = {
  23570. 'name': clip.name,
  23571. 'duration': clip.duration,
  23572. 'tracks': tracks
  23573. };
  23574. for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) {
  23575. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  23576. }
  23577. return json;
  23578. },
  23579. CreateFromMorphTargetSequence: function( name, morphTargetSequence, fps, noLoop ) {
  23580. var numMorphTargets = morphTargetSequence.length;
  23581. var tracks = [];
  23582. for ( var i = 0; i < numMorphTargets; i ++ ) {
  23583. var times = [];
  23584. var values = [];
  23585. times.push(
  23586. ( i + numMorphTargets - 1 ) % numMorphTargets,
  23587. i,
  23588. ( i + 1 ) % numMorphTargets );
  23589. values.push( 0, 1, 0 );
  23590. var order = AnimationUtils.getKeyframeOrder( times );
  23591. times = AnimationUtils.sortedArray( times, 1, order );
  23592. values = AnimationUtils.sortedArray( values, 1, order );
  23593. // if there is a key at the first frame, duplicate it as the
  23594. // last frame as well for perfect loop.
  23595. if ( ! noLoop && times[ 0 ] === 0 ) {
  23596. times.push( numMorphTargets );
  23597. values.push( values[ 0 ] );
  23598. }
  23599. tracks.push(
  23600. new NumberKeyframeTrack(
  23601. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  23602. times, values
  23603. ).scale( 1.0 / fps ) );
  23604. }
  23605. return new AnimationClip( name, -1, tracks );
  23606. },
  23607. findByName: function( objectOrClipArray, name ) {
  23608. var clipArray = objectOrClipArray;
  23609. if ( ! Array.isArray( objectOrClipArray ) ) {
  23610. var o = objectOrClipArray;
  23611. clipArray = o.geometry && o.geometry.animations || o.animations;
  23612. }
  23613. for ( var i = 0; i < clipArray.length; i ++ ) {
  23614. if ( clipArray[ i ].name === name ) {
  23615. return clipArray[ i ];
  23616. }
  23617. }
  23618. return null;
  23619. },
  23620. CreateClipsFromMorphTargetSequences: function( morphTargets, fps, noLoop ) {
  23621. var animationToMorphTargets = {};
  23622. // tested with https://regex101.com/ on trick sequences
  23623. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  23624. var pattern = /^([\w-]*?)([\d]+)$/;
  23625. // sort morph target names into animation groups based
  23626. // patterns like Walk_001, Walk_002, Run_001, Run_002
  23627. for ( var i = 0, il = morphTargets.length; i < il; i ++ ) {
  23628. var morphTarget = morphTargets[ i ];
  23629. var parts = morphTarget.name.match( pattern );
  23630. if ( parts && parts.length > 1 ) {
  23631. var name = parts[ 1 ];
  23632. var animationMorphTargets = animationToMorphTargets[ name ];
  23633. if ( ! animationMorphTargets ) {
  23634. animationToMorphTargets[ name ] = animationMorphTargets = [];
  23635. }
  23636. animationMorphTargets.push( morphTarget );
  23637. }
  23638. }
  23639. var clips = [];
  23640. for ( var name in animationToMorphTargets ) {
  23641. clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  23642. }
  23643. return clips;
  23644. },
  23645. // parse the animation.hierarchy format
  23646. parseAnimation: function( animation, bones ) {
  23647. if ( ! animation ) {
  23648. console.error( " no animation in JSONLoader data" );
  23649. return null;
  23650. }
  23651. var addNonemptyTrack = function(
  23652. trackType, trackName, animationKeys, propertyName, destTracks ) {
  23653. // only return track if there are actually keys.
  23654. if ( animationKeys.length !== 0 ) {
  23655. var times = [];
  23656. var values = [];
  23657. AnimationUtils.flattenJSON(
  23658. animationKeys, times, values, propertyName );
  23659. // empty keys are filtered out, so check again
  23660. if ( times.length !== 0 ) {
  23661. destTracks.push( new trackType( trackName, times, values ) );
  23662. }
  23663. }
  23664. };
  23665. var tracks = [];
  23666. var clipName = animation.name || 'default';
  23667. // automatic length determination in AnimationClip.
  23668. var duration = animation.length || -1;
  23669. var fps = animation.fps || 30;
  23670. var hierarchyTracks = animation.hierarchy || [];
  23671. for ( var h = 0; h < hierarchyTracks.length; h ++ ) {
  23672. var animationKeys = hierarchyTracks[ h ].keys;
  23673. // skip empty tracks
  23674. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  23675. // process morph targets in a way exactly compatible
  23676. // with AnimationHandler.init( animation )
  23677. if ( animationKeys[0].morphTargets ) {
  23678. // figure out all morph targets used in this track
  23679. var morphTargetNames = {};
  23680. for ( var k = 0; k < animationKeys.length; k ++ ) {
  23681. if ( animationKeys[k].morphTargets ) {
  23682. for ( var m = 0; m < animationKeys[k].morphTargets.length; m ++ ) {
  23683. morphTargetNames[ animationKeys[k].morphTargets[m] ] = -1;
  23684. }
  23685. }
  23686. }
  23687. // create a track for each morph target with all zero
  23688. // morphTargetInfluences except for the keys in which
  23689. // the morphTarget is named.
  23690. for ( var morphTargetName in morphTargetNames ) {
  23691. var times = [];
  23692. var values = [];
  23693. for ( var m = 0; m !== animationKeys[k].morphTargets.length; ++ m ) {
  23694. var animationKey = animationKeys[k];
  23695. times.push( animationKey.time );
  23696. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  23697. }
  23698. tracks.push( new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  23699. }
  23700. duration = morphTargetNames.length * ( fps || 1.0 );
  23701. } else {
  23702. // ...assume skeletal animation
  23703. var boneName = '.bones[' + bones[ h ].name + ']';
  23704. addNonemptyTrack(
  23705. VectorKeyframeTrack, boneName + '.position',
  23706. animationKeys, 'pos', tracks );
  23707. addNonemptyTrack(
  23708. QuaternionKeyframeTrack, boneName + '.quaternion',
  23709. animationKeys, 'rot', tracks );
  23710. addNonemptyTrack(
  23711. VectorKeyframeTrack, boneName + '.scale',
  23712. animationKeys, 'scl', tracks );
  23713. }
  23714. }
  23715. if ( tracks.length === 0 ) {
  23716. return null;
  23717. }
  23718. var clip = new AnimationClip( clipName, duration, tracks );
  23719. return clip;
  23720. }
  23721. } );
  23722. /**
  23723. * @author mrdoob / http://mrdoob.com/
  23724. */
  23725. function MaterialLoader( manager ) {
  23726. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  23727. this.textures = {};
  23728. }
  23729. Object.assign( MaterialLoader.prototype, {
  23730. load: function ( url, onLoad, onProgress, onError ) {
  23731. var scope = this;
  23732. var loader = new FileLoader( scope.manager );
  23733. loader.load( url, function ( text ) {
  23734. onLoad( scope.parse( JSON.parse( text ) ) );
  23735. }, onProgress, onError );
  23736. },
  23737. setTextures: function ( value ) {
  23738. this.textures = value;
  23739. },
  23740. parse: function ( json ) {
  23741. var textures = this.textures;
  23742. function getTexture( name ) {
  23743. if ( textures[ name ] === undefined ) {
  23744. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  23745. }
  23746. return textures[ name ];
  23747. }
  23748. var material = new Materials[ json.type ]();
  23749. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  23750. if ( json.name !== undefined ) material.name = json.name;
  23751. if ( json.color !== undefined ) material.color.setHex( json.color );
  23752. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  23753. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  23754. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  23755. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  23756. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  23757. if ( json.clearCoat !== undefined ) material.clearCoat = json.clearCoat;
  23758. if ( json.clearCoatRoughness !== undefined ) material.clearCoatRoughness = json.clearCoatRoughness;
  23759. if ( json.uniforms !== undefined ) material.uniforms = json.uniforms;
  23760. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  23761. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  23762. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  23763. if ( json.fog !== undefined ) material.fog = json.fog;
  23764. if ( json.shading !== undefined ) material.shading = json.shading;
  23765. if ( json.blending !== undefined ) material.blending = json.blending;
  23766. if ( json.side !== undefined ) material.side = json.side;
  23767. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  23768. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  23769. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  23770. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  23771. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  23772. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  23773. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  23774. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  23775. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  23776. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  23777. if ( json.skinning !== undefined ) material.skinning = json.skinning;
  23778. if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets;
  23779. // for PointsMaterial
  23780. if ( json.size !== undefined ) material.size = json.size;
  23781. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  23782. // maps
  23783. if ( json.map !== undefined ) material.map = getTexture( json.map );
  23784. if ( json.alphaMap !== undefined ) {
  23785. material.alphaMap = getTexture( json.alphaMap );
  23786. material.transparent = true;
  23787. }
  23788. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  23789. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  23790. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  23791. if ( json.normalScale !== undefined ) {
  23792. var normalScale = json.normalScale;
  23793. if ( Array.isArray( normalScale ) === false ) {
  23794. // Blender exporter used to export a scalar. See #7459
  23795. normalScale = [ normalScale, normalScale ];
  23796. }
  23797. material.normalScale = new Vector2().fromArray( normalScale );
  23798. }
  23799. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  23800. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  23801. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  23802. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  23803. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  23804. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  23805. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  23806. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  23807. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  23808. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  23809. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  23810. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  23811. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  23812. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  23813. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  23814. // MultiMaterial
  23815. if ( json.materials !== undefined ) {
  23816. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  23817. material.materials.push( this.parse( json.materials[ i ] ) );
  23818. }
  23819. }
  23820. return material;
  23821. }
  23822. } );
  23823. /**
  23824. * @author mrdoob / http://mrdoob.com/
  23825. */
  23826. function BufferGeometryLoader( manager ) {
  23827. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  23828. }
  23829. Object.assign( BufferGeometryLoader.prototype, {
  23830. load: function ( url, onLoad, onProgress, onError ) {
  23831. var scope = this;
  23832. var loader = new FileLoader( scope.manager );
  23833. loader.load( url, function ( text ) {
  23834. onLoad( scope.parse( JSON.parse( text ) ) );
  23835. }, onProgress, onError );
  23836. },
  23837. parse: function ( json ) {
  23838. var geometry = new BufferGeometry();
  23839. var index = json.data.index;
  23840. var TYPED_ARRAYS = {
  23841. 'Int8Array': Int8Array,
  23842. 'Uint8Array': Uint8Array,
  23843. 'Uint8ClampedArray': Uint8ClampedArray,
  23844. 'Int16Array': Int16Array,
  23845. 'Uint16Array': Uint16Array,
  23846. 'Int32Array': Int32Array,
  23847. 'Uint32Array': Uint32Array,
  23848. 'Float32Array': Float32Array,
  23849. 'Float64Array': Float64Array
  23850. };
  23851. if ( index !== undefined ) {
  23852. var typedArray = new TYPED_ARRAYS[ index.type ]( index.array );
  23853. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  23854. }
  23855. var attributes = json.data.attributes;
  23856. for ( var key in attributes ) {
  23857. var attribute = attributes[ key ];
  23858. var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
  23859. geometry.addAttribute( key, new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) );
  23860. }
  23861. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  23862. if ( groups !== undefined ) {
  23863. for ( var i = 0, n = groups.length; i !== n; ++ i ) {
  23864. var group = groups[ i ];
  23865. geometry.addGroup( group.start, group.count, group.materialIndex );
  23866. }
  23867. }
  23868. var boundingSphere = json.data.boundingSphere;
  23869. if ( boundingSphere !== undefined ) {
  23870. var center = new Vector3();
  23871. if ( boundingSphere.center !== undefined ) {
  23872. center.fromArray( boundingSphere.center );
  23873. }
  23874. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  23875. }
  23876. return geometry;
  23877. }
  23878. } );
  23879. /**
  23880. * @author alteredq / http://alteredqualia.com/
  23881. */
  23882. function Loader() {
  23883. this.onLoadStart = function () {};
  23884. this.onLoadProgress = function () {};
  23885. this.onLoadComplete = function () {};
  23886. }
  23887. Loader.prototype = {
  23888. constructor: Loader,
  23889. crossOrigin: undefined,
  23890. extractUrlBase: function ( url ) {
  23891. var parts = url.split( '/' );
  23892. if ( parts.length === 1 ) return './';
  23893. parts.pop();
  23894. return parts.join( '/' ) + '/';
  23895. },
  23896. initMaterials: function ( materials, texturePath, crossOrigin ) {
  23897. var array = [];
  23898. for ( var i = 0; i < materials.length; ++ i ) {
  23899. array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin );
  23900. }
  23901. return array;
  23902. },
  23903. createMaterial: ( function () {
  23904. var BlendingMode = {
  23905. NoBlending: NoBlending,
  23906. NormalBlending: NormalBlending,
  23907. AdditiveBlending: AdditiveBlending,
  23908. SubtractiveBlending: SubtractiveBlending,
  23909. MultiplyBlending: MultiplyBlending,
  23910. CustomBlending: CustomBlending
  23911. };
  23912. var color, textureLoader, materialLoader;
  23913. return function createMaterial( m, texturePath, crossOrigin ) {
  23914. if ( color === undefined ) color = new Color();
  23915. if ( textureLoader === undefined ) textureLoader = new TextureLoader();
  23916. if ( materialLoader === undefined ) materialLoader = new MaterialLoader();
  23917. // convert from old material format
  23918. var textures = {};
  23919. function loadTexture( path, repeat, offset, wrap, anisotropy ) {
  23920. var fullPath = texturePath + path;
  23921. var loader = Loader.Handlers.get( fullPath );
  23922. var texture;
  23923. if ( loader !== null ) {
  23924. texture = loader.load( fullPath );
  23925. } else {
  23926. textureLoader.setCrossOrigin( crossOrigin );
  23927. texture = textureLoader.load( fullPath );
  23928. }
  23929. if ( repeat !== undefined ) {
  23930. texture.repeat.fromArray( repeat );
  23931. if ( repeat[ 0 ] !== 1 ) texture.wrapS = RepeatWrapping;
  23932. if ( repeat[ 1 ] !== 1 ) texture.wrapT = RepeatWrapping;
  23933. }
  23934. if ( offset !== undefined ) {
  23935. texture.offset.fromArray( offset );
  23936. }
  23937. if ( wrap !== undefined ) {
  23938. if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = RepeatWrapping;
  23939. if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = MirroredRepeatWrapping;
  23940. if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = RepeatWrapping;
  23941. if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = MirroredRepeatWrapping;
  23942. }
  23943. if ( anisotropy !== undefined ) {
  23944. texture.anisotropy = anisotropy;
  23945. }
  23946. var uuid = _Math.generateUUID();
  23947. textures[ uuid ] = texture;
  23948. return uuid;
  23949. }
  23950. //
  23951. var json = {
  23952. uuid: _Math.generateUUID(),
  23953. type: 'MeshLambertMaterial'
  23954. };
  23955. for ( var name in m ) {
  23956. var value = m[ name ];
  23957. switch ( name ) {
  23958. case 'DbgColor':
  23959. case 'DbgIndex':
  23960. case 'opticalDensity':
  23961. case 'illumination':
  23962. break;
  23963. case 'DbgName':
  23964. json.name = value;
  23965. break;
  23966. case 'blending':
  23967. json.blending = BlendingMode[ value ];
  23968. break;
  23969. case 'colorAmbient':
  23970. case 'mapAmbient':
  23971. console.warn( 'THREE.Loader.createMaterial:', name, 'is no longer supported.' );
  23972. break;
  23973. case 'colorDiffuse':
  23974. json.color = color.fromArray( value ).getHex();
  23975. break;
  23976. case 'colorSpecular':
  23977. json.specular = color.fromArray( value ).getHex();
  23978. break;
  23979. case 'colorEmissive':
  23980. json.emissive = color.fromArray( value ).getHex();
  23981. break;
  23982. case 'specularCoef':
  23983. json.shininess = value;
  23984. break;
  23985. case 'shading':
  23986. if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial';
  23987. if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial';
  23988. if ( value.toLowerCase() === 'standard' ) json.type = 'MeshStandardMaterial';
  23989. break;
  23990. case 'mapDiffuse':
  23991. json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  23992. break;
  23993. case 'mapDiffuseRepeat':
  23994. case 'mapDiffuseOffset':
  23995. case 'mapDiffuseWrap':
  23996. case 'mapDiffuseAnisotropy':
  23997. break;
  23998. case 'mapEmissive':
  23999. json.emissiveMap = loadTexture( value, m.mapEmissiveRepeat, m.mapEmissiveOffset, m.mapEmissiveWrap, m.mapEmissiveAnisotropy );
  24000. break;
  24001. case 'mapEmissiveRepeat':
  24002. case 'mapEmissiveOffset':
  24003. case 'mapEmissiveWrap':
  24004. case 'mapEmissiveAnisotropy':
  24005. break;
  24006. case 'mapLight':
  24007. json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  24008. break;
  24009. case 'mapLightRepeat':
  24010. case 'mapLightOffset':
  24011. case 'mapLightWrap':
  24012. case 'mapLightAnisotropy':
  24013. break;
  24014. case 'mapAO':
  24015. json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy );
  24016. break;
  24017. case 'mapAORepeat':
  24018. case 'mapAOOffset':
  24019. case 'mapAOWrap':
  24020. case 'mapAOAnisotropy':
  24021. break;
  24022. case 'mapBump':
  24023. json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  24024. break;
  24025. case 'mapBumpScale':
  24026. json.bumpScale = value;
  24027. break;
  24028. case 'mapBumpRepeat':
  24029. case 'mapBumpOffset':
  24030. case 'mapBumpWrap':
  24031. case 'mapBumpAnisotropy':
  24032. break;
  24033. case 'mapNormal':
  24034. json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  24035. break;
  24036. case 'mapNormalFactor':
  24037. json.normalScale = [ value, value ];
  24038. break;
  24039. case 'mapNormalRepeat':
  24040. case 'mapNormalOffset':
  24041. case 'mapNormalWrap':
  24042. case 'mapNormalAnisotropy':
  24043. break;
  24044. case 'mapSpecular':
  24045. json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  24046. break;
  24047. case 'mapSpecularRepeat':
  24048. case 'mapSpecularOffset':
  24049. case 'mapSpecularWrap':
  24050. case 'mapSpecularAnisotropy':
  24051. break;
  24052. case 'mapMetalness':
  24053. json.metalnessMap = loadTexture( value, m.mapMetalnessRepeat, m.mapMetalnessOffset, m.mapMetalnessWrap, m.mapMetalnessAnisotropy );
  24054. break;
  24055. case 'mapMetalnessRepeat':
  24056. case 'mapMetalnessOffset':
  24057. case 'mapMetalnessWrap':
  24058. case 'mapMetalnessAnisotropy':
  24059. break;
  24060. case 'mapRoughness':
  24061. json.roughnessMap = loadTexture( value, m.mapRoughnessRepeat, m.mapRoughnessOffset, m.mapRoughnessWrap, m.mapRoughnessAnisotropy );
  24062. break;
  24063. case 'mapRoughnessRepeat':
  24064. case 'mapRoughnessOffset':
  24065. case 'mapRoughnessWrap':
  24066. case 'mapRoughnessAnisotropy':
  24067. break;
  24068. case 'mapAlpha':
  24069. json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy );
  24070. break;
  24071. case 'mapAlphaRepeat':
  24072. case 'mapAlphaOffset':
  24073. case 'mapAlphaWrap':
  24074. case 'mapAlphaAnisotropy':
  24075. break;
  24076. case 'flipSided':
  24077. json.side = BackSide;
  24078. break;
  24079. case 'doubleSided':
  24080. json.side = DoubleSide;
  24081. break;
  24082. case 'transparency':
  24083. console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' );
  24084. json.opacity = value;
  24085. break;
  24086. case 'depthTest':
  24087. case 'depthWrite':
  24088. case 'colorWrite':
  24089. case 'opacity':
  24090. case 'reflectivity':
  24091. case 'transparent':
  24092. case 'visible':
  24093. case 'wireframe':
  24094. json[ name ] = value;
  24095. break;
  24096. case 'vertexColors':
  24097. if ( value === true ) json.vertexColors = VertexColors;
  24098. if ( value === 'face' ) json.vertexColors = FaceColors;
  24099. break;
  24100. default:
  24101. console.error( 'THREE.Loader.createMaterial: Unsupported', name, value );
  24102. break;
  24103. }
  24104. }
  24105. if ( json.type === 'MeshBasicMaterial' ) delete json.emissive;
  24106. if ( json.type !== 'MeshPhongMaterial' ) delete json.specular;
  24107. if ( json.opacity < 1 ) json.transparent = true;
  24108. materialLoader.setTextures( textures );
  24109. return materialLoader.parse( json );
  24110. };
  24111. } )()
  24112. };
  24113. Loader.Handlers = {
  24114. handlers: [],
  24115. add: function ( regex, loader ) {
  24116. this.handlers.push( regex, loader );
  24117. },
  24118. get: function ( file ) {
  24119. var handlers = this.handlers;
  24120. for ( var i = 0, l = handlers.length; i < l; i += 2 ) {
  24121. var regex = handlers[ i ];
  24122. var loader = handlers[ i + 1 ];
  24123. if ( regex.test( file ) ) {
  24124. return loader;
  24125. }
  24126. }
  24127. return null;
  24128. }
  24129. };
  24130. /**
  24131. * @author mrdoob / http://mrdoob.com/
  24132. * @author alteredq / http://alteredqualia.com/
  24133. */
  24134. function JSONLoader( manager ) {
  24135. if ( typeof manager === 'boolean' ) {
  24136. console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' );
  24137. manager = undefined;
  24138. }
  24139. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  24140. this.withCredentials = false;
  24141. }
  24142. Object.assign( JSONLoader.prototype, {
  24143. load: function( url, onLoad, onProgress, onError ) {
  24144. var scope = this;
  24145. var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : Loader.prototype.extractUrlBase( url );
  24146. var loader = new FileLoader( this.manager );
  24147. loader.setWithCredentials( this.withCredentials );
  24148. loader.load( url, function ( text ) {
  24149. var json = JSON.parse( text );
  24150. var metadata = json.metadata;
  24151. if ( metadata !== undefined ) {
  24152. var type = metadata.type;
  24153. if ( type !== undefined ) {
  24154. if ( type.toLowerCase() === 'object' ) {
  24155. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' );
  24156. return;
  24157. }
  24158. if ( type.toLowerCase() === 'scene' ) {
  24159. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' );
  24160. return;
  24161. }
  24162. }
  24163. }
  24164. var object = scope.parse( json, texturePath );
  24165. onLoad( object.geometry, object.materials );
  24166. }, onProgress, onError );
  24167. },
  24168. setTexturePath: function ( value ) {
  24169. this.texturePath = value;
  24170. },
  24171. parse: function ( json, texturePath ) {
  24172. var geometry = new Geometry(),
  24173. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  24174. parseModel( scale );
  24175. parseSkin();
  24176. parseMorphing( scale );
  24177. parseAnimations();
  24178. geometry.computeFaceNormals();
  24179. geometry.computeBoundingSphere();
  24180. function parseModel( scale ) {
  24181. function isBitSet( value, position ) {
  24182. return value & ( 1 << position );
  24183. }
  24184. var i, j, fi,
  24185. offset, zLength,
  24186. colorIndex, normalIndex, uvIndex, materialIndex,
  24187. type,
  24188. isQuad,
  24189. hasMaterial,
  24190. hasFaceVertexUv,
  24191. hasFaceNormal, hasFaceVertexNormal,
  24192. hasFaceColor, hasFaceVertexColor,
  24193. vertex, face, faceA, faceB, hex, normal,
  24194. uvLayer, uv, u, v,
  24195. faces = json.faces,
  24196. vertices = json.vertices,
  24197. normals = json.normals,
  24198. colors = json.colors,
  24199. nUvLayers = 0;
  24200. if ( json.uvs !== undefined ) {
  24201. // disregard empty arrays
  24202. for ( i = 0; i < json.uvs.length; i ++ ) {
  24203. if ( json.uvs[ i ].length ) nUvLayers ++;
  24204. }
  24205. for ( i = 0; i < nUvLayers; i ++ ) {
  24206. geometry.faceVertexUvs[ i ] = [];
  24207. }
  24208. }
  24209. offset = 0;
  24210. zLength = vertices.length;
  24211. while ( offset < zLength ) {
  24212. vertex = new Vector3();
  24213. vertex.x = vertices[ offset ++ ] * scale;
  24214. vertex.y = vertices[ offset ++ ] * scale;
  24215. vertex.z = vertices[ offset ++ ] * scale;
  24216. geometry.vertices.push( vertex );
  24217. }
  24218. offset = 0;
  24219. zLength = faces.length;
  24220. while ( offset < zLength ) {
  24221. type = faces[ offset ++ ];
  24222. isQuad = isBitSet( type, 0 );
  24223. hasMaterial = isBitSet( type, 1 );
  24224. hasFaceVertexUv = isBitSet( type, 3 );
  24225. hasFaceNormal = isBitSet( type, 4 );
  24226. hasFaceVertexNormal = isBitSet( type, 5 );
  24227. hasFaceColor = isBitSet( type, 6 );
  24228. hasFaceVertexColor = isBitSet( type, 7 );
  24229. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  24230. if ( isQuad ) {
  24231. faceA = new Face3();
  24232. faceA.a = faces[ offset ];
  24233. faceA.b = faces[ offset + 1 ];
  24234. faceA.c = faces[ offset + 3 ];
  24235. faceB = new Face3();
  24236. faceB.a = faces[ offset + 1 ];
  24237. faceB.b = faces[ offset + 2 ];
  24238. faceB.c = faces[ offset + 3 ];
  24239. offset += 4;
  24240. if ( hasMaterial ) {
  24241. materialIndex = faces[ offset ++ ];
  24242. faceA.materialIndex = materialIndex;
  24243. faceB.materialIndex = materialIndex;
  24244. }
  24245. // to get face <=> uv index correspondence
  24246. fi = geometry.faces.length;
  24247. if ( hasFaceVertexUv ) {
  24248. for ( i = 0; i < nUvLayers; i ++ ) {
  24249. uvLayer = json.uvs[ i ];
  24250. geometry.faceVertexUvs[ i ][ fi ] = [];
  24251. geometry.faceVertexUvs[ i ][ fi + 1 ] = [];
  24252. for ( j = 0; j < 4; j ++ ) {
  24253. uvIndex = faces[ offset ++ ];
  24254. u = uvLayer[ uvIndex * 2 ];
  24255. v = uvLayer[ uvIndex * 2 + 1 ];
  24256. uv = new Vector2( u, v );
  24257. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  24258. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  24259. }
  24260. }
  24261. }
  24262. if ( hasFaceNormal ) {
  24263. normalIndex = faces[ offset ++ ] * 3;
  24264. faceA.normal.set(
  24265. normals[ normalIndex ++ ],
  24266. normals[ normalIndex ++ ],
  24267. normals[ normalIndex ]
  24268. );
  24269. faceB.normal.copy( faceA.normal );
  24270. }
  24271. if ( hasFaceVertexNormal ) {
  24272. for ( i = 0; i < 4; i ++ ) {
  24273. normalIndex = faces[ offset ++ ] * 3;
  24274. normal = new Vector3(
  24275. normals[ normalIndex ++ ],
  24276. normals[ normalIndex ++ ],
  24277. normals[ normalIndex ]
  24278. );
  24279. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  24280. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  24281. }
  24282. }
  24283. if ( hasFaceColor ) {
  24284. colorIndex = faces[ offset ++ ];
  24285. hex = colors[ colorIndex ];
  24286. faceA.color.setHex( hex );
  24287. faceB.color.setHex( hex );
  24288. }
  24289. if ( hasFaceVertexColor ) {
  24290. for ( i = 0; i < 4; i ++ ) {
  24291. colorIndex = faces[ offset ++ ];
  24292. hex = colors[ colorIndex ];
  24293. if ( i !== 2 ) faceA.vertexColors.push( new Color( hex ) );
  24294. if ( i !== 0 ) faceB.vertexColors.push( new Color( hex ) );
  24295. }
  24296. }
  24297. geometry.faces.push( faceA );
  24298. geometry.faces.push( faceB );
  24299. } else {
  24300. face = new Face3();
  24301. face.a = faces[ offset ++ ];
  24302. face.b = faces[ offset ++ ];
  24303. face.c = faces[ offset ++ ];
  24304. if ( hasMaterial ) {
  24305. materialIndex = faces[ offset ++ ];
  24306. face.materialIndex = materialIndex;
  24307. }
  24308. // to get face <=> uv index correspondence
  24309. fi = geometry.faces.length;
  24310. if ( hasFaceVertexUv ) {
  24311. for ( i = 0; i < nUvLayers; i ++ ) {
  24312. uvLayer = json.uvs[ i ];
  24313. geometry.faceVertexUvs[ i ][ fi ] = [];
  24314. for ( j = 0; j < 3; j ++ ) {
  24315. uvIndex = faces[ offset ++ ];
  24316. u = uvLayer[ uvIndex * 2 ];
  24317. v = uvLayer[ uvIndex * 2 + 1 ];
  24318. uv = new Vector2( u, v );
  24319. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  24320. }
  24321. }
  24322. }
  24323. if ( hasFaceNormal ) {
  24324. normalIndex = faces[ offset ++ ] * 3;
  24325. face.normal.set(
  24326. normals[ normalIndex ++ ],
  24327. normals[ normalIndex ++ ],
  24328. normals[ normalIndex ]
  24329. );
  24330. }
  24331. if ( hasFaceVertexNormal ) {
  24332. for ( i = 0; i < 3; i ++ ) {
  24333. normalIndex = faces[ offset ++ ] * 3;
  24334. normal = new Vector3(
  24335. normals[ normalIndex ++ ],
  24336. normals[ normalIndex ++ ],
  24337. normals[ normalIndex ]
  24338. );
  24339. face.vertexNormals.push( normal );
  24340. }
  24341. }
  24342. if ( hasFaceColor ) {
  24343. colorIndex = faces[ offset ++ ];
  24344. face.color.setHex( colors[ colorIndex ] );
  24345. }
  24346. if ( hasFaceVertexColor ) {
  24347. for ( i = 0; i < 3; i ++ ) {
  24348. colorIndex = faces[ offset ++ ];
  24349. face.vertexColors.push( new Color( colors[ colorIndex ] ) );
  24350. }
  24351. }
  24352. geometry.faces.push( face );
  24353. }
  24354. }
  24355. }
  24356. function parseSkin() {
  24357. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  24358. if ( json.skinWeights ) {
  24359. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  24360. var x = json.skinWeights[ i ];
  24361. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  24362. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  24363. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  24364. geometry.skinWeights.push( new Vector4( x, y, z, w ) );
  24365. }
  24366. }
  24367. if ( json.skinIndices ) {
  24368. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  24369. var a = json.skinIndices[ i ];
  24370. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  24371. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  24372. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  24373. geometry.skinIndices.push( new Vector4( a, b, c, d ) );
  24374. }
  24375. }
  24376. geometry.bones = json.bones;
  24377. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  24378. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  24379. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  24380. }
  24381. }
  24382. function parseMorphing( scale ) {
  24383. if ( json.morphTargets !== undefined ) {
  24384. for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  24385. geometry.morphTargets[ i ] = {};
  24386. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  24387. geometry.morphTargets[ i ].vertices = [];
  24388. var dstVertices = geometry.morphTargets[ i ].vertices;
  24389. var srcVertices = json.morphTargets[ i ].vertices;
  24390. for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  24391. var vertex = new Vector3();
  24392. vertex.x = srcVertices[ v ] * scale;
  24393. vertex.y = srcVertices[ v + 1 ] * scale;
  24394. vertex.z = srcVertices[ v + 2 ] * scale;
  24395. dstVertices.push( vertex );
  24396. }
  24397. }
  24398. }
  24399. if ( json.morphColors !== undefined && json.morphColors.length > 0 ) {
  24400. console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' );
  24401. var faces = geometry.faces;
  24402. var morphColors = json.morphColors[ 0 ].colors;
  24403. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  24404. faces[ i ].color.fromArray( morphColors, i * 3 );
  24405. }
  24406. }
  24407. }
  24408. function parseAnimations() {
  24409. var outputAnimations = [];
  24410. // parse old style Bone/Hierarchy animations
  24411. var animations = [];
  24412. if ( json.animation !== undefined ) {
  24413. animations.push( json.animation );
  24414. }
  24415. if ( json.animations !== undefined ) {
  24416. if ( json.animations.length ) {
  24417. animations = animations.concat( json.animations );
  24418. } else {
  24419. animations.push( json.animations );
  24420. }
  24421. }
  24422. for ( var i = 0; i < animations.length; i ++ ) {
  24423. var clip = AnimationClip.parseAnimation( animations[ i ], geometry.bones );
  24424. if ( clip ) outputAnimations.push( clip );
  24425. }
  24426. // parse implicit morph animations
  24427. if ( geometry.morphTargets ) {
  24428. // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary.
  24429. var morphAnimationClips = AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 );
  24430. outputAnimations = outputAnimations.concat( morphAnimationClips );
  24431. }
  24432. if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations;
  24433. }
  24434. if ( json.materials === undefined || json.materials.length === 0 ) {
  24435. return { geometry: geometry };
  24436. } else {
  24437. var materials = Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin );
  24438. return { geometry: geometry, materials: materials };
  24439. }
  24440. }
  24441. } );
  24442. /**
  24443. * @author mrdoob / http://mrdoob.com/
  24444. */
  24445. function ObjectLoader( manager ) {
  24446. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  24447. this.texturePath = '';
  24448. }
  24449. Object.assign( ObjectLoader.prototype, {
  24450. load: function ( url, onLoad, onProgress, onError ) {
  24451. if ( this.texturePath === '' ) {
  24452. this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 );
  24453. }
  24454. var scope = this;
  24455. var loader = new FileLoader( scope.manager );
  24456. loader.load( url, function ( text ) {
  24457. var json = null;
  24458. try {
  24459. json = JSON.parse( text );
  24460. } catch ( error ) {
  24461. if ( onError !== undefined ) onError( error );
  24462. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  24463. return;
  24464. }
  24465. var metadata = json.metadata;
  24466. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  24467. console.error( 'THREE.ObjectLoader: Can\'t load ' + url + '. Use THREE.JSONLoader instead.' );
  24468. return;
  24469. }
  24470. scope.parse( json, onLoad );
  24471. }, onProgress, onError );
  24472. },
  24473. setTexturePath: function ( value ) {
  24474. this.texturePath = value;
  24475. },
  24476. setCrossOrigin: function ( value ) {
  24477. this.crossOrigin = value;
  24478. },
  24479. parse: function ( json, onLoad ) {
  24480. var geometries = this.parseGeometries( json.geometries );
  24481. var images = this.parseImages( json.images, function () {
  24482. if ( onLoad !== undefined ) onLoad( object );
  24483. } );
  24484. var textures = this.parseTextures( json.textures, images );
  24485. var materials = this.parseMaterials( json.materials, textures );
  24486. var object = this.parseObject( json.object, geometries, materials );
  24487. if ( json.animations ) {
  24488. object.animations = this.parseAnimations( json.animations );
  24489. }
  24490. if ( json.images === undefined || json.images.length === 0 ) {
  24491. if ( onLoad !== undefined ) onLoad( object );
  24492. }
  24493. return object;
  24494. },
  24495. parseGeometries: function ( json ) {
  24496. var geometries = {};
  24497. if ( json !== undefined ) {
  24498. var geometryLoader = new JSONLoader();
  24499. var bufferGeometryLoader = new BufferGeometryLoader();
  24500. for ( var i = 0, l = json.length; i < l; i ++ ) {
  24501. var geometry;
  24502. var data = json[ i ];
  24503. switch ( data.type ) {
  24504. case 'PlaneGeometry':
  24505. case 'PlaneBufferGeometry':
  24506. geometry = new Geometries[ data.type ](
  24507. data.width,
  24508. data.height,
  24509. data.widthSegments,
  24510. data.heightSegments
  24511. );
  24512. break;
  24513. case 'BoxGeometry':
  24514. case 'BoxBufferGeometry':
  24515. case 'CubeGeometry': // backwards compatible
  24516. geometry = new Geometries[ data.type ](
  24517. data.width,
  24518. data.height,
  24519. data.depth,
  24520. data.widthSegments,
  24521. data.heightSegments,
  24522. data.depthSegments
  24523. );
  24524. break;
  24525. case 'CircleGeometry':
  24526. case 'CircleBufferGeometry':
  24527. geometry = new Geometries[ data.type ](
  24528. data.radius,
  24529. data.segments,
  24530. data.thetaStart,
  24531. data.thetaLength
  24532. );
  24533. break;
  24534. case 'CylinderGeometry':
  24535. case 'CylinderBufferGeometry':
  24536. geometry = new Geometries[ data.type ](
  24537. data.radiusTop,
  24538. data.radiusBottom,
  24539. data.height,
  24540. data.radialSegments,
  24541. data.heightSegments,
  24542. data.openEnded,
  24543. data.thetaStart,
  24544. data.thetaLength
  24545. );
  24546. break;
  24547. case 'ConeGeometry':
  24548. case 'ConeBufferGeometry':
  24549. geometry = new Geometries[ data.type ](
  24550. data.radius,
  24551. data.height,
  24552. data.radialSegments,
  24553. data.heightSegments,
  24554. data.openEnded,
  24555. data.thetaStart,
  24556. data.thetaLength
  24557. );
  24558. break;
  24559. case 'SphereGeometry':
  24560. case 'SphereBufferGeometry':
  24561. geometry = new Geometries[ data.type ](
  24562. data.radius,
  24563. data.widthSegments,
  24564. data.heightSegments,
  24565. data.phiStart,
  24566. data.phiLength,
  24567. data.thetaStart,
  24568. data.thetaLength
  24569. );
  24570. break;
  24571. case 'DodecahedronGeometry':
  24572. case 'IcosahedronGeometry':
  24573. case 'OctahedronGeometry':
  24574. case 'TetrahedronGeometry':
  24575. geometry = new Geometries[ data.type ](
  24576. data.radius,
  24577. data.detail
  24578. );
  24579. break;
  24580. case 'RingGeometry':
  24581. case 'RingBufferGeometry':
  24582. geometry = new Geometries[ data.type ](
  24583. data.innerRadius,
  24584. data.outerRadius,
  24585. data.thetaSegments,
  24586. data.phiSegments,
  24587. data.thetaStart,
  24588. data.thetaLength
  24589. );
  24590. break;
  24591. case 'TorusGeometry':
  24592. case 'TorusBufferGeometry':
  24593. geometry = new Geometries[ data.type ](
  24594. data.radius,
  24595. data.tube,
  24596. data.radialSegments,
  24597. data.tubularSegments,
  24598. data.arc
  24599. );
  24600. break;
  24601. case 'TorusKnotGeometry':
  24602. case 'TorusKnotBufferGeometry':
  24603. geometry = new Geometries[ data.type ](
  24604. data.radius,
  24605. data.tube,
  24606. data.tubularSegments,
  24607. data.radialSegments,
  24608. data.p,
  24609. data.q
  24610. );
  24611. break;
  24612. case 'LatheGeometry':
  24613. case 'LatheBufferGeometry':
  24614. geometry = new Geometries[ data.type ](
  24615. data.points,
  24616. data.segments,
  24617. data.phiStart,
  24618. data.phiLength
  24619. );
  24620. break;
  24621. case 'BufferGeometry':
  24622. geometry = bufferGeometryLoader.parse( data );
  24623. break;
  24624. case 'Geometry':
  24625. geometry = geometryLoader.parse( data.data, this.texturePath ).geometry;
  24626. break;
  24627. default:
  24628. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  24629. continue;
  24630. }
  24631. geometry.uuid = data.uuid;
  24632. if ( data.name !== undefined ) geometry.name = data.name;
  24633. geometries[ data.uuid ] = geometry;
  24634. }
  24635. }
  24636. return geometries;
  24637. },
  24638. parseMaterials: function ( json, textures ) {
  24639. var materials = {};
  24640. if ( json !== undefined ) {
  24641. var loader = new MaterialLoader();
  24642. loader.setTextures( textures );
  24643. for ( var i = 0, l = json.length; i < l; i ++ ) {
  24644. var material = loader.parse( json[ i ] );
  24645. materials[ material.uuid ] = material;
  24646. }
  24647. }
  24648. return materials;
  24649. },
  24650. parseAnimations: function ( json ) {
  24651. var animations = [];
  24652. for ( var i = 0; i < json.length; i ++ ) {
  24653. var clip = AnimationClip.parse( json[ i ] );
  24654. animations.push( clip );
  24655. }
  24656. return animations;
  24657. },
  24658. parseImages: function ( json, onLoad ) {
  24659. var scope = this;
  24660. var images = {};
  24661. function loadImage( url ) {
  24662. scope.manager.itemStart( url );
  24663. return loader.load( url, function () {
  24664. scope.manager.itemEnd( url );
  24665. }, undefined, function () {
  24666. scope.manager.itemError( url );
  24667. } );
  24668. }
  24669. if ( json !== undefined && json.length > 0 ) {
  24670. var manager = new LoadingManager( onLoad );
  24671. var loader = new ImageLoader( manager );
  24672. loader.setCrossOrigin( this.crossOrigin );
  24673. for ( var i = 0, l = json.length; i < l; i ++ ) {
  24674. var image = json[ i ];
  24675. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url;
  24676. images[ image.uuid ] = loadImage( path );
  24677. }
  24678. }
  24679. return images;
  24680. },
  24681. parseTextures: function ( json, images ) {
  24682. var TextureMapping = {
  24683. UVMapping: UVMapping,
  24684. CubeReflectionMapping: CubeReflectionMapping,
  24685. CubeRefractionMapping: CubeRefractionMapping,
  24686. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  24687. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  24688. SphericalReflectionMapping: SphericalReflectionMapping,
  24689. CubeUVReflectionMapping: CubeUVReflectionMapping,
  24690. CubeUVRefractionMapping: CubeUVRefractionMapping
  24691. };
  24692. var TextureWrapping = {
  24693. RepeatWrapping: RepeatWrapping,
  24694. ClampToEdgeWrapping: ClampToEdgeWrapping,
  24695. MirroredRepeatWrapping: MirroredRepeatWrapping
  24696. };
  24697. var TextureFilter = {
  24698. NearestFilter: NearestFilter,
  24699. NearestMipMapNearestFilter: NearestMipMapNearestFilter,
  24700. NearestMipMapLinearFilter: NearestMipMapLinearFilter,
  24701. LinearFilter: LinearFilter,
  24702. LinearMipMapNearestFilter: LinearMipMapNearestFilter,
  24703. LinearMipMapLinearFilter: LinearMipMapLinearFilter
  24704. };
  24705. function parseConstant( value, type ) {
  24706. if ( typeof( value ) === 'number' ) return value;
  24707. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  24708. return type[ value ];
  24709. }
  24710. var textures = {};
  24711. if ( json !== undefined ) {
  24712. for ( var i = 0, l = json.length; i < l; i ++ ) {
  24713. var data = json[ i ];
  24714. if ( data.image === undefined ) {
  24715. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  24716. }
  24717. if ( images[ data.image ] === undefined ) {
  24718. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  24719. }
  24720. var texture = new Texture( images[ data.image ] );
  24721. texture.needsUpdate = true;
  24722. texture.uuid = data.uuid;
  24723. if ( data.name !== undefined ) texture.name = data.name;
  24724. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TextureMapping );
  24725. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  24726. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  24727. if ( data.wrap !== undefined ) {
  24728. texture.wrapS = parseConstant( data.wrap[ 0 ], TextureWrapping );
  24729. texture.wrapT = parseConstant( data.wrap[ 1 ], TextureWrapping );
  24730. }
  24731. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TextureFilter );
  24732. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TextureFilter );
  24733. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  24734. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  24735. textures[ data.uuid ] = texture;
  24736. }
  24737. }
  24738. return textures;
  24739. },
  24740. parseObject: function () {
  24741. var matrix = new Matrix4();
  24742. return function parseObject( data, geometries, materials ) {
  24743. var object;
  24744. function getGeometry( name ) {
  24745. if ( geometries[ name ] === undefined ) {
  24746. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  24747. }
  24748. return geometries[ name ];
  24749. }
  24750. function getMaterial( name ) {
  24751. if ( name === undefined ) return undefined;
  24752. if ( materials[ name ] === undefined ) {
  24753. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  24754. }
  24755. return materials[ name ];
  24756. }
  24757. switch ( data.type ) {
  24758. case 'Scene':
  24759. object = new Scene();
  24760. if ( data.background !== undefined ) {
  24761. if ( Number.isInteger( data.background ) ) {
  24762. object.background = new Color( data.background );
  24763. }
  24764. }
  24765. if ( data.fog !== undefined ) {
  24766. if ( data.fog.type === 'Fog' ) {
  24767. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  24768. } else if ( data.fog.type === 'FogExp2' ) {
  24769. object.fog = new FogExp2( data.fog.color, data.fog.density );
  24770. }
  24771. }
  24772. break;
  24773. case 'PerspectiveCamera':
  24774. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  24775. if ( data.focus !== undefined ) object.focus = data.focus;
  24776. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  24777. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  24778. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  24779. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  24780. break;
  24781. case 'OrthographicCamera':
  24782. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  24783. break;
  24784. case 'AmbientLight':
  24785. object = new AmbientLight( data.color, data.intensity );
  24786. break;
  24787. case 'DirectionalLight':
  24788. object = new DirectionalLight( data.color, data.intensity );
  24789. break;
  24790. case 'PointLight':
  24791. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  24792. break;
  24793. case 'SpotLight':
  24794. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  24795. break;
  24796. case 'HemisphereLight':
  24797. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  24798. break;
  24799. case 'Mesh':
  24800. var geometry = getGeometry( data.geometry );
  24801. var material = getMaterial( data.material );
  24802. if ( geometry.bones && geometry.bones.length > 0 ) {
  24803. object = new SkinnedMesh( geometry, material );
  24804. } else {
  24805. object = new Mesh( geometry, material );
  24806. }
  24807. break;
  24808. case 'LOD':
  24809. object = new LOD();
  24810. break;
  24811. case 'Line':
  24812. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  24813. break;
  24814. case 'LineSegments':
  24815. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  24816. break;
  24817. case 'PointCloud':
  24818. case 'Points':
  24819. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  24820. break;
  24821. case 'Sprite':
  24822. object = new Sprite( getMaterial( data.material ) );
  24823. break;
  24824. case 'Group':
  24825. object = new Group();
  24826. break;
  24827. case 'SkinnedMesh':
  24828. console.warn( 'THREE.ObjectLoader.parseObject() does not support SkinnedMesh type. Instantiates Object3D instead.' );
  24829. default:
  24830. object = new Object3D();
  24831. }
  24832. object.uuid = data.uuid;
  24833. if ( data.name !== undefined ) object.name = data.name;
  24834. if ( data.matrix !== undefined ) {
  24835. matrix.fromArray( data.matrix );
  24836. matrix.decompose( object.position, object.quaternion, object.scale );
  24837. } else {
  24838. if ( data.position !== undefined ) object.position.fromArray( data.position );
  24839. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  24840. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  24841. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  24842. }
  24843. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  24844. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  24845. if ( data.shadow ) {
  24846. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  24847. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  24848. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  24849. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  24850. }
  24851. if ( data.visible !== undefined ) object.visible = data.visible;
  24852. if ( data.userData !== undefined ) object.userData = data.userData;
  24853. if ( data.children !== undefined ) {
  24854. for ( var child in data.children ) {
  24855. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  24856. }
  24857. }
  24858. if ( data.type === 'LOD' ) {
  24859. var levels = data.levels;
  24860. for ( var l = 0; l < levels.length; l ++ ) {
  24861. var level = levels[ l ];
  24862. var child = object.getObjectByProperty( 'uuid', level.object );
  24863. if ( child !== undefined ) {
  24864. object.addLevel( child, level.distance );
  24865. }
  24866. }
  24867. }
  24868. return object;
  24869. };
  24870. }()
  24871. } );
  24872. /**
  24873. * @author zz85 / http://www.lab4games.net/zz85/blog
  24874. *
  24875. * Bezier Curves formulas obtained from
  24876. * http://en.wikipedia.org/wiki/Bézier_curve
  24877. */
  24878. function CatmullRom( t, p0, p1, p2, p3 ) {
  24879. var v0 = ( p2 - p0 ) * 0.5;
  24880. var v1 = ( p3 - p1 ) * 0.5;
  24881. var t2 = t * t;
  24882. var t3 = t * t2;
  24883. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  24884. }
  24885. //
  24886. function QuadraticBezierP0( t, p ) {
  24887. var k = 1 - t;
  24888. return k * k * p;
  24889. }
  24890. function QuadraticBezierP1( t, p ) {
  24891. return 2 * ( 1 - t ) * t * p;
  24892. }
  24893. function QuadraticBezierP2( t, p ) {
  24894. return t * t * p;
  24895. }
  24896. function QuadraticBezier( t, p0, p1, p2 ) {
  24897. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  24898. QuadraticBezierP2( t, p2 );
  24899. }
  24900. //
  24901. function CubicBezierP0( t, p ) {
  24902. var k = 1 - t;
  24903. return k * k * k * p;
  24904. }
  24905. function CubicBezierP1( t, p ) {
  24906. var k = 1 - t;
  24907. return 3 * k * k * t * p;
  24908. }
  24909. function CubicBezierP2( t, p ) {
  24910. return 3 * ( 1 - t ) * t * t * p;
  24911. }
  24912. function CubicBezierP3( t, p ) {
  24913. return t * t * t * p;
  24914. }
  24915. function CubicBezier( t, p0, p1, p2, p3 ) {
  24916. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  24917. CubicBezierP3( t, p3 );
  24918. }
  24919. /**
  24920. * @author zz85 / http://www.lab4games.net/zz85/blog
  24921. * Extensible curve object
  24922. *
  24923. * Some common of Curve methods
  24924. * .getPoint(t), getTangent(t)
  24925. * .getPointAt(u), getTangentAt(u)
  24926. * .getPoints(), .getSpacedPoints()
  24927. * .getLength()
  24928. * .updateArcLengths()
  24929. *
  24930. * This following classes subclasses THREE.Curve:
  24931. *
  24932. * -- 2d classes --
  24933. * THREE.LineCurve
  24934. * THREE.QuadraticBezierCurve
  24935. * THREE.CubicBezierCurve
  24936. * THREE.SplineCurve
  24937. * THREE.ArcCurve
  24938. * THREE.EllipseCurve
  24939. *
  24940. * -- 3d classes --
  24941. * THREE.LineCurve3
  24942. * THREE.QuadraticBezierCurve3
  24943. * THREE.CubicBezierCurve3
  24944. * THREE.CatmullRomCurve3
  24945. *
  24946. * A series of curves can be represented as a THREE.CurvePath
  24947. *
  24948. **/
  24949. /**************************************************************
  24950. * Abstract Curve base class
  24951. **************************************************************/
  24952. function Curve() {}
  24953. Curve.prototype = {
  24954. constructor: Curve,
  24955. // Virtual base class method to overwrite and implement in subclasses
  24956. // - t [0 .. 1]
  24957. getPoint: function ( t ) {
  24958. console.warn( "THREE.Curve: Warning, getPoint() not implemented!" );
  24959. return null;
  24960. },
  24961. // Get point at relative position in curve according to arc length
  24962. // - u [0 .. 1]
  24963. getPointAt: function ( u ) {
  24964. var t = this.getUtoTmapping( u );
  24965. return this.getPoint( t );
  24966. },
  24967. // Get sequence of points using getPoint( t )
  24968. getPoints: function ( divisions ) {
  24969. if ( isNaN( divisions ) ) divisions = 5;
  24970. var points = [];
  24971. for ( var d = 0; d <= divisions; d ++ ) {
  24972. points.push( this.getPoint( d / divisions ) );
  24973. }
  24974. return points;
  24975. },
  24976. // Get sequence of points using getPointAt( u )
  24977. getSpacedPoints: function ( divisions ) {
  24978. if ( isNaN( divisions ) ) divisions = 5;
  24979. var points = [];
  24980. for ( var d = 0; d <= divisions; d ++ ) {
  24981. points.push( this.getPointAt( d / divisions ) );
  24982. }
  24983. return points;
  24984. },
  24985. // Get total curve arc length
  24986. getLength: function () {
  24987. var lengths = this.getLengths();
  24988. return lengths[ lengths.length - 1 ];
  24989. },
  24990. // Get list of cumulative segment lengths
  24991. getLengths: function ( divisions ) {
  24992. if ( isNaN( divisions ) ) divisions = ( this.__arcLengthDivisions ) ? ( this.__arcLengthDivisions ) : 200;
  24993. if ( this.cacheArcLengths
  24994. && ( this.cacheArcLengths.length === divisions + 1 )
  24995. && ! this.needsUpdate ) {
  24996. //console.log( "cached", this.cacheArcLengths );
  24997. return this.cacheArcLengths;
  24998. }
  24999. this.needsUpdate = false;
  25000. var cache = [];
  25001. var current, last = this.getPoint( 0 );
  25002. var p, sum = 0;
  25003. cache.push( 0 );
  25004. for ( p = 1; p <= divisions; p ++ ) {
  25005. current = this.getPoint ( p / divisions );
  25006. sum += current.distanceTo( last );
  25007. cache.push( sum );
  25008. last = current;
  25009. }
  25010. this.cacheArcLengths = cache;
  25011. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  25012. },
  25013. updateArcLengths: function() {
  25014. this.needsUpdate = true;
  25015. this.getLengths();
  25016. },
  25017. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  25018. getUtoTmapping: function ( u, distance ) {
  25019. var arcLengths = this.getLengths();
  25020. var i = 0, il = arcLengths.length;
  25021. var targetArcLength; // The targeted u distance value to get
  25022. if ( distance ) {
  25023. targetArcLength = distance;
  25024. } else {
  25025. targetArcLength = u * arcLengths[ il - 1 ];
  25026. }
  25027. //var time = Date.now();
  25028. // binary search for the index with largest value smaller than target u distance
  25029. var low = 0, high = il - 1, comparison;
  25030. while ( low <= high ) {
  25031. 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
  25032. comparison = arcLengths[ i ] - targetArcLength;
  25033. if ( comparison < 0 ) {
  25034. low = i + 1;
  25035. } else if ( comparison > 0 ) {
  25036. high = i - 1;
  25037. } else {
  25038. high = i;
  25039. break;
  25040. // DONE
  25041. }
  25042. }
  25043. i = high;
  25044. //console.log('b' , i, low, high, Date.now()- time);
  25045. if ( arcLengths[ i ] === targetArcLength ) {
  25046. var t = i / ( il - 1 );
  25047. return t;
  25048. }
  25049. // we could get finer grain at lengths, or use simple interpolation between two points
  25050. var lengthBefore = arcLengths[ i ];
  25051. var lengthAfter = arcLengths[ i + 1 ];
  25052. var segmentLength = lengthAfter - lengthBefore;
  25053. // determine where we are between the 'before' and 'after' points
  25054. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  25055. // add that fractional amount to t
  25056. var t = ( i + segmentFraction ) / ( il - 1 );
  25057. return t;
  25058. },
  25059. // Returns a unit vector tangent at t
  25060. // In case any sub curve does not implement its tangent derivation,
  25061. // 2 points a small delta apart will be used to find its gradient
  25062. // which seems to give a reasonable approximation
  25063. getTangent: function( t ) {
  25064. var delta = 0.0001;
  25065. var t1 = t - delta;
  25066. var t2 = t + delta;
  25067. // Capping in case of danger
  25068. if ( t1 < 0 ) t1 = 0;
  25069. if ( t2 > 1 ) t2 = 1;
  25070. var pt1 = this.getPoint( t1 );
  25071. var pt2 = this.getPoint( t2 );
  25072. var vec = pt2.clone().sub( pt1 );
  25073. return vec.normalize();
  25074. },
  25075. getTangentAt: function ( u ) {
  25076. var t = this.getUtoTmapping( u );
  25077. return this.getTangent( t );
  25078. },
  25079. computeFrenetFrames: function ( segments, closed ) {
  25080. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  25081. var normal = new Vector3();
  25082. var tangents = [];
  25083. var normals = [];
  25084. var binormals = [];
  25085. var vec = new Vector3();
  25086. var mat = new Matrix4();
  25087. var i, u, theta;
  25088. // compute the tangent vectors for each segment on the curve
  25089. for ( i = 0; i <= segments; i ++ ) {
  25090. u = i / segments;
  25091. tangents[ i ] = this.getTangentAt( u );
  25092. tangents[ i ].normalize();
  25093. }
  25094. // select an initial normal vector perpendicular to the first tangent vector,
  25095. // and in the direction of the minimum tangent xyz component
  25096. normals[ 0 ] = new Vector3();
  25097. binormals[ 0 ] = new Vector3();
  25098. var min = Number.MAX_VALUE;
  25099. var tx = Math.abs( tangents[ 0 ].x );
  25100. var ty = Math.abs( tangents[ 0 ].y );
  25101. var tz = Math.abs( tangents[ 0 ].z );
  25102. if ( tx <= min ) {
  25103. min = tx;
  25104. normal.set( 1, 0, 0 );
  25105. }
  25106. if ( ty <= min ) {
  25107. min = ty;
  25108. normal.set( 0, 1, 0 );
  25109. }
  25110. if ( tz <= min ) {
  25111. normal.set( 0, 0, 1 );
  25112. }
  25113. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  25114. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  25115. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  25116. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  25117. for ( i = 1; i <= segments; i ++ ) {
  25118. normals[ i ] = normals[ i - 1 ].clone();
  25119. binormals[ i ] = binormals[ i - 1 ].clone();
  25120. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  25121. if ( vec.length() > Number.EPSILON ) {
  25122. vec.normalize();
  25123. theta = Math.acos( _Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  25124. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  25125. }
  25126. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  25127. }
  25128. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  25129. if ( closed === true ) {
  25130. theta = Math.acos( _Math.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  25131. theta /= segments;
  25132. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  25133. theta = - theta;
  25134. }
  25135. for ( i = 1; i <= segments; i ++ ) {
  25136. // twist a little...
  25137. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  25138. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  25139. }
  25140. }
  25141. return {
  25142. tangents: tangents,
  25143. normals: normals,
  25144. binormals: binormals
  25145. };
  25146. }
  25147. };
  25148. function LineCurve( v1, v2 ) {
  25149. this.v1 = v1;
  25150. this.v2 = v2;
  25151. }
  25152. LineCurve.prototype = Object.create( Curve.prototype );
  25153. LineCurve.prototype.constructor = LineCurve;
  25154. LineCurve.prototype.isLineCurve = true;
  25155. LineCurve.prototype.getPoint = function ( t ) {
  25156. if ( t === 1 ) {
  25157. return this.v2.clone();
  25158. }
  25159. var point = this.v2.clone().sub( this.v1 );
  25160. point.multiplyScalar( t ).add( this.v1 );
  25161. return point;
  25162. };
  25163. // Line curve is linear, so we can overwrite default getPointAt
  25164. LineCurve.prototype.getPointAt = function ( u ) {
  25165. return this.getPoint( u );
  25166. };
  25167. LineCurve.prototype.getTangent = function ( t ) {
  25168. var tangent = this.v2.clone().sub( this.v1 );
  25169. return tangent.normalize();
  25170. };
  25171. /**
  25172. * @author zz85 / http://www.lab4games.net/zz85/blog
  25173. *
  25174. **/
  25175. /**************************************************************
  25176. * Curved Path - a curve path is simply a array of connected
  25177. * curves, but retains the api of a curve
  25178. **************************************************************/
  25179. function CurvePath() {
  25180. this.curves = [];
  25181. this.autoClose = false; // Automatically closes the path
  25182. }
  25183. CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), {
  25184. constructor: CurvePath,
  25185. add: function ( curve ) {
  25186. this.curves.push( curve );
  25187. },
  25188. closePath: function () {
  25189. // Add a line curve if start and end of lines are not connected
  25190. var startPoint = this.curves[ 0 ].getPoint( 0 );
  25191. var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  25192. if ( ! startPoint.equals( endPoint ) ) {
  25193. this.curves.push( new LineCurve( endPoint, startPoint ) );
  25194. }
  25195. },
  25196. // To get accurate point with reference to
  25197. // entire path distance at time t,
  25198. // following has to be done:
  25199. // 1. Length of each sub path have to be known
  25200. // 2. Locate and identify type of curve
  25201. // 3. Get t for the curve
  25202. // 4. Return curve.getPointAt(t')
  25203. getPoint: function ( t ) {
  25204. var d = t * this.getLength();
  25205. var curveLengths = this.getCurveLengths();
  25206. var i = 0;
  25207. // To think about boundaries points.
  25208. while ( i < curveLengths.length ) {
  25209. if ( curveLengths[ i ] >= d ) {
  25210. var diff = curveLengths[ i ] - d;
  25211. var curve = this.curves[ i ];
  25212. var segmentLength = curve.getLength();
  25213. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  25214. return curve.getPointAt( u );
  25215. }
  25216. i ++;
  25217. }
  25218. return null;
  25219. // loop where sum != 0, sum > d , sum+1 <d
  25220. },
  25221. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  25222. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  25223. // getPoint() depends on getLength
  25224. getLength: function () {
  25225. var lens = this.getCurveLengths();
  25226. return lens[ lens.length - 1 ];
  25227. },
  25228. // cacheLengths must be recalculated.
  25229. updateArcLengths: function () {
  25230. this.needsUpdate = true;
  25231. this.cacheLengths = null;
  25232. this.getLengths();
  25233. },
  25234. // Compute lengths and cache them
  25235. // We cannot overwrite getLengths() because UtoT mapping uses it.
  25236. getCurveLengths: function () {
  25237. // We use cache values if curves and cache array are same length
  25238. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  25239. return this.cacheLengths;
  25240. }
  25241. // Get length of sub-curve
  25242. // Push sums into cached array
  25243. var lengths = [], sums = 0;
  25244. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  25245. sums += this.curves[ i ].getLength();
  25246. lengths.push( sums );
  25247. }
  25248. this.cacheLengths = lengths;
  25249. return lengths;
  25250. },
  25251. getSpacedPoints: function ( divisions ) {
  25252. if ( isNaN( divisions ) ) divisions = 40;
  25253. var points = [];
  25254. for ( var i = 0; i <= divisions; i ++ ) {
  25255. points.push( this.getPoint( i / divisions ) );
  25256. }
  25257. if ( this.autoClose ) {
  25258. points.push( points[ 0 ] );
  25259. }
  25260. return points;
  25261. },
  25262. getPoints: function ( divisions ) {
  25263. divisions = divisions || 12;
  25264. var points = [], last;
  25265. for ( var i = 0, curves = this.curves; i < curves.length; i ++ ) {
  25266. var curve = curves[ i ];
  25267. var resolution = (curve && curve.isEllipseCurve) ? divisions * 2
  25268. : (curve && curve.isLineCurve) ? 1
  25269. : (curve && curve.isSplineCurve) ? divisions * curve.points.length
  25270. : divisions;
  25271. var pts = curve.getPoints( resolution );
  25272. for ( var j = 0; j < pts.length; j++ ) {
  25273. var point = pts[ j ];
  25274. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  25275. points.push( point );
  25276. last = point;
  25277. }
  25278. }
  25279. if ( this.autoClose && points.length > 1 && !points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  25280. points.push( points[ 0 ] );
  25281. }
  25282. return points;
  25283. },
  25284. /**************************************************************
  25285. * Create Geometries Helpers
  25286. **************************************************************/
  25287. /// Generate geometry from path points (for Line or Points objects)
  25288. createPointsGeometry: function ( divisions ) {
  25289. var pts = this.getPoints( divisions );
  25290. return this.createGeometry( pts );
  25291. },
  25292. // Generate geometry from equidistant sampling along the path
  25293. createSpacedPointsGeometry: function ( divisions ) {
  25294. var pts = this.getSpacedPoints( divisions );
  25295. return this.createGeometry( pts );
  25296. },
  25297. createGeometry: function ( points ) {
  25298. var geometry = new Geometry();
  25299. for ( var i = 0, l = points.length; i < l; i ++ ) {
  25300. var point = points[ i ];
  25301. geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  25302. }
  25303. return geometry;
  25304. }
  25305. } );
  25306. function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  25307. this.aX = aX;
  25308. this.aY = aY;
  25309. this.xRadius = xRadius;
  25310. this.yRadius = yRadius;
  25311. this.aStartAngle = aStartAngle;
  25312. this.aEndAngle = aEndAngle;
  25313. this.aClockwise = aClockwise;
  25314. this.aRotation = aRotation || 0;
  25315. }
  25316. EllipseCurve.prototype = Object.create( Curve.prototype );
  25317. EllipseCurve.prototype.constructor = EllipseCurve;
  25318. EllipseCurve.prototype.isEllipseCurve = true;
  25319. EllipseCurve.prototype.getPoint = function ( t ) {
  25320. var twoPi = Math.PI * 2;
  25321. var deltaAngle = this.aEndAngle - this.aStartAngle;
  25322. var samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  25323. // ensures that deltaAngle is 0 .. 2 PI
  25324. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  25325. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  25326. if ( deltaAngle < Number.EPSILON ) {
  25327. if ( samePoints ) {
  25328. deltaAngle = 0;
  25329. } else {
  25330. deltaAngle = twoPi;
  25331. }
  25332. }
  25333. if ( this.aClockwise === true && ! samePoints ) {
  25334. if ( deltaAngle === twoPi ) {
  25335. deltaAngle = - twoPi;
  25336. } else {
  25337. deltaAngle = deltaAngle - twoPi;
  25338. }
  25339. }
  25340. var angle = this.aStartAngle + t * deltaAngle;
  25341. var x = this.aX + this.xRadius * Math.cos( angle );
  25342. var y = this.aY + this.yRadius * Math.sin( angle );
  25343. if ( this.aRotation !== 0 ) {
  25344. var cos = Math.cos( this.aRotation );
  25345. var sin = Math.sin( this.aRotation );
  25346. var tx = x - this.aX;
  25347. var ty = y - this.aY;
  25348. // Rotate the point about the center of the ellipse.
  25349. x = tx * cos - ty * sin + this.aX;
  25350. y = tx * sin + ty * cos + this.aY;
  25351. }
  25352. return new Vector2( x, y );
  25353. };
  25354. function SplineCurve( points /* array of Vector2 */ ) {
  25355. this.points = ( points === undefined ) ? [] : points;
  25356. }
  25357. SplineCurve.prototype = Object.create( Curve.prototype );
  25358. SplineCurve.prototype.constructor = SplineCurve;
  25359. SplineCurve.prototype.isSplineCurve = true;
  25360. SplineCurve.prototype.getPoint = function ( t ) {
  25361. var points = this.points;
  25362. var point = ( points.length - 1 ) * t;
  25363. var intPoint = Math.floor( point );
  25364. var weight = point - intPoint;
  25365. var point0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  25366. var point1 = points[ intPoint ];
  25367. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  25368. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  25369. return new Vector2(
  25370. CatmullRom( weight, point0.x, point1.x, point2.x, point3.x ),
  25371. CatmullRom( weight, point0.y, point1.y, point2.y, point3.y )
  25372. );
  25373. };
  25374. function CubicBezierCurve( v0, v1, v2, v3 ) {
  25375. this.v0 = v0;
  25376. this.v1 = v1;
  25377. this.v2 = v2;
  25378. this.v3 = v3;
  25379. }
  25380. CubicBezierCurve.prototype = Object.create( Curve.prototype );
  25381. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  25382. CubicBezierCurve.prototype.getPoint = function ( t ) {
  25383. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  25384. return new Vector2(
  25385. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  25386. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  25387. );
  25388. };
  25389. function QuadraticBezierCurve( v0, v1, v2 ) {
  25390. this.v0 = v0;
  25391. this.v1 = v1;
  25392. this.v2 = v2;
  25393. }
  25394. QuadraticBezierCurve.prototype = Object.create( Curve.prototype );
  25395. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  25396. QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  25397. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  25398. return new Vector2(
  25399. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  25400. QuadraticBezier( t, v0.y, v1.y, v2.y )
  25401. );
  25402. };
  25403. var PathPrototype = Object.assign( Object.create( CurvePath.prototype ), {
  25404. fromPoints: function ( vectors ) {
  25405. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  25406. for ( var i = 1, l = vectors.length; i < l; i ++ ) {
  25407. this.lineTo( vectors[ i ].x, vectors[ i ].y );
  25408. }
  25409. },
  25410. moveTo: function ( x, y ) {
  25411. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  25412. },
  25413. lineTo: function ( x, y ) {
  25414. var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  25415. this.curves.push( curve );
  25416. this.currentPoint.set( x, y );
  25417. },
  25418. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  25419. var curve = new QuadraticBezierCurve(
  25420. this.currentPoint.clone(),
  25421. new Vector2( aCPx, aCPy ),
  25422. new Vector2( aX, aY )
  25423. );
  25424. this.curves.push( curve );
  25425. this.currentPoint.set( aX, aY );
  25426. },
  25427. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  25428. var curve = new CubicBezierCurve(
  25429. this.currentPoint.clone(),
  25430. new Vector2( aCP1x, aCP1y ),
  25431. new Vector2( aCP2x, aCP2y ),
  25432. new Vector2( aX, aY )
  25433. );
  25434. this.curves.push( curve );
  25435. this.currentPoint.set( aX, aY );
  25436. },
  25437. splineThru: function ( pts /*Array of Vector*/ ) {
  25438. var npts = [ this.currentPoint.clone() ].concat( pts );
  25439. var curve = new SplineCurve( npts );
  25440. this.curves.push( curve );
  25441. this.currentPoint.copy( pts[ pts.length - 1 ] );
  25442. },
  25443. arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  25444. var x0 = this.currentPoint.x;
  25445. var y0 = this.currentPoint.y;
  25446. this.absarc( aX + x0, aY + y0, aRadius,
  25447. aStartAngle, aEndAngle, aClockwise );
  25448. },
  25449. absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  25450. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  25451. },
  25452. ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  25453. var x0 = this.currentPoint.x;
  25454. var y0 = this.currentPoint.y;
  25455. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  25456. },
  25457. absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  25458. var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  25459. if ( this.curves.length > 0 ) {
  25460. // if a previous curve is present, attempt to join
  25461. var firstPoint = curve.getPoint( 0 );
  25462. if ( ! firstPoint.equals( this.currentPoint ) ) {
  25463. this.lineTo( firstPoint.x, firstPoint.y );
  25464. }
  25465. }
  25466. this.curves.push( curve );
  25467. var lastPoint = curve.getPoint( 1 );
  25468. this.currentPoint.copy( lastPoint );
  25469. }
  25470. } );
  25471. /**
  25472. * @author zz85 / http://www.lab4games.net/zz85/blog
  25473. * Creates free form 2d path using series of points, lines or curves.
  25474. **/
  25475. function Path( points ) {
  25476. CurvePath.call( this );
  25477. this.currentPoint = new Vector2();
  25478. if ( points ) {
  25479. this.fromPoints( points );
  25480. }
  25481. }
  25482. Path.prototype = PathPrototype;
  25483. PathPrototype.constructor = Path;
  25484. /**
  25485. * @author zz85 / http://www.lab4games.net/zz85/blog
  25486. * Defines a 2d shape plane using paths.
  25487. **/
  25488. // STEP 1 Create a path.
  25489. // STEP 2 Turn path into shape.
  25490. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  25491. // STEP 3a - Extract points from each shape, turn to vertices
  25492. // STEP 3b - Triangulate each shape, add faces.
  25493. function Shape() {
  25494. Path.apply( this, arguments );
  25495. this.holes = [];
  25496. }
  25497. Shape.prototype = Object.assign( Object.create( PathPrototype ), {
  25498. constructor: Shape,
  25499. getPointsHoles: function ( divisions ) {
  25500. var holesPts = [];
  25501. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  25502. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  25503. }
  25504. return holesPts;
  25505. },
  25506. // Get points of shape and holes (keypoints based on segments parameter)
  25507. extractAllPoints: function ( divisions ) {
  25508. return {
  25509. shape: this.getPoints( divisions ),
  25510. holes: this.getPointsHoles( divisions )
  25511. };
  25512. },
  25513. extractPoints: function ( divisions ) {
  25514. return this.extractAllPoints( divisions );
  25515. }
  25516. } );
  25517. /**
  25518. * @author zz85 / http://www.lab4games.net/zz85/blog
  25519. * minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
  25520. **/
  25521. function ShapePath() {
  25522. this.subPaths = [];
  25523. this.currentPath = null;
  25524. }
  25525. ShapePath.prototype = {
  25526. moveTo: function ( x, y ) {
  25527. this.currentPath = new Path();
  25528. this.subPaths.push( this.currentPath );
  25529. this.currentPath.moveTo( x, y );
  25530. },
  25531. lineTo: function ( x, y ) {
  25532. this.currentPath.lineTo( x, y );
  25533. },
  25534. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  25535. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  25536. },
  25537. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  25538. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  25539. },
  25540. splineThru: function ( pts ) {
  25541. this.currentPath.splineThru( pts );
  25542. },
  25543. toShapes: function ( isCCW, noHoles ) {
  25544. function toShapesNoHoles( inSubpaths ) {
  25545. var shapes = [];
  25546. for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) {
  25547. var tmpPath = inSubpaths[ i ];
  25548. var tmpShape = new Shape();
  25549. tmpShape.curves = tmpPath.curves;
  25550. shapes.push( tmpShape );
  25551. }
  25552. return shapes;
  25553. }
  25554. function isPointInsidePolygon( inPt, inPolygon ) {
  25555. var polyLen = inPolygon.length;
  25556. // inPt on polygon contour => immediate success or
  25557. // toggling of inside/outside at every single! intersection point of an edge
  25558. // with the horizontal line through inPt, left of inPt
  25559. // not counting lowerY endpoints of edges and whole edges on that line
  25560. var inside = false;
  25561. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  25562. var edgeLowPt = inPolygon[ p ];
  25563. var edgeHighPt = inPolygon[ q ];
  25564. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  25565. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  25566. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  25567. // not parallel
  25568. if ( edgeDy < 0 ) {
  25569. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  25570. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  25571. }
  25572. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  25573. if ( inPt.y === edgeLowPt.y ) {
  25574. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  25575. // continue; // no intersection or edgeLowPt => doesn't count !!!
  25576. } else {
  25577. var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  25578. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  25579. if ( perpEdge < 0 ) continue;
  25580. inside = ! inside; // true intersection left of inPt
  25581. }
  25582. } else {
  25583. // parallel or collinear
  25584. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  25585. // edge lies on the same horizontal line as inPt
  25586. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  25587. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  25588. // continue;
  25589. }
  25590. }
  25591. return inside;
  25592. }
  25593. var isClockWise = ShapeUtils.isClockWise;
  25594. var subPaths = this.subPaths;
  25595. if ( subPaths.length === 0 ) return [];
  25596. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  25597. var solid, tmpPath, tmpShape, shapes = [];
  25598. if ( subPaths.length === 1 ) {
  25599. tmpPath = subPaths[ 0 ];
  25600. tmpShape = new Shape();
  25601. tmpShape.curves = tmpPath.curves;
  25602. shapes.push( tmpShape );
  25603. return shapes;
  25604. }
  25605. var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  25606. holesFirst = isCCW ? ! holesFirst : holesFirst;
  25607. // console.log("Holes first", holesFirst);
  25608. var betterShapeHoles = [];
  25609. var newShapes = [];
  25610. var newShapeHoles = [];
  25611. var mainIdx = 0;
  25612. var tmpPoints;
  25613. newShapes[ mainIdx ] = undefined;
  25614. newShapeHoles[ mainIdx ] = [];
  25615. for ( var i = 0, l = subPaths.length; i < l; i ++ ) {
  25616. tmpPath = subPaths[ i ];
  25617. tmpPoints = tmpPath.getPoints();
  25618. solid = isClockWise( tmpPoints );
  25619. solid = isCCW ? ! solid : solid;
  25620. if ( solid ) {
  25621. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  25622. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  25623. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  25624. if ( holesFirst ) mainIdx ++;
  25625. newShapeHoles[ mainIdx ] = [];
  25626. //console.log('cw', i);
  25627. } else {
  25628. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  25629. //console.log('ccw', i);
  25630. }
  25631. }
  25632. // only Holes? -> probably all Shapes with wrong orientation
  25633. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  25634. if ( newShapes.length > 1 ) {
  25635. var ambiguous = false;
  25636. var toChange = [];
  25637. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  25638. betterShapeHoles[ sIdx ] = [];
  25639. }
  25640. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  25641. var sho = newShapeHoles[ sIdx ];
  25642. for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  25643. var ho = sho[ hIdx ];
  25644. var hole_unassigned = true;
  25645. for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  25646. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  25647. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  25648. if ( hole_unassigned ) {
  25649. hole_unassigned = false;
  25650. betterShapeHoles[ s2Idx ].push( ho );
  25651. } else {
  25652. ambiguous = true;
  25653. }
  25654. }
  25655. }
  25656. if ( hole_unassigned ) {
  25657. betterShapeHoles[ sIdx ].push( ho );
  25658. }
  25659. }
  25660. }
  25661. // console.log("ambiguous: ", ambiguous);
  25662. if ( toChange.length > 0 ) {
  25663. // console.log("to change: ", toChange);
  25664. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  25665. }
  25666. }
  25667. var tmpHoles;
  25668. for ( var i = 0, il = newShapes.length; i < il; i ++ ) {
  25669. tmpShape = newShapes[ i ].s;
  25670. shapes.push( tmpShape );
  25671. tmpHoles = newShapeHoles[ i ];
  25672. for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  25673. tmpShape.holes.push( tmpHoles[ j ].h );
  25674. }
  25675. }
  25676. //console.log("shape", shapes);
  25677. return shapes;
  25678. }
  25679. };
  25680. /**
  25681. * @author zz85 / http://www.lab4games.net/zz85/blog
  25682. * @author mrdoob / http://mrdoob.com/
  25683. */
  25684. function Font( data ) {
  25685. this.data = data;
  25686. }
  25687. Object.assign( Font.prototype, {
  25688. isFont: true,
  25689. generateShapes: function ( text, size, divisions ) {
  25690. function createPaths( text ) {
  25691. var chars = String( text ).split( '' );
  25692. var scale = size / data.resolution;
  25693. var line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale;
  25694. var offsetX = 0, offsetY = 0;
  25695. var paths = [];
  25696. for ( var i = 0; i < chars.length; i ++ ) {
  25697. var char = chars[ i ];
  25698. if ( char === '\n' ) {
  25699. offsetX = 0;
  25700. offsetY -= line_height;
  25701. } else {
  25702. var ret = createPath( char, scale, offsetX, offsetY );
  25703. offsetX += ret.offsetX;
  25704. paths.push( ret.path );
  25705. }
  25706. }
  25707. return paths;
  25708. }
  25709. function createPath( c, scale, offsetX, offsetY ) {
  25710. var glyph = data.glyphs[ c ] || data.glyphs[ '?' ];
  25711. if ( ! glyph ) return;
  25712. var path = new ShapePath();
  25713. var pts = [];
  25714. var x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2, laste;
  25715. if ( glyph.o ) {
  25716. var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  25717. for ( var i = 0, l = outline.length; i < l; ) {
  25718. var action = outline[ i ++ ];
  25719. switch ( action ) {
  25720. case 'm': // moveTo
  25721. x = outline[ i ++ ] * scale + offsetX;
  25722. y = outline[ i ++ ] * scale + offsetY;
  25723. path.moveTo( x, y );
  25724. break;
  25725. case 'l': // lineTo
  25726. x = outline[ i ++ ] * scale + offsetX;
  25727. y = outline[ i ++ ] * scale + offsetY;
  25728. path.lineTo( x, y );
  25729. break;
  25730. case 'q': // quadraticCurveTo
  25731. cpx = outline[ i ++ ] * scale + offsetX;
  25732. cpy = outline[ i ++ ] * scale + offsetY;
  25733. cpx1 = outline[ i ++ ] * scale + offsetX;
  25734. cpy1 = outline[ i ++ ] * scale + offsetY;
  25735. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  25736. laste = pts[ pts.length - 1 ];
  25737. if ( laste ) {
  25738. cpx0 = laste.x;
  25739. cpy0 = laste.y;
  25740. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  25741. var t = i2 / divisions;
  25742. QuadraticBezier( t, cpx0, cpx1, cpx );
  25743. QuadraticBezier( t, cpy0, cpy1, cpy );
  25744. }
  25745. }
  25746. break;
  25747. case 'b': // bezierCurveTo
  25748. cpx = outline[ i ++ ] * scale + offsetX;
  25749. cpy = outline[ i ++ ] * scale + offsetY;
  25750. cpx1 = outline[ i ++ ] * scale + offsetX;
  25751. cpy1 = outline[ i ++ ] * scale + offsetY;
  25752. cpx2 = outline[ i ++ ] * scale + offsetX;
  25753. cpy2 = outline[ i ++ ] * scale + offsetY;
  25754. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  25755. laste = pts[ pts.length - 1 ];
  25756. if ( laste ) {
  25757. cpx0 = laste.x;
  25758. cpy0 = laste.y;
  25759. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  25760. var t = i2 / divisions;
  25761. CubicBezier( t, cpx0, cpx1, cpx2, cpx );
  25762. CubicBezier( t, cpy0, cpy1, cpy2, cpy );
  25763. }
  25764. }
  25765. break;
  25766. }
  25767. }
  25768. }
  25769. return { offsetX: glyph.ha * scale, path: path };
  25770. }
  25771. //
  25772. if ( size === undefined ) size = 100;
  25773. if ( divisions === undefined ) divisions = 4;
  25774. var data = this.data;
  25775. var paths = createPaths( text );
  25776. var shapes = [];
  25777. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  25778. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  25779. }
  25780. return shapes;
  25781. }
  25782. } );
  25783. /**
  25784. * @author mrdoob / http://mrdoob.com/
  25785. */
  25786. function FontLoader( manager ) {
  25787. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  25788. }
  25789. Object.assign( FontLoader.prototype, {
  25790. load: function ( url, onLoad, onProgress, onError ) {
  25791. var scope = this;
  25792. var loader = new FileLoader( this.manager );
  25793. loader.load( url, function ( text ) {
  25794. var json;
  25795. try {
  25796. json = JSON.parse( text );
  25797. } catch ( e ) {
  25798. console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
  25799. json = JSON.parse( text.substring( 65, text.length - 2 ) );
  25800. }
  25801. var font = scope.parse( json );
  25802. if ( onLoad ) onLoad( font );
  25803. }, onProgress, onError );
  25804. },
  25805. parse: function ( json ) {
  25806. return new Font( json );
  25807. }
  25808. } );
  25809. var context;
  25810. var AudioContext = {
  25811. getContext: function () {
  25812. if ( context === undefined ) {
  25813. context = new ( window.AudioContext || window.webkitAudioContext )();
  25814. }
  25815. return context;
  25816. },
  25817. setContext: function ( value ) {
  25818. context = value;
  25819. }
  25820. };
  25821. /**
  25822. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  25823. */
  25824. function AudioLoader( manager ) {
  25825. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  25826. }
  25827. Object.assign( AudioLoader.prototype, {
  25828. load: function ( url, onLoad, onProgress, onError ) {
  25829. var loader = new FileLoader( this.manager );
  25830. loader.setResponseType( 'arraybuffer' );
  25831. loader.load( url, function ( buffer ) {
  25832. var context = AudioContext.getContext();
  25833. context.decodeAudioData( buffer, function ( audioBuffer ) {
  25834. onLoad( audioBuffer );
  25835. } );
  25836. }, onProgress, onError );
  25837. }
  25838. } );
  25839. /**
  25840. * @author abelnation / http://github.com/abelnation
  25841. */
  25842. function RectAreaLight ( color, intensity, width, height ) {
  25843. Light.call( this, color, intensity );
  25844. this.type = 'RectAreaLight';
  25845. this.position.set( 0, 1, 0 );
  25846. this.updateMatrix();
  25847. this.width = ( width !== undefined ) ? width : 10;
  25848. this.height = ( height !== undefined ) ? height : 10;
  25849. // TODO (abelnation): distance/decay
  25850. // TODO (abelnation): update method for RectAreaLight to update transform to lookat target
  25851. // TODO (abelnation): shadows
  25852. // this.shadow = new THREE.RectAreaLightShadow( new THREE.PerspectiveCamera( 90, 1, 0.5, 500 ) );
  25853. }
  25854. // TODO (abelnation): RectAreaLight update when light shape is changed
  25855. RectAreaLight.prototype = Object.assign( Object.create( Light.prototype ), {
  25856. constructor: RectAreaLight,
  25857. isRectAreaLight: true,
  25858. copy: function ( source ) {
  25859. Light.prototype.copy.call( this, source );
  25860. this.width = source.width;
  25861. this.height = source.height;
  25862. // this.shadow = source.shadow.clone();
  25863. return this;
  25864. }
  25865. } );
  25866. /**
  25867. * @author mrdoob / http://mrdoob.com/
  25868. */
  25869. function StereoCamera() {
  25870. this.type = 'StereoCamera';
  25871. this.aspect = 1;
  25872. this.eyeSep = 0.064;
  25873. this.cameraL = new PerspectiveCamera();
  25874. this.cameraL.layers.enable( 1 );
  25875. this.cameraL.matrixAutoUpdate = false;
  25876. this.cameraR = new PerspectiveCamera();
  25877. this.cameraR.layers.enable( 2 );
  25878. this.cameraR.matrixAutoUpdate = false;
  25879. }
  25880. Object.assign( StereoCamera.prototype, {
  25881. update: ( function () {
  25882. var instance, focus, fov, aspect, near, far, zoom;
  25883. var eyeRight = new Matrix4();
  25884. var eyeLeft = new Matrix4();
  25885. return function update( camera ) {
  25886. var needsUpdate = instance !== this || focus !== camera.focus || fov !== camera.fov ||
  25887. aspect !== camera.aspect * this.aspect || near !== camera.near ||
  25888. far !== camera.far || zoom !== camera.zoom;
  25889. if ( needsUpdate ) {
  25890. instance = this;
  25891. focus = camera.focus;
  25892. fov = camera.fov;
  25893. aspect = camera.aspect * this.aspect;
  25894. near = camera.near;
  25895. far = camera.far;
  25896. zoom = camera.zoom;
  25897. // Off-axis stereoscopic effect based on
  25898. // http://paulbourke.net/stereographics/stereorender/
  25899. var projectionMatrix = camera.projectionMatrix.clone();
  25900. var eyeSep = this.eyeSep / 2;
  25901. var eyeSepOnProjection = eyeSep * near / focus;
  25902. var ymax = ( near * Math.tan( _Math.DEG2RAD * fov * 0.5 ) ) / zoom;
  25903. var xmin, xmax;
  25904. // translate xOffset
  25905. eyeLeft.elements[ 12 ] = - eyeSep;
  25906. eyeRight.elements[ 12 ] = eyeSep;
  25907. // for left eye
  25908. xmin = - ymax * aspect + eyeSepOnProjection;
  25909. xmax = ymax * aspect + eyeSepOnProjection;
  25910. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  25911. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  25912. this.cameraL.projectionMatrix.copy( projectionMatrix );
  25913. // for right eye
  25914. xmin = - ymax * aspect - eyeSepOnProjection;
  25915. xmax = ymax * aspect - eyeSepOnProjection;
  25916. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  25917. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  25918. this.cameraR.projectionMatrix.copy( projectionMatrix );
  25919. }
  25920. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( eyeLeft );
  25921. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( eyeRight );
  25922. };
  25923. } )()
  25924. } );
  25925. /**
  25926. * Camera for rendering cube maps
  25927. * - renders scene into axis-aligned cube
  25928. *
  25929. * @author alteredq / http://alteredqualia.com/
  25930. */
  25931. function CubeCamera( near, far, cubeResolution ) {
  25932. Object3D.call( this );
  25933. this.type = 'CubeCamera';
  25934. var fov = 90, aspect = 1;
  25935. var cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  25936. cameraPX.up.set( 0, - 1, 0 );
  25937. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  25938. this.add( cameraPX );
  25939. var cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  25940. cameraNX.up.set( 0, - 1, 0 );
  25941. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  25942. this.add( cameraNX );
  25943. var cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  25944. cameraPY.up.set( 0, 0, 1 );
  25945. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  25946. this.add( cameraPY );
  25947. var cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  25948. cameraNY.up.set( 0, 0, - 1 );
  25949. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  25950. this.add( cameraNY );
  25951. var cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  25952. cameraPZ.up.set( 0, - 1, 0 );
  25953. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  25954. this.add( cameraPZ );
  25955. var cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  25956. cameraNZ.up.set( 0, - 1, 0 );
  25957. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  25958. this.add( cameraNZ );
  25959. var options = { format: RGBFormat, magFilter: LinearFilter, minFilter: LinearFilter };
  25960. this.renderTarget = new WebGLRenderTargetCube( cubeResolution, cubeResolution, options );
  25961. this.updateCubeMap = function ( renderer, scene ) {
  25962. if ( this.parent === null ) this.updateMatrixWorld();
  25963. var renderTarget = this.renderTarget;
  25964. var generateMipmaps = renderTarget.texture.generateMipmaps;
  25965. renderTarget.texture.generateMipmaps = false;
  25966. renderTarget.activeCubeFace = 0;
  25967. renderer.render( scene, cameraPX, renderTarget );
  25968. renderTarget.activeCubeFace = 1;
  25969. renderer.render( scene, cameraNX, renderTarget );
  25970. renderTarget.activeCubeFace = 2;
  25971. renderer.render( scene, cameraPY, renderTarget );
  25972. renderTarget.activeCubeFace = 3;
  25973. renderer.render( scene, cameraNY, renderTarget );
  25974. renderTarget.activeCubeFace = 4;
  25975. renderer.render( scene, cameraPZ, renderTarget );
  25976. renderTarget.texture.generateMipmaps = generateMipmaps;
  25977. renderTarget.activeCubeFace = 5;
  25978. renderer.render( scene, cameraNZ, renderTarget );
  25979. renderer.setRenderTarget( null );
  25980. };
  25981. }
  25982. CubeCamera.prototype = Object.create( Object3D.prototype );
  25983. CubeCamera.prototype.constructor = CubeCamera;
  25984. /**
  25985. * @author mrdoob / http://mrdoob.com/
  25986. */
  25987. function AudioListener() {
  25988. Object3D.call( this );
  25989. this.type = 'AudioListener';
  25990. this.context = AudioContext.getContext();
  25991. this.gain = this.context.createGain();
  25992. this.gain.connect( this.context.destination );
  25993. this.filter = null;
  25994. }
  25995. AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), {
  25996. constructor: AudioListener,
  25997. getInput: function () {
  25998. return this.gain;
  25999. },
  26000. removeFilter: function ( ) {
  26001. if ( this.filter !== null ) {
  26002. this.gain.disconnect( this.filter );
  26003. this.filter.disconnect( this.context.destination );
  26004. this.gain.connect( this.context.destination );
  26005. this.filter = null;
  26006. }
  26007. },
  26008. getFilter: function () {
  26009. return this.filter;
  26010. },
  26011. setFilter: function ( value ) {
  26012. if ( this.filter !== null ) {
  26013. this.gain.disconnect( this.filter );
  26014. this.filter.disconnect( this.context.destination );
  26015. } else {
  26016. this.gain.disconnect( this.context.destination );
  26017. }
  26018. this.filter = value;
  26019. this.gain.connect( this.filter );
  26020. this.filter.connect( this.context.destination );
  26021. },
  26022. getMasterVolume: function () {
  26023. return this.gain.gain.value;
  26024. },
  26025. setMasterVolume: function ( value ) {
  26026. this.gain.gain.value = value;
  26027. },
  26028. updateMatrixWorld: ( function () {
  26029. var position = new Vector3();
  26030. var quaternion = new Quaternion();
  26031. var scale = new Vector3();
  26032. var orientation = new Vector3();
  26033. return function updateMatrixWorld( force ) {
  26034. Object3D.prototype.updateMatrixWorld.call( this, force );
  26035. var listener = this.context.listener;
  26036. var up = this.up;
  26037. this.matrixWorld.decompose( position, quaternion, scale );
  26038. orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  26039. if ( listener.positionX ) {
  26040. listener.positionX.setValueAtTime( position.x, this.context.currentTime );
  26041. listener.positionY.setValueAtTime( position.y, this.context.currentTime );
  26042. listener.positionZ.setValueAtTime( position.z, this.context.currentTime );
  26043. listener.forwardX.setValueAtTime( orientation.x, this.context.currentTime );
  26044. listener.forwardY.setValueAtTime( orientation.y, this.context.currentTime );
  26045. listener.forwardZ.setValueAtTime( orientation.z, this.context.currentTime );
  26046. listener.upX.setValueAtTime( up.x, this.context.currentTime );
  26047. listener.upY.setValueAtTime( up.y, this.context.currentTime );
  26048. listener.upZ.setValueAtTime( up.z, this.context.currentTime );
  26049. } else {
  26050. listener.setPosition( position.x, position.y, position.z );
  26051. listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z );
  26052. }
  26053. };
  26054. } )()
  26055. } );
  26056. /**
  26057. * @author mrdoob / http://mrdoob.com/
  26058. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  26059. */
  26060. function Audio( listener ) {
  26061. Object3D.call( this );
  26062. this.type = 'Audio';
  26063. this.context = listener.context;
  26064. this.gain = this.context.createGain();
  26065. this.gain.connect( listener.getInput() );
  26066. this.autoplay = false;
  26067. this.buffer = null;
  26068. this.loop = false;
  26069. this.startTime = 0;
  26070. this.playbackRate = 1;
  26071. this.isPlaying = false;
  26072. this.hasPlaybackControl = true;
  26073. this.sourceType = 'empty';
  26074. this.filters = [];
  26075. }
  26076. Audio.prototype = Object.assign( Object.create( Object3D.prototype ), {
  26077. constructor: Audio,
  26078. getOutput: function () {
  26079. return this.gain;
  26080. },
  26081. setNodeSource: function ( audioNode ) {
  26082. this.hasPlaybackControl = false;
  26083. this.sourceType = 'audioNode';
  26084. this.source = audioNode;
  26085. this.connect();
  26086. return this;
  26087. },
  26088. setBuffer: function ( audioBuffer ) {
  26089. this.buffer = audioBuffer;
  26090. this.sourceType = 'buffer';
  26091. if ( this.autoplay ) this.play();
  26092. return this;
  26093. },
  26094. play: function () {
  26095. if ( this.isPlaying === true ) {
  26096. console.warn( 'THREE.Audio: Audio is already playing.' );
  26097. return;
  26098. }
  26099. if ( this.hasPlaybackControl === false ) {
  26100. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26101. return;
  26102. }
  26103. var source = this.context.createBufferSource();
  26104. source.buffer = this.buffer;
  26105. source.loop = this.loop;
  26106. source.onended = this.onEnded.bind( this );
  26107. source.playbackRate.setValueAtTime( this.playbackRate, this.startTime );
  26108. source.start( 0, this.startTime );
  26109. this.isPlaying = true;
  26110. this.source = source;
  26111. return this.connect();
  26112. },
  26113. pause: function () {
  26114. if ( this.hasPlaybackControl === false ) {
  26115. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26116. return;
  26117. }
  26118. this.source.stop();
  26119. this.startTime = this.context.currentTime;
  26120. this.isPlaying = false;
  26121. return this;
  26122. },
  26123. stop: function () {
  26124. if ( this.hasPlaybackControl === false ) {
  26125. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26126. return;
  26127. }
  26128. this.source.stop();
  26129. this.startTime = 0;
  26130. this.isPlaying = false;
  26131. return this;
  26132. },
  26133. connect: function () {
  26134. if ( this.filters.length > 0 ) {
  26135. this.source.connect( this.filters[ 0 ] );
  26136. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  26137. this.filters[ i - 1 ].connect( this.filters[ i ] );
  26138. }
  26139. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  26140. } else {
  26141. this.source.connect( this.getOutput() );
  26142. }
  26143. return this;
  26144. },
  26145. disconnect: function () {
  26146. if ( this.filters.length > 0 ) {
  26147. this.source.disconnect( this.filters[ 0 ] );
  26148. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  26149. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  26150. }
  26151. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  26152. } else {
  26153. this.source.disconnect( this.getOutput() );
  26154. }
  26155. return this;
  26156. },
  26157. getFilters: function () {
  26158. return this.filters;
  26159. },
  26160. setFilters: function ( value ) {
  26161. if ( ! value ) value = [];
  26162. if ( this.isPlaying === true ) {
  26163. this.disconnect();
  26164. this.filters = value;
  26165. this.connect();
  26166. } else {
  26167. this.filters = value;
  26168. }
  26169. return this;
  26170. },
  26171. getFilter: function () {
  26172. return this.getFilters()[ 0 ];
  26173. },
  26174. setFilter: function ( filter ) {
  26175. return this.setFilters( filter ? [ filter ] : [] );
  26176. },
  26177. setPlaybackRate: function ( value ) {
  26178. if ( this.hasPlaybackControl === false ) {
  26179. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26180. return;
  26181. }
  26182. this.playbackRate = value;
  26183. if ( this.isPlaying === true ) {
  26184. this.source.playbackRate.setValueAtTime( this.playbackRate, this.context.currentTime );
  26185. }
  26186. return this;
  26187. },
  26188. getPlaybackRate: function () {
  26189. return this.playbackRate;
  26190. },
  26191. onEnded: function () {
  26192. this.isPlaying = false;
  26193. },
  26194. getLoop: function () {
  26195. if ( this.hasPlaybackControl === false ) {
  26196. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26197. return false;
  26198. }
  26199. return this.loop;
  26200. },
  26201. setLoop: function ( value ) {
  26202. if ( this.hasPlaybackControl === false ) {
  26203. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26204. return;
  26205. }
  26206. this.loop = value;
  26207. if ( this.isPlaying === true ) {
  26208. this.source.loop = this.loop;
  26209. }
  26210. return this;
  26211. },
  26212. getVolume: function () {
  26213. return this.gain.gain.value;
  26214. },
  26215. setVolume: function ( value ) {
  26216. this.gain.gain.value = value;
  26217. return this;
  26218. }
  26219. } );
  26220. /**
  26221. * @author mrdoob / http://mrdoob.com/
  26222. */
  26223. function PositionalAudio( listener ) {
  26224. Audio.call( this, listener );
  26225. this.panner = this.context.createPanner();
  26226. this.panner.connect( this.gain );
  26227. }
  26228. PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), {
  26229. constructor: PositionalAudio,
  26230. getOutput: function () {
  26231. return this.panner;
  26232. },
  26233. getRefDistance: function () {
  26234. return this.panner.refDistance;
  26235. },
  26236. setRefDistance: function ( value ) {
  26237. this.panner.refDistance = value;
  26238. },
  26239. getRolloffFactor: function () {
  26240. return this.panner.rolloffFactor;
  26241. },
  26242. setRolloffFactor: function ( value ) {
  26243. this.panner.rolloffFactor = value;
  26244. },
  26245. getDistanceModel: function () {
  26246. return this.panner.distanceModel;
  26247. },
  26248. setDistanceModel: function ( value ) {
  26249. this.panner.distanceModel = value;
  26250. },
  26251. getMaxDistance: function () {
  26252. return this.panner.maxDistance;
  26253. },
  26254. setMaxDistance: function ( value ) {
  26255. this.panner.maxDistance = value;
  26256. },
  26257. updateMatrixWorld: ( function () {
  26258. var position = new Vector3();
  26259. return function updateMatrixWorld( force ) {
  26260. Object3D.prototype.updateMatrixWorld.call( this, force );
  26261. position.setFromMatrixPosition( this.matrixWorld );
  26262. this.panner.setPosition( position.x, position.y, position.z );
  26263. };
  26264. } )()
  26265. } );
  26266. /**
  26267. * @author mrdoob / http://mrdoob.com/
  26268. */
  26269. function AudioAnalyser( audio, fftSize ) {
  26270. this.analyser = audio.context.createAnalyser();
  26271. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  26272. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  26273. audio.getOutput().connect( this.analyser );
  26274. }
  26275. Object.assign( AudioAnalyser.prototype, {
  26276. getFrequencyData: function () {
  26277. this.analyser.getByteFrequencyData( this.data );
  26278. return this.data;
  26279. },
  26280. getAverageFrequency: function () {
  26281. var value = 0, data = this.getFrequencyData();
  26282. for ( var i = 0; i < data.length; i ++ ) {
  26283. value += data[ i ];
  26284. }
  26285. return value / data.length;
  26286. }
  26287. } );
  26288. /**
  26289. *
  26290. * Buffered scene graph property that allows weighted accumulation.
  26291. *
  26292. *
  26293. * @author Ben Houston / http://clara.io/
  26294. * @author David Sarno / http://lighthaus.us/
  26295. * @author tschw
  26296. */
  26297. function PropertyMixer( binding, typeName, valueSize ) {
  26298. this.binding = binding;
  26299. this.valueSize = valueSize;
  26300. var bufferType = Float64Array,
  26301. mixFunction;
  26302. switch ( typeName ) {
  26303. case 'quaternion':
  26304. mixFunction = this._slerp;
  26305. break;
  26306. case 'string':
  26307. case 'bool':
  26308. bufferType = Array;
  26309. mixFunction = this._select;
  26310. break;
  26311. default:
  26312. mixFunction = this._lerp;
  26313. }
  26314. this.buffer = new bufferType( valueSize * 4 );
  26315. // layout: [ incoming | accu0 | accu1 | orig ]
  26316. //
  26317. // interpolators can use .buffer as their .result
  26318. // the data then goes to 'incoming'
  26319. //
  26320. // 'accu0' and 'accu1' are used frame-interleaved for
  26321. // the cumulative result and are compared to detect
  26322. // changes
  26323. //
  26324. // 'orig' stores the original state of the property
  26325. this._mixBufferRegion = mixFunction;
  26326. this.cumulativeWeight = 0;
  26327. this.useCount = 0;
  26328. this.referenceCount = 0;
  26329. }
  26330. PropertyMixer.prototype = {
  26331. constructor: PropertyMixer,
  26332. // accumulate data in the 'incoming' region into 'accu<i>'
  26333. accumulate: function( accuIndex, weight ) {
  26334. // note: happily accumulating nothing when weight = 0, the caller knows
  26335. // the weight and shouldn't have made the call in the first place
  26336. var buffer = this.buffer,
  26337. stride = this.valueSize,
  26338. offset = accuIndex * stride + stride,
  26339. currentWeight = this.cumulativeWeight;
  26340. if ( currentWeight === 0 ) {
  26341. // accuN := incoming * weight
  26342. for ( var i = 0; i !== stride; ++ i ) {
  26343. buffer[ offset + i ] = buffer[ i ];
  26344. }
  26345. currentWeight = weight;
  26346. } else {
  26347. // accuN := accuN + incoming * weight
  26348. currentWeight += weight;
  26349. var mix = weight / currentWeight;
  26350. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  26351. }
  26352. this.cumulativeWeight = currentWeight;
  26353. },
  26354. // apply the state of 'accu<i>' to the binding when accus differ
  26355. apply: function( accuIndex ) {
  26356. var stride = this.valueSize,
  26357. buffer = this.buffer,
  26358. offset = accuIndex * stride + stride,
  26359. weight = this.cumulativeWeight,
  26360. binding = this.binding;
  26361. this.cumulativeWeight = 0;
  26362. if ( weight < 1 ) {
  26363. // accuN := accuN + original * ( 1 - cumulativeWeight )
  26364. var originalValueOffset = stride * 3;
  26365. this._mixBufferRegion(
  26366. buffer, offset, originalValueOffset, 1 - weight, stride );
  26367. }
  26368. for ( var i = stride, e = stride + stride; i !== e; ++ i ) {
  26369. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  26370. // value has changed -> update scene graph
  26371. binding.setValue( buffer, offset );
  26372. break;
  26373. }
  26374. }
  26375. },
  26376. // remember the state of the bound property and copy it to both accus
  26377. saveOriginalState: function() {
  26378. var binding = this.binding;
  26379. var buffer = this.buffer,
  26380. stride = this.valueSize,
  26381. originalValueOffset = stride * 3;
  26382. binding.getValue( buffer, originalValueOffset );
  26383. // accu[0..1] := orig -- initially detect changes against the original
  26384. for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) {
  26385. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  26386. }
  26387. this.cumulativeWeight = 0;
  26388. },
  26389. // apply the state previously taken via 'saveOriginalState' to the binding
  26390. restoreOriginalState: function() {
  26391. var originalValueOffset = this.valueSize * 3;
  26392. this.binding.setValue( this.buffer, originalValueOffset );
  26393. },
  26394. // mix functions
  26395. _select: function( buffer, dstOffset, srcOffset, t, stride ) {
  26396. if ( t >= 0.5 ) {
  26397. for ( var i = 0; i !== stride; ++ i ) {
  26398. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  26399. }
  26400. }
  26401. },
  26402. _slerp: function( buffer, dstOffset, srcOffset, t, stride ) {
  26403. Quaternion.slerpFlat( buffer, dstOffset,
  26404. buffer, dstOffset, buffer, srcOffset, t );
  26405. },
  26406. _lerp: function( buffer, dstOffset, srcOffset, t, stride ) {
  26407. var s = 1 - t;
  26408. for ( var i = 0; i !== stride; ++ i ) {
  26409. var j = dstOffset + i;
  26410. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  26411. }
  26412. }
  26413. };
  26414. /**
  26415. *
  26416. * A reference to a real property in the scene graph.
  26417. *
  26418. *
  26419. * @author Ben Houston / http://clara.io/
  26420. * @author David Sarno / http://lighthaus.us/
  26421. * @author tschw
  26422. */
  26423. function PropertyBinding( rootNode, path, parsedPath ) {
  26424. this.path = path;
  26425. this.parsedPath = parsedPath ||
  26426. PropertyBinding.parseTrackName( path );
  26427. this.node = PropertyBinding.findNode(
  26428. rootNode, this.parsedPath.nodeName ) || rootNode;
  26429. this.rootNode = rootNode;
  26430. }
  26431. PropertyBinding.prototype = {
  26432. constructor: PropertyBinding,
  26433. getValue: function getValue_unbound( targetArray, offset ) {
  26434. this.bind();
  26435. this.getValue( targetArray, offset );
  26436. // Note: This class uses a State pattern on a per-method basis:
  26437. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  26438. // prototype version of these methods with one that represents
  26439. // the bound state. When the property is not found, the methods
  26440. // become no-ops.
  26441. },
  26442. setValue: function getValue_unbound( sourceArray, offset ) {
  26443. this.bind();
  26444. this.setValue( sourceArray, offset );
  26445. },
  26446. // create getter / setter pair for a property in the scene graph
  26447. bind: function() {
  26448. var targetObject = this.node,
  26449. parsedPath = this.parsedPath,
  26450. objectName = parsedPath.objectName,
  26451. propertyName = parsedPath.propertyName,
  26452. propertyIndex = parsedPath.propertyIndex;
  26453. if ( ! targetObject ) {
  26454. targetObject = PropertyBinding.findNode(
  26455. this.rootNode, parsedPath.nodeName ) || this.rootNode;
  26456. this.node = targetObject;
  26457. }
  26458. // set fail state so we can just 'return' on error
  26459. this.getValue = this._getValue_unavailable;
  26460. this.setValue = this._setValue_unavailable;
  26461. // ensure there is a value node
  26462. if ( ! targetObject ) {
  26463. console.error( " trying to update node for track: " + this.path + " but it wasn't found." );
  26464. return;
  26465. }
  26466. if ( objectName ) {
  26467. var objectIndex = parsedPath.objectIndex;
  26468. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  26469. switch ( objectName ) {
  26470. case 'materials':
  26471. if ( ! targetObject.material ) {
  26472. console.error( ' can not bind to material as node does not have a material', this );
  26473. return;
  26474. }
  26475. if ( ! targetObject.material.materials ) {
  26476. console.error( ' can not bind to material.materials as node.material does not have a materials array', this );
  26477. return;
  26478. }
  26479. targetObject = targetObject.material.materials;
  26480. break;
  26481. case 'bones':
  26482. if ( ! targetObject.skeleton ) {
  26483. console.error( ' can not bind to bones as node does not have a skeleton', this );
  26484. return;
  26485. }
  26486. // potential future optimization: skip this if propertyIndex is already an integer
  26487. // and convert the integer string to a true integer.
  26488. targetObject = targetObject.skeleton.bones;
  26489. // support resolving morphTarget names into indices.
  26490. for ( var i = 0; i < targetObject.length; i ++ ) {
  26491. if ( targetObject[ i ].name === objectIndex ) {
  26492. objectIndex = i;
  26493. break;
  26494. }
  26495. }
  26496. break;
  26497. default:
  26498. if ( targetObject[ objectName ] === undefined ) {
  26499. console.error( ' can not bind to objectName of node, undefined', this );
  26500. return;
  26501. }
  26502. targetObject = targetObject[ objectName ];
  26503. }
  26504. if ( objectIndex !== undefined ) {
  26505. if ( targetObject[ objectIndex ] === undefined ) {
  26506. console.error( " trying to bind to objectIndex of objectName, but is undefined:", this, targetObject );
  26507. return;
  26508. }
  26509. targetObject = targetObject[ objectIndex ];
  26510. }
  26511. }
  26512. // resolve property
  26513. var nodeProperty = targetObject[ propertyName ];
  26514. if ( nodeProperty === undefined ) {
  26515. var nodeName = parsedPath.nodeName;
  26516. console.error( " trying to update property for track: " + nodeName +
  26517. '.' + propertyName + " but it wasn't found.", targetObject );
  26518. return;
  26519. }
  26520. // determine versioning scheme
  26521. var versioning = this.Versioning.None;
  26522. if ( targetObject.needsUpdate !== undefined ) { // material
  26523. versioning = this.Versioning.NeedsUpdate;
  26524. this.targetObject = targetObject;
  26525. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  26526. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  26527. this.targetObject = targetObject;
  26528. }
  26529. // determine how the property gets bound
  26530. var bindingType = this.BindingType.Direct;
  26531. if ( propertyIndex !== undefined ) {
  26532. // access a sub element of the property array (only primitives are supported right now)
  26533. if ( propertyName === "morphTargetInfluences" ) {
  26534. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  26535. // support resolving morphTarget names into indices.
  26536. if ( ! targetObject.geometry ) {
  26537. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry', this );
  26538. return;
  26539. }
  26540. if ( ! targetObject.geometry.morphTargets ) {
  26541. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry.morphTargets', this );
  26542. return;
  26543. }
  26544. for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {
  26545. if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) {
  26546. propertyIndex = i;
  26547. break;
  26548. }
  26549. }
  26550. }
  26551. bindingType = this.BindingType.ArrayElement;
  26552. this.resolvedProperty = nodeProperty;
  26553. this.propertyIndex = propertyIndex;
  26554. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  26555. // must use copy for Object3D.Euler/Quaternion
  26556. bindingType = this.BindingType.HasFromToArray;
  26557. this.resolvedProperty = nodeProperty;
  26558. } else if ( nodeProperty.length !== undefined ) {
  26559. bindingType = this.BindingType.EntireArray;
  26560. this.resolvedProperty = nodeProperty;
  26561. } else {
  26562. this.propertyName = propertyName;
  26563. }
  26564. // select getter / setter
  26565. this.getValue = this.GetterByBindingType[ bindingType ];
  26566. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  26567. },
  26568. unbind: function() {
  26569. this.node = null;
  26570. // back to the prototype version of getValue / setValue
  26571. // note: avoiding to mutate the shape of 'this' via 'delete'
  26572. this.getValue = this._getValue_unbound;
  26573. this.setValue = this._setValue_unbound;
  26574. }
  26575. };
  26576. Object.assign( PropertyBinding.prototype, { // prototype, continued
  26577. // these are used to "bind" a nonexistent property
  26578. _getValue_unavailable: function() {},
  26579. _setValue_unavailable: function() {},
  26580. // initial state of these methods that calls 'bind'
  26581. _getValue_unbound: PropertyBinding.prototype.getValue,
  26582. _setValue_unbound: PropertyBinding.prototype.setValue,
  26583. BindingType: {
  26584. Direct: 0,
  26585. EntireArray: 1,
  26586. ArrayElement: 2,
  26587. HasFromToArray: 3
  26588. },
  26589. Versioning: {
  26590. None: 0,
  26591. NeedsUpdate: 1,
  26592. MatrixWorldNeedsUpdate: 2
  26593. },
  26594. GetterByBindingType: [
  26595. function getValue_direct( buffer, offset ) {
  26596. buffer[ offset ] = this.node[ this.propertyName ];
  26597. },
  26598. function getValue_array( buffer, offset ) {
  26599. var source = this.resolvedProperty;
  26600. for ( var i = 0, n = source.length; i !== n; ++ i ) {
  26601. buffer[ offset ++ ] = source[ i ];
  26602. }
  26603. },
  26604. function getValue_arrayElement( buffer, offset ) {
  26605. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  26606. },
  26607. function getValue_toArray( buffer, offset ) {
  26608. this.resolvedProperty.toArray( buffer, offset );
  26609. }
  26610. ],
  26611. SetterByBindingTypeAndVersioning: [
  26612. [
  26613. // Direct
  26614. function setValue_direct( buffer, offset ) {
  26615. this.node[ this.propertyName ] = buffer[ offset ];
  26616. },
  26617. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  26618. this.node[ this.propertyName ] = buffer[ offset ];
  26619. this.targetObject.needsUpdate = true;
  26620. },
  26621. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26622. this.node[ this.propertyName ] = buffer[ offset ];
  26623. this.targetObject.matrixWorldNeedsUpdate = true;
  26624. }
  26625. ], [
  26626. // EntireArray
  26627. function setValue_array( buffer, offset ) {
  26628. var dest = this.resolvedProperty;
  26629. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  26630. dest[ i ] = buffer[ offset ++ ];
  26631. }
  26632. },
  26633. function setValue_array_setNeedsUpdate( buffer, offset ) {
  26634. var dest = this.resolvedProperty;
  26635. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  26636. dest[ i ] = buffer[ offset ++ ];
  26637. }
  26638. this.targetObject.needsUpdate = true;
  26639. },
  26640. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26641. var dest = this.resolvedProperty;
  26642. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  26643. dest[ i ] = buffer[ offset ++ ];
  26644. }
  26645. this.targetObject.matrixWorldNeedsUpdate = true;
  26646. }
  26647. ], [
  26648. // ArrayElement
  26649. function setValue_arrayElement( buffer, offset ) {
  26650. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26651. },
  26652. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  26653. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26654. this.targetObject.needsUpdate = true;
  26655. },
  26656. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26657. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26658. this.targetObject.matrixWorldNeedsUpdate = true;
  26659. }
  26660. ], [
  26661. // HasToFromArray
  26662. function setValue_fromArray( buffer, offset ) {
  26663. this.resolvedProperty.fromArray( buffer, offset );
  26664. },
  26665. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  26666. this.resolvedProperty.fromArray( buffer, offset );
  26667. this.targetObject.needsUpdate = true;
  26668. },
  26669. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26670. this.resolvedProperty.fromArray( buffer, offset );
  26671. this.targetObject.matrixWorldNeedsUpdate = true;
  26672. }
  26673. ]
  26674. ]
  26675. } );
  26676. PropertyBinding.Composite =
  26677. function( targetGroup, path, optionalParsedPath ) {
  26678. var parsedPath = optionalParsedPath ||
  26679. PropertyBinding.parseTrackName( path );
  26680. this._targetGroup = targetGroup;
  26681. this._bindings = targetGroup.subscribe_( path, parsedPath );
  26682. };
  26683. PropertyBinding.Composite.prototype = {
  26684. constructor: PropertyBinding.Composite,
  26685. getValue: function( array, offset ) {
  26686. this.bind(); // bind all binding
  26687. var firstValidIndex = this._targetGroup.nCachedObjects_,
  26688. binding = this._bindings[ firstValidIndex ];
  26689. // and only call .getValue on the first
  26690. if ( binding !== undefined ) binding.getValue( array, offset );
  26691. },
  26692. setValue: function( array, offset ) {
  26693. var bindings = this._bindings;
  26694. for ( var i = this._targetGroup.nCachedObjects_,
  26695. n = bindings.length; i !== n; ++ i ) {
  26696. bindings[ i ].setValue( array, offset );
  26697. }
  26698. },
  26699. bind: function() {
  26700. var bindings = this._bindings;
  26701. for ( var i = this._targetGroup.nCachedObjects_,
  26702. n = bindings.length; i !== n; ++ i ) {
  26703. bindings[ i ].bind();
  26704. }
  26705. },
  26706. unbind: function() {
  26707. var bindings = this._bindings;
  26708. for ( var i = this._targetGroup.nCachedObjects_,
  26709. n = bindings.length; i !== n; ++ i ) {
  26710. bindings[ i ].unbind();
  26711. }
  26712. }
  26713. };
  26714. PropertyBinding.create = function( root, path, parsedPath ) {
  26715. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  26716. return new PropertyBinding( root, path, parsedPath );
  26717. } else {
  26718. return new PropertyBinding.Composite( root, path, parsedPath );
  26719. }
  26720. };
  26721. PropertyBinding.parseTrackName = function( trackName ) {
  26722. // matches strings in the form of:
  26723. // nodeName.property
  26724. // nodeName.property[accessor]
  26725. // nodeName.material.property[accessor]
  26726. // uuid.property[accessor]
  26727. // uuid.objectName[objectIndex].propertyName[propertyIndex]
  26728. // parentName/nodeName.property
  26729. // parentName/parentName/nodeName.property[index]
  26730. // .bone[Armature.DEF_cog].position
  26731. // scene:helium_balloon_model:helium_balloon_model.position
  26732. // created and tested via https://regex101.com/#javascript
  26733. var re = /^((?:[\w-]+[\/:])*)([\w-]+)?(?:\.([\w-]+)(?:\[(.+)\])?)?\.([\w-]+)(?:\[(.+)\])?$/;
  26734. var matches = re.exec( trackName );
  26735. if ( ! matches ) {
  26736. throw new Error( "cannot parse trackName at all: " + trackName );
  26737. }
  26738. var results = {
  26739. // directoryName: matches[ 1 ], // (tschw) currently unused
  26740. nodeName: matches[ 2 ], // allowed to be null, specified root node.
  26741. objectName: matches[ 3 ],
  26742. objectIndex: matches[ 4 ],
  26743. propertyName: matches[ 5 ],
  26744. propertyIndex: matches[ 6 ] // allowed to be null, specifies that the whole property is set.
  26745. };
  26746. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  26747. throw new Error( "can not parse propertyName from trackName: " + trackName );
  26748. }
  26749. return results;
  26750. };
  26751. PropertyBinding.findNode = function( root, nodeName ) {
  26752. if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  26753. return root;
  26754. }
  26755. // search into skeleton bones.
  26756. if ( root.skeleton ) {
  26757. var searchSkeleton = function( skeleton ) {
  26758. for( var i = 0; i < skeleton.bones.length; i ++ ) {
  26759. var bone = skeleton.bones[ i ];
  26760. if ( bone.name === nodeName ) {
  26761. return bone;
  26762. }
  26763. }
  26764. return null;
  26765. };
  26766. var bone = searchSkeleton( root.skeleton );
  26767. if ( bone ) {
  26768. return bone;
  26769. }
  26770. }
  26771. // search into node subtree.
  26772. if ( root.children ) {
  26773. var searchNodeSubtree = function( children ) {
  26774. for( var i = 0; i < children.length; i ++ ) {
  26775. var childNode = children[ i ];
  26776. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  26777. return childNode;
  26778. }
  26779. var result = searchNodeSubtree( childNode.children );
  26780. if ( result ) return result;
  26781. }
  26782. return null;
  26783. };
  26784. var subTreeNode = searchNodeSubtree( root.children );
  26785. if ( subTreeNode ) {
  26786. return subTreeNode;
  26787. }
  26788. }
  26789. return null;
  26790. };
  26791. /**
  26792. *
  26793. * A group of objects that receives a shared animation state.
  26794. *
  26795. * Usage:
  26796. *
  26797. * - Add objects you would otherwise pass as 'root' to the
  26798. * constructor or the .clipAction method of AnimationMixer.
  26799. *
  26800. * - Instead pass this object as 'root'.
  26801. *
  26802. * - You can also add and remove objects later when the mixer
  26803. * is running.
  26804. *
  26805. * Note:
  26806. *
  26807. * Objects of this class appear as one object to the mixer,
  26808. * so cache control of the individual objects must be done
  26809. * on the group.
  26810. *
  26811. * Limitation:
  26812. *
  26813. * - The animated properties must be compatible among the
  26814. * all objects in the group.
  26815. *
  26816. * - A single property can either be controlled through a
  26817. * target group or directly, but not both.
  26818. *
  26819. * @author tschw
  26820. */
  26821. function AnimationObjectGroup( var_args ) {
  26822. this.uuid = _Math.generateUUID();
  26823. // cached objects followed by the active ones
  26824. this._objects = Array.prototype.slice.call( arguments );
  26825. this.nCachedObjects_ = 0; // threshold
  26826. // note: read by PropertyBinding.Composite
  26827. var indices = {};
  26828. this._indicesByUUID = indices; // for bookkeeping
  26829. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  26830. indices[ arguments[ i ].uuid ] = i;
  26831. }
  26832. this._paths = []; // inside: string
  26833. this._parsedPaths = []; // inside: { we don't care, here }
  26834. this._bindings = []; // inside: Array< PropertyBinding >
  26835. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  26836. var scope = this;
  26837. this.stats = {
  26838. objects: {
  26839. get total() { return scope._objects.length; },
  26840. get inUse() { return this.total - scope.nCachedObjects_; }
  26841. },
  26842. get bindingsPerObject() { return scope._bindings.length; }
  26843. };
  26844. }
  26845. AnimationObjectGroup.prototype = {
  26846. constructor: AnimationObjectGroup,
  26847. isAnimationObjectGroup: true,
  26848. add: function( var_args ) {
  26849. var objects = this._objects,
  26850. nObjects = objects.length,
  26851. nCachedObjects = this.nCachedObjects_,
  26852. indicesByUUID = this._indicesByUUID,
  26853. paths = this._paths,
  26854. parsedPaths = this._parsedPaths,
  26855. bindings = this._bindings,
  26856. nBindings = bindings.length;
  26857. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  26858. var object = arguments[ i ],
  26859. uuid = object.uuid,
  26860. index = indicesByUUID[ uuid ],
  26861. knownObject = undefined;
  26862. if ( index === undefined ) {
  26863. // unknown object -> add it to the ACTIVE region
  26864. index = nObjects ++;
  26865. indicesByUUID[ uuid ] = index;
  26866. objects.push( object );
  26867. // accounting is done, now do the same for all bindings
  26868. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  26869. bindings[ j ].push(
  26870. new PropertyBinding(
  26871. object, paths[ j ], parsedPaths[ j ] ) );
  26872. }
  26873. } else if ( index < nCachedObjects ) {
  26874. knownObject = objects[ index ];
  26875. // move existing object to the ACTIVE region
  26876. var firstActiveIndex = -- nCachedObjects,
  26877. lastCachedObject = objects[ firstActiveIndex ];
  26878. indicesByUUID[ lastCachedObject.uuid ] = index;
  26879. objects[ index ] = lastCachedObject;
  26880. indicesByUUID[ uuid ] = firstActiveIndex;
  26881. objects[ firstActiveIndex ] = object;
  26882. // accounting is done, now do the same for all bindings
  26883. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  26884. var bindingsForPath = bindings[ j ],
  26885. lastCached = bindingsForPath[ firstActiveIndex ],
  26886. binding = bindingsForPath[ index ];
  26887. bindingsForPath[ index ] = lastCached;
  26888. if ( binding === undefined ) {
  26889. // since we do not bother to create new bindings
  26890. // for objects that are cached, the binding may
  26891. // or may not exist
  26892. binding = new PropertyBinding(
  26893. object, paths[ j ], parsedPaths[ j ] );
  26894. }
  26895. bindingsForPath[ firstActiveIndex ] = binding;
  26896. }
  26897. } else if ( objects[ index ] !== knownObject) {
  26898. console.error( "Different objects with the same UUID " +
  26899. "detected. Clean the caches or recreate your " +
  26900. "infrastructure when reloading scenes..." );
  26901. } // else the object is already where we want it to be
  26902. } // for arguments
  26903. this.nCachedObjects_ = nCachedObjects;
  26904. },
  26905. remove: function( var_args ) {
  26906. var objects = this._objects,
  26907. nCachedObjects = this.nCachedObjects_,
  26908. indicesByUUID = this._indicesByUUID,
  26909. bindings = this._bindings,
  26910. nBindings = bindings.length;
  26911. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  26912. var object = arguments[ i ],
  26913. uuid = object.uuid,
  26914. index = indicesByUUID[ uuid ];
  26915. if ( index !== undefined && index >= nCachedObjects ) {
  26916. // move existing object into the CACHED region
  26917. var lastCachedIndex = nCachedObjects ++,
  26918. firstActiveObject = objects[ lastCachedIndex ];
  26919. indicesByUUID[ firstActiveObject.uuid ] = index;
  26920. objects[ index ] = firstActiveObject;
  26921. indicesByUUID[ uuid ] = lastCachedIndex;
  26922. objects[ lastCachedIndex ] = object;
  26923. // accounting is done, now do the same for all bindings
  26924. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  26925. var bindingsForPath = bindings[ j ],
  26926. firstActive = bindingsForPath[ lastCachedIndex ],
  26927. binding = bindingsForPath[ index ];
  26928. bindingsForPath[ index ] = firstActive;
  26929. bindingsForPath[ lastCachedIndex ] = binding;
  26930. }
  26931. }
  26932. } // for arguments
  26933. this.nCachedObjects_ = nCachedObjects;
  26934. },
  26935. // remove & forget
  26936. uncache: function( var_args ) {
  26937. var objects = this._objects,
  26938. nObjects = objects.length,
  26939. nCachedObjects = this.nCachedObjects_,
  26940. indicesByUUID = this._indicesByUUID,
  26941. bindings = this._bindings,
  26942. nBindings = bindings.length;
  26943. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  26944. var object = arguments[ i ],
  26945. uuid = object.uuid,
  26946. index = indicesByUUID[ uuid ];
  26947. if ( index !== undefined ) {
  26948. delete indicesByUUID[ uuid ];
  26949. if ( index < nCachedObjects ) {
  26950. // object is cached, shrink the CACHED region
  26951. var firstActiveIndex = -- nCachedObjects,
  26952. lastCachedObject = objects[ firstActiveIndex ],
  26953. lastIndex = -- nObjects,
  26954. lastObject = objects[ lastIndex ];
  26955. // last cached object takes this object's place
  26956. indicesByUUID[ lastCachedObject.uuid ] = index;
  26957. objects[ index ] = lastCachedObject;
  26958. // last object goes to the activated slot and pop
  26959. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  26960. objects[ firstActiveIndex ] = lastObject;
  26961. objects.pop();
  26962. // accounting is done, now do the same for all bindings
  26963. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  26964. var bindingsForPath = bindings[ j ],
  26965. lastCached = bindingsForPath[ firstActiveIndex ],
  26966. last = bindingsForPath[ lastIndex ];
  26967. bindingsForPath[ index ] = lastCached;
  26968. bindingsForPath[ firstActiveIndex ] = last;
  26969. bindingsForPath.pop();
  26970. }
  26971. } else {
  26972. // object is active, just swap with the last and pop
  26973. var lastIndex = -- nObjects,
  26974. lastObject = objects[ lastIndex ];
  26975. indicesByUUID[ lastObject.uuid ] = index;
  26976. objects[ index ] = lastObject;
  26977. objects.pop();
  26978. // accounting is done, now do the same for all bindings
  26979. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  26980. var bindingsForPath = bindings[ j ];
  26981. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  26982. bindingsForPath.pop();
  26983. }
  26984. } // cached or active
  26985. } // if object is known
  26986. } // for arguments
  26987. this.nCachedObjects_ = nCachedObjects;
  26988. },
  26989. // Internal interface used by befriended PropertyBinding.Composite:
  26990. subscribe_: function( path, parsedPath ) {
  26991. // returns an array of bindings for the given path that is changed
  26992. // according to the contained objects in the group
  26993. var indicesByPath = this._bindingsIndicesByPath,
  26994. index = indicesByPath[ path ],
  26995. bindings = this._bindings;
  26996. if ( index !== undefined ) return bindings[ index ];
  26997. var paths = this._paths,
  26998. parsedPaths = this._parsedPaths,
  26999. objects = this._objects,
  27000. nObjects = objects.length,
  27001. nCachedObjects = this.nCachedObjects_,
  27002. bindingsForPath = new Array( nObjects );
  27003. index = bindings.length;
  27004. indicesByPath[ path ] = index;
  27005. paths.push( path );
  27006. parsedPaths.push( parsedPath );
  27007. bindings.push( bindingsForPath );
  27008. for ( var i = nCachedObjects,
  27009. n = objects.length; i !== n; ++ i ) {
  27010. var object = objects[ i ];
  27011. bindingsForPath[ i ] =
  27012. new PropertyBinding( object, path, parsedPath );
  27013. }
  27014. return bindingsForPath;
  27015. },
  27016. unsubscribe_: function( path ) {
  27017. // tells the group to forget about a property path and no longer
  27018. // update the array previously obtained with 'subscribe_'
  27019. var indicesByPath = this._bindingsIndicesByPath,
  27020. index = indicesByPath[ path ];
  27021. if ( index !== undefined ) {
  27022. var paths = this._paths,
  27023. parsedPaths = this._parsedPaths,
  27024. bindings = this._bindings,
  27025. lastBindingsIndex = bindings.length - 1,
  27026. lastBindings = bindings[ lastBindingsIndex ],
  27027. lastBindingsPath = path[ lastBindingsIndex ];
  27028. indicesByPath[ lastBindingsPath ] = index;
  27029. bindings[ index ] = lastBindings;
  27030. bindings.pop();
  27031. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  27032. parsedPaths.pop();
  27033. paths[ index ] = paths[ lastBindingsIndex ];
  27034. paths.pop();
  27035. }
  27036. }
  27037. };
  27038. /**
  27039. *
  27040. * Action provided by AnimationMixer for scheduling clip playback on specific
  27041. * objects.
  27042. *
  27043. * @author Ben Houston / http://clara.io/
  27044. * @author David Sarno / http://lighthaus.us/
  27045. * @author tschw
  27046. *
  27047. */
  27048. function AnimationAction( mixer, clip, localRoot ) {
  27049. this._mixer = mixer;
  27050. this._clip = clip;
  27051. this._localRoot = localRoot || null;
  27052. var tracks = clip.tracks,
  27053. nTracks = tracks.length,
  27054. interpolants = new Array( nTracks );
  27055. var interpolantSettings = {
  27056. endingStart: ZeroCurvatureEnding,
  27057. endingEnd: ZeroCurvatureEnding
  27058. };
  27059. for ( var i = 0; i !== nTracks; ++ i ) {
  27060. var interpolant = tracks[ i ].createInterpolant( null );
  27061. interpolants[ i ] = interpolant;
  27062. interpolant.settings = interpolantSettings;
  27063. }
  27064. this._interpolantSettings = interpolantSettings;
  27065. this._interpolants = interpolants; // bound by the mixer
  27066. // inside: PropertyMixer (managed by the mixer)
  27067. this._propertyBindings = new Array( nTracks );
  27068. this._cacheIndex = null; // for the memory manager
  27069. this._byClipCacheIndex = null; // for the memory manager
  27070. this._timeScaleInterpolant = null;
  27071. this._weightInterpolant = null;
  27072. this.loop = LoopRepeat;
  27073. this._loopCount = -1;
  27074. // global mixer time when the action is to be started
  27075. // it's set back to 'null' upon start of the action
  27076. this._startTime = null;
  27077. // scaled local time of the action
  27078. // gets clamped or wrapped to 0..clip.duration according to loop
  27079. this.time = 0;
  27080. this.timeScale = 1;
  27081. this._effectiveTimeScale = 1;
  27082. this.weight = 1;
  27083. this._effectiveWeight = 1;
  27084. this.repetitions = Infinity; // no. of repetitions when looping
  27085. this.paused = false; // false -> zero effective time scale
  27086. this.enabled = true; // true -> zero effective weight
  27087. this.clampWhenFinished = false; // keep feeding the last frame?
  27088. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  27089. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  27090. }
  27091. AnimationAction.prototype = {
  27092. constructor: AnimationAction,
  27093. // State & Scheduling
  27094. play: function() {
  27095. this._mixer._activateAction( this );
  27096. return this;
  27097. },
  27098. stop: function() {
  27099. this._mixer._deactivateAction( this );
  27100. return this.reset();
  27101. },
  27102. reset: function() {
  27103. this.paused = false;
  27104. this.enabled = true;
  27105. this.time = 0; // restart clip
  27106. this._loopCount = -1; // forget previous loops
  27107. this._startTime = null; // forget scheduling
  27108. return this.stopFading().stopWarping();
  27109. },
  27110. isRunning: function() {
  27111. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  27112. this._startTime === null && this._mixer._isActiveAction( this );
  27113. },
  27114. // return true when play has been called
  27115. isScheduled: function() {
  27116. return this._mixer._isActiveAction( this );
  27117. },
  27118. startAt: function( time ) {
  27119. this._startTime = time;
  27120. return this;
  27121. },
  27122. setLoop: function( mode, repetitions ) {
  27123. this.loop = mode;
  27124. this.repetitions = repetitions;
  27125. return this;
  27126. },
  27127. // Weight
  27128. // set the weight stopping any scheduled fading
  27129. // although .enabled = false yields an effective weight of zero, this
  27130. // method does *not* change .enabled, because it would be confusing
  27131. setEffectiveWeight: function( weight ) {
  27132. this.weight = weight;
  27133. // note: same logic as when updated at runtime
  27134. this._effectiveWeight = this.enabled ? weight : 0;
  27135. return this.stopFading();
  27136. },
  27137. // return the weight considering fading and .enabled
  27138. getEffectiveWeight: function() {
  27139. return this._effectiveWeight;
  27140. },
  27141. fadeIn: function( duration ) {
  27142. return this._scheduleFading( duration, 0, 1 );
  27143. },
  27144. fadeOut: function( duration ) {
  27145. return this._scheduleFading( duration, 1, 0 );
  27146. },
  27147. crossFadeFrom: function( fadeOutAction, duration, warp ) {
  27148. fadeOutAction.fadeOut( duration );
  27149. this.fadeIn( duration );
  27150. if( warp ) {
  27151. var fadeInDuration = this._clip.duration,
  27152. fadeOutDuration = fadeOutAction._clip.duration,
  27153. startEndRatio = fadeOutDuration / fadeInDuration,
  27154. endStartRatio = fadeInDuration / fadeOutDuration;
  27155. fadeOutAction.warp( 1.0, startEndRatio, duration );
  27156. this.warp( endStartRatio, 1.0, duration );
  27157. }
  27158. return this;
  27159. },
  27160. crossFadeTo: function( fadeInAction, duration, warp ) {
  27161. return fadeInAction.crossFadeFrom( this, duration, warp );
  27162. },
  27163. stopFading: function() {
  27164. var weightInterpolant = this._weightInterpolant;
  27165. if ( weightInterpolant !== null ) {
  27166. this._weightInterpolant = null;
  27167. this._mixer._takeBackControlInterpolant( weightInterpolant );
  27168. }
  27169. return this;
  27170. },
  27171. // Time Scale Control
  27172. // set the weight stopping any scheduled warping
  27173. // although .paused = true yields an effective time scale of zero, this
  27174. // method does *not* change .paused, because it would be confusing
  27175. setEffectiveTimeScale: function( timeScale ) {
  27176. this.timeScale = timeScale;
  27177. this._effectiveTimeScale = this.paused ? 0 :timeScale;
  27178. return this.stopWarping();
  27179. },
  27180. // return the time scale considering warping and .paused
  27181. getEffectiveTimeScale: function() {
  27182. return this._effectiveTimeScale;
  27183. },
  27184. setDuration: function( duration ) {
  27185. this.timeScale = this._clip.duration / duration;
  27186. return this.stopWarping();
  27187. },
  27188. syncWith: function( action ) {
  27189. this.time = action.time;
  27190. this.timeScale = action.timeScale;
  27191. return this.stopWarping();
  27192. },
  27193. halt: function( duration ) {
  27194. return this.warp( this._effectiveTimeScale, 0, duration );
  27195. },
  27196. warp: function( startTimeScale, endTimeScale, duration ) {
  27197. var mixer = this._mixer, now = mixer.time,
  27198. interpolant = this._timeScaleInterpolant,
  27199. timeScale = this.timeScale;
  27200. if ( interpolant === null ) {
  27201. interpolant = mixer._lendControlInterpolant();
  27202. this._timeScaleInterpolant = interpolant;
  27203. }
  27204. var times = interpolant.parameterPositions,
  27205. values = interpolant.sampleValues;
  27206. times[ 0 ] = now;
  27207. times[ 1 ] = now + duration;
  27208. values[ 0 ] = startTimeScale / timeScale;
  27209. values[ 1 ] = endTimeScale / timeScale;
  27210. return this;
  27211. },
  27212. stopWarping: function() {
  27213. var timeScaleInterpolant = this._timeScaleInterpolant;
  27214. if ( timeScaleInterpolant !== null ) {
  27215. this._timeScaleInterpolant = null;
  27216. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  27217. }
  27218. return this;
  27219. },
  27220. // Object Accessors
  27221. getMixer: function() {
  27222. return this._mixer;
  27223. },
  27224. getClip: function() {
  27225. return this._clip;
  27226. },
  27227. getRoot: function() {
  27228. return this._localRoot || this._mixer._root;
  27229. },
  27230. // Interna
  27231. _update: function( time, deltaTime, timeDirection, accuIndex ) {
  27232. // called by the mixer
  27233. var startTime = this._startTime;
  27234. if ( startTime !== null ) {
  27235. // check for scheduled start of action
  27236. var timeRunning = ( time - startTime ) * timeDirection;
  27237. if ( timeRunning < 0 || timeDirection === 0 ) {
  27238. return; // yet to come / don't decide when delta = 0
  27239. }
  27240. // start
  27241. this._startTime = null; // unschedule
  27242. deltaTime = timeDirection * timeRunning;
  27243. }
  27244. // apply time scale and advance time
  27245. deltaTime *= this._updateTimeScale( time );
  27246. var clipTime = this._updateTime( deltaTime );
  27247. // note: _updateTime may disable the action resulting in
  27248. // an effective weight of 0
  27249. var weight = this._updateWeight( time );
  27250. if ( weight > 0 ) {
  27251. var interpolants = this._interpolants;
  27252. var propertyMixers = this._propertyBindings;
  27253. for ( var j = 0, m = interpolants.length; j !== m; ++ j ) {
  27254. interpolants[ j ].evaluate( clipTime );
  27255. propertyMixers[ j ].accumulate( accuIndex, weight );
  27256. }
  27257. }
  27258. },
  27259. _updateWeight: function( time ) {
  27260. var weight = 0;
  27261. if ( this.enabled ) {
  27262. weight = this.weight;
  27263. var interpolant = this._weightInterpolant;
  27264. if ( interpolant !== null ) {
  27265. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  27266. weight *= interpolantValue;
  27267. if ( time > interpolant.parameterPositions[ 1 ] ) {
  27268. this.stopFading();
  27269. if ( interpolantValue === 0 ) {
  27270. // faded out, disable
  27271. this.enabled = false;
  27272. }
  27273. }
  27274. }
  27275. }
  27276. this._effectiveWeight = weight;
  27277. return weight;
  27278. },
  27279. _updateTimeScale: function( time ) {
  27280. var timeScale = 0;
  27281. if ( ! this.paused ) {
  27282. timeScale = this.timeScale;
  27283. var interpolant = this._timeScaleInterpolant;
  27284. if ( interpolant !== null ) {
  27285. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  27286. timeScale *= interpolantValue;
  27287. if ( time > interpolant.parameterPositions[ 1 ] ) {
  27288. this.stopWarping();
  27289. if ( timeScale === 0 ) {
  27290. // motion has halted, pause
  27291. this.paused = true;
  27292. } else {
  27293. // warp done - apply final time scale
  27294. this.timeScale = timeScale;
  27295. }
  27296. }
  27297. }
  27298. }
  27299. this._effectiveTimeScale = timeScale;
  27300. return timeScale;
  27301. },
  27302. _updateTime: function( deltaTime ) {
  27303. var time = this.time + deltaTime;
  27304. if ( deltaTime === 0 ) return time;
  27305. var duration = this._clip.duration,
  27306. loop = this.loop,
  27307. loopCount = this._loopCount;
  27308. if ( loop === LoopOnce ) {
  27309. if ( loopCount === -1 ) {
  27310. // just started
  27311. this._loopCount = 0;
  27312. this._setEndings( true, true, false );
  27313. }
  27314. handle_stop: {
  27315. if ( time >= duration ) {
  27316. time = duration;
  27317. } else if ( time < 0 ) {
  27318. time = 0;
  27319. } else break handle_stop;
  27320. if ( this.clampWhenFinished ) this.paused = true;
  27321. else this.enabled = false;
  27322. this._mixer.dispatchEvent( {
  27323. type: 'finished', action: this,
  27324. direction: deltaTime < 0 ? -1 : 1
  27325. } );
  27326. }
  27327. } else { // repetitive Repeat or PingPong
  27328. var pingPong = ( loop === LoopPingPong );
  27329. if ( loopCount === -1 ) {
  27330. // just started
  27331. if ( deltaTime >= 0 ) {
  27332. loopCount = 0;
  27333. this._setEndings(
  27334. true, this.repetitions === 0, pingPong );
  27335. } else {
  27336. // when looping in reverse direction, the initial
  27337. // transition through zero counts as a repetition,
  27338. // so leave loopCount at -1
  27339. this._setEndings(
  27340. this.repetitions === 0, true, pingPong );
  27341. }
  27342. }
  27343. if ( time >= duration || time < 0 ) {
  27344. // wrap around
  27345. var loopDelta = Math.floor( time / duration ); // signed
  27346. time -= duration * loopDelta;
  27347. loopCount += Math.abs( loopDelta );
  27348. var pending = this.repetitions - loopCount;
  27349. if ( pending < 0 ) {
  27350. // have to stop (switch state, clamp time, fire event)
  27351. if ( this.clampWhenFinished ) this.paused = true;
  27352. else this.enabled = false;
  27353. time = deltaTime > 0 ? duration : 0;
  27354. this._mixer.dispatchEvent( {
  27355. type: 'finished', action: this,
  27356. direction: deltaTime > 0 ? 1 : -1
  27357. } );
  27358. } else {
  27359. // keep running
  27360. if ( pending === 0 ) {
  27361. // entering the last round
  27362. var atStart = deltaTime < 0;
  27363. this._setEndings( atStart, ! atStart, pingPong );
  27364. } else {
  27365. this._setEndings( false, false, pingPong );
  27366. }
  27367. this._loopCount = loopCount;
  27368. this._mixer.dispatchEvent( {
  27369. type: 'loop', action: this, loopDelta: loopDelta
  27370. } );
  27371. }
  27372. }
  27373. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  27374. // invert time for the "pong round"
  27375. this.time = time;
  27376. return duration - time;
  27377. }
  27378. }
  27379. this.time = time;
  27380. return time;
  27381. },
  27382. _setEndings: function( atStart, atEnd, pingPong ) {
  27383. var settings = this._interpolantSettings;
  27384. if ( pingPong ) {
  27385. settings.endingStart = ZeroSlopeEnding;
  27386. settings.endingEnd = ZeroSlopeEnding;
  27387. } else {
  27388. // assuming for LoopOnce atStart == atEnd == true
  27389. if ( atStart ) {
  27390. settings.endingStart = this.zeroSlopeAtStart ?
  27391. ZeroSlopeEnding : ZeroCurvatureEnding;
  27392. } else {
  27393. settings.endingStart = WrapAroundEnding;
  27394. }
  27395. if ( atEnd ) {
  27396. settings.endingEnd = this.zeroSlopeAtEnd ?
  27397. ZeroSlopeEnding : ZeroCurvatureEnding;
  27398. } else {
  27399. settings.endingEnd = WrapAroundEnding;
  27400. }
  27401. }
  27402. },
  27403. _scheduleFading: function( duration, weightNow, weightThen ) {
  27404. var mixer = this._mixer, now = mixer.time,
  27405. interpolant = this._weightInterpolant;
  27406. if ( interpolant === null ) {
  27407. interpolant = mixer._lendControlInterpolant();
  27408. this._weightInterpolant = interpolant;
  27409. }
  27410. var times = interpolant.parameterPositions,
  27411. values = interpolant.sampleValues;
  27412. times[ 0 ] = now; values[ 0 ] = weightNow;
  27413. times[ 1 ] = now + duration; values[ 1 ] = weightThen;
  27414. return this;
  27415. }
  27416. };
  27417. /**
  27418. *
  27419. * Player for AnimationClips.
  27420. *
  27421. *
  27422. * @author Ben Houston / http://clara.io/
  27423. * @author David Sarno / http://lighthaus.us/
  27424. * @author tschw
  27425. */
  27426. function AnimationMixer( root ) {
  27427. this._root = root;
  27428. this._initMemoryManager();
  27429. this._accuIndex = 0;
  27430. this.time = 0;
  27431. this.timeScale = 1.0;
  27432. }
  27433. AnimationMixer.prototype = {
  27434. constructor: AnimationMixer,
  27435. // return an action for a clip optionally using a custom root target
  27436. // object (this method allocates a lot of dynamic memory in case a
  27437. // previously unknown clip/root combination is specified)
  27438. clipAction: function ( clip, optionalRoot ) {
  27439. var root = optionalRoot || this._root,
  27440. rootUuid = root.uuid,
  27441. clipObject = typeof clip === 'string' ?
  27442. AnimationClip.findByName( root, clip ) : clip,
  27443. clipUuid = clipObject !== null ? clipObject.uuid : clip,
  27444. actionsForClip = this._actionsByClip[ clipUuid ],
  27445. prototypeAction = null;
  27446. if ( actionsForClip !== undefined ) {
  27447. var existingAction =
  27448. actionsForClip.actionByRoot[ rootUuid ];
  27449. if ( existingAction !== undefined ) {
  27450. return existingAction;
  27451. }
  27452. // we know the clip, so we don't have to parse all
  27453. // the bindings again but can just copy
  27454. prototypeAction = actionsForClip.knownActions[ 0 ];
  27455. // also, take the clip from the prototype action
  27456. if ( clipObject === null )
  27457. clipObject = prototypeAction._clip;
  27458. }
  27459. // clip must be known when specified via string
  27460. if ( clipObject === null ) return null;
  27461. // allocate all resources required to run it
  27462. var newAction = new AnimationAction( this, clipObject, optionalRoot );
  27463. this._bindAction( newAction, prototypeAction );
  27464. // and make the action known to the memory manager
  27465. this._addInactiveAction( newAction, clipUuid, rootUuid );
  27466. return newAction;
  27467. },
  27468. // get an existing action
  27469. existingAction: function ( clip, optionalRoot ) {
  27470. var root = optionalRoot || this._root,
  27471. rootUuid = root.uuid,
  27472. clipObject = typeof clip === 'string' ?
  27473. AnimationClip.findByName( root, clip ) : clip,
  27474. clipUuid = clipObject ? clipObject.uuid : clip,
  27475. actionsForClip = this._actionsByClip[ clipUuid ];
  27476. if ( actionsForClip !== undefined ) {
  27477. return actionsForClip.actionByRoot[ rootUuid ] || null;
  27478. }
  27479. return null;
  27480. },
  27481. // deactivates all previously scheduled actions
  27482. stopAllAction: function () {
  27483. var actions = this._actions,
  27484. nActions = this._nActiveActions,
  27485. bindings = this._bindings,
  27486. nBindings = this._nActiveBindings;
  27487. this._nActiveActions = 0;
  27488. this._nActiveBindings = 0;
  27489. for ( var i = 0; i !== nActions; ++ i ) {
  27490. actions[ i ].reset();
  27491. }
  27492. for ( var i = 0; i !== nBindings; ++ i ) {
  27493. bindings[ i ].useCount = 0;
  27494. }
  27495. return this;
  27496. },
  27497. // advance the time and update apply the animation
  27498. update: function ( deltaTime ) {
  27499. deltaTime *= this.timeScale;
  27500. var actions = this._actions,
  27501. nActions = this._nActiveActions,
  27502. time = this.time += deltaTime,
  27503. timeDirection = Math.sign( deltaTime ),
  27504. accuIndex = this._accuIndex ^= 1;
  27505. // run active actions
  27506. for ( var i = 0; i !== nActions; ++ i ) {
  27507. var action = actions[ i ];
  27508. if ( action.enabled ) {
  27509. action._update( time, deltaTime, timeDirection, accuIndex );
  27510. }
  27511. }
  27512. // update scene graph
  27513. var bindings = this._bindings,
  27514. nBindings = this._nActiveBindings;
  27515. for ( var i = 0; i !== nBindings; ++ i ) {
  27516. bindings[ i ].apply( accuIndex );
  27517. }
  27518. return this;
  27519. },
  27520. // return this mixer's root target object
  27521. getRoot: function () {
  27522. return this._root;
  27523. },
  27524. // free all resources specific to a particular clip
  27525. uncacheClip: function ( clip ) {
  27526. var actions = this._actions,
  27527. clipUuid = clip.uuid,
  27528. actionsByClip = this._actionsByClip,
  27529. actionsForClip = actionsByClip[ clipUuid ];
  27530. if ( actionsForClip !== undefined ) {
  27531. // note: just calling _removeInactiveAction would mess up the
  27532. // iteration state and also require updating the state we can
  27533. // just throw away
  27534. var actionsToRemove = actionsForClip.knownActions;
  27535. for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  27536. var action = actionsToRemove[ i ];
  27537. this._deactivateAction( action );
  27538. var cacheIndex = action._cacheIndex,
  27539. lastInactiveAction = actions[ actions.length - 1 ];
  27540. action._cacheIndex = null;
  27541. action._byClipCacheIndex = null;
  27542. lastInactiveAction._cacheIndex = cacheIndex;
  27543. actions[ cacheIndex ] = lastInactiveAction;
  27544. actions.pop();
  27545. this._removeInactiveBindingsForAction( action );
  27546. }
  27547. delete actionsByClip[ clipUuid ];
  27548. }
  27549. },
  27550. // free all resources specific to a particular root target object
  27551. uncacheRoot: function ( root ) {
  27552. var rootUuid = root.uuid,
  27553. actionsByClip = this._actionsByClip;
  27554. for ( var clipUuid in actionsByClip ) {
  27555. var actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  27556. action = actionByRoot[ rootUuid ];
  27557. if ( action !== undefined ) {
  27558. this._deactivateAction( action );
  27559. this._removeInactiveAction( action );
  27560. }
  27561. }
  27562. var bindingsByRoot = this._bindingsByRootAndName,
  27563. bindingByName = bindingsByRoot[ rootUuid ];
  27564. if ( bindingByName !== undefined ) {
  27565. for ( var trackName in bindingByName ) {
  27566. var binding = bindingByName[ trackName ];
  27567. binding.restoreOriginalState();
  27568. this._removeInactiveBinding( binding );
  27569. }
  27570. }
  27571. },
  27572. // remove a targeted clip from the cache
  27573. uncacheAction: function ( clip, optionalRoot ) {
  27574. var action = this.existingAction( clip, optionalRoot );
  27575. if ( action !== null ) {
  27576. this._deactivateAction( action );
  27577. this._removeInactiveAction( action );
  27578. }
  27579. }
  27580. };
  27581. // Implementation details:
  27582. Object.assign( AnimationMixer.prototype, {
  27583. _bindAction: function ( action, prototypeAction ) {
  27584. var root = action._localRoot || this._root,
  27585. tracks = action._clip.tracks,
  27586. nTracks = tracks.length,
  27587. bindings = action._propertyBindings,
  27588. interpolants = action._interpolants,
  27589. rootUuid = root.uuid,
  27590. bindingsByRoot = this._bindingsByRootAndName,
  27591. bindingsByName = bindingsByRoot[ rootUuid ];
  27592. if ( bindingsByName === undefined ) {
  27593. bindingsByName = {};
  27594. bindingsByRoot[ rootUuid ] = bindingsByName;
  27595. }
  27596. for ( var i = 0; i !== nTracks; ++ i ) {
  27597. var track = tracks[ i ],
  27598. trackName = track.name,
  27599. binding = bindingsByName[ trackName ];
  27600. if ( binding !== undefined ) {
  27601. bindings[ i ] = binding;
  27602. } else {
  27603. binding = bindings[ i ];
  27604. if ( binding !== undefined ) {
  27605. // existing binding, make sure the cache knows
  27606. if ( binding._cacheIndex === null ) {
  27607. ++ binding.referenceCount;
  27608. this._addInactiveBinding( binding, rootUuid, trackName );
  27609. }
  27610. continue;
  27611. }
  27612. var path = prototypeAction && prototypeAction.
  27613. _propertyBindings[ i ].binding.parsedPath;
  27614. binding = new PropertyMixer(
  27615. PropertyBinding.create( root, trackName, path ),
  27616. track.ValueTypeName, track.getValueSize() );
  27617. ++ binding.referenceCount;
  27618. this._addInactiveBinding( binding, rootUuid, trackName );
  27619. bindings[ i ] = binding;
  27620. }
  27621. interpolants[ i ].resultBuffer = binding.buffer;
  27622. }
  27623. },
  27624. _activateAction: function ( action ) {
  27625. if ( ! this._isActiveAction( action ) ) {
  27626. if ( action._cacheIndex === null ) {
  27627. // this action has been forgotten by the cache, but the user
  27628. // appears to be still using it -> rebind
  27629. var rootUuid = ( action._localRoot || this._root ).uuid,
  27630. clipUuid = action._clip.uuid,
  27631. actionsForClip = this._actionsByClip[ clipUuid ];
  27632. this._bindAction( action,
  27633. actionsForClip && actionsForClip.knownActions[ 0 ] );
  27634. this._addInactiveAction( action, clipUuid, rootUuid );
  27635. }
  27636. var bindings = action._propertyBindings;
  27637. // increment reference counts / sort out state
  27638. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  27639. var binding = bindings[ i ];
  27640. if ( binding.useCount ++ === 0 ) {
  27641. this._lendBinding( binding );
  27642. binding.saveOriginalState();
  27643. }
  27644. }
  27645. this._lendAction( action );
  27646. }
  27647. },
  27648. _deactivateAction: function ( action ) {
  27649. if ( this._isActiveAction( action ) ) {
  27650. var bindings = action._propertyBindings;
  27651. // decrement reference counts / sort out state
  27652. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  27653. var binding = bindings[ i ];
  27654. if ( -- binding.useCount === 0 ) {
  27655. binding.restoreOriginalState();
  27656. this._takeBackBinding( binding );
  27657. }
  27658. }
  27659. this._takeBackAction( action );
  27660. }
  27661. },
  27662. // Memory manager
  27663. _initMemoryManager: function () {
  27664. this._actions = []; // 'nActiveActions' followed by inactive ones
  27665. this._nActiveActions = 0;
  27666. this._actionsByClip = {};
  27667. // inside:
  27668. // {
  27669. // knownActions: Array< AnimationAction > - used as prototypes
  27670. // actionByRoot: AnimationAction - lookup
  27671. // }
  27672. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  27673. this._nActiveBindings = 0;
  27674. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  27675. this._controlInterpolants = []; // same game as above
  27676. this._nActiveControlInterpolants = 0;
  27677. var scope = this;
  27678. this.stats = {
  27679. actions: {
  27680. get total() { return scope._actions.length; },
  27681. get inUse() { return scope._nActiveActions; }
  27682. },
  27683. bindings: {
  27684. get total() { return scope._bindings.length; },
  27685. get inUse() { return scope._nActiveBindings; }
  27686. },
  27687. controlInterpolants: {
  27688. get total() { return scope._controlInterpolants.length; },
  27689. get inUse() { return scope._nActiveControlInterpolants; }
  27690. }
  27691. };
  27692. },
  27693. // Memory management for AnimationAction objects
  27694. _isActiveAction: function ( action ) {
  27695. var index = action._cacheIndex;
  27696. return index !== null && index < this._nActiveActions;
  27697. },
  27698. _addInactiveAction: function ( action, clipUuid, rootUuid ) {
  27699. var actions = this._actions,
  27700. actionsByClip = this._actionsByClip,
  27701. actionsForClip = actionsByClip[ clipUuid ];
  27702. if ( actionsForClip === undefined ) {
  27703. actionsForClip = {
  27704. knownActions: [ action ],
  27705. actionByRoot: {}
  27706. };
  27707. action._byClipCacheIndex = 0;
  27708. actionsByClip[ clipUuid ] = actionsForClip;
  27709. } else {
  27710. var knownActions = actionsForClip.knownActions;
  27711. action._byClipCacheIndex = knownActions.length;
  27712. knownActions.push( action );
  27713. }
  27714. action._cacheIndex = actions.length;
  27715. actions.push( action );
  27716. actionsForClip.actionByRoot[ rootUuid ] = action;
  27717. },
  27718. _removeInactiveAction: function ( action ) {
  27719. var actions = this._actions,
  27720. lastInactiveAction = actions[ actions.length - 1 ],
  27721. cacheIndex = action._cacheIndex;
  27722. lastInactiveAction._cacheIndex = cacheIndex;
  27723. actions[ cacheIndex ] = lastInactiveAction;
  27724. actions.pop();
  27725. action._cacheIndex = null;
  27726. var clipUuid = action._clip.uuid,
  27727. actionsByClip = this._actionsByClip,
  27728. actionsForClip = actionsByClip[ clipUuid ],
  27729. knownActionsForClip = actionsForClip.knownActions,
  27730. lastKnownAction =
  27731. knownActionsForClip[ knownActionsForClip.length - 1 ],
  27732. byClipCacheIndex = action._byClipCacheIndex;
  27733. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  27734. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  27735. knownActionsForClip.pop();
  27736. action._byClipCacheIndex = null;
  27737. var actionByRoot = actionsForClip.actionByRoot,
  27738. rootUuid = ( actions._localRoot || this._root ).uuid;
  27739. delete actionByRoot[ rootUuid ];
  27740. if ( knownActionsForClip.length === 0 ) {
  27741. delete actionsByClip[ clipUuid ];
  27742. }
  27743. this._removeInactiveBindingsForAction( action );
  27744. },
  27745. _removeInactiveBindingsForAction: function ( action ) {
  27746. var bindings = action._propertyBindings;
  27747. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  27748. var binding = bindings[ i ];
  27749. if ( -- binding.referenceCount === 0 ) {
  27750. this._removeInactiveBinding( binding );
  27751. }
  27752. }
  27753. },
  27754. _lendAction: function ( action ) {
  27755. // [ active actions | inactive actions ]
  27756. // [ active actions >| inactive actions ]
  27757. // s a
  27758. // <-swap->
  27759. // a s
  27760. var actions = this._actions,
  27761. prevIndex = action._cacheIndex,
  27762. lastActiveIndex = this._nActiveActions ++,
  27763. firstInactiveAction = actions[ lastActiveIndex ];
  27764. action._cacheIndex = lastActiveIndex;
  27765. actions[ lastActiveIndex ] = action;
  27766. firstInactiveAction._cacheIndex = prevIndex;
  27767. actions[ prevIndex ] = firstInactiveAction;
  27768. },
  27769. _takeBackAction: function ( action ) {
  27770. // [ active actions | inactive actions ]
  27771. // [ active actions |< inactive actions ]
  27772. // a s
  27773. // <-swap->
  27774. // s a
  27775. var actions = this._actions,
  27776. prevIndex = action._cacheIndex,
  27777. firstInactiveIndex = -- this._nActiveActions,
  27778. lastActiveAction = actions[ firstInactiveIndex ];
  27779. action._cacheIndex = firstInactiveIndex;
  27780. actions[ firstInactiveIndex ] = action;
  27781. lastActiveAction._cacheIndex = prevIndex;
  27782. actions[ prevIndex ] = lastActiveAction;
  27783. },
  27784. // Memory management for PropertyMixer objects
  27785. _addInactiveBinding: function ( binding, rootUuid, trackName ) {
  27786. var bindingsByRoot = this._bindingsByRootAndName,
  27787. bindingByName = bindingsByRoot[ rootUuid ],
  27788. bindings = this._bindings;
  27789. if ( bindingByName === undefined ) {
  27790. bindingByName = {};
  27791. bindingsByRoot[ rootUuid ] = bindingByName;
  27792. }
  27793. bindingByName[ trackName ] = binding;
  27794. binding._cacheIndex = bindings.length;
  27795. bindings.push( binding );
  27796. },
  27797. _removeInactiveBinding: function ( binding ) {
  27798. var bindings = this._bindings,
  27799. propBinding = binding.binding,
  27800. rootUuid = propBinding.rootNode.uuid,
  27801. trackName = propBinding.path,
  27802. bindingsByRoot = this._bindingsByRootAndName,
  27803. bindingByName = bindingsByRoot[ rootUuid ],
  27804. lastInactiveBinding = bindings[ bindings.length - 1 ],
  27805. cacheIndex = binding._cacheIndex;
  27806. lastInactiveBinding._cacheIndex = cacheIndex;
  27807. bindings[ cacheIndex ] = lastInactiveBinding;
  27808. bindings.pop();
  27809. delete bindingByName[ trackName ];
  27810. remove_empty_map: {
  27811. for ( var _ in bindingByName ) break remove_empty_map;
  27812. delete bindingsByRoot[ rootUuid ];
  27813. }
  27814. },
  27815. _lendBinding: function ( binding ) {
  27816. var bindings = this._bindings,
  27817. prevIndex = binding._cacheIndex,
  27818. lastActiveIndex = this._nActiveBindings ++,
  27819. firstInactiveBinding = bindings[ lastActiveIndex ];
  27820. binding._cacheIndex = lastActiveIndex;
  27821. bindings[ lastActiveIndex ] = binding;
  27822. firstInactiveBinding._cacheIndex = prevIndex;
  27823. bindings[ prevIndex ] = firstInactiveBinding;
  27824. },
  27825. _takeBackBinding: function ( binding ) {
  27826. var bindings = this._bindings,
  27827. prevIndex = binding._cacheIndex,
  27828. firstInactiveIndex = -- this._nActiveBindings,
  27829. lastActiveBinding = bindings[ firstInactiveIndex ];
  27830. binding._cacheIndex = firstInactiveIndex;
  27831. bindings[ firstInactiveIndex ] = binding;
  27832. lastActiveBinding._cacheIndex = prevIndex;
  27833. bindings[ prevIndex ] = lastActiveBinding;
  27834. },
  27835. // Memory management of Interpolants for weight and time scale
  27836. _lendControlInterpolant: function () {
  27837. var interpolants = this._controlInterpolants,
  27838. lastActiveIndex = this._nActiveControlInterpolants ++,
  27839. interpolant = interpolants[ lastActiveIndex ];
  27840. if ( interpolant === undefined ) {
  27841. interpolant = new LinearInterpolant(
  27842. new Float32Array( 2 ), new Float32Array( 2 ),
  27843. 1, this._controlInterpolantsResultBuffer );
  27844. interpolant.__cacheIndex = lastActiveIndex;
  27845. interpolants[ lastActiveIndex ] = interpolant;
  27846. }
  27847. return interpolant;
  27848. },
  27849. _takeBackControlInterpolant: function ( interpolant ) {
  27850. var interpolants = this._controlInterpolants,
  27851. prevIndex = interpolant.__cacheIndex,
  27852. firstInactiveIndex = -- this._nActiveControlInterpolants,
  27853. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  27854. interpolant.__cacheIndex = firstInactiveIndex;
  27855. interpolants[ firstInactiveIndex ] = interpolant;
  27856. lastActiveInterpolant.__cacheIndex = prevIndex;
  27857. interpolants[ prevIndex ] = lastActiveInterpolant;
  27858. },
  27859. _controlInterpolantsResultBuffer: new Float32Array( 1 )
  27860. } );
  27861. Object.assign( AnimationMixer.prototype, EventDispatcher.prototype );
  27862. /**
  27863. * @author mrdoob / http://mrdoob.com/
  27864. */
  27865. function Uniform( value ) {
  27866. if ( typeof value === 'string' ) {
  27867. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  27868. value = arguments[ 1 ];
  27869. }
  27870. this.value = value;
  27871. }
  27872. Uniform.prototype.clone = function () {
  27873. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  27874. };
  27875. /**
  27876. * @author benaadams / https://twitter.com/ben_a_adams
  27877. */
  27878. function InstancedBufferGeometry() {
  27879. BufferGeometry.call( this );
  27880. this.type = 'InstancedBufferGeometry';
  27881. this.maxInstancedCount = undefined;
  27882. }
  27883. InstancedBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  27884. InstancedBufferGeometry.prototype.constructor = InstancedBufferGeometry;
  27885. InstancedBufferGeometry.prototype.isInstancedBufferGeometry = true;
  27886. InstancedBufferGeometry.prototype.addGroup = function ( start, count, materialIndex ) {
  27887. this.groups.push( {
  27888. start: start,
  27889. count: count,
  27890. materialIndex: materialIndex
  27891. } );
  27892. };
  27893. InstancedBufferGeometry.prototype.copy = function ( source ) {
  27894. var index = source.index;
  27895. if ( index !== null ) {
  27896. this.setIndex( index.clone() );
  27897. }
  27898. var attributes = source.attributes;
  27899. for ( var name in attributes ) {
  27900. var attribute = attributes[ name ];
  27901. this.addAttribute( name, attribute.clone() );
  27902. }
  27903. var groups = source.groups;
  27904. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  27905. var group = groups[ i ];
  27906. this.addGroup( group.start, group.count, group.materialIndex );
  27907. }
  27908. return this;
  27909. };
  27910. /**
  27911. * @author benaadams / https://twitter.com/ben_a_adams
  27912. */
  27913. function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) {
  27914. this.uuid = _Math.generateUUID();
  27915. this.data = interleavedBuffer;
  27916. this.itemSize = itemSize;
  27917. this.offset = offset;
  27918. this.normalized = normalized === true;
  27919. }
  27920. InterleavedBufferAttribute.prototype = {
  27921. constructor: InterleavedBufferAttribute,
  27922. isInterleavedBufferAttribute: true,
  27923. get count() {
  27924. return this.data.count;
  27925. },
  27926. get array() {
  27927. return this.data.array;
  27928. },
  27929. setX: function ( index, x ) {
  27930. this.data.array[ index * this.data.stride + this.offset ] = x;
  27931. return this;
  27932. },
  27933. setY: function ( index, y ) {
  27934. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  27935. return this;
  27936. },
  27937. setZ: function ( index, z ) {
  27938. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  27939. return this;
  27940. },
  27941. setW: function ( index, w ) {
  27942. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  27943. return this;
  27944. },
  27945. getX: function ( index ) {
  27946. return this.data.array[ index * this.data.stride + this.offset ];
  27947. },
  27948. getY: function ( index ) {
  27949. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  27950. },
  27951. getZ: function ( index ) {
  27952. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  27953. },
  27954. getW: function ( index ) {
  27955. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  27956. },
  27957. setXY: function ( index, x, y ) {
  27958. index = index * this.data.stride + this.offset;
  27959. this.data.array[ index + 0 ] = x;
  27960. this.data.array[ index + 1 ] = y;
  27961. return this;
  27962. },
  27963. setXYZ: function ( index, x, y, z ) {
  27964. index = index * this.data.stride + this.offset;
  27965. this.data.array[ index + 0 ] = x;
  27966. this.data.array[ index + 1 ] = y;
  27967. this.data.array[ index + 2 ] = z;
  27968. return this;
  27969. },
  27970. setXYZW: function ( index, x, y, z, w ) {
  27971. index = index * this.data.stride + this.offset;
  27972. this.data.array[ index + 0 ] = x;
  27973. this.data.array[ index + 1 ] = y;
  27974. this.data.array[ index + 2 ] = z;
  27975. this.data.array[ index + 3 ] = w;
  27976. return this;
  27977. }
  27978. };
  27979. /**
  27980. * @author benaadams / https://twitter.com/ben_a_adams
  27981. */
  27982. function InterleavedBuffer( array, stride ) {
  27983. this.uuid = _Math.generateUUID();
  27984. this.array = array;
  27985. this.stride = stride;
  27986. this.count = array !== undefined ? array.length / stride : 0;
  27987. this.dynamic = false;
  27988. this.updateRange = { offset: 0, count: - 1 };
  27989. this.onUploadCallback = function () {};
  27990. this.version = 0;
  27991. }
  27992. InterleavedBuffer.prototype = {
  27993. constructor: InterleavedBuffer,
  27994. isInterleavedBuffer: true,
  27995. set needsUpdate( value ) {
  27996. if ( value === true ) this.version ++;
  27997. },
  27998. setArray: function ( array ) {
  27999. if ( Array.isArray( array ) ) {
  28000. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  28001. }
  28002. this.count = array !== undefined ? array.length / this.stride : 0;
  28003. this.array = array;
  28004. },
  28005. setDynamic: function ( value ) {
  28006. this.dynamic = value;
  28007. return this;
  28008. },
  28009. copy: function ( source ) {
  28010. this.array = new source.array.constructor( source.array );
  28011. this.count = source.count;
  28012. this.stride = source.stride;
  28013. this.dynamic = source.dynamic;
  28014. return this;
  28015. },
  28016. copyAt: function ( index1, attribute, index2 ) {
  28017. index1 *= this.stride;
  28018. index2 *= attribute.stride;
  28019. for ( var i = 0, l = this.stride; i < l; i ++ ) {
  28020. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  28021. }
  28022. return this;
  28023. },
  28024. set: function ( value, offset ) {
  28025. if ( offset === undefined ) offset = 0;
  28026. this.array.set( value, offset );
  28027. return this;
  28028. },
  28029. clone: function () {
  28030. return new this.constructor().copy( this );
  28031. },
  28032. onUpload: function ( callback ) {
  28033. this.onUploadCallback = callback;
  28034. return this;
  28035. }
  28036. };
  28037. /**
  28038. * @author benaadams / https://twitter.com/ben_a_adams
  28039. */
  28040. function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) {
  28041. InterleavedBuffer.call( this, array, stride );
  28042. this.meshPerAttribute = meshPerAttribute || 1;
  28043. }
  28044. InstancedInterleavedBuffer.prototype = Object.create( InterleavedBuffer.prototype );
  28045. InstancedInterleavedBuffer.prototype.constructor = InstancedInterleavedBuffer;
  28046. InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true;
  28047. InstancedInterleavedBuffer.prototype.copy = function ( source ) {
  28048. InterleavedBuffer.prototype.copy.call( this, source );
  28049. this.meshPerAttribute = source.meshPerAttribute;
  28050. return this;
  28051. };
  28052. /**
  28053. * @author benaadams / https://twitter.com/ben_a_adams
  28054. */
  28055. function InstancedBufferAttribute( array, itemSize, meshPerAttribute ) {
  28056. BufferAttribute.call( this, array, itemSize );
  28057. this.meshPerAttribute = meshPerAttribute || 1;
  28058. }
  28059. InstancedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  28060. InstancedBufferAttribute.prototype.constructor = InstancedBufferAttribute;
  28061. InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true;
  28062. InstancedBufferAttribute.prototype.copy = function ( source ) {
  28063. BufferAttribute.prototype.copy.call( this, source );
  28064. this.meshPerAttribute = source.meshPerAttribute;
  28065. return this;
  28066. };
  28067. /**
  28068. * @author mrdoob / http://mrdoob.com/
  28069. * @author bhouston / http://clara.io/
  28070. * @author stephomi / http://stephaneginier.com/
  28071. */
  28072. function Raycaster( origin, direction, near, far ) {
  28073. this.ray = new Ray( origin, direction );
  28074. // direction is assumed to be normalized (for accurate distance calculations)
  28075. this.near = near || 0;
  28076. this.far = far || Infinity;
  28077. this.params = {
  28078. Mesh: {},
  28079. Line: {},
  28080. LOD: {},
  28081. Points: { threshold: 1 },
  28082. Sprite: {}
  28083. };
  28084. Object.defineProperties( this.params, {
  28085. PointCloud: {
  28086. get: function () {
  28087. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  28088. return this.Points;
  28089. }
  28090. }
  28091. } );
  28092. }
  28093. function ascSort( a, b ) {
  28094. return a.distance - b.distance;
  28095. }
  28096. function intersectObject( object, raycaster, intersects, recursive ) {
  28097. if ( object.visible === false ) return;
  28098. object.raycast( raycaster, intersects );
  28099. if ( recursive === true ) {
  28100. var children = object.children;
  28101. for ( var i = 0, l = children.length; i < l; i ++ ) {
  28102. intersectObject( children[ i ], raycaster, intersects, true );
  28103. }
  28104. }
  28105. }
  28106. //
  28107. Raycaster.prototype = {
  28108. constructor: Raycaster,
  28109. linePrecision: 1,
  28110. set: function ( origin, direction ) {
  28111. // direction is assumed to be normalized (for accurate distance calculations)
  28112. this.ray.set( origin, direction );
  28113. },
  28114. setFromCamera: function ( coords, camera ) {
  28115. if ( (camera && camera.isPerspectiveCamera) ) {
  28116. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  28117. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  28118. } else if ( (camera && camera.isOrthographicCamera) ) {
  28119. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  28120. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  28121. } else {
  28122. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  28123. }
  28124. },
  28125. intersectObject: function ( object, recursive ) {
  28126. var intersects = [];
  28127. intersectObject( object, this, intersects, recursive );
  28128. intersects.sort( ascSort );
  28129. return intersects;
  28130. },
  28131. intersectObjects: function ( objects, recursive ) {
  28132. var intersects = [];
  28133. if ( Array.isArray( objects ) === false ) {
  28134. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  28135. return intersects;
  28136. }
  28137. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  28138. intersectObject( objects[ i ], this, intersects, recursive );
  28139. }
  28140. intersects.sort( ascSort );
  28141. return intersects;
  28142. }
  28143. };
  28144. /**
  28145. * @author alteredq / http://alteredqualia.com/
  28146. */
  28147. function Clock( autoStart ) {
  28148. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  28149. this.startTime = 0;
  28150. this.oldTime = 0;
  28151. this.elapsedTime = 0;
  28152. this.running = false;
  28153. }
  28154. Clock.prototype = {
  28155. constructor: Clock,
  28156. start: function () {
  28157. this.startTime = ( performance || Date ).now();
  28158. this.oldTime = this.startTime;
  28159. this.elapsedTime = 0;
  28160. this.running = true;
  28161. },
  28162. stop: function () {
  28163. this.getElapsedTime();
  28164. this.running = false;
  28165. },
  28166. getElapsedTime: function () {
  28167. this.getDelta();
  28168. return this.elapsedTime;
  28169. },
  28170. getDelta: function () {
  28171. var diff = 0;
  28172. if ( this.autoStart && ! this.running ) {
  28173. this.start();
  28174. }
  28175. if ( this.running ) {
  28176. var newTime = ( performance || Date ).now();
  28177. diff = ( newTime - this.oldTime ) / 1000;
  28178. this.oldTime = newTime;
  28179. this.elapsedTime += diff;
  28180. }
  28181. return diff;
  28182. }
  28183. };
  28184. /**
  28185. * @author bhouston / http://clara.io
  28186. * @author WestLangley / http://github.com/WestLangley
  28187. *
  28188. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  28189. *
  28190. * The poles (phi) are at the positive and negative y axis.
  28191. * The equator starts at positive z.
  28192. */
  28193. function Spherical( radius, phi, theta ) {
  28194. this.radius = ( radius !== undefined ) ? radius : 1.0;
  28195. this.phi = ( phi !== undefined ) ? phi : 0; // up / down towards top and bottom pole
  28196. this.theta = ( theta !== undefined ) ? theta : 0; // around the equator of the sphere
  28197. return this;
  28198. }
  28199. Spherical.prototype = {
  28200. constructor: Spherical,
  28201. set: function ( radius, phi, theta ) {
  28202. this.radius = radius;
  28203. this.phi = phi;
  28204. this.theta = theta;
  28205. return this;
  28206. },
  28207. clone: function () {
  28208. return new this.constructor().copy( this );
  28209. },
  28210. copy: function ( other ) {
  28211. this.radius = other.radius;
  28212. this.phi = other.phi;
  28213. this.theta = other.theta;
  28214. return this;
  28215. },
  28216. // restrict phi to be betwee EPS and PI-EPS
  28217. makeSafe: function() {
  28218. var EPS = 0.000001;
  28219. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  28220. return this;
  28221. },
  28222. setFromVector3: function( vec3 ) {
  28223. this.radius = vec3.length();
  28224. if ( this.radius === 0 ) {
  28225. this.theta = 0;
  28226. this.phi = 0;
  28227. } else {
  28228. this.theta = Math.atan2( vec3.x, vec3.z ); // equator angle around y-up axis
  28229. this.phi = Math.acos( _Math.clamp( vec3.y / this.radius, - 1, 1 ) ); // polar angle
  28230. }
  28231. return this;
  28232. }
  28233. };
  28234. /**
  28235. * @author Mugen87 / https://github.com/Mugen87
  28236. *
  28237. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  28238. *
  28239. */
  28240. function Cylindrical( radius, theta, y ) {
  28241. this.radius = ( radius !== undefined ) ? radius : 1.0; // distance from the origin to a point in the x-z plane
  28242. this.theta = ( theta !== undefined ) ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  28243. this.y = ( y !== undefined ) ? y : 0; // height above the x-z plane
  28244. return this;
  28245. }
  28246. Cylindrical.prototype = {
  28247. constructor: Cylindrical,
  28248. set: function ( radius, theta, y ) {
  28249. this.radius = radius;
  28250. this.theta = theta;
  28251. this.y = y;
  28252. return this;
  28253. },
  28254. clone: function () {
  28255. return new this.constructor().copy( this );
  28256. },
  28257. copy: function ( other ) {
  28258. this.radius = other.radius;
  28259. this.theta = other.theta;
  28260. this.y = other.y;
  28261. return this;
  28262. },
  28263. setFromVector3: function( vec3 ) {
  28264. this.radius = Math.sqrt( vec3.x * vec3.x + vec3.z * vec3.z );
  28265. this.theta = Math.atan2( vec3.x, vec3.z );
  28266. this.y = vec3.y;
  28267. return this;
  28268. }
  28269. };
  28270. /**
  28271. * @author alteredq / http://alteredqualia.com/
  28272. */
  28273. function MorphBlendMesh( geometry, material ) {
  28274. Mesh.call( this, geometry, material );
  28275. this.animationsMap = {};
  28276. this.animationsList = [];
  28277. // prepare default animation
  28278. // (all frames played together in 1 second)
  28279. var numFrames = this.geometry.morphTargets.length;
  28280. var name = "__default";
  28281. var startFrame = 0;
  28282. var endFrame = numFrames - 1;
  28283. var fps = numFrames / 1;
  28284. this.createAnimation( name, startFrame, endFrame, fps );
  28285. this.setAnimationWeight( name, 1 );
  28286. }
  28287. MorphBlendMesh.prototype = Object.create( Mesh.prototype );
  28288. MorphBlendMesh.prototype.constructor = MorphBlendMesh;
  28289. MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  28290. var animation = {
  28291. start: start,
  28292. end: end,
  28293. length: end - start + 1,
  28294. fps: fps,
  28295. duration: ( end - start ) / fps,
  28296. lastFrame: 0,
  28297. currentFrame: 0,
  28298. active: false,
  28299. time: 0,
  28300. direction: 1,
  28301. weight: 1,
  28302. directionBackwards: false,
  28303. mirroredLoop: false
  28304. };
  28305. this.animationsMap[ name ] = animation;
  28306. this.animationsList.push( animation );
  28307. };
  28308. MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  28309. var pattern = /([a-z]+)_?(\d+)/i;
  28310. var firstAnimation, frameRanges = {};
  28311. var geometry = this.geometry;
  28312. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  28313. var morph = geometry.morphTargets[ i ];
  28314. var chunks = morph.name.match( pattern );
  28315. if ( chunks && chunks.length > 1 ) {
  28316. var name = chunks[ 1 ];
  28317. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity };
  28318. var range = frameRanges[ name ];
  28319. if ( i < range.start ) range.start = i;
  28320. if ( i > range.end ) range.end = i;
  28321. if ( ! firstAnimation ) firstAnimation = name;
  28322. }
  28323. }
  28324. for ( var name in frameRanges ) {
  28325. var range = frameRanges[ name ];
  28326. this.createAnimation( name, range.start, range.end, fps );
  28327. }
  28328. this.firstAnimation = firstAnimation;
  28329. };
  28330. MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  28331. var animation = this.animationsMap[ name ];
  28332. if ( animation ) {
  28333. animation.direction = 1;
  28334. animation.directionBackwards = false;
  28335. }
  28336. };
  28337. MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  28338. var animation = this.animationsMap[ name ];
  28339. if ( animation ) {
  28340. animation.direction = - 1;
  28341. animation.directionBackwards = true;
  28342. }
  28343. };
  28344. MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  28345. var animation = this.animationsMap[ name ];
  28346. if ( animation ) {
  28347. animation.fps = fps;
  28348. animation.duration = ( animation.end - animation.start ) / animation.fps;
  28349. }
  28350. };
  28351. MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  28352. var animation = this.animationsMap[ name ];
  28353. if ( animation ) {
  28354. animation.duration = duration;
  28355. animation.fps = ( animation.end - animation.start ) / animation.duration;
  28356. }
  28357. };
  28358. MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  28359. var animation = this.animationsMap[ name ];
  28360. if ( animation ) {
  28361. animation.weight = weight;
  28362. }
  28363. };
  28364. MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  28365. var animation = this.animationsMap[ name ];
  28366. if ( animation ) {
  28367. animation.time = time;
  28368. }
  28369. };
  28370. MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  28371. var time = 0;
  28372. var animation = this.animationsMap[ name ];
  28373. if ( animation ) {
  28374. time = animation.time;
  28375. }
  28376. return time;
  28377. };
  28378. MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  28379. var duration = - 1;
  28380. var animation = this.animationsMap[ name ];
  28381. if ( animation ) {
  28382. duration = animation.duration;
  28383. }
  28384. return duration;
  28385. };
  28386. MorphBlendMesh.prototype.playAnimation = function ( name ) {
  28387. var animation = this.animationsMap[ name ];
  28388. if ( animation ) {
  28389. animation.time = 0;
  28390. animation.active = true;
  28391. } else {
  28392. console.warn( "THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()" );
  28393. }
  28394. };
  28395. MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  28396. var animation = this.animationsMap[ name ];
  28397. if ( animation ) {
  28398. animation.active = false;
  28399. }
  28400. };
  28401. MorphBlendMesh.prototype.update = function ( delta ) {
  28402. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  28403. var animation = this.animationsList[ i ];
  28404. if ( ! animation.active ) continue;
  28405. var frameTime = animation.duration / animation.length;
  28406. animation.time += animation.direction * delta;
  28407. if ( animation.mirroredLoop ) {
  28408. if ( animation.time > animation.duration || animation.time < 0 ) {
  28409. animation.direction *= - 1;
  28410. if ( animation.time > animation.duration ) {
  28411. animation.time = animation.duration;
  28412. animation.directionBackwards = true;
  28413. }
  28414. if ( animation.time < 0 ) {
  28415. animation.time = 0;
  28416. animation.directionBackwards = false;
  28417. }
  28418. }
  28419. } else {
  28420. animation.time = animation.time % animation.duration;
  28421. if ( animation.time < 0 ) animation.time += animation.duration;
  28422. }
  28423. var keyframe = animation.start + _Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  28424. var weight = animation.weight;
  28425. if ( keyframe !== animation.currentFrame ) {
  28426. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  28427. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  28428. this.morphTargetInfluences[ keyframe ] = 0;
  28429. animation.lastFrame = animation.currentFrame;
  28430. animation.currentFrame = keyframe;
  28431. }
  28432. var mix = ( animation.time % frameTime ) / frameTime;
  28433. if ( animation.directionBackwards ) mix = 1 - mix;
  28434. if ( animation.currentFrame !== animation.lastFrame ) {
  28435. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  28436. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  28437. } else {
  28438. this.morphTargetInfluences[ animation.currentFrame ] = weight;
  28439. }
  28440. }
  28441. };
  28442. /**
  28443. * @author alteredq / http://alteredqualia.com/
  28444. */
  28445. function ImmediateRenderObject( material ) {
  28446. Object3D.call( this );
  28447. this.material = material;
  28448. this.render = function ( renderCallback ) {};
  28449. }
  28450. ImmediateRenderObject.prototype = Object.create( Object3D.prototype );
  28451. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  28452. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  28453. /**
  28454. * @author mrdoob / http://mrdoob.com/
  28455. * @author WestLangley / http://github.com/WestLangley
  28456. */
  28457. function VertexNormalsHelper( object, size, hex, linewidth ) {
  28458. this.object = object;
  28459. this.size = ( size !== undefined ) ? size : 1;
  28460. var color = ( hex !== undefined ) ? hex : 0xff0000;
  28461. var width = ( linewidth !== undefined ) ? linewidth : 1;
  28462. //
  28463. var nNormals = 0;
  28464. var objGeometry = this.object.geometry;
  28465. if ( objGeometry && objGeometry.isGeometry ) {
  28466. nNormals = objGeometry.faces.length * 3;
  28467. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  28468. nNormals = objGeometry.attributes.normal.count;
  28469. }
  28470. //
  28471. var geometry = new BufferGeometry();
  28472. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  28473. geometry.addAttribute( 'position', positions );
  28474. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  28475. //
  28476. this.matrixAutoUpdate = false;
  28477. this.update();
  28478. }
  28479. VertexNormalsHelper.prototype = Object.create( LineSegments.prototype );
  28480. VertexNormalsHelper.prototype.constructor = VertexNormalsHelper;
  28481. VertexNormalsHelper.prototype.update = ( function () {
  28482. var v1 = new Vector3();
  28483. var v2 = new Vector3();
  28484. var normalMatrix = new Matrix3();
  28485. return function update() {
  28486. var keys = [ 'a', 'b', 'c' ];
  28487. this.object.updateMatrixWorld( true );
  28488. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  28489. var matrixWorld = this.object.matrixWorld;
  28490. var position = this.geometry.attributes.position;
  28491. //
  28492. var objGeometry = this.object.geometry;
  28493. if ( objGeometry && objGeometry.isGeometry ) {
  28494. var vertices = objGeometry.vertices;
  28495. var faces = objGeometry.faces;
  28496. var idx = 0;
  28497. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  28498. var face = faces[ i ];
  28499. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  28500. var vertex = vertices[ face[ keys[ j ] ] ];
  28501. var normal = face.vertexNormals[ j ];
  28502. v1.copy( vertex ).applyMatrix4( matrixWorld );
  28503. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  28504. position.setXYZ( idx, v1.x, v1.y, v1.z );
  28505. idx = idx + 1;
  28506. position.setXYZ( idx, v2.x, v2.y, v2.z );
  28507. idx = idx + 1;
  28508. }
  28509. }
  28510. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  28511. var objPos = objGeometry.attributes.position;
  28512. var objNorm = objGeometry.attributes.normal;
  28513. var idx = 0;
  28514. // for simplicity, ignore index and drawcalls, and render every normal
  28515. for ( var j = 0, jl = objPos.count; j < jl; j ++ ) {
  28516. v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld );
  28517. v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) );
  28518. v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  28519. position.setXYZ( idx, v1.x, v1.y, v1.z );
  28520. idx = idx + 1;
  28521. position.setXYZ( idx, v2.x, v2.y, v2.z );
  28522. idx = idx + 1;
  28523. }
  28524. }
  28525. position.needsUpdate = true;
  28526. return this;
  28527. };
  28528. }() );
  28529. /**
  28530. * @author alteredq / http://alteredqualia.com/
  28531. * @author mrdoob / http://mrdoob.com/
  28532. * @author WestLangley / http://github.com/WestLangley
  28533. */
  28534. function SpotLightHelper( light ) {
  28535. Object3D.call( this );
  28536. this.light = light;
  28537. this.light.updateMatrixWorld();
  28538. this.matrix = light.matrixWorld;
  28539. this.matrixAutoUpdate = false;
  28540. var geometry = new BufferGeometry();
  28541. var positions = [
  28542. 0, 0, 0, 0, 0, 1,
  28543. 0, 0, 0, 1, 0, 1,
  28544. 0, 0, 0, - 1, 0, 1,
  28545. 0, 0, 0, 0, 1, 1,
  28546. 0, 0, 0, 0, - 1, 1
  28547. ];
  28548. for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  28549. var p1 = ( i / l ) * Math.PI * 2;
  28550. var p2 = ( j / l ) * Math.PI * 2;
  28551. positions.push(
  28552. Math.cos( p1 ), Math.sin( p1 ), 1,
  28553. Math.cos( p2 ), Math.sin( p2 ), 1
  28554. );
  28555. }
  28556. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28557. var material = new LineBasicMaterial( { fog: false } );
  28558. this.cone = new LineSegments( geometry, material );
  28559. this.add( this.cone );
  28560. this.update();
  28561. }
  28562. SpotLightHelper.prototype = Object.create( Object3D.prototype );
  28563. SpotLightHelper.prototype.constructor = SpotLightHelper;
  28564. SpotLightHelper.prototype.dispose = function () {
  28565. this.cone.geometry.dispose();
  28566. this.cone.material.dispose();
  28567. };
  28568. SpotLightHelper.prototype.update = function () {
  28569. var vector = new Vector3();
  28570. var vector2 = new Vector3();
  28571. return function update() {
  28572. var coneLength = this.light.distance ? this.light.distance : 1000;
  28573. var coneWidth = coneLength * Math.tan( this.light.angle );
  28574. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  28575. vector.setFromMatrixPosition( this.light.matrixWorld );
  28576. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  28577. this.cone.lookAt( vector2.sub( vector ) );
  28578. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  28579. };
  28580. }();
  28581. /**
  28582. * @author Sean Griffin / http://twitter.com/sgrif
  28583. * @author Michael Guerrero / http://realitymeltdown.com
  28584. * @author mrdoob / http://mrdoob.com/
  28585. * @author ikerr / http://verold.com
  28586. * @author Mugen87 / https://github.com/Mugen87
  28587. */
  28588. function SkeletonHelper( object ) {
  28589. this.bones = this.getBoneList( object );
  28590. var geometry = new BufferGeometry();
  28591. var vertices = [];
  28592. var colors = [];
  28593. var color1 = new Color( 0, 0, 1 );
  28594. var color2 = new Color( 0, 1, 0 );
  28595. for ( var i = 0; i < this.bones.length; i ++ ) {
  28596. var bone = this.bones[ i ];
  28597. if ( bone.parent && bone.parent.isBone ) {
  28598. vertices.push( 0, 0, 0 );
  28599. vertices.push( 0, 0, 0 );
  28600. colors.push( color1.r, color1.g, color1.b );
  28601. colors.push( color2.r, color2.g, color2.b );
  28602. }
  28603. }
  28604. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28605. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28606. var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  28607. LineSegments.call( this, geometry, material );
  28608. this.root = object;
  28609. this.matrix = object.matrixWorld;
  28610. this.matrixAutoUpdate = false;
  28611. this.update();
  28612. }
  28613. SkeletonHelper.prototype = Object.create( LineSegments.prototype );
  28614. SkeletonHelper.prototype.constructor = SkeletonHelper;
  28615. SkeletonHelper.prototype.getBoneList = function( object ) {
  28616. var boneList = [];
  28617. if ( object && object.isBone ) {
  28618. boneList.push( object );
  28619. }
  28620. for ( var i = 0; i < object.children.length; i ++ ) {
  28621. boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) );
  28622. }
  28623. return boneList;
  28624. };
  28625. SkeletonHelper.prototype.update = function () {
  28626. var vector = new Vector3();
  28627. var boneMatrix = new Matrix4();
  28628. var matrixWorldInv = new Matrix4();
  28629. return function update() {
  28630. var geometry = this.geometry;
  28631. var position = geometry.getAttribute( 'position' );
  28632. matrixWorldInv.getInverse( this.root.matrixWorld );
  28633. for ( var i = 0, j = 0; i < this.bones.length; i ++ ) {
  28634. var bone = this.bones[ i ];
  28635. if ( bone.parent && bone.parent.isBone ) {
  28636. boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
  28637. vector.setFromMatrixPosition( boneMatrix );
  28638. position.setXYZ( j, vector.x, vector.y, vector.z );
  28639. boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
  28640. vector.setFromMatrixPosition( boneMatrix );
  28641. position.setXYZ( j + 1, vector.x, vector.y, vector.z );
  28642. j += 2;
  28643. }
  28644. }
  28645. geometry.getAttribute( 'position' ).needsUpdate = true;
  28646. };
  28647. }();
  28648. /**
  28649. * @author alteredq / http://alteredqualia.com/
  28650. * @author mrdoob / http://mrdoob.com/
  28651. */
  28652. function PointLightHelper( light, sphereSize ) {
  28653. this.light = light;
  28654. this.light.updateMatrixWorld();
  28655. var geometry = new SphereBufferGeometry( sphereSize, 4, 2 );
  28656. var material = new MeshBasicMaterial( { wireframe: true, fog: false } );
  28657. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  28658. Mesh.call( this, geometry, material );
  28659. this.matrix = this.light.matrixWorld;
  28660. this.matrixAutoUpdate = false;
  28661. /*
  28662. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  28663. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  28664. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  28665. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  28666. var d = light.distance;
  28667. if ( d === 0.0 ) {
  28668. this.lightDistance.visible = false;
  28669. } else {
  28670. this.lightDistance.scale.set( d, d, d );
  28671. }
  28672. this.add( this.lightDistance );
  28673. */
  28674. }
  28675. PointLightHelper.prototype = Object.create( Mesh.prototype );
  28676. PointLightHelper.prototype.constructor = PointLightHelper;
  28677. PointLightHelper.prototype.dispose = function () {
  28678. this.geometry.dispose();
  28679. this.material.dispose();
  28680. };
  28681. PointLightHelper.prototype.update = function () {
  28682. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  28683. /*
  28684. var d = this.light.distance;
  28685. if ( d === 0.0 ) {
  28686. this.lightDistance.visible = false;
  28687. } else {
  28688. this.lightDistance.visible = true;
  28689. this.lightDistance.scale.set( d, d, d );
  28690. }
  28691. */
  28692. };
  28693. /**
  28694. * @author abelnation / http://github.com/abelnation
  28695. * @author Mugen87 / http://github.com/Mugen87
  28696. */
  28697. function RectAreaLightHelper( light ) {
  28698. Object3D.call( this );
  28699. this.light = light;
  28700. this.light.updateMatrixWorld();
  28701. var materialFront = new MeshBasicMaterial( {
  28702. color: light.color,
  28703. fog: false
  28704. } );
  28705. var materialBack = new MeshBasicMaterial( {
  28706. color: light.color,
  28707. fog: false,
  28708. wireframe: true
  28709. } );
  28710. var geometry = new BufferGeometry();
  28711. geometry.addAttribute( 'position', new BufferAttribute( new Float32Array( 6 * 3 ), 3 ) );
  28712. // shows the "front" of the light, e.g. where light comes from
  28713. this.add( new Mesh( geometry, materialFront ) );
  28714. // shows the "back" of the light, which does not emit light
  28715. this.add( new Mesh( geometry, materialBack ) );
  28716. this.update();
  28717. }
  28718. RectAreaLightHelper.prototype = Object.create( Object3D.prototype );
  28719. RectAreaLightHelper.prototype.constructor = RectAreaLightHelper;
  28720. RectAreaLightHelper.prototype.dispose = function () {
  28721. this.children[ 0 ].geometry.dispose();
  28722. this.children[ 0 ].material.dispose();
  28723. this.children[ 1 ].geometry.dispose();
  28724. this.children[ 1 ].material.dispose();
  28725. };
  28726. RectAreaLightHelper.prototype.update = function () {
  28727. var vector1 = new Vector3();
  28728. var vector2 = new Vector3();
  28729. return function update() {
  28730. var mesh1 = this.children[ 0 ];
  28731. var mesh2 = this.children[ 1 ];
  28732. if ( this.light.target ) {
  28733. vector1.setFromMatrixPosition( this.light.matrixWorld );
  28734. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  28735. var lookVec = vector2.clone().sub( vector1 );
  28736. mesh1.lookAt( lookVec );
  28737. mesh2.lookAt( lookVec );
  28738. }
  28739. // update materials
  28740. mesh1.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  28741. mesh2.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  28742. // calculate new dimensions of the helper
  28743. var hx = this.light.width * 0.5;
  28744. var hy = this.light.height * 0.5;
  28745. // because the buffer attribute is shared over both geometries, we only have to update once
  28746. var position = mesh1.geometry.getAttribute( 'position' );
  28747. var array = position.array;
  28748. // first face
  28749. array[ 0 ] = hx; array[ 1 ] = - hy; array[ 2 ] = 0;
  28750. array[ 3 ] = hx; array[ 4 ] = hy; array[ 5 ] = 0;
  28751. array[ 6 ] = - hx; array[ 7 ] = hy; array[ 8 ] = 0;
  28752. // second face
  28753. array[ 9 ] = - hx; array[ 10 ] = hy; array[ 11 ] = 0;
  28754. array[ 12 ] = - hx; array[ 13 ] = - hy; array[ 14 ] = 0;
  28755. array[ 15 ] = hx; array[ 16 ] = - hy; array[ 17 ] = 0;
  28756. position.needsUpdate = true;
  28757. };
  28758. }();
  28759. /**
  28760. * @author alteredq / http://alteredqualia.com/
  28761. * @author mrdoob / http://mrdoob.com/
  28762. * @author Mugen87 / https://github.com/Mugen87
  28763. */
  28764. function HemisphereLightHelper( light, size ) {
  28765. Object3D.call( this );
  28766. this.light = light;
  28767. this.light.updateMatrixWorld();
  28768. this.matrix = light.matrixWorld;
  28769. this.matrixAutoUpdate = false;
  28770. var geometry = new OctahedronBufferGeometry( size );
  28771. geometry.rotateY( Math.PI * 0.5 );
  28772. var material = new MeshBasicMaterial( { vertexColors: VertexColors, wireframe: true } );
  28773. var position = geometry.getAttribute( 'position' );
  28774. var colors = new Float32Array( position.count * 3 );
  28775. geometry.addAttribute( 'color', new BufferAttribute( colors, 3 ) );
  28776. this.add( new Mesh( geometry, material ) );
  28777. this.update();
  28778. }
  28779. HemisphereLightHelper.prototype = Object.create( Object3D.prototype );
  28780. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  28781. HemisphereLightHelper.prototype.dispose = function () {
  28782. this.children[ 0 ].geometry.dispose();
  28783. this.children[ 0 ].material.dispose();
  28784. };
  28785. HemisphereLightHelper.prototype.update = function () {
  28786. var vector = new Vector3();
  28787. var color1 = new Color();
  28788. var color2 = new Color();
  28789. return function update() {
  28790. var mesh = this.children[ 0 ];
  28791. var colors = mesh.geometry.getAttribute( 'color' );
  28792. color1.copy( this.light.color ).multiplyScalar( this.light.intensity );
  28793. color2.copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  28794. for ( var i = 0, l = colors.count; i < l; i ++ ) {
  28795. var color = ( i < ( l / 2 ) ) ? color1 : color2;
  28796. colors.setXYZ( i, color.r, color.g, color.b );
  28797. }
  28798. mesh.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  28799. colors.needsUpdate = true;
  28800. };
  28801. }();
  28802. /**
  28803. * @author mrdoob / http://mrdoob.com/
  28804. */
  28805. function GridHelper( size, divisions, color1, color2 ) {
  28806. size = size || 10;
  28807. divisions = divisions || 10;
  28808. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  28809. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  28810. var center = divisions / 2;
  28811. var step = size / divisions;
  28812. var halfSize = size / 2;
  28813. var vertices = [], colors = [];
  28814. for ( var i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  28815. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  28816. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  28817. var color = i === center ? color1 : color2;
  28818. color.toArray( colors, j ); j += 3;
  28819. color.toArray( colors, j ); j += 3;
  28820. color.toArray( colors, j ); j += 3;
  28821. color.toArray( colors, j ); j += 3;
  28822. }
  28823. var geometry = new BufferGeometry();
  28824. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28825. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28826. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  28827. LineSegments.call( this, geometry, material );
  28828. }
  28829. GridHelper.prototype = Object.create( LineSegments.prototype );
  28830. GridHelper.prototype.constructor = GridHelper;
  28831. /**
  28832. * @author mrdoob / http://mrdoob.com/
  28833. * @author Mugen87 / http://github.com/Mugen87
  28834. * @author Hectate / http://www.github.com/Hectate
  28835. */
  28836. function PolarGridHelper( radius, radials, circles, divisions, color1, color2 ) {
  28837. radius = radius || 10;
  28838. radials = radials || 16;
  28839. circles = circles || 8;
  28840. divisions = divisions || 64;
  28841. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  28842. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  28843. var vertices = [];
  28844. var colors = [];
  28845. var x, z;
  28846. var v, i, j, r, color;
  28847. // create the radials
  28848. for ( i = 0; i <= radials; i ++ ) {
  28849. v = ( i / radials ) * ( Math.PI * 2 );
  28850. x = Math.sin( v ) * radius;
  28851. z = Math.cos( v ) * radius;
  28852. vertices.push( 0, 0, 0 );
  28853. vertices.push( x, 0, z );
  28854. color = ( i & 1 ) ? color1 : color2;
  28855. colors.push( color.r, color.g, color.b );
  28856. colors.push( color.r, color.g, color.b );
  28857. }
  28858. // create the circles
  28859. for ( i = 0; i <= circles; i ++ ) {
  28860. color = ( i & 1 ) ? color1 : color2;
  28861. r = radius - ( radius / circles * i );
  28862. for ( j = 0; j < divisions; j ++ ) {
  28863. // first vertex
  28864. v = ( j / divisions ) * ( Math.PI * 2 );
  28865. x = Math.sin( v ) * r;
  28866. z = Math.cos( v ) * r;
  28867. vertices.push( x, 0, z );
  28868. colors.push( color.r, color.g, color.b );
  28869. // second vertex
  28870. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  28871. x = Math.sin( v ) * r;
  28872. z = Math.cos( v ) * r;
  28873. vertices.push( x, 0, z );
  28874. colors.push( color.r, color.g, color.b );
  28875. }
  28876. }
  28877. var geometry = new BufferGeometry();
  28878. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28879. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28880. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  28881. LineSegments.call( this, geometry, material );
  28882. }
  28883. PolarGridHelper.prototype = Object.create( LineSegments.prototype );
  28884. PolarGridHelper.prototype.constructor = PolarGridHelper;
  28885. /**
  28886. * @author mrdoob / http://mrdoob.com/
  28887. * @author WestLangley / http://github.com/WestLangley
  28888. */
  28889. function FaceNormalsHelper( object, size, hex, linewidth ) {
  28890. // FaceNormalsHelper only supports THREE.Geometry
  28891. this.object = object;
  28892. this.size = ( size !== undefined ) ? size : 1;
  28893. var color = ( hex !== undefined ) ? hex : 0xffff00;
  28894. var width = ( linewidth !== undefined ) ? linewidth : 1;
  28895. //
  28896. var nNormals = 0;
  28897. var objGeometry = this.object.geometry;
  28898. if ( objGeometry && objGeometry.isGeometry ) {
  28899. nNormals = objGeometry.faces.length;
  28900. } else {
  28901. console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' );
  28902. }
  28903. //
  28904. var geometry = new BufferGeometry();
  28905. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  28906. geometry.addAttribute( 'position', positions );
  28907. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  28908. //
  28909. this.matrixAutoUpdate = false;
  28910. this.update();
  28911. }
  28912. FaceNormalsHelper.prototype = Object.create( LineSegments.prototype );
  28913. FaceNormalsHelper.prototype.constructor = FaceNormalsHelper;
  28914. FaceNormalsHelper.prototype.update = ( function () {
  28915. var v1 = new Vector3();
  28916. var v2 = new Vector3();
  28917. var normalMatrix = new Matrix3();
  28918. return function update() {
  28919. this.object.updateMatrixWorld( true );
  28920. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  28921. var matrixWorld = this.object.matrixWorld;
  28922. var position = this.geometry.attributes.position;
  28923. //
  28924. var objGeometry = this.object.geometry;
  28925. var vertices = objGeometry.vertices;
  28926. var faces = objGeometry.faces;
  28927. var idx = 0;
  28928. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  28929. var face = faces[ i ];
  28930. var normal = face.normal;
  28931. v1.copy( vertices[ face.a ] )
  28932. .add( vertices[ face.b ] )
  28933. .add( vertices[ face.c ] )
  28934. .divideScalar( 3 )
  28935. .applyMatrix4( matrixWorld );
  28936. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  28937. position.setXYZ( idx, v1.x, v1.y, v1.z );
  28938. idx = idx + 1;
  28939. position.setXYZ( idx, v2.x, v2.y, v2.z );
  28940. idx = idx + 1;
  28941. }
  28942. position.needsUpdate = true;
  28943. return this;
  28944. };
  28945. }() );
  28946. /**
  28947. * @author alteredq / http://alteredqualia.com/
  28948. * @author mrdoob / http://mrdoob.com/
  28949. * @author WestLangley / http://github.com/WestLangley
  28950. */
  28951. function DirectionalLightHelper( light, size ) {
  28952. Object3D.call( this );
  28953. this.light = light;
  28954. this.light.updateMatrixWorld();
  28955. this.matrix = light.matrixWorld;
  28956. this.matrixAutoUpdate = false;
  28957. if ( size === undefined ) size = 1;
  28958. var geometry = new BufferGeometry();
  28959. geometry.addAttribute( 'position', new Float32BufferAttribute( [
  28960. - size, size, 0,
  28961. size, size, 0,
  28962. size, - size, 0,
  28963. - size, - size, 0,
  28964. - size, size, 0
  28965. ], 3 ) );
  28966. var material = new LineBasicMaterial( { fog: false } );
  28967. this.add( new Line( geometry, material ) );
  28968. geometry = new BufferGeometry();
  28969. geometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  28970. this.add( new Line( geometry, material ));
  28971. this.update();
  28972. }
  28973. DirectionalLightHelper.prototype = Object.create( Object3D.prototype );
  28974. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  28975. DirectionalLightHelper.prototype.dispose = function () {
  28976. var lightPlane = this.children[ 0 ];
  28977. var targetLine = this.children[ 1 ];
  28978. lightPlane.geometry.dispose();
  28979. lightPlane.material.dispose();
  28980. targetLine.geometry.dispose();
  28981. targetLine.material.dispose();
  28982. };
  28983. DirectionalLightHelper.prototype.update = function () {
  28984. var v1 = new Vector3();
  28985. var v2 = new Vector3();
  28986. var v3 = new Vector3();
  28987. return function update() {
  28988. v1.setFromMatrixPosition( this.light.matrixWorld );
  28989. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  28990. v3.subVectors( v2, v1 );
  28991. var lightPlane = this.children[ 0 ];
  28992. var targetLine = this.children[ 1 ];
  28993. lightPlane.lookAt( v3 );
  28994. lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  28995. targetLine.lookAt( v3 );
  28996. targetLine.scale.z = v3.length();
  28997. };
  28998. }();
  28999. /**
  29000. * @author alteredq / http://alteredqualia.com/
  29001. * @author Mugen87 / https://github.com/Mugen87
  29002. *
  29003. * - shows frustum, line of sight and up of the camera
  29004. * - suitable for fast updates
  29005. * - based on frustum visualization in lightgl.js shadowmap example
  29006. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  29007. */
  29008. function CameraHelper( camera ) {
  29009. var geometry = new BufferGeometry();
  29010. var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: FaceColors } );
  29011. var vertices = [];
  29012. var colors = [];
  29013. var pointMap = {};
  29014. // colors
  29015. var colorFrustum = new Color( 0xffaa00 );
  29016. var colorCone = new Color( 0xff0000 );
  29017. var colorUp = new Color( 0x00aaff );
  29018. var colorTarget = new Color( 0xffffff );
  29019. var colorCross = new Color( 0x333333 );
  29020. // near
  29021. addLine( "n1", "n2", colorFrustum );
  29022. addLine( "n2", "n4", colorFrustum );
  29023. addLine( "n4", "n3", colorFrustum );
  29024. addLine( "n3", "n1", colorFrustum );
  29025. // far
  29026. addLine( "f1", "f2", colorFrustum );
  29027. addLine( "f2", "f4", colorFrustum );
  29028. addLine( "f4", "f3", colorFrustum );
  29029. addLine( "f3", "f1", colorFrustum );
  29030. // sides
  29031. addLine( "n1", "f1", colorFrustum );
  29032. addLine( "n2", "f2", colorFrustum );
  29033. addLine( "n3", "f3", colorFrustum );
  29034. addLine( "n4", "f4", colorFrustum );
  29035. // cone
  29036. addLine( "p", "n1", colorCone );
  29037. addLine( "p", "n2", colorCone );
  29038. addLine( "p", "n3", colorCone );
  29039. addLine( "p", "n4", colorCone );
  29040. // up
  29041. addLine( "u1", "u2", colorUp );
  29042. addLine( "u2", "u3", colorUp );
  29043. addLine( "u3", "u1", colorUp );
  29044. // target
  29045. addLine( "c", "t", colorTarget );
  29046. addLine( "p", "c", colorCross );
  29047. // cross
  29048. addLine( "cn1", "cn2", colorCross );
  29049. addLine( "cn3", "cn4", colorCross );
  29050. addLine( "cf1", "cf2", colorCross );
  29051. addLine( "cf3", "cf4", colorCross );
  29052. function addLine( a, b, color ) {
  29053. addPoint( a, color );
  29054. addPoint( b, color );
  29055. }
  29056. function addPoint( id, color ) {
  29057. vertices.push( 0, 0, 0 );
  29058. colors.push( color.r, color.g, color.b );
  29059. if ( pointMap[ id ] === undefined ) {
  29060. pointMap[ id ] = [];
  29061. }
  29062. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  29063. }
  29064. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29065. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29066. LineSegments.call( this, geometry, material );
  29067. this.camera = camera;
  29068. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  29069. this.matrix = camera.matrixWorld;
  29070. this.matrixAutoUpdate = false;
  29071. this.pointMap = pointMap;
  29072. this.update();
  29073. }
  29074. CameraHelper.prototype = Object.create( LineSegments.prototype );
  29075. CameraHelper.prototype.constructor = CameraHelper;
  29076. CameraHelper.prototype.update = function () {
  29077. var geometry, pointMap;
  29078. var vector = new Vector3();
  29079. var camera = new Camera();
  29080. function setPoint( point, x, y, z ) {
  29081. vector.set( x, y, z ).unproject( camera );
  29082. var points = pointMap[ point ];
  29083. if ( points !== undefined ) {
  29084. var position = geometry.getAttribute( 'position' );
  29085. for ( var i = 0, l = points.length; i < l; i ++ ) {
  29086. position.setXYZ( points[ i ], vector.x, vector.y, vector.z );
  29087. }
  29088. }
  29089. }
  29090. return function update() {
  29091. geometry = this.geometry;
  29092. pointMap = this.pointMap;
  29093. var w = 1, h = 1;
  29094. // we need just camera projection matrix
  29095. // world matrix must be identity
  29096. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  29097. // center / target
  29098. setPoint( "c", 0, 0, - 1 );
  29099. setPoint( "t", 0, 0, 1 );
  29100. // near
  29101. setPoint( "n1", - w, - h, - 1 );
  29102. setPoint( "n2", w, - h, - 1 );
  29103. setPoint( "n3", - w, h, - 1 );
  29104. setPoint( "n4", w, h, - 1 );
  29105. // far
  29106. setPoint( "f1", - w, - h, 1 );
  29107. setPoint( "f2", w, - h, 1 );
  29108. setPoint( "f3", - w, h, 1 );
  29109. setPoint( "f4", w, h, 1 );
  29110. // up
  29111. setPoint( "u1", w * 0.7, h * 1.1, - 1 );
  29112. setPoint( "u2", - w * 0.7, h * 1.1, - 1 );
  29113. setPoint( "u3", 0, h * 2, - 1 );
  29114. // cross
  29115. setPoint( "cf1", - w, 0, 1 );
  29116. setPoint( "cf2", w, 0, 1 );
  29117. setPoint( "cf3", 0, - h, 1 );
  29118. setPoint( "cf4", 0, h, 1 );
  29119. setPoint( "cn1", - w, 0, - 1 );
  29120. setPoint( "cn2", w, 0, - 1 );
  29121. setPoint( "cn3", 0, - h, - 1 );
  29122. setPoint( "cn4", 0, h, - 1 );
  29123. geometry.getAttribute( 'position' ).needsUpdate = true;
  29124. };
  29125. }();
  29126. /**
  29127. * @author mrdoob / http://mrdoob.com/
  29128. */
  29129. function BoxHelper( object, color ) {
  29130. if ( color === undefined ) color = 0xffff00;
  29131. 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 ] );
  29132. var positions = new Float32Array( 8 * 3 );
  29133. var geometry = new BufferGeometry();
  29134. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  29135. geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) );
  29136. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  29137. if ( object !== undefined ) {
  29138. this.update( object );
  29139. }
  29140. }
  29141. BoxHelper.prototype = Object.create( LineSegments.prototype );
  29142. BoxHelper.prototype.constructor = BoxHelper;
  29143. BoxHelper.prototype.update = ( function () {
  29144. var box = new Box3();
  29145. return function update( object ) {
  29146. if ( object && object.isBox3 ) {
  29147. box.copy( object );
  29148. } else {
  29149. box.setFromObject( object );
  29150. }
  29151. if ( box.isEmpty() ) return;
  29152. var min = box.min;
  29153. var max = box.max;
  29154. /*
  29155. 5____4
  29156. 1/___0/|
  29157. | 6__|_7
  29158. 2/___3/
  29159. 0: max.x, max.y, max.z
  29160. 1: min.x, max.y, max.z
  29161. 2: min.x, min.y, max.z
  29162. 3: max.x, min.y, max.z
  29163. 4: max.x, max.y, min.z
  29164. 5: min.x, max.y, min.z
  29165. 6: min.x, min.y, min.z
  29166. 7: max.x, min.y, min.z
  29167. */
  29168. var position = this.geometry.attributes.position;
  29169. var array = position.array;
  29170. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  29171. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  29172. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  29173. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  29174. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  29175. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  29176. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  29177. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  29178. position.needsUpdate = true;
  29179. this.geometry.computeBoundingSphere();
  29180. };
  29181. } )();
  29182. /**
  29183. * @author WestLangley / http://github.com/WestLangley
  29184. * @author zz85 / http://github.com/zz85
  29185. * @author bhouston / http://clara.io
  29186. *
  29187. * Creates an arrow for visualizing directions
  29188. *
  29189. * Parameters:
  29190. * dir - Vector3
  29191. * origin - Vector3
  29192. * length - Number
  29193. * color - color in hex value
  29194. * headLength - Number
  29195. * headWidth - Number
  29196. */
  29197. var lineGeometry;
  29198. var coneGeometry;
  29199. function ArrowHelper( dir, origin, length, color, headLength, headWidth ) {
  29200. // dir is assumed to be normalized
  29201. Object3D.call( this );
  29202. if ( color === undefined ) color = 0xffff00;
  29203. if ( length === undefined ) length = 1;
  29204. if ( headLength === undefined ) headLength = 0.2 * length;
  29205. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  29206. if ( lineGeometry === undefined ) {
  29207. lineGeometry = new BufferGeometry();
  29208. lineGeometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  29209. coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 );
  29210. coneGeometry.translate( 0, - 0.5, 0 );
  29211. }
  29212. this.position.copy( origin );
  29213. this.line = new Line( lineGeometry, new LineBasicMaterial( { color: color } ) );
  29214. this.line.matrixAutoUpdate = false;
  29215. this.add( this.line );
  29216. this.cone = new Mesh( coneGeometry, new MeshBasicMaterial( { color: color } ) );
  29217. this.cone.matrixAutoUpdate = false;
  29218. this.add( this.cone );
  29219. this.setDirection( dir );
  29220. this.setLength( length, headLength, headWidth );
  29221. }
  29222. ArrowHelper.prototype = Object.create( Object3D.prototype );
  29223. ArrowHelper.prototype.constructor = ArrowHelper;
  29224. ArrowHelper.prototype.setDirection = ( function () {
  29225. var axis = new Vector3();
  29226. var radians;
  29227. return function setDirection( dir ) {
  29228. // dir is assumed to be normalized
  29229. if ( dir.y > 0.99999 ) {
  29230. this.quaternion.set( 0, 0, 0, 1 );
  29231. } else if ( dir.y < - 0.99999 ) {
  29232. this.quaternion.set( 1, 0, 0, 0 );
  29233. } else {
  29234. axis.set( dir.z, 0, - dir.x ).normalize();
  29235. radians = Math.acos( dir.y );
  29236. this.quaternion.setFromAxisAngle( axis, radians );
  29237. }
  29238. };
  29239. }() );
  29240. ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  29241. if ( headLength === undefined ) headLength = 0.2 * length;
  29242. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  29243. this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 );
  29244. this.line.updateMatrix();
  29245. this.cone.scale.set( headWidth, headLength, headWidth );
  29246. this.cone.position.y = length;
  29247. this.cone.updateMatrix();
  29248. };
  29249. ArrowHelper.prototype.setColor = function ( color ) {
  29250. this.line.material.color.copy( color );
  29251. this.cone.material.color.copy( color );
  29252. };
  29253. /**
  29254. * @author sroucheray / http://sroucheray.org/
  29255. * @author mrdoob / http://mrdoob.com/
  29256. */
  29257. function AxisHelper( size ) {
  29258. size = size || 1;
  29259. var vertices = [
  29260. 0, 0, 0, size, 0, 0,
  29261. 0, 0, 0, 0, size, 0,
  29262. 0, 0, 0, 0, 0, size
  29263. ];
  29264. var colors = [
  29265. 1, 0, 0, 1, 0.6, 0,
  29266. 0, 1, 0, 0.6, 1, 0,
  29267. 0, 0, 1, 0, 0.6, 1
  29268. ];
  29269. var geometry = new BufferGeometry();
  29270. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29271. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29272. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  29273. LineSegments.call( this, geometry, material );
  29274. }
  29275. AxisHelper.prototype = Object.create( LineSegments.prototype );
  29276. AxisHelper.prototype.constructor = AxisHelper;
  29277. /**
  29278. * @author zz85 https://github.com/zz85
  29279. *
  29280. * Centripetal CatmullRom Curve - which is useful for avoiding
  29281. * cusps and self-intersections in non-uniform catmull rom curves.
  29282. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  29283. *
  29284. * curve.type accepts centripetal(default), chordal and catmullrom
  29285. * curve.tension is used for catmullrom which defaults to 0.5
  29286. */
  29287. /*
  29288. Based on an optimized c++ solution in
  29289. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  29290. - http://ideone.com/NoEbVM
  29291. This CubicPoly class could be used for reusing some variables and calculations,
  29292. but for three.js curve use, it could be possible inlined and flatten into a single function call
  29293. which can be placed in CurveUtils.
  29294. */
  29295. function CubicPoly() {
  29296. var c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  29297. /*
  29298. * Compute coefficients for a cubic polynomial
  29299. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  29300. * such that
  29301. * p(0) = x0, p(1) = x1
  29302. * and
  29303. * p'(0) = t0, p'(1) = t1.
  29304. */
  29305. function init( x0, x1, t0, t1 ) {
  29306. c0 = x0;
  29307. c1 = t0;
  29308. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  29309. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  29310. }
  29311. return {
  29312. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  29313. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  29314. },
  29315. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  29316. // compute tangents when parameterized in [t1,t2]
  29317. var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  29318. var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  29319. // rescale tangents for parametrization in [0,1]
  29320. t1 *= dt1;
  29321. t2 *= dt1;
  29322. init( x1, x2, t1, t2 );
  29323. },
  29324. calc: function ( t ) {
  29325. var t2 = t * t;
  29326. var t3 = t2 * t;
  29327. return c0 + c1 * t + c2 * t2 + c3 * t3;
  29328. }
  29329. };
  29330. }
  29331. //
  29332. var tmp = new Vector3();
  29333. var px = new CubicPoly();
  29334. var py = new CubicPoly();
  29335. var pz = new CubicPoly();
  29336. function CatmullRomCurve3( p /* array of Vector3 */ ) {
  29337. this.points = p || [];
  29338. this.closed = false;
  29339. }
  29340. CatmullRomCurve3.prototype = Object.create( Curve.prototype );
  29341. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  29342. CatmullRomCurve3.prototype.getPoint = function ( t ) {
  29343. var points = this.points;
  29344. var l = points.length;
  29345. if ( l < 2 ) console.log( 'duh, you need at least 2 points' );
  29346. var point = ( l - ( this.closed ? 0 : 1 ) ) * t;
  29347. var intPoint = Math.floor( point );
  29348. var weight = point - intPoint;
  29349. if ( this.closed ) {
  29350. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  29351. } else if ( weight === 0 && intPoint === l - 1 ) {
  29352. intPoint = l - 2;
  29353. weight = 1;
  29354. }
  29355. var p0, p1, p2, p3; // 4 points
  29356. if ( this.closed || intPoint > 0 ) {
  29357. p0 = points[ ( intPoint - 1 ) % l ];
  29358. } else {
  29359. // extrapolate first point
  29360. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  29361. p0 = tmp;
  29362. }
  29363. p1 = points[ intPoint % l ];
  29364. p2 = points[ ( intPoint + 1 ) % l ];
  29365. if ( this.closed || intPoint + 2 < l ) {
  29366. p3 = points[ ( intPoint + 2 ) % l ];
  29367. } else {
  29368. // extrapolate last point
  29369. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  29370. p3 = tmp;
  29371. }
  29372. if ( this.type === undefined || this.type === 'centripetal' || this.type === 'chordal' ) {
  29373. // init Centripetal / Chordal Catmull-Rom
  29374. var pow = this.type === 'chordal' ? 0.5 : 0.25;
  29375. var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  29376. var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  29377. var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  29378. // safety check for repeated points
  29379. if ( dt1 < 1e-4 ) dt1 = 1.0;
  29380. if ( dt0 < 1e-4 ) dt0 = dt1;
  29381. if ( dt2 < 1e-4 ) dt2 = dt1;
  29382. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  29383. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  29384. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  29385. } else if ( this.type === 'catmullrom' ) {
  29386. var tension = this.tension !== undefined ? this.tension : 0.5;
  29387. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, tension );
  29388. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, tension );
  29389. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, tension );
  29390. }
  29391. return new Vector3( px.calc( weight ), py.calc( weight ), pz.calc( weight ) );
  29392. };
  29393. function CubicBezierCurve3( v0, v1, v2, v3 ) {
  29394. this.v0 = v0;
  29395. this.v1 = v1;
  29396. this.v2 = v2;
  29397. this.v3 = v3;
  29398. }
  29399. CubicBezierCurve3.prototype = Object.create( Curve.prototype );
  29400. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  29401. CubicBezierCurve3.prototype.getPoint = function ( t ) {
  29402. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  29403. return new Vector3(
  29404. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  29405. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  29406. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  29407. );
  29408. };
  29409. function QuadraticBezierCurve3( v0, v1, v2 ) {
  29410. this.v0 = v0;
  29411. this.v1 = v1;
  29412. this.v2 = v2;
  29413. }
  29414. QuadraticBezierCurve3.prototype = Object.create( Curve.prototype );
  29415. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  29416. QuadraticBezierCurve3.prototype.getPoint = function ( t ) {
  29417. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  29418. return new Vector3(
  29419. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  29420. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  29421. QuadraticBezier( t, v0.z, v1.z, v2.z )
  29422. );
  29423. };
  29424. function LineCurve3( v1, v2 ) {
  29425. this.v1 = v1;
  29426. this.v2 = v2;
  29427. }
  29428. LineCurve3.prototype = Object.create( Curve.prototype );
  29429. LineCurve3.prototype.constructor = LineCurve3;
  29430. LineCurve3.prototype.getPoint = function ( t ) {
  29431. if ( t === 1 ) {
  29432. return this.v2.clone();
  29433. }
  29434. var vector = new Vector3();
  29435. vector.subVectors( this.v2, this.v1 ); // diff
  29436. vector.multiplyScalar( t );
  29437. vector.add( this.v1 );
  29438. return vector;
  29439. };
  29440. function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  29441. EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  29442. }
  29443. ArcCurve.prototype = Object.create( EllipseCurve.prototype );
  29444. ArcCurve.prototype.constructor = ArcCurve;
  29445. /**
  29446. * @author alteredq / http://alteredqualia.com/
  29447. */
  29448. var SceneUtils = {
  29449. createMultiMaterialObject: function ( geometry, materials ) {
  29450. var group = new Group();
  29451. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  29452. group.add( new Mesh( geometry, materials[ i ] ) );
  29453. }
  29454. return group;
  29455. },
  29456. detach: function ( child, parent, scene ) {
  29457. child.applyMatrix( parent.matrixWorld );
  29458. parent.remove( child );
  29459. scene.add( child );
  29460. },
  29461. attach: function ( child, scene, parent ) {
  29462. var matrixWorldInverse = new Matrix4();
  29463. matrixWorldInverse.getInverse( parent.matrixWorld );
  29464. child.applyMatrix( matrixWorldInverse );
  29465. scene.remove( child );
  29466. parent.add( child );
  29467. }
  29468. };
  29469. /**
  29470. * @author mrdoob / http://mrdoob.com/
  29471. */
  29472. function Face4( a, b, c, d, normal, color, materialIndex ) {
  29473. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  29474. return new Face3( a, b, c, normal, color, materialIndex );
  29475. }
  29476. var LineStrip = 0;
  29477. var LinePieces = 1;
  29478. function MeshFaceMaterial( materials ) {
  29479. console.warn( 'THREE.MeshFaceMaterial has been renamed to THREE.MultiMaterial.' );
  29480. return new MultiMaterial( materials );
  29481. }
  29482. function PointCloud( geometry, material ) {
  29483. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  29484. return new Points( geometry, material );
  29485. }
  29486. function Particle( material ) {
  29487. console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
  29488. return new Sprite( material );
  29489. }
  29490. function ParticleSystem( geometry, material ) {
  29491. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  29492. return new Points( geometry, material );
  29493. }
  29494. function PointCloudMaterial( parameters ) {
  29495. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  29496. return new PointsMaterial( parameters );
  29497. }
  29498. function ParticleBasicMaterial( parameters ) {
  29499. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  29500. return new PointsMaterial( parameters );
  29501. }
  29502. function ParticleSystemMaterial( parameters ) {
  29503. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  29504. return new PointsMaterial( parameters );
  29505. }
  29506. function Vertex( x, y, z ) {
  29507. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  29508. return new Vector3( x, y, z );
  29509. }
  29510. //
  29511. function DynamicBufferAttribute( array, itemSize ) {
  29512. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' );
  29513. return new BufferAttribute( array, itemSize ).setDynamic( true );
  29514. }
  29515. function Int8Attribute( array, itemSize ) {
  29516. console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
  29517. return new Int8BufferAttribute( array, itemSize );
  29518. }
  29519. function Uint8Attribute( array, itemSize ) {
  29520. console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
  29521. return new Uint8BufferAttribute( array, itemSize );
  29522. }
  29523. function Uint8ClampedAttribute( array, itemSize ) {
  29524. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
  29525. return new Uint8ClampedBufferAttribute( array, itemSize );
  29526. }
  29527. function Int16Attribute( array, itemSize ) {
  29528. console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
  29529. return new Int16BufferAttribute( array, itemSize );
  29530. }
  29531. function Uint16Attribute( array, itemSize ) {
  29532. console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
  29533. return new Uint16BufferAttribute( array, itemSize );
  29534. }
  29535. function Int32Attribute( array, itemSize ) {
  29536. console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
  29537. return new Int32BufferAttribute( array, itemSize );
  29538. }
  29539. function Uint32Attribute( array, itemSize ) {
  29540. console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
  29541. return new Uint32BufferAttribute( array, itemSize );
  29542. }
  29543. function Float32Attribute( array, itemSize ) {
  29544. console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
  29545. return new Float32BufferAttribute( array, itemSize );
  29546. }
  29547. function Float64Attribute( array, itemSize ) {
  29548. console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
  29549. return new Float64BufferAttribute( array, itemSize );
  29550. }
  29551. //
  29552. Curve.create = function ( construct, getPoint ) {
  29553. console.log( 'THREE.Curve.create() has been deprecated' );
  29554. construct.prototype = Object.create( Curve.prototype );
  29555. construct.prototype.constructor = construct;
  29556. construct.prototype.getPoint = getPoint;
  29557. return construct;
  29558. };
  29559. //
  29560. function ClosedSplineCurve3( points ) {
  29561. console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  29562. CatmullRomCurve3.call( this, points );
  29563. this.type = 'catmullrom';
  29564. this.closed = true;
  29565. }
  29566. ClosedSplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  29567. //
  29568. function SplineCurve3( points ) {
  29569. console.warn( 'THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  29570. CatmullRomCurve3.call( this, points );
  29571. this.type = 'catmullrom';
  29572. }
  29573. SplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  29574. //
  29575. function Spline( points ) {
  29576. console.warn( 'THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.' );
  29577. CatmullRomCurve3.call( this, points );
  29578. this.type = 'catmullrom';
  29579. }
  29580. Spline.prototype = Object.create( CatmullRomCurve3.prototype );
  29581. Object.assign( Spline.prototype, {
  29582. initFromArray: function ( a ) {
  29583. console.error( 'THREE.Spline: .initFromArray() has been removed.' );
  29584. },
  29585. getControlPointsArray: function ( optionalTarget ) {
  29586. console.error( 'THREE.Spline: .getControlPointsArray() has been removed.' );
  29587. },
  29588. reparametrizeByArcLength: function ( samplingCoef ) {
  29589. console.error( 'THREE.Spline: .reparametrizeByArcLength() has been removed.' );
  29590. }
  29591. } );
  29592. //
  29593. function BoundingBoxHelper( object, color ) {
  29594. console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
  29595. return new BoxHelper( object, color );
  29596. }
  29597. function EdgesHelper( object, hex ) {
  29598. console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
  29599. return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  29600. }
  29601. GridHelper.prototype.setColors = function () {
  29602. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  29603. };
  29604. function WireframeHelper( object, hex ) {
  29605. console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
  29606. return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  29607. }
  29608. //
  29609. function XHRLoader( manager ) {
  29610. console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
  29611. return new FileLoader( manager );
  29612. }
  29613. function BinaryTextureLoader( manager ) {
  29614. console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' );
  29615. return new DataTextureLoader( manager );
  29616. }
  29617. //
  29618. Object.assign( Box2.prototype, {
  29619. center: function ( optionalTarget ) {
  29620. console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
  29621. return this.getCenter( optionalTarget );
  29622. },
  29623. empty: function () {
  29624. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  29625. return this.isEmpty();
  29626. },
  29627. isIntersectionBox: function ( box ) {
  29628. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  29629. return this.intersectsBox( box );
  29630. },
  29631. size: function ( optionalTarget ) {
  29632. console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
  29633. return this.getSize( optionalTarget );
  29634. }
  29635. } );
  29636. Object.assign( Box3.prototype, {
  29637. center: function ( optionalTarget ) {
  29638. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  29639. return this.getCenter( optionalTarget );
  29640. },
  29641. empty: function () {
  29642. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  29643. return this.isEmpty();
  29644. },
  29645. isIntersectionBox: function ( box ) {
  29646. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  29647. return this.intersectsBox( box );
  29648. },
  29649. isIntersectionSphere: function ( sphere ) {
  29650. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  29651. return this.intersectsSphere( sphere );
  29652. },
  29653. size: function ( optionalTarget ) {
  29654. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  29655. return this.getSize( optionalTarget );
  29656. }
  29657. } );
  29658. Line3.prototype.center = function ( optionalTarget ) {
  29659. console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
  29660. return this.getCenter( optionalTarget );
  29661. };
  29662. _Math.random16 = function () {
  29663. console.warn( 'THREE.Math.random16() has been deprecated. Use Math.random() instead.' );
  29664. return Math.random();
  29665. };
  29666. Object.assign( Matrix3.prototype, {
  29667. flattenToArrayOffset: function ( array, offset ) {
  29668. console.warn( "THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  29669. return this.toArray( array, offset );
  29670. },
  29671. multiplyVector3: function ( vector ) {
  29672. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  29673. return vector.applyMatrix3( this );
  29674. },
  29675. multiplyVector3Array: function ( a ) {
  29676. console.warn( 'THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  29677. return this.applyToVector3Array( a );
  29678. },
  29679. applyToBuffer: function( buffer, offset, length ) {
  29680. console.warn( 'THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  29681. return this.applyToBufferAttribute( buffer );
  29682. },
  29683. applyToVector3Array: function( array, offset, length ) {
  29684. console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' );
  29685. }
  29686. } );
  29687. Object.assign( Matrix4.prototype, {
  29688. extractPosition: function ( m ) {
  29689. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  29690. return this.copyPosition( m );
  29691. },
  29692. flattenToArrayOffset: function ( array, offset ) {
  29693. console.warn( "THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  29694. return this.toArray( array, offset );
  29695. },
  29696. getPosition: function () {
  29697. var v1;
  29698. return function getPosition() {
  29699. if ( v1 === undefined ) v1 = new Vector3();
  29700. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  29701. return v1.setFromMatrixColumn( this, 3 );
  29702. };
  29703. }(),
  29704. setRotationFromQuaternion: function ( q ) {
  29705. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  29706. return this.makeRotationFromQuaternion( q );
  29707. },
  29708. multiplyVector3: function ( vector ) {
  29709. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  29710. return vector.applyMatrix4( this );
  29711. },
  29712. multiplyVector4: function ( vector ) {
  29713. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  29714. return vector.applyMatrix4( this );
  29715. },
  29716. multiplyVector3Array: function ( a ) {
  29717. console.warn( 'THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  29718. return this.applyToVector3Array( a );
  29719. },
  29720. rotateAxis: function ( v ) {
  29721. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  29722. v.transformDirection( this );
  29723. },
  29724. crossVector: function ( vector ) {
  29725. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  29726. return vector.applyMatrix4( this );
  29727. },
  29728. translate: function () {
  29729. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  29730. },
  29731. rotateX: function () {
  29732. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  29733. },
  29734. rotateY: function () {
  29735. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  29736. },
  29737. rotateZ: function () {
  29738. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  29739. },
  29740. rotateByAxis: function () {
  29741. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  29742. },
  29743. applyToBuffer: function( buffer, offset, length ) {
  29744. console.warn( 'THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  29745. return this.applyToBufferAttribute( buffer );
  29746. },
  29747. applyToVector3Array: function( array, offset, length ) {
  29748. console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' );
  29749. },
  29750. makeFrustum: function( left, right, bottom, top, near, far ) {
  29751. console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' );
  29752. return this.makePerspective( left, right, top, bottom, near, far );
  29753. }
  29754. } );
  29755. Plane.prototype.isIntersectionLine = function ( line ) {
  29756. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  29757. return this.intersectsLine( line );
  29758. };
  29759. Quaternion.prototype.multiplyVector3 = function ( vector ) {
  29760. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  29761. return vector.applyQuaternion( this );
  29762. };
  29763. Object.assign( Ray.prototype, {
  29764. isIntersectionBox: function ( box ) {
  29765. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  29766. return this.intersectsBox( box );
  29767. },
  29768. isIntersectionPlane: function ( plane ) {
  29769. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  29770. return this.intersectsPlane( plane );
  29771. },
  29772. isIntersectionSphere: function ( sphere ) {
  29773. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  29774. return this.intersectsSphere( sphere );
  29775. }
  29776. } );
  29777. Object.assign( Shape.prototype, {
  29778. extrude: function ( options ) {
  29779. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  29780. return new ExtrudeGeometry( this, options );
  29781. },
  29782. makeGeometry: function ( options ) {
  29783. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  29784. return new ShapeGeometry( this, options );
  29785. }
  29786. } );
  29787. Object.assign( Vector2.prototype, {
  29788. fromAttribute: function ( attribute, index, offset ) {
  29789. console.error( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  29790. return this.fromBufferAttribute( attribute, index, offset );
  29791. }
  29792. } );
  29793. Object.assign( Vector3.prototype, {
  29794. setEulerFromRotationMatrix: function () {
  29795. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  29796. },
  29797. setEulerFromQuaternion: function () {
  29798. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  29799. },
  29800. getPositionFromMatrix: function ( m ) {
  29801. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  29802. return this.setFromMatrixPosition( m );
  29803. },
  29804. getScaleFromMatrix: function ( m ) {
  29805. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  29806. return this.setFromMatrixScale( m );
  29807. },
  29808. getColumnFromMatrix: function ( index, matrix ) {
  29809. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  29810. return this.setFromMatrixColumn( matrix, index );
  29811. },
  29812. applyProjection: function ( m ) {
  29813. console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' );
  29814. return this.applyMatrix4( m );
  29815. },
  29816. fromAttribute: function ( attribute, index, offset ) {
  29817. console.error( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  29818. return this.fromBufferAttribute( attribute, index, offset );
  29819. }
  29820. } );
  29821. Object.assign( Vector4.prototype, {
  29822. fromAttribute: function ( attribute, index, offset ) {
  29823. console.error( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  29824. return this.fromBufferAttribute( attribute, index, offset );
  29825. }
  29826. } );
  29827. //
  29828. Geometry.prototype.computeTangents = function () {
  29829. console.warn( 'THREE.Geometry: .computeTangents() has been removed.' );
  29830. };
  29831. Object.assign( Object3D.prototype, {
  29832. getChildByName: function ( name ) {
  29833. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  29834. return this.getObjectByName( name );
  29835. },
  29836. renderDepth: function () {
  29837. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  29838. },
  29839. translate: function ( distance, axis ) {
  29840. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  29841. return this.translateOnAxis( axis, distance );
  29842. }
  29843. } );
  29844. Object.defineProperties( Object3D.prototype, {
  29845. eulerOrder: {
  29846. get: function () {
  29847. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  29848. return this.rotation.order;
  29849. },
  29850. set: function ( value ) {
  29851. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  29852. this.rotation.order = value;
  29853. }
  29854. },
  29855. useQuaternion: {
  29856. get: function () {
  29857. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  29858. },
  29859. set: function () {
  29860. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  29861. }
  29862. }
  29863. } );
  29864. Object.defineProperties( LOD.prototype, {
  29865. objects: {
  29866. get: function () {
  29867. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  29868. return this.levels;
  29869. }
  29870. }
  29871. } );
  29872. //
  29873. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  29874. console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " +
  29875. "Use .setFocalLength and .filmGauge for a photographic setup." );
  29876. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  29877. this.setFocalLength( focalLength );
  29878. };
  29879. //
  29880. Object.defineProperties( Light.prototype, {
  29881. onlyShadow: {
  29882. set: function () {
  29883. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  29884. }
  29885. },
  29886. shadowCameraFov: {
  29887. set: function ( value ) {
  29888. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  29889. this.shadow.camera.fov = value;
  29890. }
  29891. },
  29892. shadowCameraLeft: {
  29893. set: function ( value ) {
  29894. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  29895. this.shadow.camera.left = value;
  29896. }
  29897. },
  29898. shadowCameraRight: {
  29899. set: function ( value ) {
  29900. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  29901. this.shadow.camera.right = value;
  29902. }
  29903. },
  29904. shadowCameraTop: {
  29905. set: function ( value ) {
  29906. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  29907. this.shadow.camera.top = value;
  29908. }
  29909. },
  29910. shadowCameraBottom: {
  29911. set: function ( value ) {
  29912. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  29913. this.shadow.camera.bottom = value;
  29914. }
  29915. },
  29916. shadowCameraNear: {
  29917. set: function ( value ) {
  29918. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  29919. this.shadow.camera.near = value;
  29920. }
  29921. },
  29922. shadowCameraFar: {
  29923. set: function ( value ) {
  29924. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  29925. this.shadow.camera.far = value;
  29926. }
  29927. },
  29928. shadowCameraVisible: {
  29929. set: function () {
  29930. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  29931. }
  29932. },
  29933. shadowBias: {
  29934. set: function ( value ) {
  29935. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  29936. this.shadow.bias = value;
  29937. }
  29938. },
  29939. shadowDarkness: {
  29940. set: function () {
  29941. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  29942. }
  29943. },
  29944. shadowMapWidth: {
  29945. set: function ( value ) {
  29946. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  29947. this.shadow.mapSize.width = value;
  29948. }
  29949. },
  29950. shadowMapHeight: {
  29951. set: function ( value ) {
  29952. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  29953. this.shadow.mapSize.height = value;
  29954. }
  29955. }
  29956. } );
  29957. //
  29958. Object.defineProperties( BufferAttribute.prototype, {
  29959. length: {
  29960. get: function () {
  29961. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  29962. return this.array.length;
  29963. }
  29964. }
  29965. } );
  29966. Object.assign( BufferGeometry.prototype, {
  29967. addIndex: function ( index ) {
  29968. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  29969. this.setIndex( index );
  29970. },
  29971. addDrawCall: function ( start, count, indexOffset ) {
  29972. if ( indexOffset !== undefined ) {
  29973. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  29974. }
  29975. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  29976. this.addGroup( start, count );
  29977. },
  29978. clearDrawCalls: function () {
  29979. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  29980. this.clearGroups();
  29981. },
  29982. computeTangents: function () {
  29983. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  29984. },
  29985. computeOffsets: function () {
  29986. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  29987. }
  29988. } );
  29989. Object.defineProperties( BufferGeometry.prototype, {
  29990. drawcalls: {
  29991. get: function () {
  29992. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  29993. return this.groups;
  29994. }
  29995. },
  29996. offsets: {
  29997. get: function () {
  29998. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  29999. return this.groups;
  30000. }
  30001. }
  30002. } );
  30003. //
  30004. Object.defineProperties( Uniform.prototype, {
  30005. dynamic: {
  30006. set: function () {
  30007. console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' );
  30008. }
  30009. },
  30010. onUpdate: {
  30011. value: function () {
  30012. console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
  30013. return this;
  30014. }
  30015. }
  30016. } );
  30017. //
  30018. Object.defineProperties( Material.prototype, {
  30019. wrapAround: {
  30020. get: function () {
  30021. console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' );
  30022. },
  30023. set: function () {
  30024. console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' );
  30025. }
  30026. },
  30027. wrapRGB: {
  30028. get: function () {
  30029. console.warn( 'THREE.' + this.type + ': .wrapRGB has been removed.' );
  30030. return new Color();
  30031. }
  30032. }
  30033. } );
  30034. Object.defineProperties( MeshPhongMaterial.prototype, {
  30035. metal: {
  30036. get: function () {
  30037. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  30038. return false;
  30039. },
  30040. set: function () {
  30041. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  30042. }
  30043. }
  30044. } );
  30045. Object.defineProperties( ShaderMaterial.prototype, {
  30046. derivatives: {
  30047. get: function () {
  30048. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  30049. return this.extensions.derivatives;
  30050. },
  30051. set: function ( value ) {
  30052. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  30053. this.extensions.derivatives = value;
  30054. }
  30055. }
  30056. } );
  30057. //
  30058. Object.assign( WebGLRenderer.prototype, {
  30059. supportsFloatTextures: function () {
  30060. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  30061. return this.extensions.get( 'OES_texture_float' );
  30062. },
  30063. supportsHalfFloatTextures: function () {
  30064. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  30065. return this.extensions.get( 'OES_texture_half_float' );
  30066. },
  30067. supportsStandardDerivatives: function () {
  30068. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  30069. return this.extensions.get( 'OES_standard_derivatives' );
  30070. },
  30071. supportsCompressedTextureS3TC: function () {
  30072. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  30073. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  30074. },
  30075. supportsCompressedTexturePVRTC: function () {
  30076. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  30077. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  30078. },
  30079. supportsBlendMinMax: function () {
  30080. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  30081. return this.extensions.get( 'EXT_blend_minmax' );
  30082. },
  30083. supportsVertexTextures: function () {
  30084. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  30085. return this.capabilities.vertexTextures;
  30086. },
  30087. supportsInstancedArrays: function () {
  30088. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  30089. return this.extensions.get( 'ANGLE_instanced_arrays' );
  30090. },
  30091. enableScissorTest: function ( boolean ) {
  30092. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  30093. this.setScissorTest( boolean );
  30094. },
  30095. initMaterial: function () {
  30096. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  30097. },
  30098. addPrePlugin: function () {
  30099. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  30100. },
  30101. addPostPlugin: function () {
  30102. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  30103. },
  30104. updateShadowMap: function () {
  30105. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  30106. }
  30107. } );
  30108. Object.defineProperties( WebGLRenderer.prototype, {
  30109. shadowMapEnabled: {
  30110. get: function () {
  30111. return this.shadowMap.enabled;
  30112. },
  30113. set: function ( value ) {
  30114. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  30115. this.shadowMap.enabled = value;
  30116. }
  30117. },
  30118. shadowMapType: {
  30119. get: function () {
  30120. return this.shadowMap.type;
  30121. },
  30122. set: function ( value ) {
  30123. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  30124. this.shadowMap.type = value;
  30125. }
  30126. },
  30127. shadowMapCullFace: {
  30128. get: function () {
  30129. return this.shadowMap.cullFace;
  30130. },
  30131. set: function ( value ) {
  30132. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.' );
  30133. this.shadowMap.cullFace = value;
  30134. }
  30135. }
  30136. } );
  30137. Object.defineProperties( WebGLShadowMap.prototype, {
  30138. cullFace: {
  30139. get: function () {
  30140. return this.renderReverseSided ? CullFaceFront : CullFaceBack;
  30141. },
  30142. set: function ( cullFace ) {
  30143. var value = ( cullFace !== CullFaceBack );
  30144. console.warn( "WebGLRenderer: .shadowMap.cullFace is deprecated. Set .shadowMap.renderReverseSided to " + value + "." );
  30145. this.renderReverseSided = value;
  30146. }
  30147. }
  30148. } );
  30149. //
  30150. Object.defineProperties( WebGLRenderTarget.prototype, {
  30151. wrapS: {
  30152. get: function () {
  30153. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  30154. return this.texture.wrapS;
  30155. },
  30156. set: function ( value ) {
  30157. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  30158. this.texture.wrapS = value;
  30159. }
  30160. },
  30161. wrapT: {
  30162. get: function () {
  30163. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  30164. return this.texture.wrapT;
  30165. },
  30166. set: function ( value ) {
  30167. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  30168. this.texture.wrapT = value;
  30169. }
  30170. },
  30171. magFilter: {
  30172. get: function () {
  30173. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  30174. return this.texture.magFilter;
  30175. },
  30176. set: function ( value ) {
  30177. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  30178. this.texture.magFilter = value;
  30179. }
  30180. },
  30181. minFilter: {
  30182. get: function () {
  30183. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  30184. return this.texture.minFilter;
  30185. },
  30186. set: function ( value ) {
  30187. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  30188. this.texture.minFilter = value;
  30189. }
  30190. },
  30191. anisotropy: {
  30192. get: function () {
  30193. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  30194. return this.texture.anisotropy;
  30195. },
  30196. set: function ( value ) {
  30197. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  30198. this.texture.anisotropy = value;
  30199. }
  30200. },
  30201. offset: {
  30202. get: function () {
  30203. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  30204. return this.texture.offset;
  30205. },
  30206. set: function ( value ) {
  30207. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  30208. this.texture.offset = value;
  30209. }
  30210. },
  30211. repeat: {
  30212. get: function () {
  30213. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  30214. return this.texture.repeat;
  30215. },
  30216. set: function ( value ) {
  30217. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  30218. this.texture.repeat = value;
  30219. }
  30220. },
  30221. format: {
  30222. get: function () {
  30223. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  30224. return this.texture.format;
  30225. },
  30226. set: function ( value ) {
  30227. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  30228. this.texture.format = value;
  30229. }
  30230. },
  30231. type: {
  30232. get: function () {
  30233. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  30234. return this.texture.type;
  30235. },
  30236. set: function ( value ) {
  30237. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  30238. this.texture.type = value;
  30239. }
  30240. },
  30241. generateMipmaps: {
  30242. get: function () {
  30243. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  30244. return this.texture.generateMipmaps;
  30245. },
  30246. set: function ( value ) {
  30247. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  30248. this.texture.generateMipmaps = value;
  30249. }
  30250. }
  30251. } );
  30252. //
  30253. Audio.prototype.load = function ( file ) {
  30254. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  30255. var scope = this;
  30256. var audioLoader = new AudioLoader();
  30257. audioLoader.load( file, function ( buffer ) {
  30258. scope.setBuffer( buffer );
  30259. } );
  30260. return this;
  30261. };
  30262. AudioAnalyser.prototype.getData = function () {
  30263. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  30264. return this.getFrequencyData();
  30265. };
  30266. //
  30267. var GeometryUtils = {
  30268. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  30269. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  30270. var matrix;
  30271. if ( geometry2.isMesh ) {
  30272. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  30273. matrix = geometry2.matrix;
  30274. geometry2 = geometry2.geometry;
  30275. }
  30276. geometry1.merge( geometry2, matrix, materialIndexOffset );
  30277. },
  30278. center: function ( geometry ) {
  30279. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  30280. return geometry.center();
  30281. }
  30282. };
  30283. var ImageUtils = {
  30284. crossOrigin: undefined,
  30285. loadTexture: function ( url, mapping, onLoad, onError ) {
  30286. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  30287. var loader = new TextureLoader();
  30288. loader.setCrossOrigin( this.crossOrigin );
  30289. var texture = loader.load( url, onLoad, undefined, onError );
  30290. if ( mapping ) texture.mapping = mapping;
  30291. return texture;
  30292. },
  30293. loadTextureCube: function ( urls, mapping, onLoad, onError ) {
  30294. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  30295. var loader = new CubeTextureLoader();
  30296. loader.setCrossOrigin( this.crossOrigin );
  30297. var texture = loader.load( urls, onLoad, undefined, onError );
  30298. if ( mapping ) texture.mapping = mapping;
  30299. return texture;
  30300. },
  30301. loadCompressedTexture: function () {
  30302. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  30303. },
  30304. loadCompressedTextureCube: function () {
  30305. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  30306. }
  30307. };
  30308. //
  30309. function Projector() {
  30310. console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' );
  30311. this.projectVector = function ( vector, camera ) {
  30312. console.warn( 'THREE.Projector: .projectVector() is now vector.project().' );
  30313. vector.project( camera );
  30314. };
  30315. this.unprojectVector = function ( vector, camera ) {
  30316. console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' );
  30317. vector.unproject( camera );
  30318. };
  30319. this.pickingRay = function () {
  30320. console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' );
  30321. };
  30322. }
  30323. //
  30324. function CanvasRenderer() {
  30325. console.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' );
  30326. this.domElement = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  30327. this.clear = function () {};
  30328. this.render = function () {};
  30329. this.setClearColor = function () {};
  30330. this.setSize = function () {};
  30331. }
  30332. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  30333. exports.WebGLRenderTarget = WebGLRenderTarget;
  30334. exports.WebGLRenderer = WebGLRenderer;
  30335. exports.ShaderLib = ShaderLib;
  30336. exports.UniformsLib = UniformsLib;
  30337. exports.UniformsUtils = UniformsUtils;
  30338. exports.ShaderChunk = ShaderChunk;
  30339. exports.FogExp2 = FogExp2;
  30340. exports.Fog = Fog;
  30341. exports.Scene = Scene;
  30342. exports.LensFlare = LensFlare;
  30343. exports.Sprite = Sprite;
  30344. exports.LOD = LOD;
  30345. exports.SkinnedMesh = SkinnedMesh;
  30346. exports.Skeleton = Skeleton;
  30347. exports.Bone = Bone;
  30348. exports.Mesh = Mesh;
  30349. exports.LineSegments = LineSegments;
  30350. exports.Line = Line;
  30351. exports.Points = Points;
  30352. exports.Group = Group;
  30353. exports.VideoTexture = VideoTexture;
  30354. exports.DataTexture = DataTexture;
  30355. exports.CompressedTexture = CompressedTexture;
  30356. exports.CubeTexture = CubeTexture;
  30357. exports.CanvasTexture = CanvasTexture;
  30358. exports.DepthTexture = DepthTexture;
  30359. exports.Texture = Texture;
  30360. exports.CompressedTextureLoader = CompressedTextureLoader;
  30361. exports.DataTextureLoader = DataTextureLoader;
  30362. exports.CubeTextureLoader = CubeTextureLoader;
  30363. exports.TextureLoader = TextureLoader;
  30364. exports.ObjectLoader = ObjectLoader;
  30365. exports.MaterialLoader = MaterialLoader;
  30366. exports.BufferGeometryLoader = BufferGeometryLoader;
  30367. exports.DefaultLoadingManager = DefaultLoadingManager;
  30368. exports.LoadingManager = LoadingManager;
  30369. exports.JSONLoader = JSONLoader;
  30370. exports.ImageLoader = ImageLoader;
  30371. exports.FontLoader = FontLoader;
  30372. exports.FileLoader = FileLoader;
  30373. exports.Loader = Loader;
  30374. exports.Cache = Cache;
  30375. exports.AudioLoader = AudioLoader;
  30376. exports.SpotLightShadow = SpotLightShadow;
  30377. exports.SpotLight = SpotLight;
  30378. exports.PointLight = PointLight;
  30379. exports.RectAreaLight = RectAreaLight;
  30380. exports.HemisphereLight = HemisphereLight;
  30381. exports.DirectionalLightShadow = DirectionalLightShadow;
  30382. exports.DirectionalLight = DirectionalLight;
  30383. exports.AmbientLight = AmbientLight;
  30384. exports.LightShadow = LightShadow;
  30385. exports.Light = Light;
  30386. exports.StereoCamera = StereoCamera;
  30387. exports.PerspectiveCamera = PerspectiveCamera;
  30388. exports.OrthographicCamera = OrthographicCamera;
  30389. exports.CubeCamera = CubeCamera;
  30390. exports.Camera = Camera;
  30391. exports.AudioListener = AudioListener;
  30392. exports.PositionalAudio = PositionalAudio;
  30393. exports.AudioContext = AudioContext;
  30394. exports.AudioAnalyser = AudioAnalyser;
  30395. exports.Audio = Audio;
  30396. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  30397. exports.StringKeyframeTrack = StringKeyframeTrack;
  30398. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  30399. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  30400. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  30401. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  30402. exports.PropertyMixer = PropertyMixer;
  30403. exports.PropertyBinding = PropertyBinding;
  30404. exports.KeyframeTrack = KeyframeTrack;
  30405. exports.AnimationUtils = AnimationUtils;
  30406. exports.AnimationObjectGroup = AnimationObjectGroup;
  30407. exports.AnimationMixer = AnimationMixer;
  30408. exports.AnimationClip = AnimationClip;
  30409. exports.Uniform = Uniform;
  30410. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  30411. exports.BufferGeometry = BufferGeometry;
  30412. exports.GeometryIdCount = GeometryIdCount;
  30413. exports.Geometry = Geometry;
  30414. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  30415. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  30416. exports.InterleavedBuffer = InterleavedBuffer;
  30417. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  30418. exports.Face3 = Face3;
  30419. exports.Object3D = Object3D;
  30420. exports.Raycaster = Raycaster;
  30421. exports.Layers = Layers;
  30422. exports.EventDispatcher = EventDispatcher;
  30423. exports.Clock = Clock;
  30424. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  30425. exports.LinearInterpolant = LinearInterpolant;
  30426. exports.DiscreteInterpolant = DiscreteInterpolant;
  30427. exports.CubicInterpolant = CubicInterpolant;
  30428. exports.Interpolant = Interpolant;
  30429. exports.Triangle = Triangle;
  30430. exports.Math = _Math;
  30431. exports.Spherical = Spherical;
  30432. exports.Cylindrical = Cylindrical;
  30433. exports.Plane = Plane;
  30434. exports.Frustum = Frustum;
  30435. exports.Sphere = Sphere;
  30436. exports.Ray = Ray;
  30437. exports.Matrix4 = Matrix4;
  30438. exports.Matrix3 = Matrix3;
  30439. exports.Box3 = Box3;
  30440. exports.Box2 = Box2;
  30441. exports.Line3 = Line3;
  30442. exports.Euler = Euler;
  30443. exports.Vector4 = Vector4;
  30444. exports.Vector3 = Vector3;
  30445. exports.Vector2 = Vector2;
  30446. exports.Quaternion = Quaternion;
  30447. exports.Color = Color;
  30448. exports.MorphBlendMesh = MorphBlendMesh;
  30449. exports.ImmediateRenderObject = ImmediateRenderObject;
  30450. exports.VertexNormalsHelper = VertexNormalsHelper;
  30451. exports.SpotLightHelper = SpotLightHelper;
  30452. exports.SkeletonHelper = SkeletonHelper;
  30453. exports.PointLightHelper = PointLightHelper;
  30454. exports.RectAreaLightHelper = RectAreaLightHelper;
  30455. exports.HemisphereLightHelper = HemisphereLightHelper;
  30456. exports.GridHelper = GridHelper;
  30457. exports.PolarGridHelper = PolarGridHelper;
  30458. exports.FaceNormalsHelper = FaceNormalsHelper;
  30459. exports.DirectionalLightHelper = DirectionalLightHelper;
  30460. exports.CameraHelper = CameraHelper;
  30461. exports.BoxHelper = BoxHelper;
  30462. exports.ArrowHelper = ArrowHelper;
  30463. exports.AxisHelper = AxisHelper;
  30464. exports.CatmullRomCurve3 = CatmullRomCurve3;
  30465. exports.CubicBezierCurve3 = CubicBezierCurve3;
  30466. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  30467. exports.LineCurve3 = LineCurve3;
  30468. exports.ArcCurve = ArcCurve;
  30469. exports.EllipseCurve = EllipseCurve;
  30470. exports.SplineCurve = SplineCurve;
  30471. exports.CubicBezierCurve = CubicBezierCurve;
  30472. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  30473. exports.LineCurve = LineCurve;
  30474. exports.Shape = Shape;
  30475. exports.Path = Path;
  30476. exports.ShapePath = ShapePath;
  30477. exports.Font = Font;
  30478. exports.CurvePath = CurvePath;
  30479. exports.Curve = Curve;
  30480. exports.ShapeUtils = ShapeUtils;
  30481. exports.SceneUtils = SceneUtils;
  30482. exports.WireframeGeometry = WireframeGeometry;
  30483. exports.ParametricGeometry = ParametricGeometry;
  30484. exports.ParametricBufferGeometry = ParametricBufferGeometry;
  30485. exports.TetrahedronGeometry = TetrahedronGeometry;
  30486. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  30487. exports.OctahedronGeometry = OctahedronGeometry;
  30488. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  30489. exports.IcosahedronGeometry = IcosahedronGeometry;
  30490. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  30491. exports.DodecahedronGeometry = DodecahedronGeometry;
  30492. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  30493. exports.PolyhedronGeometry = PolyhedronGeometry;
  30494. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  30495. exports.TubeGeometry = TubeGeometry;
  30496. exports.TubeBufferGeometry = TubeBufferGeometry;
  30497. exports.TorusKnotGeometry = TorusKnotGeometry;
  30498. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  30499. exports.TorusGeometry = TorusGeometry;
  30500. exports.TorusBufferGeometry = TorusBufferGeometry;
  30501. exports.TextGeometry = TextGeometry;
  30502. exports.SphereGeometry = SphereGeometry;
  30503. exports.SphereBufferGeometry = SphereBufferGeometry;
  30504. exports.RingGeometry = RingGeometry;
  30505. exports.RingBufferGeometry = RingBufferGeometry;
  30506. exports.PlaneGeometry = PlaneGeometry;
  30507. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  30508. exports.LatheGeometry = LatheGeometry;
  30509. exports.LatheBufferGeometry = LatheBufferGeometry;
  30510. exports.ShapeGeometry = ShapeGeometry;
  30511. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  30512. exports.ExtrudeGeometry = ExtrudeGeometry;
  30513. exports.EdgesGeometry = EdgesGeometry;
  30514. exports.ConeGeometry = ConeGeometry;
  30515. exports.ConeBufferGeometry = ConeBufferGeometry;
  30516. exports.CylinderGeometry = CylinderGeometry;
  30517. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  30518. exports.CircleGeometry = CircleGeometry;
  30519. exports.CircleBufferGeometry = CircleBufferGeometry;
  30520. exports.BoxGeometry = BoxGeometry;
  30521. exports.BoxBufferGeometry = BoxBufferGeometry;
  30522. exports.ShadowMaterial = ShadowMaterial;
  30523. exports.SpriteMaterial = SpriteMaterial;
  30524. exports.RawShaderMaterial = RawShaderMaterial;
  30525. exports.ShaderMaterial = ShaderMaterial;
  30526. exports.PointsMaterial = PointsMaterial;
  30527. exports.MultiMaterial = MultiMaterial;
  30528. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  30529. exports.MeshStandardMaterial = MeshStandardMaterial;
  30530. exports.MeshPhongMaterial = MeshPhongMaterial;
  30531. exports.MeshToonMaterial = MeshToonMaterial;
  30532. exports.MeshNormalMaterial = MeshNormalMaterial;
  30533. exports.MeshLambertMaterial = MeshLambertMaterial;
  30534. exports.MeshDepthMaterial = MeshDepthMaterial;
  30535. exports.MeshBasicMaterial = MeshBasicMaterial;
  30536. exports.LineDashedMaterial = LineDashedMaterial;
  30537. exports.LineBasicMaterial = LineBasicMaterial;
  30538. exports.Material = Material;
  30539. exports.Float64BufferAttribute = Float64BufferAttribute;
  30540. exports.Float32BufferAttribute = Float32BufferAttribute;
  30541. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  30542. exports.Int32BufferAttribute = Int32BufferAttribute;
  30543. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  30544. exports.Int16BufferAttribute = Int16BufferAttribute;
  30545. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  30546. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  30547. exports.Int8BufferAttribute = Int8BufferAttribute;
  30548. exports.BufferAttribute = BufferAttribute;
  30549. exports.REVISION = REVISION;
  30550. exports.MOUSE = MOUSE;
  30551. exports.CullFaceNone = CullFaceNone;
  30552. exports.CullFaceBack = CullFaceBack;
  30553. exports.CullFaceFront = CullFaceFront;
  30554. exports.CullFaceFrontBack = CullFaceFrontBack;
  30555. exports.FrontFaceDirectionCW = FrontFaceDirectionCW;
  30556. exports.FrontFaceDirectionCCW = FrontFaceDirectionCCW;
  30557. exports.BasicShadowMap = BasicShadowMap;
  30558. exports.PCFShadowMap = PCFShadowMap;
  30559. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  30560. exports.FrontSide = FrontSide;
  30561. exports.BackSide = BackSide;
  30562. exports.DoubleSide = DoubleSide;
  30563. exports.FlatShading = FlatShading;
  30564. exports.SmoothShading = SmoothShading;
  30565. exports.NoColors = NoColors;
  30566. exports.FaceColors = FaceColors;
  30567. exports.VertexColors = VertexColors;
  30568. exports.NoBlending = NoBlending;
  30569. exports.NormalBlending = NormalBlending;
  30570. exports.AdditiveBlending = AdditiveBlending;
  30571. exports.SubtractiveBlending = SubtractiveBlending;
  30572. exports.MultiplyBlending = MultiplyBlending;
  30573. exports.CustomBlending = CustomBlending;
  30574. exports.AddEquation = AddEquation;
  30575. exports.SubtractEquation = SubtractEquation;
  30576. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  30577. exports.MinEquation = MinEquation;
  30578. exports.MaxEquation = MaxEquation;
  30579. exports.ZeroFactor = ZeroFactor;
  30580. exports.OneFactor = OneFactor;
  30581. exports.SrcColorFactor = SrcColorFactor;
  30582. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  30583. exports.SrcAlphaFactor = SrcAlphaFactor;
  30584. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  30585. exports.DstAlphaFactor = DstAlphaFactor;
  30586. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  30587. exports.DstColorFactor = DstColorFactor;
  30588. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  30589. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  30590. exports.NeverDepth = NeverDepth;
  30591. exports.AlwaysDepth = AlwaysDepth;
  30592. exports.LessDepth = LessDepth;
  30593. exports.LessEqualDepth = LessEqualDepth;
  30594. exports.EqualDepth = EqualDepth;
  30595. exports.GreaterEqualDepth = GreaterEqualDepth;
  30596. exports.GreaterDepth = GreaterDepth;
  30597. exports.NotEqualDepth = NotEqualDepth;
  30598. exports.MultiplyOperation = MultiplyOperation;
  30599. exports.MixOperation = MixOperation;
  30600. exports.AddOperation = AddOperation;
  30601. exports.NoToneMapping = NoToneMapping;
  30602. exports.LinearToneMapping = LinearToneMapping;
  30603. exports.ReinhardToneMapping = ReinhardToneMapping;
  30604. exports.Uncharted2ToneMapping = Uncharted2ToneMapping;
  30605. exports.CineonToneMapping = CineonToneMapping;
  30606. exports.UVMapping = UVMapping;
  30607. exports.CubeReflectionMapping = CubeReflectionMapping;
  30608. exports.CubeRefractionMapping = CubeRefractionMapping;
  30609. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  30610. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  30611. exports.SphericalReflectionMapping = SphericalReflectionMapping;
  30612. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  30613. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  30614. exports.RepeatWrapping = RepeatWrapping;
  30615. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  30616. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  30617. exports.NearestFilter = NearestFilter;
  30618. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  30619. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  30620. exports.LinearFilter = LinearFilter;
  30621. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  30622. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  30623. exports.UnsignedByteType = UnsignedByteType;
  30624. exports.ByteType = ByteType;
  30625. exports.ShortType = ShortType;
  30626. exports.UnsignedShortType = UnsignedShortType;
  30627. exports.IntType = IntType;
  30628. exports.UnsignedIntType = UnsignedIntType;
  30629. exports.FloatType = FloatType;
  30630. exports.HalfFloatType = HalfFloatType;
  30631. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  30632. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  30633. exports.UnsignedShort565Type = UnsignedShort565Type;
  30634. exports.UnsignedInt248Type = UnsignedInt248Type;
  30635. exports.AlphaFormat = AlphaFormat;
  30636. exports.RGBFormat = RGBFormat;
  30637. exports.RGBAFormat = RGBAFormat;
  30638. exports.LuminanceFormat = LuminanceFormat;
  30639. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  30640. exports.RGBEFormat = RGBEFormat;
  30641. exports.DepthFormat = DepthFormat;
  30642. exports.DepthStencilFormat = DepthStencilFormat;
  30643. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  30644. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  30645. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  30646. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  30647. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  30648. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  30649. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  30650. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  30651. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  30652. exports.LoopOnce = LoopOnce;
  30653. exports.LoopRepeat = LoopRepeat;
  30654. exports.LoopPingPong = LoopPingPong;
  30655. exports.InterpolateDiscrete = InterpolateDiscrete;
  30656. exports.InterpolateLinear = InterpolateLinear;
  30657. exports.InterpolateSmooth = InterpolateSmooth;
  30658. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  30659. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  30660. exports.WrapAroundEnding = WrapAroundEnding;
  30661. exports.TrianglesDrawMode = TrianglesDrawMode;
  30662. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  30663. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  30664. exports.LinearEncoding = LinearEncoding;
  30665. exports.sRGBEncoding = sRGBEncoding;
  30666. exports.GammaEncoding = GammaEncoding;
  30667. exports.RGBEEncoding = RGBEEncoding;
  30668. exports.LogLuvEncoding = LogLuvEncoding;
  30669. exports.RGBM7Encoding = RGBM7Encoding;
  30670. exports.RGBM16Encoding = RGBM16Encoding;
  30671. exports.RGBDEncoding = RGBDEncoding;
  30672. exports.BasicDepthPacking = BasicDepthPacking;
  30673. exports.RGBADepthPacking = RGBADepthPacking;
  30674. exports.CubeGeometry = BoxGeometry;
  30675. exports.Face4 = Face4;
  30676. exports.LineStrip = LineStrip;
  30677. exports.LinePieces = LinePieces;
  30678. exports.MeshFaceMaterial = MeshFaceMaterial;
  30679. exports.PointCloud = PointCloud;
  30680. exports.Particle = Particle;
  30681. exports.ParticleSystem = ParticleSystem;
  30682. exports.PointCloudMaterial = PointCloudMaterial;
  30683. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  30684. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  30685. exports.Vertex = Vertex;
  30686. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  30687. exports.Int8Attribute = Int8Attribute;
  30688. exports.Uint8Attribute = Uint8Attribute;
  30689. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  30690. exports.Int16Attribute = Int16Attribute;
  30691. exports.Uint16Attribute = Uint16Attribute;
  30692. exports.Int32Attribute = Int32Attribute;
  30693. exports.Uint32Attribute = Uint32Attribute;
  30694. exports.Float32Attribute = Float32Attribute;
  30695. exports.Float64Attribute = Float64Attribute;
  30696. exports.ClosedSplineCurve3 = ClosedSplineCurve3;
  30697. exports.SplineCurve3 = SplineCurve3;
  30698. exports.Spline = Spline;
  30699. exports.BoundingBoxHelper = BoundingBoxHelper;
  30700. exports.EdgesHelper = EdgesHelper;
  30701. exports.WireframeHelper = WireframeHelper;
  30702. exports.XHRLoader = XHRLoader;
  30703. exports.BinaryTextureLoader = BinaryTextureLoader;
  30704. exports.GeometryUtils = GeometryUtils;
  30705. exports.ImageUtils = ImageUtils;
  30706. exports.Projector = Projector;
  30707. exports.CanvasRenderer = CanvasRenderer;
  30708. Object.defineProperty(exports, '__esModule', { value: true });
  30709. })));
  30710. },{}],43:[function(_dereq_,module,exports){
  30711. /**
  30712. * @author Tim Knip / http://www.floorplanner.com/ / tim at floorplanner.com
  30713. * @author Tony Parisi / http://www.tonyparisi.com/
  30714. */
  30715. THREE.ColladaLoader = function () {
  30716. var COLLADA = null;
  30717. var scene = null;
  30718. var visualScene;
  30719. var kinematicsModel;
  30720. var readyCallbackFunc = null;
  30721. var sources = {};
  30722. var images = {};
  30723. var animations = {};
  30724. var controllers = {};
  30725. var geometries = {};
  30726. var materials = {};
  30727. var effects = {};
  30728. var cameras = {};
  30729. var lights = {};
  30730. var animData;
  30731. var kinematics;
  30732. var visualScenes;
  30733. var kinematicsModels;
  30734. var baseUrl;
  30735. var morphs;
  30736. var skins;
  30737. var flip_uv = true;
  30738. var preferredShading = THREE.SmoothShading;
  30739. var options = {
  30740. // Force Geometry to always be centered at the local origin of the
  30741. // containing Mesh.
  30742. centerGeometry: false,
  30743. // Axis conversion is done for geometries, animations, and controllers.
  30744. // If we ever pull cameras or lights out of the COLLADA file, they'll
  30745. // need extra work.
  30746. convertUpAxis: false,
  30747. subdivideFaces: true,
  30748. upAxis: 'Y',
  30749. // For reflective or refractive materials we'll use this cubemap
  30750. defaultEnvMap: null
  30751. };
  30752. var colladaUnit = 1.0;
  30753. var colladaUp = 'Y';
  30754. var upConversion = null;
  30755. function load ( url, readyCallback, progressCallback, failCallback ) {
  30756. var length = 0;
  30757. if ( document.implementation && document.implementation.createDocument ) {
  30758. var request = new XMLHttpRequest();
  30759. request.onreadystatechange = function() {
  30760. if ( request.readyState === 4 ) {
  30761. if ( request.status === 0 || request.status === 200 ) {
  30762. if ( request.response ) {
  30763. readyCallbackFunc = readyCallback;
  30764. parse( request.response, undefined, url );
  30765. } else {
  30766. if ( failCallback ) {
  30767. failCallback( { type: 'error', url: url } );
  30768. } else {
  30769. console.error( "ColladaLoader: Empty or non-existing file (" + url + ")" );
  30770. }
  30771. }
  30772. }else{
  30773. if( failCallback ){
  30774. failCallback( { type: 'error', url: url } );
  30775. }else{
  30776. console.error( 'ColladaLoader: Couldn\'t load "' + url + '" (' + request.status + ')' );
  30777. }
  30778. }
  30779. } else if ( request.readyState === 3 ) {
  30780. if ( progressCallback ) {
  30781. if ( length === 0 ) {
  30782. length = request.getResponseHeader( "Content-Length" );
  30783. }
  30784. progressCallback( { total: length, loaded: request.responseText.length } );
  30785. }
  30786. }
  30787. };
  30788. request.open( "GET", url, true );
  30789. request.send( null );
  30790. } else {
  30791. alert( "Don't know how to parse XML!" );
  30792. }
  30793. }
  30794. function parse( text, callBack, url ) {
  30795. COLLADA = new DOMParser().parseFromString( text, 'text/xml' );
  30796. callBack = callBack || readyCallbackFunc;
  30797. if ( url !== undefined ) {
  30798. var parts = url.split( '/' );
  30799. parts.pop();
  30800. baseUrl = ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  30801. }
  30802. parseAsset();
  30803. setUpConversion();
  30804. images = parseLib( "library_images image", _Image, "image" );
  30805. materials = parseLib( "library_materials material", Material, "material" );
  30806. effects = parseLib( "library_effects effect", Effect, "effect" );
  30807. geometries = parseLib( "library_geometries geometry", Geometry, "geometry" );
  30808. cameras = parseLib( "library_cameras camera", Camera, "camera" );
  30809. lights = parseLib( "library_lights light", Light, "light" );
  30810. controllers = parseLib( "library_controllers controller", Controller, "controller" );
  30811. animations = parseLib( "library_animations animation", Animation, "animation" );
  30812. visualScenes = parseLib( "library_visual_scenes visual_scene", VisualScene, "visual_scene" );
  30813. kinematicsModels = parseLib( "library_kinematics_models kinematics_model", KinematicsModel, "kinematics_model" );
  30814. morphs = [];
  30815. skins = [];
  30816. visualScene = parseScene();
  30817. scene = new THREE.Group();
  30818. for ( var i = 0; i < visualScene.nodes.length; i ++ ) {
  30819. scene.add( createSceneGraph( visualScene.nodes[ i ] ) );
  30820. }
  30821. // unit conversion
  30822. scene.scale.multiplyScalar( colladaUnit );
  30823. createAnimations();
  30824. kinematicsModel = parseKinematicsModel();
  30825. createKinematics();
  30826. var result = {
  30827. scene: scene,
  30828. morphs: morphs,
  30829. skins: skins,
  30830. animations: animData,
  30831. kinematics: kinematics,
  30832. dae: {
  30833. images: images,
  30834. materials: materials,
  30835. cameras: cameras,
  30836. lights: lights,
  30837. effects: effects,
  30838. geometries: geometries,
  30839. controllers: controllers,
  30840. animations: animations,
  30841. visualScenes: visualScenes,
  30842. visualScene: visualScene,
  30843. scene: visualScene,
  30844. kinematicsModels: kinematicsModels,
  30845. kinematicsModel: kinematicsModel
  30846. }
  30847. };
  30848. if ( callBack ) {
  30849. callBack( result );
  30850. }
  30851. return result;
  30852. }
  30853. function setPreferredShading ( shading ) {
  30854. preferredShading = shading;
  30855. }
  30856. function parseAsset () {
  30857. var elements = COLLADA.querySelectorAll('asset');
  30858. var element = elements[0];
  30859. if ( element && element.childNodes ) {
  30860. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  30861. var child = element.childNodes[ i ];
  30862. switch ( child.nodeName ) {
  30863. case 'unit':
  30864. var meter = child.getAttribute( 'meter' );
  30865. if ( meter ) {
  30866. colladaUnit = parseFloat( meter );
  30867. }
  30868. break;
  30869. case 'up_axis':
  30870. colladaUp = child.textContent.charAt(0);
  30871. break;
  30872. }
  30873. }
  30874. }
  30875. }
  30876. function parseLib ( q, classSpec, prefix ) {
  30877. var elements = COLLADA.querySelectorAll(q);
  30878. var lib = {};
  30879. var i = 0;
  30880. var elementsLength = elements.length;
  30881. for ( var j = 0; j < elementsLength; j ++ ) {
  30882. var element = elements[j];
  30883. var daeElement = ( new classSpec() ).parse( element );
  30884. if ( !daeElement.id || daeElement.id.length === 0 ) daeElement.id = prefix + ( i ++ );
  30885. lib[ daeElement.id ] = daeElement;
  30886. }
  30887. return lib;
  30888. }
  30889. function parseScene() {
  30890. var sceneElement = COLLADA.querySelectorAll('scene instance_visual_scene')[0];
  30891. if ( sceneElement ) {
  30892. var url = sceneElement.getAttribute( 'url' ).replace( /^#/, '' );
  30893. return visualScenes[ url.length > 0 ? url : 'visual_scene0' ];
  30894. } else {
  30895. return null;
  30896. }
  30897. }
  30898. function parseKinematicsModel() {
  30899. var kinematicsModelElement = COLLADA.querySelectorAll('instance_kinematics_model')[0];
  30900. if ( kinematicsModelElement ) {
  30901. var url = kinematicsModelElement.getAttribute( 'url' ).replace(/^#/, '');
  30902. return kinematicsModels[ url.length > 0 ? url : 'kinematics_model0' ];
  30903. } else {
  30904. return null;
  30905. }
  30906. }
  30907. function createAnimations() {
  30908. animData = [];
  30909. // fill in the keys
  30910. recurseHierarchy( scene );
  30911. }
  30912. function recurseHierarchy( node ) {
  30913. var n = visualScene.getChildById( node.colladaId, true ),
  30914. newData = null;
  30915. if ( n && n.keys ) {
  30916. newData = {
  30917. fps: 60,
  30918. hierarchy: [ {
  30919. node: n,
  30920. keys: n.keys,
  30921. sids: n.sids
  30922. } ],
  30923. node: node,
  30924. name: 'animation_' + node.name,
  30925. length: 0
  30926. };
  30927. animData.push(newData);
  30928. for ( var i = 0, il = n.keys.length; i < il; i ++ ) {
  30929. newData.length = Math.max( newData.length, n.keys[i].time );
  30930. }
  30931. } else {
  30932. newData = {
  30933. hierarchy: [ {
  30934. keys: [],
  30935. sids: []
  30936. } ]
  30937. }
  30938. }
  30939. for ( var i = 0, il = node.children.length; i < il; i ++ ) {
  30940. var d = recurseHierarchy( node.children[i] );
  30941. for ( var j = 0, jl = d.hierarchy.length; j < jl; j ++ ) {
  30942. newData.hierarchy.push( {
  30943. keys: [],
  30944. sids: []
  30945. } );
  30946. }
  30947. }
  30948. return newData;
  30949. }
  30950. function calcAnimationBounds () {
  30951. var start = 1000000;
  30952. var end = -start;
  30953. var frames = 0;
  30954. var ID;
  30955. for ( var id in animations ) {
  30956. var animation = animations[ id ];
  30957. ID = ID || animation.id;
  30958. for ( var i = 0; i < animation.sampler.length; i ++ ) {
  30959. var sampler = animation.sampler[ i ];
  30960. sampler.create();
  30961. start = Math.min( start, sampler.startTime );
  30962. end = Math.max( end, sampler.endTime );
  30963. frames = Math.max( frames, sampler.input.length );
  30964. }
  30965. }
  30966. return { start:start, end:end, frames:frames,ID:ID };
  30967. }
  30968. function createMorph ( geometry, ctrl ) {
  30969. var morphCtrl = ctrl instanceof InstanceController ? controllers[ ctrl.url ] : ctrl;
  30970. if ( !morphCtrl || !morphCtrl.morph ) {
  30971. console.log("could not find morph controller!");
  30972. return;
  30973. }
  30974. var morph = morphCtrl.morph;
  30975. for ( var i = 0; i < morph.targets.length; i ++ ) {
  30976. var target_id = morph.targets[ i ];
  30977. var daeGeometry = geometries[ target_id ];
  30978. if ( !daeGeometry.mesh ||
  30979. !daeGeometry.mesh.primitives ||
  30980. !daeGeometry.mesh.primitives.length ) {
  30981. continue;
  30982. }
  30983. var target = daeGeometry.mesh.primitives[ 0 ].geometry;
  30984. if ( target.vertices.length === geometry.vertices.length ) {
  30985. geometry.morphTargets.push( { name: "target_1", vertices: target.vertices } );
  30986. }
  30987. }
  30988. geometry.morphTargets.push( { name: "target_Z", vertices: geometry.vertices } );
  30989. }
  30990. function createSkin ( geometry, ctrl, applyBindShape ) {
  30991. var skinCtrl = controllers[ ctrl.url ];
  30992. if ( !skinCtrl || !skinCtrl.skin ) {
  30993. console.log( "could not find skin controller!" );
  30994. return;
  30995. }
  30996. if ( !ctrl.skeleton || !ctrl.skeleton.length ) {
  30997. console.log( "could not find the skeleton for the skin!" );
  30998. return;
  30999. }
  31000. var skin = skinCtrl.skin;
  31001. var skeleton = visualScene.getChildById( ctrl.skeleton[ 0 ] );
  31002. var hierarchy = [];
  31003. applyBindShape = applyBindShape !== undefined ? applyBindShape : true;
  31004. var bones = [];
  31005. geometry.skinWeights = [];
  31006. geometry.skinIndices = [];
  31007. //createBones( geometry.bones, skin, hierarchy, skeleton, null, -1 );
  31008. //createWeights( skin, geometry.bones, geometry.skinIndices, geometry.skinWeights );
  31009. /*
  31010. geometry.animation = {
  31011. name: 'take_001',
  31012. fps: 30,
  31013. length: 2,
  31014. JIT: true,
  31015. hierarchy: hierarchy
  31016. };
  31017. */
  31018. if ( applyBindShape ) {
  31019. for ( var i = 0; i < geometry.vertices.length; i ++ ) {
  31020. geometry.vertices[ i ].applyMatrix4( skin.bindShapeMatrix );
  31021. }
  31022. }
  31023. }
  31024. function setupSkeleton ( node, bones, frame, parent ) {
  31025. node.world = node.world || new THREE.Matrix4();
  31026. node.localworld = node.localworld || new THREE.Matrix4();
  31027. node.world.copy( node.matrix );
  31028. node.localworld.copy( node.matrix );
  31029. if ( node.channels && node.channels.length ) {
  31030. var channel = node.channels[ 0 ];
  31031. var m = channel.sampler.output[ frame ];
  31032. if ( m instanceof THREE.Matrix4 ) {
  31033. node.world.copy( m );
  31034. node.localworld.copy(m);
  31035. if (frame === 0)
  31036. node.matrix.copy(m);
  31037. }
  31038. }
  31039. if ( parent ) {
  31040. node.world.multiplyMatrices( parent, node.world );
  31041. }
  31042. bones.push( node );
  31043. for ( var i = 0; i < node.nodes.length; i ++ ) {
  31044. setupSkeleton( node.nodes[ i ], bones, frame, node.world );
  31045. }
  31046. }
  31047. function setupSkinningMatrices ( bones, skin ) {
  31048. // FIXME: this is dumb...
  31049. for ( var i = 0; i < bones.length; i ++ ) {
  31050. var bone = bones[ i ];
  31051. var found = -1;
  31052. if ( bone.type != 'JOINT' ) continue;
  31053. for ( var j = 0; j < skin.joints.length; j ++ ) {
  31054. if ( bone.sid === skin.joints[ j ] ) {
  31055. found = j;
  31056. break;
  31057. }
  31058. }
  31059. if ( found >= 0 ) {
  31060. var inv = skin.invBindMatrices[ found ];
  31061. bone.invBindMatrix = inv;
  31062. bone.skinningMatrix = new THREE.Matrix4();
  31063. bone.skinningMatrix.multiplyMatrices(bone.world, inv); // (IBMi * JMi)
  31064. bone.animatrix = new THREE.Matrix4();
  31065. bone.animatrix.copy(bone.localworld);
  31066. bone.weights = [];
  31067. for ( var j = 0; j < skin.weights.length; j ++ ) {
  31068. for (var k = 0; k < skin.weights[ j ].length; k ++ ) {
  31069. var w = skin.weights[ j ][ k ];
  31070. if ( w.joint === found ) {
  31071. bone.weights.push( w );
  31072. }
  31073. }
  31074. }
  31075. } else {
  31076. console.warn( "ColladaLoader: Could not find joint '" + bone.sid + "'." );
  31077. bone.skinningMatrix = new THREE.Matrix4();
  31078. bone.weights = [];
  31079. }
  31080. }
  31081. }
  31082. //Walk the Collada tree and flatten the bones into a list, extract the position, quat and scale from the matrix
  31083. function flattenSkeleton(skeleton) {
  31084. var list = [];
  31085. var walk = function(parentid, node, list) {
  31086. var bone = {};
  31087. bone.name = node.sid;
  31088. bone.parent = parentid;
  31089. bone.matrix = node.matrix;
  31090. var data = [ new THREE.Vector3(),new THREE.Quaternion(),new THREE.Vector3() ];
  31091. bone.matrix.decompose(data[0], data[1], data[2]);
  31092. bone.pos = [ data[0].x,data[0].y,data[0].z ];
  31093. bone.scl = [ data[2].x,data[2].y,data[2].z ];
  31094. bone.rotq = [ data[1].x,data[1].y,data[1].z,data[1].w ];
  31095. list.push(bone);
  31096. for (var i in node.nodes) {
  31097. walk(node.sid, node.nodes[i], list);
  31098. }
  31099. };
  31100. walk(-1, skeleton, list);
  31101. return list;
  31102. }
  31103. //Move the vertices into the pose that is proper for the start of the animation
  31104. function skinToBindPose(geometry,skeleton,skinController) {
  31105. var bones = [];
  31106. setupSkeleton( skeleton, bones, -1 );
  31107. setupSkinningMatrices( bones, skinController.skin );
  31108. var v = new THREE.Vector3();
  31109. var skinned = [];
  31110. for (var i = 0; i < geometry.vertices.length; i ++) {
  31111. skinned.push(new THREE.Vector3());
  31112. }
  31113. for ( i = 0; i < bones.length; i ++ ) {
  31114. if ( bones[ i ].type != 'JOINT' ) continue;
  31115. for ( var j = 0; j < bones[ i ].weights.length; j ++ ) {
  31116. var w = bones[ i ].weights[ j ];
  31117. var vidx = w.index;
  31118. var weight = w.weight;
  31119. var o = geometry.vertices[vidx];
  31120. var s = skinned[vidx];
  31121. v.x = o.x;
  31122. v.y = o.y;
  31123. v.z = o.z;
  31124. v.applyMatrix4( bones[i].skinningMatrix );
  31125. s.x += (v.x * weight);
  31126. s.y += (v.y * weight);
  31127. s.z += (v.z * weight);
  31128. }
  31129. }
  31130. for (var i = 0; i < geometry.vertices.length; i ++) {
  31131. geometry.vertices[i] = skinned[i];
  31132. }
  31133. }
  31134. function applySkin ( geometry, instanceCtrl, frame ) {
  31135. var skinController = controllers[ instanceCtrl.url ];
  31136. frame = frame !== undefined ? frame : 40;
  31137. if ( !skinController || !skinController.skin ) {
  31138. console.log( 'ColladaLoader: Could not find skin controller.' );
  31139. return;
  31140. }
  31141. if ( !instanceCtrl.skeleton || !instanceCtrl.skeleton.length ) {
  31142. console.log( 'ColladaLoader: Could not find the skeleton for the skin. ' );
  31143. return;
  31144. }
  31145. var animationBounds = calcAnimationBounds();
  31146. var skeleton = visualScene.getChildById( instanceCtrl.skeleton[0], true ) || visualScene.getChildBySid( instanceCtrl.skeleton[0], true );
  31147. //flatten the skeleton into a list of bones
  31148. var bonelist = flattenSkeleton(skeleton);
  31149. var joints = skinController.skin.joints;
  31150. //sort that list so that the order reflects the order in the joint list
  31151. var sortedbones = [];
  31152. for (var i = 0; i < joints.length; i ++) {
  31153. for (var j = 0; j < bonelist.length; j ++) {
  31154. if (bonelist[j].name === joints[i]) {
  31155. sortedbones[i] = bonelist[j];
  31156. }
  31157. }
  31158. }
  31159. //hook up the parents by index instead of name
  31160. for (var i = 0; i < sortedbones.length; i ++) {
  31161. for (var j = 0; j < sortedbones.length; j ++) {
  31162. if (sortedbones[i].parent === sortedbones[j].name) {
  31163. sortedbones[i].parent = j;
  31164. }
  31165. }
  31166. }
  31167. var i, j, w, vidx, weight;
  31168. var v = new THREE.Vector3(), o, s;
  31169. // move vertices to bind shape
  31170. for ( i = 0; i < geometry.vertices.length; i ++ ) {
  31171. geometry.vertices[i].applyMatrix4( skinController.skin.bindShapeMatrix );
  31172. }
  31173. var skinIndices = [];
  31174. var skinWeights = [];
  31175. var weights = skinController.skin.weights;
  31176. // hook up the skin weights
  31177. // TODO - this might be a good place to choose greatest 4 weights
  31178. for ( var i =0; i < weights.length; i ++ ) {
  31179. 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);
  31180. 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);
  31181. skinIndices.push(indicies);
  31182. skinWeights.push(weight);
  31183. }
  31184. geometry.skinIndices = skinIndices;
  31185. geometry.skinWeights = skinWeights;
  31186. geometry.bones = sortedbones;
  31187. // process animation, or simply pose the rig if no animation
  31188. //create an animation for the animated bones
  31189. //NOTE: this has no effect when using morphtargets
  31190. var animationdata = { "name":animationBounds.ID,"fps":30,"length":animationBounds.frames / 30,"hierarchy":[] };
  31191. for (var j = 0; j < sortedbones.length; j ++) {
  31192. animationdata.hierarchy.push({ parent:sortedbones[j].parent, name:sortedbones[j].name, keys:[] });
  31193. }
  31194. console.log( 'ColladaLoader:', animationBounds.ID + ' has ' + sortedbones.length + ' bones.' );
  31195. skinToBindPose(geometry, skeleton, skinController);
  31196. for ( frame = 0; frame < animationBounds.frames; frame ++ ) {
  31197. var bones = [];
  31198. var skinned = [];
  31199. // process the frame and setup the rig with a fresh
  31200. // transform, possibly from the bone's animation channel(s)
  31201. setupSkeleton( skeleton, bones, frame );
  31202. setupSkinningMatrices( bones, skinController.skin );
  31203. for (var i = 0; i < bones.length; i ++) {
  31204. for (var j = 0; j < animationdata.hierarchy.length; j ++) {
  31205. if (animationdata.hierarchy[j].name === bones[i].sid) {
  31206. var key = {};
  31207. key.time = (frame / 30);
  31208. key.matrix = bones[i].animatrix;
  31209. if (frame === 0)
  31210. bones[i].matrix = key.matrix;
  31211. var data = [ new THREE.Vector3(),new THREE.Quaternion(),new THREE.Vector3() ];
  31212. key.matrix.decompose(data[0], data[1], data[2]);
  31213. key.pos = [ data[0].x,data[0].y,data[0].z ];
  31214. key.scl = [ data[2].x,data[2].y,data[2].z ];
  31215. key.rot = data[1];
  31216. animationdata.hierarchy[j].keys.push(key);
  31217. }
  31218. }
  31219. }
  31220. geometry.animation = animationdata;
  31221. }
  31222. }
  31223. function createKinematics() {
  31224. if ( kinematicsModel && kinematicsModel.joints.length === 0 ) {
  31225. kinematics = undefined;
  31226. return;
  31227. }
  31228. var jointMap = {};
  31229. var _addToMap = function( jointIndex, parentVisualElement ) {
  31230. var parentVisualElementId = parentVisualElement.getAttribute( 'id' );
  31231. var colladaNode = visualScene.getChildById( parentVisualElementId, true );
  31232. var joint = kinematicsModel.joints[ jointIndex ];
  31233. scene.traverse(function( node ) {
  31234. if ( node.colladaId == parentVisualElementId ) {
  31235. jointMap[ jointIndex ] = {
  31236. node: node,
  31237. transforms: colladaNode.transforms,
  31238. joint: joint,
  31239. position: joint.zeroPosition
  31240. };
  31241. }
  31242. });
  31243. };
  31244. kinematics = {
  31245. joints: kinematicsModel && kinematicsModel.joints,
  31246. getJointValue: function( jointIndex ) {
  31247. var jointData = jointMap[ jointIndex ];
  31248. if ( jointData ) {
  31249. return jointData.position;
  31250. } else {
  31251. console.log( 'getJointValue: joint ' + jointIndex + ' doesn\'t exist' );
  31252. }
  31253. },
  31254. setJointValue: function( jointIndex, value ) {
  31255. var jointData = jointMap[ jointIndex ];
  31256. if ( jointData ) {
  31257. var joint = jointData.joint;
  31258. if ( value > joint.limits.max || value < joint.limits.min ) {
  31259. console.log( 'setJointValue: joint ' + jointIndex + ' value ' + value + ' outside of limits (min: ' + joint.limits.min + ', max: ' + joint.limits.max + ')' );
  31260. } else if ( joint.static ) {
  31261. console.log( 'setJointValue: joint ' + jointIndex + ' is static' );
  31262. } else {
  31263. var threejsNode = jointData.node;
  31264. var axis = joint.axis;
  31265. var transforms = jointData.transforms;
  31266. var matrix = new THREE.Matrix4();
  31267. for (i = 0; i < transforms.length; i ++ ) {
  31268. var transform = transforms[ i ];
  31269. // kinda ghetto joint detection
  31270. if ( transform.sid && transform.sid.indexOf( 'joint' + jointIndex ) !== -1 ) {
  31271. // apply actual joint value here
  31272. switch ( joint.type ) {
  31273. case 'revolute':
  31274. matrix.multiply( m1.makeRotationAxis( axis, THREE.Math.degToRad(value) ) );
  31275. break;
  31276. case 'prismatic':
  31277. matrix.multiply( m1.makeTranslation(axis.x * value, axis.y * value, axis.z * value ) );
  31278. break;
  31279. default:
  31280. console.warn( 'setJointValue: unknown joint type: ' + joint.type );
  31281. break;
  31282. }
  31283. } else {
  31284. var m1 = new THREE.Matrix4();
  31285. switch ( transform.type ) {
  31286. case 'matrix':
  31287. matrix.multiply( transform.obj );
  31288. break;
  31289. case 'translate':
  31290. matrix.multiply( m1.makeTranslation( transform.obj.x, transform.obj.y, transform.obj.z ) );
  31291. break;
  31292. case 'rotate':
  31293. matrix.multiply( m1.makeRotationAxis( transform.obj, transform.angle ) );
  31294. break;
  31295. }
  31296. }
  31297. }
  31298. // apply the matrix to the threejs node
  31299. var elementsFloat32Arr = matrix.elements;
  31300. var elements = Array.prototype.slice.call( elementsFloat32Arr );
  31301. var elementsRowMajor = [
  31302. elements[ 0 ],
  31303. elements[ 4 ],
  31304. elements[ 8 ],
  31305. elements[ 12 ],
  31306. elements[ 1 ],
  31307. elements[ 5 ],
  31308. elements[ 9 ],
  31309. elements[ 13 ],
  31310. elements[ 2 ],
  31311. elements[ 6 ],
  31312. elements[ 10 ],
  31313. elements[ 14 ],
  31314. elements[ 3 ],
  31315. elements[ 7 ],
  31316. elements[ 11 ],
  31317. elements[ 15 ]
  31318. ];
  31319. threejsNode.matrix.set.apply( threejsNode.matrix, elementsRowMajor );
  31320. threejsNode.matrix.decompose( threejsNode.position, threejsNode.quaternion, threejsNode.scale );
  31321. }
  31322. } else {
  31323. console.log( 'setJointValue: joint ' + jointIndex + ' doesn\'t exist' );
  31324. }
  31325. }
  31326. };
  31327. var element = COLLADA.querySelector('scene instance_kinematics_scene');
  31328. if ( element ) {
  31329. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  31330. var child = element.childNodes[ i ];
  31331. if ( child.nodeType != 1 ) continue;
  31332. switch ( child.nodeName ) {
  31333. case 'bind_joint_axis':
  31334. var visualTarget = child.getAttribute( 'target' ).split( '/' ).pop();
  31335. var axis = child.querySelector('axis param').textContent;
  31336. var jointIndex = parseInt( axis.split( 'joint' ).pop().split( '.' )[0] );
  31337. var visualTargetElement = COLLADA.querySelector( '[sid="' + visualTarget + '"]' );
  31338. if ( visualTargetElement ) {
  31339. var parentVisualElement = visualTargetElement.parentElement;
  31340. _addToMap(jointIndex, parentVisualElement);
  31341. }
  31342. break;
  31343. default:
  31344. break;
  31345. }
  31346. }
  31347. }
  31348. }
  31349. function createSceneGraph ( node, parent ) {
  31350. var obj = new THREE.Object3D();
  31351. var skinned = false;
  31352. var skinController;
  31353. var morphController;
  31354. var i, j;
  31355. // FIXME: controllers
  31356. for ( i = 0; i < node.controllers.length; i ++ ) {
  31357. var controller = controllers[ node.controllers[ i ].url ];
  31358. switch ( controller.type ) {
  31359. case 'skin':
  31360. if ( geometries[ controller.skin.source ] ) {
  31361. var inst_geom = new InstanceGeometry();
  31362. inst_geom.url = controller.skin.source;
  31363. inst_geom.instance_material = node.controllers[ i ].instance_material;
  31364. node.geometries.push( inst_geom );
  31365. skinned = true;
  31366. skinController = node.controllers[ i ];
  31367. } else if ( controllers[ controller.skin.source ] ) {
  31368. // urgh: controller can be chained
  31369. // handle the most basic case...
  31370. var second = controllers[ controller.skin.source ];
  31371. morphController = second;
  31372. // skinController = node.controllers[i];
  31373. if ( second.morph && geometries[ second.morph.source ] ) {
  31374. var inst_geom = new InstanceGeometry();
  31375. inst_geom.url = second.morph.source;
  31376. inst_geom.instance_material = node.controllers[ i ].instance_material;
  31377. node.geometries.push( inst_geom );
  31378. }
  31379. }
  31380. break;
  31381. case 'morph':
  31382. if ( geometries[ controller.morph.source ] ) {
  31383. var inst_geom = new InstanceGeometry();
  31384. inst_geom.url = controller.morph.source;
  31385. inst_geom.instance_material = node.controllers[ i ].instance_material;
  31386. node.geometries.push( inst_geom );
  31387. morphController = node.controllers[ i ];
  31388. }
  31389. console.log( 'ColladaLoader: Morph-controller partially supported.' );
  31390. default:
  31391. break;
  31392. }
  31393. }
  31394. // geometries
  31395. var double_sided_materials = {};
  31396. for ( i = 0; i < node.geometries.length; i ++ ) {
  31397. var instance_geometry = node.geometries[i];
  31398. var instance_materials = instance_geometry.instance_material;
  31399. var geometry = geometries[ instance_geometry.url ];
  31400. var used_materials = {};
  31401. var used_materials_array = [];
  31402. var num_materials = 0;
  31403. var first_material;
  31404. if ( geometry ) {
  31405. if ( !geometry.mesh || !geometry.mesh.primitives )
  31406. continue;
  31407. if ( obj.name.length === 0 ) {
  31408. obj.name = geometry.id;
  31409. }
  31410. // collect used fx for this geometry-instance
  31411. if ( instance_materials ) {
  31412. for ( j = 0; j < instance_materials.length; j ++ ) {
  31413. var instance_material = instance_materials[ j ];
  31414. var mat = materials[ instance_material.target ];
  31415. var effect_id = mat.instance_effect.url;
  31416. var shader = effects[ effect_id ].shader;
  31417. var material3js = shader.material;
  31418. if ( geometry.doubleSided ) {
  31419. if ( !( instance_material.symbol in double_sided_materials ) ) {
  31420. var _copied_material = material3js.clone();
  31421. _copied_material.side = THREE.DoubleSide;
  31422. double_sided_materials[ instance_material.symbol ] = _copied_material;
  31423. }
  31424. material3js = double_sided_materials[ instance_material.symbol ];
  31425. }
  31426. material3js.opacity = !material3js.opacity ? 1 : material3js.opacity;
  31427. used_materials[ instance_material.symbol ] = num_materials;
  31428. used_materials_array.push( material3js );
  31429. first_material = material3js;
  31430. first_material.name = mat.name === null || mat.name === '' ? mat.id : mat.name;
  31431. num_materials ++;
  31432. }
  31433. }
  31434. var mesh;
  31435. var material = first_material || new THREE.MeshLambertMaterial( { color: 0xdddddd, side: geometry.doubleSided ? THREE.DoubleSide : THREE.FrontSide } );
  31436. var geom = geometry.mesh.geometry3js;
  31437. if ( num_materials > 1 ) {
  31438. material = new THREE.MultiMaterial( used_materials_array );
  31439. for ( j = 0; j < geom.faces.length; j ++ ) {
  31440. var face = geom.faces[ j ];
  31441. face.materialIndex = used_materials[ face.daeMaterial ]
  31442. }
  31443. }
  31444. if ( skinController !== undefined ) {
  31445. applySkin( geom, skinController );
  31446. if ( geom.morphTargets.length > 0 ) {
  31447. material.morphTargets = true;
  31448. material.skinning = false;
  31449. } else {
  31450. material.morphTargets = false;
  31451. material.skinning = true;
  31452. }
  31453. mesh = new THREE.SkinnedMesh( geom, material, false );
  31454. //mesh.skeleton = skinController.skeleton;
  31455. //mesh.skinController = controllers[ skinController.url ];
  31456. //mesh.skinInstanceController = skinController;
  31457. mesh.name = 'skin_' + skins.length;
  31458. //mesh.animationHandle.setKey(0);
  31459. skins.push( mesh );
  31460. } else if ( morphController !== undefined ) {
  31461. createMorph( geom, morphController );
  31462. material.morphTargets = true;
  31463. mesh = new THREE.Mesh( geom, material );
  31464. mesh.name = 'morph_' + morphs.length;
  31465. morphs.push( mesh );
  31466. } else {
  31467. if ( geom.isLineStrip === true ) {
  31468. mesh = new THREE.Line( geom );
  31469. } else {
  31470. mesh = new THREE.Mesh( geom, material );
  31471. }
  31472. }
  31473. obj.add(mesh);
  31474. }
  31475. }
  31476. for ( i = 0; i < node.cameras.length; i ++ ) {
  31477. var instance_camera = node.cameras[i];
  31478. var cparams = cameras[instance_camera.url];
  31479. var cam = new THREE.PerspectiveCamera(cparams.yfov, parseFloat(cparams.aspect_ratio),
  31480. parseFloat(cparams.znear), parseFloat(cparams.zfar));
  31481. obj.add(cam);
  31482. }
  31483. for ( i = 0; i < node.lights.length; i ++ ) {
  31484. var light = null;
  31485. var instance_light = node.lights[i];
  31486. var lparams = lights[instance_light.url];
  31487. if ( lparams && lparams.technique ) {
  31488. var color = lparams.color.getHex();
  31489. var intensity = lparams.intensity;
  31490. var distance = lparams.distance;
  31491. var angle = lparams.falloff_angle;
  31492. switch ( lparams.technique ) {
  31493. case 'directional':
  31494. light = new THREE.DirectionalLight( color, intensity, distance );
  31495. light.position.set(0, 0, 1);
  31496. break;
  31497. case 'point':
  31498. light = new THREE.PointLight( color, intensity, distance );
  31499. break;
  31500. case 'spot':
  31501. light = new THREE.SpotLight( color, intensity, distance, angle );
  31502. light.position.set(0, 0, 1);
  31503. break;
  31504. case 'ambient':
  31505. light = new THREE.AmbientLight( color );
  31506. break;
  31507. }
  31508. }
  31509. if (light) {
  31510. obj.add(light);
  31511. }
  31512. }
  31513. obj.name = node.name || node.id || "";
  31514. obj.colladaId = node.id || "";
  31515. obj.layer = node.layer || "";
  31516. obj.matrix = node.matrix;
  31517. obj.matrix.decompose( obj.position, obj.quaternion, obj.scale );
  31518. if ( options.centerGeometry && obj.geometry ) {
  31519. var delta = obj.geometry.center();
  31520. delta.multiply( obj.scale );
  31521. delta.applyQuaternion( obj.quaternion );
  31522. obj.position.sub( delta );
  31523. }
  31524. for ( i = 0; i < node.nodes.length; i ++ ) {
  31525. obj.add( createSceneGraph( node.nodes[i], node ) );
  31526. }
  31527. return obj;
  31528. }
  31529. function getJointId( skin, id ) {
  31530. for ( var i = 0; i < skin.joints.length; i ++ ) {
  31531. if ( skin.joints[ i ] === id ) {
  31532. return i;
  31533. }
  31534. }
  31535. }
  31536. function getLibraryNode( id ) {
  31537. var nodes = COLLADA.querySelectorAll('library_nodes node');
  31538. for ( var i = 0; i < nodes.length; i++ ) {
  31539. var attObj = nodes[i].attributes.getNamedItem('id');
  31540. if ( attObj && attObj.value === id ) {
  31541. return nodes[i];
  31542. }
  31543. }
  31544. return undefined;
  31545. }
  31546. function getChannelsForNode ( node ) {
  31547. var channels = [];
  31548. var startTime = 1000000;
  31549. var endTime = -1000000;
  31550. for ( var id in animations ) {
  31551. var animation = animations[id];
  31552. for ( var i = 0; i < animation.channel.length; i ++ ) {
  31553. var channel = animation.channel[i];
  31554. var sampler = animation.sampler[i];
  31555. var id = channel.target.split('/')[0];
  31556. if ( id == node.id ) {
  31557. sampler.create();
  31558. channel.sampler = sampler;
  31559. startTime = Math.min(startTime, sampler.startTime);
  31560. endTime = Math.max(endTime, sampler.endTime);
  31561. channels.push(channel);
  31562. }
  31563. }
  31564. }
  31565. if ( channels.length ) {
  31566. node.startTime = startTime;
  31567. node.endTime = endTime;
  31568. }
  31569. return channels;
  31570. }
  31571. function calcFrameDuration( node ) {
  31572. var minT = 10000000;
  31573. for ( var i = 0; i < node.channels.length; i ++ ) {
  31574. var sampler = node.channels[i].sampler;
  31575. for ( var j = 0; j < sampler.input.length - 1; j ++ ) {
  31576. var t0 = sampler.input[ j ];
  31577. var t1 = sampler.input[ j + 1 ];
  31578. minT = Math.min( minT, t1 - t0 );
  31579. }
  31580. }
  31581. return minT;
  31582. }
  31583. function calcMatrixAt( node, t ) {
  31584. var animated = {};
  31585. var i, j;
  31586. for ( i = 0; i < node.channels.length; i ++ ) {
  31587. var channel = node.channels[ i ];
  31588. animated[ channel.sid ] = channel;
  31589. }
  31590. var matrix = new THREE.Matrix4();
  31591. for ( i = 0; i < node.transforms.length; i ++ ) {
  31592. var transform = node.transforms[ i ];
  31593. var channel = animated[ transform.sid ];
  31594. if ( channel !== undefined ) {
  31595. var sampler = channel.sampler;
  31596. var value;
  31597. for ( j = 0; j < sampler.input.length - 1; j ++ ) {
  31598. if ( sampler.input[ j + 1 ] > t ) {
  31599. value = sampler.output[ j ];
  31600. //console.log(value.flatten)
  31601. break;
  31602. }
  31603. }
  31604. if ( value !== undefined ) {
  31605. if ( value instanceof THREE.Matrix4 ) {
  31606. matrix.multiplyMatrices( matrix, value );
  31607. } else {
  31608. // FIXME: handle other types
  31609. matrix.multiplyMatrices( matrix, transform.matrix );
  31610. }
  31611. } else {
  31612. matrix.multiplyMatrices( matrix, transform.matrix );
  31613. }
  31614. } else {
  31615. matrix.multiplyMatrices( matrix, transform.matrix );
  31616. }
  31617. }
  31618. return matrix;
  31619. }
  31620. function bakeAnimations ( node ) {
  31621. if ( node.channels && node.channels.length ) {
  31622. var keys = [],
  31623. sids = [];
  31624. for ( var i = 0, il = node.channels.length; i < il; i ++ ) {
  31625. var channel = node.channels[i],
  31626. fullSid = channel.fullSid,
  31627. sampler = channel.sampler,
  31628. input = sampler.input,
  31629. transform = node.getTransformBySid( channel.sid ),
  31630. member;
  31631. if ( channel.arrIndices ) {
  31632. member = [];
  31633. for ( var j = 0, jl = channel.arrIndices.length; j < jl; j ++ ) {
  31634. member[ j ] = getConvertedIndex( channel.arrIndices[ j ] );
  31635. }
  31636. } else {
  31637. member = getConvertedMember( channel.member );
  31638. }
  31639. if ( transform ) {
  31640. if ( sids.indexOf( fullSid ) === -1 ) {
  31641. sids.push( fullSid );
  31642. }
  31643. for ( var j = 0, jl = input.length; j < jl; j ++ ) {
  31644. var time = input[j],
  31645. data = sampler.getData( transform.type, j, member ),
  31646. key = findKey( keys, time );
  31647. if ( !key ) {
  31648. key = new Key( time );
  31649. var timeNdx = findTimeNdx( keys, time );
  31650. keys.splice( timeNdx === -1 ? keys.length : timeNdx, 0, key );
  31651. }
  31652. key.addTarget( fullSid, transform, member, data );
  31653. }
  31654. } else {
  31655. console.log( 'Could not find transform "' + channel.sid + '" in node ' + node.id );
  31656. }
  31657. }
  31658. // post process
  31659. for ( var i = 0; i < sids.length; i ++ ) {
  31660. var sid = sids[ i ];
  31661. for ( var j = 0; j < keys.length; j ++ ) {
  31662. var key = keys[ j ];
  31663. if ( !key.hasTarget( sid ) ) {
  31664. interpolateKeys( keys, key, j, sid );
  31665. }
  31666. }
  31667. }
  31668. node.keys = keys;
  31669. node.sids = sids;
  31670. }
  31671. }
  31672. function findKey ( keys, time) {
  31673. var retVal = null;
  31674. for ( var i = 0, il = keys.length; i < il && retVal === null; i ++ ) {
  31675. var key = keys[i];
  31676. if ( key.time === time ) {
  31677. retVal = key;
  31678. } else if ( key.time > time ) {
  31679. break;
  31680. }
  31681. }
  31682. return retVal;
  31683. }
  31684. function findTimeNdx ( keys, time) {
  31685. var ndx = -1;
  31686. for ( var i = 0, il = keys.length; i < il && ndx === -1; i ++ ) {
  31687. var key = keys[i];
  31688. if ( key.time >= time ) {
  31689. ndx = i;
  31690. }
  31691. }
  31692. return ndx;
  31693. }
  31694. function interpolateKeys ( keys, key, ndx, fullSid ) {
  31695. var prevKey = getPrevKeyWith( keys, fullSid, ndx ? ndx - 1 : 0 ),
  31696. nextKey = getNextKeyWith( keys, fullSid, ndx + 1 );
  31697. if ( prevKey && nextKey ) {
  31698. var scale = (key.time - prevKey.time) / (nextKey.time - prevKey.time),
  31699. prevTarget = prevKey.getTarget( fullSid ),
  31700. nextData = nextKey.getTarget( fullSid ).data,
  31701. prevData = prevTarget.data,
  31702. data;
  31703. if ( prevTarget.type === 'matrix' ) {
  31704. data = prevData;
  31705. } else if ( prevData.length ) {
  31706. data = [];
  31707. for ( var i = 0; i < prevData.length; ++ i ) {
  31708. data[ i ] = prevData[ i ] + ( nextData[ i ] - prevData[ i ] ) * scale;
  31709. }
  31710. } else {
  31711. data = prevData + ( nextData - prevData ) * scale;
  31712. }
  31713. key.addTarget( fullSid, prevTarget.transform, prevTarget.member, data );
  31714. }
  31715. }
  31716. // Get next key with given sid
  31717. function getNextKeyWith( keys, fullSid, ndx ) {
  31718. for ( ; ndx < keys.length; ndx ++ ) {
  31719. var key = keys[ ndx ];
  31720. if ( key.hasTarget( fullSid ) ) {
  31721. return key;
  31722. }
  31723. }
  31724. return null;
  31725. }
  31726. // Get previous key with given sid
  31727. function getPrevKeyWith( keys, fullSid, ndx ) {
  31728. ndx = ndx >= 0 ? ndx : ndx + keys.length;
  31729. for ( ; ndx >= 0; ndx -- ) {
  31730. var key = keys[ ndx ];
  31731. if ( key.hasTarget( fullSid ) ) {
  31732. return key;
  31733. }
  31734. }
  31735. return null;
  31736. }
  31737. function _Image() {
  31738. this.id = "";
  31739. this.init_from = "";
  31740. }
  31741. _Image.prototype.parse = function(element) {
  31742. this.id = element.getAttribute('id');
  31743. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  31744. var child = element.childNodes[ i ];
  31745. if ( child.nodeName === 'init_from' ) {
  31746. this.init_from = child.textContent;
  31747. }
  31748. }
  31749. return this;
  31750. };
  31751. function Controller() {
  31752. this.id = "";
  31753. this.name = "";
  31754. this.type = "";
  31755. this.skin = null;
  31756. this.morph = null;
  31757. }
  31758. Controller.prototype.parse = function( element ) {
  31759. this.id = element.getAttribute('id');
  31760. this.name = element.getAttribute('name');
  31761. this.type = "none";
  31762. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  31763. var child = element.childNodes[ i ];
  31764. switch ( child.nodeName ) {
  31765. case 'skin':
  31766. this.skin = (new Skin()).parse(child);
  31767. this.type = child.nodeName;
  31768. break;
  31769. case 'morph':
  31770. this.morph = (new Morph()).parse(child);
  31771. this.type = child.nodeName;
  31772. break;
  31773. default:
  31774. break;
  31775. }
  31776. }
  31777. return this;
  31778. };
  31779. function Morph() {
  31780. this.method = null;
  31781. this.source = null;
  31782. this.targets = null;
  31783. this.weights = null;
  31784. }
  31785. Morph.prototype.parse = function( element ) {
  31786. var sources = {};
  31787. var inputs = [];
  31788. var i;
  31789. this.method = element.getAttribute( 'method' );
  31790. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  31791. for ( i = 0; i < element.childNodes.length; i ++ ) {
  31792. var child = element.childNodes[ i ];
  31793. if ( child.nodeType != 1 ) continue;
  31794. switch ( child.nodeName ) {
  31795. case 'source':
  31796. var source = ( new Source() ).parse( child );
  31797. sources[ source.id ] = source;
  31798. break;
  31799. case 'targets':
  31800. inputs = this.parseInputs( child );
  31801. break;
  31802. default:
  31803. console.log( child.nodeName );
  31804. break;
  31805. }
  31806. }
  31807. for ( i = 0; i < inputs.length; i ++ ) {
  31808. var input = inputs[ i ];
  31809. var source = sources[ input.source ];
  31810. switch ( input.semantic ) {
  31811. case 'MORPH_TARGET':
  31812. this.targets = source.read();
  31813. break;
  31814. case 'MORPH_WEIGHT':
  31815. this.weights = source.read();
  31816. break;
  31817. default:
  31818. break;
  31819. }
  31820. }
  31821. return this;
  31822. };
  31823. Morph.prototype.parseInputs = function(element) {
  31824. var inputs = [];
  31825. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  31826. var child = element.childNodes[i];
  31827. if ( child.nodeType != 1) continue;
  31828. switch ( child.nodeName ) {
  31829. case 'input':
  31830. inputs.push( (new Input()).parse(child) );
  31831. break;
  31832. default:
  31833. break;
  31834. }
  31835. }
  31836. return inputs;
  31837. };
  31838. function Skin() {
  31839. this.source = "";
  31840. this.bindShapeMatrix = null;
  31841. this.invBindMatrices = [];
  31842. this.joints = [];
  31843. this.weights = [];
  31844. }
  31845. Skin.prototype.parse = function( element ) {
  31846. var sources = {};
  31847. var joints, weights;
  31848. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  31849. this.invBindMatrices = [];
  31850. this.joints = [];
  31851. this.weights = [];
  31852. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  31853. var child = element.childNodes[i];
  31854. if ( child.nodeType != 1 ) continue;
  31855. switch ( child.nodeName ) {
  31856. case 'bind_shape_matrix':
  31857. var f = _floats(child.textContent);
  31858. this.bindShapeMatrix = getConvertedMat4( f );
  31859. break;
  31860. case 'source':
  31861. var src = new Source().parse(child);
  31862. sources[ src.id ] = src;
  31863. break;
  31864. case 'joints':
  31865. joints = child;
  31866. break;
  31867. case 'vertex_weights':
  31868. weights = child;
  31869. break;
  31870. default:
  31871. console.log( child.nodeName );
  31872. break;
  31873. }
  31874. }
  31875. this.parseJoints( joints, sources );
  31876. this.parseWeights( weights, sources );
  31877. return this;
  31878. };
  31879. Skin.prototype.parseJoints = function ( element, sources ) {
  31880. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  31881. var child = element.childNodes[ i ];
  31882. if ( child.nodeType != 1 ) continue;
  31883. switch ( child.nodeName ) {
  31884. case 'input':
  31885. var input = ( new Input() ).parse( child );
  31886. var source = sources[ input.source ];
  31887. if ( input.semantic === 'JOINT' ) {
  31888. this.joints = source.read();
  31889. } else if ( input.semantic === 'INV_BIND_MATRIX' ) {
  31890. this.invBindMatrices = source.read();
  31891. }
  31892. break;
  31893. default:
  31894. break;
  31895. }
  31896. }
  31897. };
  31898. Skin.prototype.parseWeights = function ( element, sources ) {
  31899. var v, vcount, inputs = [];
  31900. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  31901. var child = element.childNodes[ i ];
  31902. if ( child.nodeType != 1 ) continue;
  31903. switch ( child.nodeName ) {
  31904. case 'input':
  31905. inputs.push( ( new Input() ).parse( child ) );
  31906. break;
  31907. case 'v':
  31908. v = _ints( child.textContent );
  31909. break;
  31910. case 'vcount':
  31911. vcount = _ints( child.textContent );
  31912. break;
  31913. default:
  31914. break;
  31915. }
  31916. }
  31917. var index = 0;
  31918. for ( var i = 0; i < vcount.length; i ++ ) {
  31919. var numBones = vcount[i];
  31920. var vertex_weights = [];
  31921. for ( var j = 0; j < numBones; j ++ ) {
  31922. var influence = {};
  31923. for ( var k = 0; k < inputs.length; k ++ ) {
  31924. var input = inputs[ k ];
  31925. var value = v[ index + input.offset ];
  31926. switch ( input.semantic ) {
  31927. case 'JOINT':
  31928. influence.joint = value;//this.joints[value];
  31929. break;
  31930. case 'WEIGHT':
  31931. influence.weight = sources[ input.source ].data[ value ];
  31932. break;
  31933. default:
  31934. break;
  31935. }
  31936. }
  31937. vertex_weights.push( influence );
  31938. index += inputs.length;
  31939. }
  31940. for ( var j = 0; j < vertex_weights.length; j ++ ) {
  31941. vertex_weights[ j ].index = i;
  31942. }
  31943. this.weights.push( vertex_weights );
  31944. }
  31945. };
  31946. function VisualScene () {
  31947. this.id = "";
  31948. this.name = "";
  31949. this.nodes = [];
  31950. this.scene = new THREE.Group();
  31951. }
  31952. VisualScene.prototype.getChildById = function( id, recursive ) {
  31953. for ( var i = 0; i < this.nodes.length; i ++ ) {
  31954. var node = this.nodes[ i ].getChildById( id, recursive );
  31955. if ( node ) {
  31956. return node;
  31957. }
  31958. }
  31959. return null;
  31960. };
  31961. VisualScene.prototype.getChildBySid = function( sid, recursive ) {
  31962. for ( var i = 0; i < this.nodes.length; i ++ ) {
  31963. var node = this.nodes[ i ].getChildBySid( sid, recursive );
  31964. if ( node ) {
  31965. return node;
  31966. }
  31967. }
  31968. return null;
  31969. };
  31970. VisualScene.prototype.parse = function( element ) {
  31971. this.id = element.getAttribute( 'id' );
  31972. this.name = element.getAttribute( 'name' );
  31973. this.nodes = [];
  31974. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  31975. var child = element.childNodes[ i ];
  31976. if ( child.nodeType != 1 ) continue;
  31977. switch ( child.nodeName ) {
  31978. case 'node':
  31979. this.nodes.push( ( new Node() ).parse( child ) );
  31980. break;
  31981. default:
  31982. break;
  31983. }
  31984. }
  31985. return this;
  31986. };
  31987. function Node() {
  31988. this.id = "";
  31989. this.name = "";
  31990. this.sid = "";
  31991. this.nodes = [];
  31992. this.controllers = [];
  31993. this.transforms = [];
  31994. this.geometries = [];
  31995. this.channels = [];
  31996. this.matrix = new THREE.Matrix4();
  31997. }
  31998. Node.prototype.getChannelForTransform = function( transformSid ) {
  31999. for ( var i = 0; i < this.channels.length; i ++ ) {
  32000. var channel = this.channels[i];
  32001. var parts = channel.target.split('/');
  32002. var id = parts.shift();
  32003. var sid = parts.shift();
  32004. var dotSyntax = (sid.indexOf(".") >= 0);
  32005. var arrSyntax = (sid.indexOf("(") >= 0);
  32006. var arrIndices;
  32007. var member;
  32008. if ( dotSyntax ) {
  32009. parts = sid.split(".");
  32010. sid = parts.shift();
  32011. member = parts.shift();
  32012. } else if ( arrSyntax ) {
  32013. arrIndices = sid.split("(");
  32014. sid = arrIndices.shift();
  32015. for ( var j = 0; j < arrIndices.length; j ++ ) {
  32016. arrIndices[ j ] = parseInt( arrIndices[ j ].replace( /\)/, '' ) );
  32017. }
  32018. }
  32019. if ( sid === transformSid ) {
  32020. channel.info = { sid: sid, dotSyntax: dotSyntax, arrSyntax: arrSyntax, arrIndices: arrIndices };
  32021. return channel;
  32022. }
  32023. }
  32024. return null;
  32025. };
  32026. Node.prototype.getChildById = function ( id, recursive ) {
  32027. if ( this.id === id ) {
  32028. return this;
  32029. }
  32030. if ( recursive ) {
  32031. for ( var i = 0; i < this.nodes.length; i ++ ) {
  32032. var n = this.nodes[ i ].getChildById( id, recursive );
  32033. if ( n ) {
  32034. return n;
  32035. }
  32036. }
  32037. }
  32038. return null;
  32039. };
  32040. Node.prototype.getChildBySid = function ( sid, recursive ) {
  32041. if ( this.sid === sid ) {
  32042. return this;
  32043. }
  32044. if ( recursive ) {
  32045. for ( var i = 0; i < this.nodes.length; i ++ ) {
  32046. var n = this.nodes[ i ].getChildBySid( sid, recursive );
  32047. if ( n ) {
  32048. return n;
  32049. }
  32050. }
  32051. }
  32052. return null;
  32053. };
  32054. Node.prototype.getTransformBySid = function ( sid ) {
  32055. for ( var i = 0; i < this.transforms.length; i ++ ) {
  32056. if ( this.transforms[ i ].sid === sid ) return this.transforms[ i ];
  32057. }
  32058. return null;
  32059. };
  32060. Node.prototype.parse = function( element ) {
  32061. var url;
  32062. this.id = element.getAttribute('id');
  32063. this.sid = element.getAttribute('sid');
  32064. this.name = element.getAttribute('name');
  32065. this.type = element.getAttribute('type');
  32066. this.layer = element.getAttribute('layer');
  32067. this.type = this.type === 'JOINT' ? this.type : 'NODE';
  32068. this.nodes = [];
  32069. this.transforms = [];
  32070. this.geometries = [];
  32071. this.cameras = [];
  32072. this.lights = [];
  32073. this.controllers = [];
  32074. this.matrix = new THREE.Matrix4();
  32075. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32076. var child = element.childNodes[ i ];
  32077. if ( child.nodeType != 1 ) continue;
  32078. switch ( child.nodeName ) {
  32079. case 'node':
  32080. this.nodes.push( ( new Node() ).parse( child ) );
  32081. break;
  32082. case 'instance_camera':
  32083. this.cameras.push( ( new InstanceCamera() ).parse( child ) );
  32084. break;
  32085. case 'instance_controller':
  32086. this.controllers.push( ( new InstanceController() ).parse( child ) );
  32087. break;
  32088. case 'instance_geometry':
  32089. this.geometries.push( ( new InstanceGeometry() ).parse( child ) );
  32090. break;
  32091. case 'instance_light':
  32092. this.lights.push( ( new InstanceLight() ).parse( child ) );
  32093. break;
  32094. case 'instance_node':
  32095. url = child.getAttribute( 'url' ).replace( /^#/, '' );
  32096. var iNode = getLibraryNode( url );
  32097. if ( iNode ) {
  32098. this.nodes.push( ( new Node() ).parse( iNode )) ;
  32099. }
  32100. break;
  32101. case 'rotate':
  32102. case 'translate':
  32103. case 'scale':
  32104. case 'matrix':
  32105. case 'lookat':
  32106. case 'skew':
  32107. this.transforms.push( ( new Transform() ).parse( child ) );
  32108. break;
  32109. case 'extra':
  32110. break;
  32111. default:
  32112. console.log( child.nodeName );
  32113. break;
  32114. }
  32115. }
  32116. this.channels = getChannelsForNode( this );
  32117. bakeAnimations( this );
  32118. this.updateMatrix();
  32119. return this;
  32120. };
  32121. Node.prototype.updateMatrix = function () {
  32122. this.matrix.identity();
  32123. for ( var i = 0; i < this.transforms.length; i ++ ) {
  32124. this.transforms[ i ].apply( this.matrix );
  32125. }
  32126. };
  32127. function Transform () {
  32128. this.sid = "";
  32129. this.type = "";
  32130. this.data = [];
  32131. this.obj = null;
  32132. }
  32133. Transform.prototype.parse = function ( element ) {
  32134. this.sid = element.getAttribute( 'sid' );
  32135. this.type = element.nodeName;
  32136. this.data = _floats( element.textContent );
  32137. this.convert();
  32138. return this;
  32139. };
  32140. Transform.prototype.convert = function () {
  32141. switch ( this.type ) {
  32142. case 'matrix':
  32143. this.obj = getConvertedMat4( this.data );
  32144. break;
  32145. case 'rotate':
  32146. this.angle = THREE.Math.degToRad( this.data[3] );
  32147. case 'translate':
  32148. fixCoords( this.data, -1 );
  32149. this.obj = new THREE.Vector3( this.data[ 0 ], this.data[ 1 ], this.data[ 2 ] );
  32150. break;
  32151. case 'scale':
  32152. fixCoords( this.data, 1 );
  32153. this.obj = new THREE.Vector3( this.data[ 0 ], this.data[ 1 ], this.data[ 2 ] );
  32154. break;
  32155. default:
  32156. console.log( 'Can not convert Transform of type ' + this.type );
  32157. break;
  32158. }
  32159. };
  32160. Transform.prototype.apply = function () {
  32161. var m1 = new THREE.Matrix4();
  32162. return function ( matrix ) {
  32163. switch ( this.type ) {
  32164. case 'matrix':
  32165. matrix.multiply( this.obj );
  32166. break;
  32167. case 'translate':
  32168. matrix.multiply( m1.makeTranslation( this.obj.x, this.obj.y, this.obj.z ) );
  32169. break;
  32170. case 'rotate':
  32171. matrix.multiply( m1.makeRotationAxis( this.obj, this.angle ) );
  32172. break;
  32173. case 'scale':
  32174. matrix.scale( this.obj );
  32175. break;
  32176. }
  32177. };
  32178. }();
  32179. Transform.prototype.update = function ( data, member ) {
  32180. var members = [ 'X', 'Y', 'Z', 'ANGLE' ];
  32181. switch ( this.type ) {
  32182. case 'matrix':
  32183. if ( ! member ) {
  32184. this.obj.copy( data );
  32185. } else if ( member.length === 1 ) {
  32186. switch ( member[ 0 ] ) {
  32187. case 0:
  32188. this.obj.n11 = data[ 0 ];
  32189. this.obj.n21 = data[ 1 ];
  32190. this.obj.n31 = data[ 2 ];
  32191. this.obj.n41 = data[ 3 ];
  32192. break;
  32193. case 1:
  32194. this.obj.n12 = data[ 0 ];
  32195. this.obj.n22 = data[ 1 ];
  32196. this.obj.n32 = data[ 2 ];
  32197. this.obj.n42 = data[ 3 ];
  32198. break;
  32199. case 2:
  32200. this.obj.n13 = data[ 0 ];
  32201. this.obj.n23 = data[ 1 ];
  32202. this.obj.n33 = data[ 2 ];
  32203. this.obj.n43 = data[ 3 ];
  32204. break;
  32205. case 3:
  32206. this.obj.n14 = data[ 0 ];
  32207. this.obj.n24 = data[ 1 ];
  32208. this.obj.n34 = data[ 2 ];
  32209. this.obj.n44 = data[ 3 ];
  32210. break;
  32211. }
  32212. } else if ( member.length === 2 ) {
  32213. var propName = 'n' + ( member[ 0 ] + 1 ) + ( member[ 1 ] + 1 );
  32214. this.obj[ propName ] = data;
  32215. } else {
  32216. console.log('Incorrect addressing of matrix in transform.');
  32217. }
  32218. break;
  32219. case 'translate':
  32220. case 'scale':
  32221. if ( Object.prototype.toString.call( member ) === '[object Array]' ) {
  32222. member = members[ member[ 0 ] ];
  32223. }
  32224. switch ( member ) {
  32225. case 'X':
  32226. this.obj.x = data;
  32227. break;
  32228. case 'Y':
  32229. this.obj.y = data;
  32230. break;
  32231. case 'Z':
  32232. this.obj.z = data;
  32233. break;
  32234. default:
  32235. this.obj.x = data[ 0 ];
  32236. this.obj.y = data[ 1 ];
  32237. this.obj.z = data[ 2 ];
  32238. break;
  32239. }
  32240. break;
  32241. case 'rotate':
  32242. if ( Object.prototype.toString.call( member ) === '[object Array]' ) {
  32243. member = members[ member[ 0 ] ];
  32244. }
  32245. switch ( member ) {
  32246. case 'X':
  32247. this.obj.x = data;
  32248. break;
  32249. case 'Y':
  32250. this.obj.y = data;
  32251. break;
  32252. case 'Z':
  32253. this.obj.z = data;
  32254. break;
  32255. case 'ANGLE':
  32256. this.angle = THREE.Math.degToRad( data );
  32257. break;
  32258. default:
  32259. this.obj.x = data[ 0 ];
  32260. this.obj.y = data[ 1 ];
  32261. this.obj.z = data[ 2 ];
  32262. this.angle = THREE.Math.degToRad( data[ 3 ] );
  32263. break;
  32264. }
  32265. break;
  32266. }
  32267. };
  32268. function InstanceController() {
  32269. this.url = "";
  32270. this.skeleton = [];
  32271. this.instance_material = [];
  32272. }
  32273. InstanceController.prototype.parse = function ( element ) {
  32274. this.url = element.getAttribute('url').replace(/^#/, '');
  32275. this.skeleton = [];
  32276. this.instance_material = [];
  32277. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32278. var child = element.childNodes[ i ];
  32279. if ( child.nodeType !== 1 ) continue;
  32280. switch ( child.nodeName ) {
  32281. case 'skeleton':
  32282. this.skeleton.push( child.textContent.replace(/^#/, '') );
  32283. break;
  32284. case 'bind_material':
  32285. var instances = child.querySelectorAll('instance_material');
  32286. for ( var j = 0; j < instances.length; j ++ ) {
  32287. var instance = instances[j];
  32288. this.instance_material.push( (new InstanceMaterial()).parse(instance) );
  32289. }
  32290. break;
  32291. case 'extra':
  32292. break;
  32293. default:
  32294. break;
  32295. }
  32296. }
  32297. return this;
  32298. };
  32299. function InstanceMaterial () {
  32300. this.symbol = "";
  32301. this.target = "";
  32302. }
  32303. InstanceMaterial.prototype.parse = function ( element ) {
  32304. this.symbol = element.getAttribute('symbol');
  32305. this.target = element.getAttribute('target').replace(/^#/, '');
  32306. return this;
  32307. };
  32308. function InstanceGeometry() {
  32309. this.url = "";
  32310. this.instance_material = [];
  32311. }
  32312. InstanceGeometry.prototype.parse = function ( element ) {
  32313. this.url = element.getAttribute('url').replace(/^#/, '');
  32314. this.instance_material = [];
  32315. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32316. var child = element.childNodes[i];
  32317. if ( child.nodeType != 1 ) continue;
  32318. if ( child.nodeName === 'bind_material' ) {
  32319. var instances = child.querySelectorAll('instance_material');
  32320. for ( var j = 0; j < instances.length; j ++ ) {
  32321. var instance = instances[j];
  32322. this.instance_material.push( (new InstanceMaterial()).parse(instance) );
  32323. }
  32324. break;
  32325. }
  32326. }
  32327. return this;
  32328. };
  32329. function Geometry() {
  32330. this.id = "";
  32331. this.mesh = null;
  32332. }
  32333. Geometry.prototype.parse = function ( element ) {
  32334. this.id = element.getAttribute('id');
  32335. extractDoubleSided( this, element );
  32336. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32337. var child = element.childNodes[i];
  32338. switch ( child.nodeName ) {
  32339. case 'mesh':
  32340. this.mesh = (new Mesh(this)).parse(child);
  32341. break;
  32342. case 'extra':
  32343. // console.log( child );
  32344. break;
  32345. default:
  32346. break;
  32347. }
  32348. }
  32349. return this;
  32350. };
  32351. function Mesh( geometry ) {
  32352. this.geometry = geometry.id;
  32353. this.primitives = [];
  32354. this.vertices = null;
  32355. this.geometry3js = null;
  32356. }
  32357. Mesh.prototype.parse = function ( element ) {
  32358. this.primitives = [];
  32359. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32360. var child = element.childNodes[ i ];
  32361. switch ( child.nodeName ) {
  32362. case 'source':
  32363. _source( child );
  32364. break;
  32365. case 'vertices':
  32366. this.vertices = ( new Vertices() ).parse( child );
  32367. break;
  32368. case 'linestrips':
  32369. this.primitives.push( ( new LineStrips().parse( child ) ) );
  32370. break;
  32371. case 'triangles':
  32372. this.primitives.push( ( new Triangles().parse( child ) ) );
  32373. break;
  32374. case 'polygons':
  32375. this.primitives.push( ( new Polygons().parse( child ) ) );
  32376. break;
  32377. case 'polylist':
  32378. this.primitives.push( ( new Polylist().parse( child ) ) );
  32379. break;
  32380. default:
  32381. break;
  32382. }
  32383. }
  32384. this.geometry3js = new THREE.Geometry();
  32385. if ( this.vertices === null ) {
  32386. // TODO (mrdoob): Study case when this is null (carrier.dae)
  32387. return this;
  32388. }
  32389. var vertexData = sources[ this.vertices.input['POSITION'].source ].data;
  32390. for ( var i = 0; i < vertexData.length; i += 3 ) {
  32391. this.geometry3js.vertices.push( getConvertedVec3( vertexData, i ).clone() );
  32392. }
  32393. for ( var i = 0; i < this.primitives.length; i ++ ) {
  32394. var primitive = this.primitives[ i ];
  32395. primitive.setVertices( this.vertices );
  32396. this.handlePrimitive( primitive, this.geometry3js );
  32397. }
  32398. if ( this.geometry3js.calcNormals ) {
  32399. this.geometry3js.computeVertexNormals();
  32400. delete this.geometry3js.calcNormals;
  32401. }
  32402. return this;
  32403. };
  32404. Mesh.prototype.handlePrimitive = function ( primitive, geom ) {
  32405. if ( primitive instanceof LineStrips ) {
  32406. // TODO: Handle indices. Maybe easier with BufferGeometry?
  32407. geom.isLineStrip = true;
  32408. return;
  32409. }
  32410. var j, k, pList = primitive.p, inputs = primitive.inputs;
  32411. var input, index, idx32;
  32412. var source, numParams;
  32413. var vcIndex = 0, vcount = 3, maxOffset = 0;
  32414. var texture_sets = [];
  32415. for ( j = 0; j < inputs.length; j ++ ) {
  32416. input = inputs[ j ];
  32417. var offset = input.offset + 1;
  32418. maxOffset = (maxOffset < offset) ? offset : maxOffset;
  32419. switch ( input.semantic ) {
  32420. case 'TEXCOORD':
  32421. texture_sets.push( input.set );
  32422. break;
  32423. }
  32424. }
  32425. for ( var pCount = 0; pCount < pList.length; ++ pCount ) {
  32426. var p = pList[ pCount ], i = 0;
  32427. while ( i < p.length ) {
  32428. var vs = [];
  32429. var ns = [];
  32430. var ts = null;
  32431. var cs = [];
  32432. if ( primitive.vcount ) {
  32433. vcount = primitive.vcount.length ? primitive.vcount[ vcIndex ++ ] : primitive.vcount;
  32434. } else {
  32435. vcount = p.length / maxOffset;
  32436. }
  32437. for ( j = 0; j < vcount; j ++ ) {
  32438. for ( k = 0; k < inputs.length; k ++ ) {
  32439. input = inputs[ k ];
  32440. source = sources[ input.source ];
  32441. index = p[ i + ( j * maxOffset ) + input.offset ];
  32442. numParams = source.accessor.params.length;
  32443. idx32 = index * numParams;
  32444. switch ( input.semantic ) {
  32445. case 'VERTEX':
  32446. vs.push( index );
  32447. break;
  32448. case 'NORMAL':
  32449. ns.push( getConvertedVec3( source.data, idx32 ) );
  32450. break;
  32451. case 'TEXCOORD':
  32452. ts = ts || { };
  32453. if ( ts[ input.set ] === undefined ) ts[ input.set ] = [];
  32454. // invert the V
  32455. ts[ input.set ].push( new THREE.Vector2( source.data[ idx32 ], source.data[ idx32 + 1 ] ) );
  32456. break;
  32457. case 'COLOR':
  32458. cs.push( new THREE.Color().setRGB( source.data[ idx32 ], source.data[ idx32 + 1 ], source.data[ idx32 + 2 ] ) );
  32459. break;
  32460. default:
  32461. break;
  32462. }
  32463. }
  32464. }
  32465. if ( ns.length === 0 ) {
  32466. // check the vertices inputs
  32467. input = this.vertices.input.NORMAL;
  32468. if ( input ) {
  32469. source = sources[ input.source ];
  32470. numParams = source.accessor.params.length;
  32471. for ( var ndx = 0, len = vs.length; ndx < len; ndx ++ ) {
  32472. ns.push( getConvertedVec3( source.data, vs[ ndx ] * numParams ) );
  32473. }
  32474. } else {
  32475. geom.calcNormals = true;
  32476. }
  32477. }
  32478. if ( !ts ) {
  32479. ts = { };
  32480. // check the vertices inputs
  32481. input = this.vertices.input.TEXCOORD;
  32482. if ( input ) {
  32483. texture_sets.push( input.set );
  32484. source = sources[ input.source ];
  32485. numParams = source.accessor.params.length;
  32486. for ( var ndx = 0, len = vs.length; ndx < len; ndx ++ ) {
  32487. idx32 = vs[ ndx ] * numParams;
  32488. if ( ts[ input.set ] === undefined ) ts[ input.set ] = [ ];
  32489. // invert the V
  32490. ts[ input.set ].push( new THREE.Vector2( source.data[ idx32 ], 1.0 - source.data[ idx32 + 1 ] ) );
  32491. }
  32492. }
  32493. }
  32494. if ( cs.length === 0 ) {
  32495. // check the vertices inputs
  32496. input = this.vertices.input.COLOR;
  32497. if ( input ) {
  32498. source = sources[ input.source ];
  32499. numParams = source.accessor.params.length;
  32500. for ( var ndx = 0, len = vs.length; ndx < len; ndx ++ ) {
  32501. idx32 = vs[ ndx ] * numParams;
  32502. cs.push( new THREE.Color().setRGB( source.data[ idx32 ], source.data[ idx32 + 1 ], source.data[ idx32 + 2 ] ) );
  32503. }
  32504. }
  32505. }
  32506. var face = null, faces = [], uv, uvArr;
  32507. if ( vcount === 3 ) {
  32508. faces.push( new THREE.Face3( vs[0], vs[1], vs[2], ns, cs.length ? cs : new THREE.Color() ) );
  32509. } else if ( vcount === 4 ) {
  32510. 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() ) );
  32511. 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() ) );
  32512. } else if ( vcount > 4 && options.subdivideFaces ) {
  32513. var clr = cs.length ? cs : new THREE.Color(),
  32514. vec1, vec2, vec3, v1, v2, norm;
  32515. // subdivide into multiple Face3s
  32516. for ( k = 1; k < vcount - 1; ) {
  32517. faces.push( new THREE.Face3( vs[0], vs[k], vs[k + 1], ns.length ? [ ns[0].clone(), ns[k ++].clone(), ns[k].clone() ] : [], clr ) );
  32518. }
  32519. }
  32520. if ( faces.length ) {
  32521. for ( var ndx = 0, len = faces.length; ndx < len; ndx ++ ) {
  32522. face = faces[ndx];
  32523. face.daeMaterial = primitive.material;
  32524. geom.faces.push( face );
  32525. for ( k = 0; k < texture_sets.length; k ++ ) {
  32526. uv = ts[ texture_sets[k] ];
  32527. if ( vcount > 4 ) {
  32528. // Grab the right UVs for the vertices in this face
  32529. uvArr = [ uv[0], uv[ndx + 1], uv[ndx + 2] ];
  32530. } else if ( vcount === 4 ) {
  32531. if ( ndx === 0 ) {
  32532. uvArr = [ uv[0], uv[1], uv[3] ];
  32533. } else {
  32534. uvArr = [ uv[1].clone(), uv[2], uv[3].clone() ];
  32535. }
  32536. } else {
  32537. uvArr = [ uv[0], uv[1], uv[2] ];
  32538. }
  32539. if ( geom.faceVertexUvs[k] === undefined ) {
  32540. geom.faceVertexUvs[k] = [];
  32541. }
  32542. geom.faceVertexUvs[k].push( uvArr );
  32543. }
  32544. }
  32545. } else {
  32546. console.log( 'dropped face with vcount ' + vcount + ' for geometry with id: ' + geom.id );
  32547. }
  32548. i += maxOffset * vcount;
  32549. }
  32550. }
  32551. };
  32552. function Polygons () {
  32553. this.material = "";
  32554. this.count = 0;
  32555. this.inputs = [];
  32556. this.vcount = null;
  32557. this.p = [];
  32558. this.geometry = new THREE.Geometry();
  32559. }
  32560. Polygons.prototype.setVertices = function ( vertices ) {
  32561. for ( var i = 0; i < this.inputs.length; i ++ ) {
  32562. if ( this.inputs[ i ].source === vertices.id ) {
  32563. this.inputs[ i ].source = vertices.input[ 'POSITION' ].source;
  32564. }
  32565. }
  32566. };
  32567. Polygons.prototype.parse = function ( element ) {
  32568. this.material = element.getAttribute( 'material' );
  32569. this.count = _attr_as_int( element, 'count', 0 );
  32570. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32571. var child = element.childNodes[ i ];
  32572. switch ( child.nodeName ) {
  32573. case 'input':
  32574. this.inputs.push( ( new Input() ).parse( element.childNodes[ i ] ) );
  32575. break;
  32576. case 'vcount':
  32577. this.vcount = _ints( child.textContent );
  32578. break;
  32579. case 'p':
  32580. this.p.push( _ints( child.textContent ) );
  32581. break;
  32582. case 'ph':
  32583. console.warn( 'polygon holes not yet supported!' );
  32584. break;
  32585. default:
  32586. break;
  32587. }
  32588. }
  32589. return this;
  32590. };
  32591. function Polylist () {
  32592. Polygons.call( this );
  32593. this.vcount = [];
  32594. }
  32595. Polylist.prototype = Object.create( Polygons.prototype );
  32596. Polylist.prototype.constructor = Polylist;
  32597. function LineStrips() {
  32598. Polygons.call( this );
  32599. this.vcount = 1;
  32600. }
  32601. LineStrips.prototype = Object.create( Polygons.prototype );
  32602. LineStrips.prototype.constructor = LineStrips;
  32603. function Triangles () {
  32604. Polygons.call( this );
  32605. this.vcount = 3;
  32606. }
  32607. Triangles.prototype = Object.create( Polygons.prototype );
  32608. Triangles.prototype.constructor = Triangles;
  32609. function Accessor() {
  32610. this.source = "";
  32611. this.count = 0;
  32612. this.stride = 0;
  32613. this.params = [];
  32614. }
  32615. Accessor.prototype.parse = function ( element ) {
  32616. this.params = [];
  32617. this.source = element.getAttribute( 'source' );
  32618. this.count = _attr_as_int( element, 'count', 0 );
  32619. this.stride = _attr_as_int( element, 'stride', 0 );
  32620. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32621. var child = element.childNodes[ i ];
  32622. if ( child.nodeName === 'param' ) {
  32623. var param = {};
  32624. param[ 'name' ] = child.getAttribute( 'name' );
  32625. param[ 'type' ] = child.getAttribute( 'type' );
  32626. this.params.push( param );
  32627. }
  32628. }
  32629. return this;
  32630. };
  32631. function Vertices() {
  32632. this.input = {};
  32633. }
  32634. Vertices.prototype.parse = function ( element ) {
  32635. this.id = element.getAttribute('id');
  32636. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32637. if ( element.childNodes[i].nodeName === 'input' ) {
  32638. var input = ( new Input() ).parse( element.childNodes[ i ] );
  32639. this.input[ input.semantic ] = input;
  32640. }
  32641. }
  32642. return this;
  32643. };
  32644. function Input () {
  32645. this.semantic = "";
  32646. this.offset = 0;
  32647. this.source = "";
  32648. this.set = 0;
  32649. }
  32650. Input.prototype.parse = function ( element ) {
  32651. this.semantic = element.getAttribute('semantic');
  32652. this.source = element.getAttribute('source').replace(/^#/, '');
  32653. this.set = _attr_as_int(element, 'set', -1);
  32654. this.offset = _attr_as_int(element, 'offset', 0);
  32655. if ( this.semantic === 'TEXCOORD' && this.set < 0 ) {
  32656. this.set = 0;
  32657. }
  32658. return this;
  32659. };
  32660. function Source ( id ) {
  32661. this.id = id;
  32662. this.type = null;
  32663. }
  32664. Source.prototype.parse = function ( element ) {
  32665. this.id = element.getAttribute( 'id' );
  32666. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32667. var child = element.childNodes[i];
  32668. switch ( child.nodeName ) {
  32669. case 'bool_array':
  32670. this.data = _bools( child.textContent );
  32671. this.type = child.nodeName;
  32672. break;
  32673. case 'float_array':
  32674. this.data = _floats( child.textContent );
  32675. this.type = child.nodeName;
  32676. break;
  32677. case 'int_array':
  32678. this.data = _ints( child.textContent );
  32679. this.type = child.nodeName;
  32680. break;
  32681. case 'IDREF_array':
  32682. case 'Name_array':
  32683. this.data = _strings( child.textContent );
  32684. this.type = child.nodeName;
  32685. break;
  32686. case 'technique_common':
  32687. for ( var j = 0; j < child.childNodes.length; j ++ ) {
  32688. if ( child.childNodes[ j ].nodeName === 'accessor' ) {
  32689. this.accessor = ( new Accessor() ).parse( child.childNodes[ j ] );
  32690. break;
  32691. }
  32692. }
  32693. break;
  32694. default:
  32695. // console.log(child.nodeName);
  32696. break;
  32697. }
  32698. }
  32699. return this;
  32700. };
  32701. Source.prototype.read = function () {
  32702. var result = [];
  32703. //for (var i = 0; i < this.accessor.params.length; i++) {
  32704. var param = this.accessor.params[ 0 ];
  32705. //console.log(param.name + " " + param.type);
  32706. switch ( param.type ) {
  32707. case 'IDREF':
  32708. case 'Name': case 'name':
  32709. case 'float':
  32710. return this.data;
  32711. case 'float4x4':
  32712. for ( var j = 0; j < this.data.length; j += 16 ) {
  32713. var s = this.data.slice( j, j + 16 );
  32714. var m = getConvertedMat4( s );
  32715. result.push( m );
  32716. }
  32717. break;
  32718. default:
  32719. console.log( 'ColladaLoader: Source: Read dont know how to read ' + param.type + '.' );
  32720. break;
  32721. }
  32722. //}
  32723. return result;
  32724. };
  32725. function Material () {
  32726. this.id = "";
  32727. this.name = "";
  32728. this.instance_effect = null;
  32729. }
  32730. Material.prototype.parse = function ( element ) {
  32731. this.id = element.getAttribute( 'id' );
  32732. this.name = element.getAttribute( 'name' );
  32733. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32734. if ( element.childNodes[ i ].nodeName === 'instance_effect' ) {
  32735. this.instance_effect = ( new InstanceEffect() ).parse( element.childNodes[ i ] );
  32736. break;
  32737. }
  32738. }
  32739. return this;
  32740. };
  32741. function ColorOrTexture () {
  32742. this.color = new THREE.Color();
  32743. this.color.setRGB( Math.random(), Math.random(), Math.random() );
  32744. this.color.a = 1.0;
  32745. this.texture = null;
  32746. this.texcoord = null;
  32747. this.texOpts = null;
  32748. }
  32749. ColorOrTexture.prototype.isColor = function () {
  32750. return ( this.texture === null );
  32751. };
  32752. ColorOrTexture.prototype.isTexture = function () {
  32753. return ( this.texture != null );
  32754. };
  32755. ColorOrTexture.prototype.parse = function ( element ) {
  32756. if (element.nodeName === 'transparent') {
  32757. this.opaque = element.getAttribute('opaque');
  32758. }
  32759. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32760. var child = element.childNodes[ i ];
  32761. if ( child.nodeType != 1 ) continue;
  32762. switch ( child.nodeName ) {
  32763. case 'color':
  32764. var rgba = _floats( child.textContent );
  32765. this.color = new THREE.Color();
  32766. this.color.setRGB( rgba[0], rgba[1], rgba[2] );
  32767. this.color.a = rgba[3];
  32768. break;
  32769. case 'texture':
  32770. this.texture = child.getAttribute('texture');
  32771. this.texcoord = child.getAttribute('texcoord');
  32772. // Defaults from:
  32773. // https://collada.org/mediawiki/index.php/Maya_texture_placement_MAYA_extension
  32774. this.texOpts = {
  32775. offsetU: 0,
  32776. offsetV: 0,
  32777. repeatU: 1,
  32778. repeatV: 1,
  32779. wrapU: 1,
  32780. wrapV: 1
  32781. };
  32782. this.parseTexture( child );
  32783. break;
  32784. default:
  32785. break;
  32786. }
  32787. }
  32788. return this;
  32789. };
  32790. ColorOrTexture.prototype.parseTexture = function ( element ) {
  32791. if ( ! element.childNodes ) return this;
  32792. // This should be supported by Maya, 3dsMax, and MotionBuilder
  32793. if ( element.childNodes[1] && element.childNodes[1].nodeName === 'extra' ) {
  32794. element = element.childNodes[1];
  32795. if ( element.childNodes[1] && element.childNodes[1].nodeName === 'technique' ) {
  32796. element = element.childNodes[1];
  32797. }
  32798. }
  32799. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32800. var child = element.childNodes[ i ];
  32801. switch ( child.nodeName ) {
  32802. case 'offsetU':
  32803. case 'offsetV':
  32804. case 'repeatU':
  32805. case 'repeatV':
  32806. this.texOpts[ child.nodeName ] = parseFloat( child.textContent );
  32807. break;
  32808. case 'wrapU':
  32809. case 'wrapV':
  32810. // some dae have a value of true which becomes NaN via parseInt
  32811. if ( child.textContent.toUpperCase() === 'TRUE' ) {
  32812. this.texOpts[ child.nodeName ] = 1;
  32813. } else {
  32814. this.texOpts[ child.nodeName ] = parseInt( child.textContent );
  32815. }
  32816. break;
  32817. default:
  32818. this.texOpts[ child.nodeName ] = child.textContent;
  32819. break;
  32820. }
  32821. }
  32822. return this;
  32823. };
  32824. function Shader ( type, effect ) {
  32825. this.type = type;
  32826. this.effect = effect;
  32827. this.material = null;
  32828. }
  32829. Shader.prototype.parse = function ( element ) {
  32830. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32831. var child = element.childNodes[ i ];
  32832. if ( child.nodeType != 1 ) continue;
  32833. switch ( child.nodeName ) {
  32834. case 'emission':
  32835. case 'diffuse':
  32836. case 'specular':
  32837. case 'transparent':
  32838. this[ child.nodeName ] = ( new ColorOrTexture() ).parse( child );
  32839. break;
  32840. case 'bump':
  32841. // If 'bumptype' is 'heightfield', create a 'bump' property
  32842. // Else if 'bumptype' is 'normalmap', create a 'normal' property
  32843. // (Default to 'bump')
  32844. var bumpType = child.getAttribute( 'bumptype' );
  32845. if ( bumpType ) {
  32846. if ( bumpType.toLowerCase() === "heightfield" ) {
  32847. this[ 'bump' ] = ( new ColorOrTexture() ).parse( child );
  32848. } else if ( bumpType.toLowerCase() === "normalmap" ) {
  32849. this[ 'normal' ] = ( new ColorOrTexture() ).parse( child );
  32850. } else {
  32851. console.error( "Shader.prototype.parse: Invalid value for attribute 'bumptype' (" + bumpType + ") - valid bumptypes are 'HEIGHTFIELD' and 'NORMALMAP' - defaulting to 'HEIGHTFIELD'" );
  32852. this[ 'bump' ] = ( new ColorOrTexture() ).parse( child );
  32853. }
  32854. } else {
  32855. console.warn( "Shader.prototype.parse: Attribute 'bumptype' missing from bump node - defaulting to 'HEIGHTFIELD'" );
  32856. this[ 'bump' ] = ( new ColorOrTexture() ).parse( child );
  32857. }
  32858. break;
  32859. case 'shininess':
  32860. case 'reflectivity':
  32861. case 'index_of_refraction':
  32862. case 'transparency':
  32863. var f = child.querySelectorAll('float');
  32864. if ( f.length > 0 )
  32865. this[ child.nodeName ] = parseFloat( f[ 0 ].textContent );
  32866. break;
  32867. default:
  32868. break;
  32869. }
  32870. }
  32871. this.create();
  32872. return this;
  32873. };
  32874. Shader.prototype.create = function() {
  32875. var props = {};
  32876. var transparent = false;
  32877. if (this['transparency'] !== undefined && this['transparent'] !== undefined) {
  32878. // convert transparent color RBG to average value
  32879. var transparentColor = this['transparent'];
  32880. var transparencyLevel = (this.transparent.color.r + this.transparent.color.g + this.transparent.color.b) / 3 * this.transparency;
  32881. if (transparencyLevel > 0) {
  32882. transparent = true;
  32883. props[ 'transparent' ] = true;
  32884. props[ 'opacity' ] = 1 - transparencyLevel;
  32885. }
  32886. }
  32887. var keys = {
  32888. 'diffuse':'map',
  32889. 'ambient':'lightMap',
  32890. 'specular':'specularMap',
  32891. 'emission':'emissionMap',
  32892. 'bump':'bumpMap',
  32893. 'normal':'normalMap'
  32894. };
  32895. for ( var prop in this ) {
  32896. switch ( prop ) {
  32897. case 'ambient':
  32898. case 'emission':
  32899. case 'diffuse':
  32900. case 'specular':
  32901. case 'bump':
  32902. case 'normal':
  32903. var cot = this[ prop ];
  32904. if ( cot instanceof ColorOrTexture ) {
  32905. if ( cot.isTexture() ) {
  32906. var samplerId = cot.texture;
  32907. var sampler = this.effect.sampler[samplerId];
  32908. if ( sampler !== undefined && sampler.source !== undefined ) {
  32909. var surface = this.effect.surface[sampler.source];
  32910. if ( surface !== undefined ) {
  32911. var image = images[ surface.init_from ];
  32912. if ( image ) {
  32913. var url = baseUrl + image.init_from;
  32914. var texture;
  32915. var loader = THREE.Loader.Handlers.get( url );
  32916. if ( loader !== null ) {
  32917. texture = loader.load( url );
  32918. } else {
  32919. texture = new THREE.Texture();
  32920. loadTextureImage( texture, url );
  32921. }
  32922. if ( sampler.wrap_s === "MIRROR" ) {
  32923. texture.wrapS = THREE.MirroredRepeatWrapping;
  32924. } else if ( sampler.wrap_s === "WRAP" || cot.texOpts.wrapU ) {
  32925. texture.wrapS = THREE.RepeatWrapping;
  32926. } else {
  32927. texture.wrapS = THREE.ClampToEdgeWrapping;
  32928. }
  32929. if ( sampler.wrap_t === "MIRROR" ) {
  32930. texture.wrapT = THREE.MirroredRepeatWrapping;
  32931. } else if ( sampler.wrap_t === "WRAP" || cot.texOpts.wrapV ) {
  32932. texture.wrapT = THREE.RepeatWrapping;
  32933. } else {
  32934. texture.wrapT = THREE.ClampToEdgeWrapping;
  32935. }
  32936. texture.offset.x = cot.texOpts.offsetU;
  32937. texture.offset.y = cot.texOpts.offsetV;
  32938. texture.repeat.x = cot.texOpts.repeatU;
  32939. texture.repeat.y = cot.texOpts.repeatV;
  32940. props[keys[prop]] = texture;
  32941. // Texture with baked lighting?
  32942. if (prop === 'emission') props['emissive'] = 0xffffff;
  32943. }
  32944. }
  32945. }
  32946. } else if ( prop === 'diffuse' || !transparent ) {
  32947. if ( prop === 'emission' ) {
  32948. props[ 'emissive' ] = cot.color.getHex();
  32949. } else {
  32950. props[ prop ] = cot.color.getHex();
  32951. }
  32952. }
  32953. }
  32954. break;
  32955. case 'shininess':
  32956. props[ prop ] = this[ prop ];
  32957. break;
  32958. case 'reflectivity':
  32959. props[ prop ] = this[ prop ];
  32960. if ( props[ prop ] > 0.0 ) props['envMap'] = options.defaultEnvMap;
  32961. props['combine'] = THREE.MixOperation; //mix regular shading with reflective component
  32962. break;
  32963. case 'index_of_refraction':
  32964. props[ 'refractionRatio' ] = this[ prop ]; //TODO: "index_of_refraction" becomes "refractionRatio" in shader, but I'm not sure if the two are actually comparable
  32965. if ( this[ prop ] !== 1.0 ) props['envMap'] = options.defaultEnvMap;
  32966. break;
  32967. case 'transparency':
  32968. // gets figured out up top
  32969. break;
  32970. default:
  32971. break;
  32972. }
  32973. }
  32974. props[ 'shading' ] = preferredShading;
  32975. props[ 'side' ] = this.effect.doubleSided ? THREE.DoubleSide : THREE.FrontSide;
  32976. if ( props.diffuse !== undefined ) {
  32977. props.color = props.diffuse;
  32978. delete props.diffuse;
  32979. }
  32980. switch ( this.type ) {
  32981. case 'constant':
  32982. if (props.emissive != undefined) props.color = props.emissive;
  32983. this.material = new THREE.MeshBasicMaterial( props );
  32984. break;
  32985. case 'phong':
  32986. case 'blinn':
  32987. this.material = new THREE.MeshPhongMaterial( props );
  32988. break;
  32989. case 'lambert':
  32990. default:
  32991. this.material = new THREE.MeshLambertMaterial( props );
  32992. break;
  32993. }
  32994. return this.material;
  32995. };
  32996. function Surface ( effect ) {
  32997. this.effect = effect;
  32998. this.init_from = null;
  32999. this.format = null;
  33000. }
  33001. Surface.prototype.parse = function ( element ) {
  33002. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33003. var child = element.childNodes[ i ];
  33004. if ( child.nodeType != 1 ) continue;
  33005. switch ( child.nodeName ) {
  33006. case 'init_from':
  33007. this.init_from = child.textContent;
  33008. break;
  33009. case 'format':
  33010. this.format = child.textContent;
  33011. break;
  33012. default:
  33013. console.log( "unhandled Surface prop: " + child.nodeName );
  33014. break;
  33015. }
  33016. }
  33017. return this;
  33018. };
  33019. function Sampler2D ( effect ) {
  33020. this.effect = effect;
  33021. this.source = null;
  33022. this.wrap_s = null;
  33023. this.wrap_t = null;
  33024. this.minfilter = null;
  33025. this.magfilter = null;
  33026. this.mipfilter = null;
  33027. }
  33028. Sampler2D.prototype.parse = function ( element ) {
  33029. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33030. var child = element.childNodes[ i ];
  33031. if ( child.nodeType != 1 ) continue;
  33032. switch ( child.nodeName ) {
  33033. case 'source':
  33034. this.source = child.textContent;
  33035. break;
  33036. case 'minfilter':
  33037. this.minfilter = child.textContent;
  33038. break;
  33039. case 'magfilter':
  33040. this.magfilter = child.textContent;
  33041. break;
  33042. case 'mipfilter':
  33043. this.mipfilter = child.textContent;
  33044. break;
  33045. case 'wrap_s':
  33046. this.wrap_s = child.textContent;
  33047. break;
  33048. case 'wrap_t':
  33049. this.wrap_t = child.textContent;
  33050. break;
  33051. default:
  33052. console.log( "unhandled Sampler2D prop: " + child.nodeName );
  33053. break;
  33054. }
  33055. }
  33056. return this;
  33057. };
  33058. function Effect () {
  33059. this.id = "";
  33060. this.name = "";
  33061. this.shader = null;
  33062. this.surface = {};
  33063. this.sampler = {};
  33064. }
  33065. Effect.prototype.create = function () {
  33066. if ( this.shader === null ) {
  33067. return null;
  33068. }
  33069. };
  33070. Effect.prototype.parse = function ( element ) {
  33071. this.id = element.getAttribute( 'id' );
  33072. this.name = element.getAttribute( 'name' );
  33073. extractDoubleSided( this, element );
  33074. this.shader = null;
  33075. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33076. var child = element.childNodes[ i ];
  33077. if ( child.nodeType != 1 ) continue;
  33078. switch ( child.nodeName ) {
  33079. case 'profile_COMMON':
  33080. this.parseTechnique( this.parseProfileCOMMON( child ) );
  33081. break;
  33082. default:
  33083. break;
  33084. }
  33085. }
  33086. return this;
  33087. };
  33088. Effect.prototype.parseNewparam = function ( element ) {
  33089. var sid = element.getAttribute( 'sid' );
  33090. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33091. var child = element.childNodes[ i ];
  33092. if ( child.nodeType != 1 ) continue;
  33093. switch ( child.nodeName ) {
  33094. case 'surface':
  33095. this.surface[sid] = ( new Surface( this ) ).parse( child );
  33096. break;
  33097. case 'sampler2D':
  33098. this.sampler[sid] = ( new Sampler2D( this ) ).parse( child );
  33099. break;
  33100. case 'extra':
  33101. break;
  33102. default:
  33103. console.log( child.nodeName );
  33104. break;
  33105. }
  33106. }
  33107. };
  33108. Effect.prototype.parseProfileCOMMON = function ( element ) {
  33109. var technique;
  33110. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33111. var child = element.childNodes[ i ];
  33112. if ( child.nodeType != 1 ) continue;
  33113. switch ( child.nodeName ) {
  33114. case 'profile_COMMON':
  33115. this.parseProfileCOMMON( child );
  33116. break;
  33117. case 'technique':
  33118. technique = child;
  33119. break;
  33120. case 'newparam':
  33121. this.parseNewparam( child );
  33122. break;
  33123. case 'image':
  33124. var _image = ( new _Image() ).parse( child );
  33125. images[ _image.id ] = _image;
  33126. break;
  33127. case 'extra':
  33128. break;
  33129. default:
  33130. console.log( child.nodeName );
  33131. break;
  33132. }
  33133. }
  33134. return technique;
  33135. };
  33136. Effect.prototype.parseTechnique = function ( element ) {
  33137. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33138. var child = element.childNodes[i];
  33139. if ( child.nodeType != 1 ) continue;
  33140. switch ( child.nodeName ) {
  33141. case 'constant':
  33142. case 'lambert':
  33143. case 'blinn':
  33144. case 'phong':
  33145. this.shader = ( new Shader( child.nodeName, this ) ).parse( child );
  33146. break;
  33147. case 'extra':
  33148. this.parseExtra(child);
  33149. break;
  33150. default:
  33151. break;
  33152. }
  33153. }
  33154. };
  33155. Effect.prototype.parseExtra = function ( element ) {
  33156. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33157. var child = element.childNodes[i];
  33158. if ( child.nodeType != 1 ) continue;
  33159. switch ( child.nodeName ) {
  33160. case 'technique':
  33161. this.parseExtraTechnique( child );
  33162. break;
  33163. default:
  33164. break;
  33165. }
  33166. }
  33167. };
  33168. Effect.prototype.parseExtraTechnique = function ( element ) {
  33169. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33170. var child = element.childNodes[i];
  33171. if ( child.nodeType != 1 ) continue;
  33172. switch ( child.nodeName ) {
  33173. case 'bump':
  33174. this.shader.parse( element );
  33175. break;
  33176. default:
  33177. break;
  33178. }
  33179. }
  33180. };
  33181. function InstanceEffect () {
  33182. this.url = "";
  33183. }
  33184. InstanceEffect.prototype.parse = function ( element ) {
  33185. this.url = element.getAttribute( 'url' ).replace( /^#/, '' );
  33186. return this;
  33187. };
  33188. function Animation() {
  33189. this.id = "";
  33190. this.name = "";
  33191. this.source = {};
  33192. this.sampler = [];
  33193. this.channel = [];
  33194. }
  33195. Animation.prototype.parse = function ( element ) {
  33196. this.id = element.getAttribute( 'id' );
  33197. this.name = element.getAttribute( 'name' );
  33198. this.source = {};
  33199. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33200. var child = element.childNodes[ i ];
  33201. if ( child.nodeType != 1 ) continue;
  33202. switch ( child.nodeName ) {
  33203. case 'animation':
  33204. var anim = ( new Animation() ).parse( child );
  33205. for ( var src in anim.source ) {
  33206. this.source[ src ] = anim.source[ src ];
  33207. }
  33208. for ( var j = 0; j < anim.channel.length; j ++ ) {
  33209. this.channel.push( anim.channel[ j ] );
  33210. this.sampler.push( anim.sampler[ j ] );
  33211. }
  33212. break;
  33213. case 'source':
  33214. var src = ( new Source() ).parse( child );
  33215. this.source[ src.id ] = src;
  33216. break;
  33217. case 'sampler':
  33218. this.sampler.push( ( new Sampler( this ) ).parse( child ) );
  33219. break;
  33220. case 'channel':
  33221. this.channel.push( ( new Channel( this ) ).parse( child ) );
  33222. break;
  33223. default:
  33224. break;
  33225. }
  33226. }
  33227. return this;
  33228. };
  33229. function Channel( animation ) {
  33230. this.animation = animation;
  33231. this.source = "";
  33232. this.target = "";
  33233. this.fullSid = null;
  33234. this.sid = null;
  33235. this.dotSyntax = null;
  33236. this.arrSyntax = null;
  33237. this.arrIndices = null;
  33238. this.member = null;
  33239. }
  33240. Channel.prototype.parse = function ( element ) {
  33241. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  33242. this.target = element.getAttribute( 'target' );
  33243. var parts = this.target.split( '/' );
  33244. var id = parts.shift();
  33245. var sid = parts.shift();
  33246. var dotSyntax = ( sid.indexOf(".") >= 0 );
  33247. var arrSyntax = ( sid.indexOf("(") >= 0 );
  33248. if ( dotSyntax ) {
  33249. parts = sid.split(".");
  33250. this.sid = parts.shift();
  33251. this.member = parts.shift();
  33252. } else if ( arrSyntax ) {
  33253. var arrIndices = sid.split("(");
  33254. this.sid = arrIndices.shift();
  33255. for (var j = 0; j < arrIndices.length; j ++ ) {
  33256. arrIndices[j] = parseInt( arrIndices[j].replace(/\)/, '') );
  33257. }
  33258. this.arrIndices = arrIndices;
  33259. } else {
  33260. this.sid = sid;
  33261. }
  33262. this.fullSid = sid;
  33263. this.dotSyntax = dotSyntax;
  33264. this.arrSyntax = arrSyntax;
  33265. return this;
  33266. };
  33267. function Sampler ( animation ) {
  33268. this.id = "";
  33269. this.animation = animation;
  33270. this.inputs = [];
  33271. this.input = null;
  33272. this.output = null;
  33273. this.strideOut = null;
  33274. this.interpolation = null;
  33275. this.startTime = null;
  33276. this.endTime = null;
  33277. this.duration = 0;
  33278. }
  33279. Sampler.prototype.parse = function ( element ) {
  33280. this.id = element.getAttribute( 'id' );
  33281. this.inputs = [];
  33282. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33283. var child = element.childNodes[ i ];
  33284. if ( child.nodeType != 1 ) continue;
  33285. switch ( child.nodeName ) {
  33286. case 'input':
  33287. this.inputs.push( (new Input()).parse( child ) );
  33288. break;
  33289. default:
  33290. break;
  33291. }
  33292. }
  33293. return this;
  33294. };
  33295. Sampler.prototype.create = function () {
  33296. for ( var i = 0; i < this.inputs.length; i ++ ) {
  33297. var input = this.inputs[ i ];
  33298. var source = this.animation.source[ input.source ];
  33299. switch ( input.semantic ) {
  33300. case 'INPUT':
  33301. this.input = source.read();
  33302. break;
  33303. case 'OUTPUT':
  33304. this.output = source.read();
  33305. this.strideOut = source.accessor.stride;
  33306. break;
  33307. case 'INTERPOLATION':
  33308. this.interpolation = source.read();
  33309. break;
  33310. case 'IN_TANGENT':
  33311. break;
  33312. case 'OUT_TANGENT':
  33313. break;
  33314. default:
  33315. console.log(input.semantic);
  33316. break;
  33317. }
  33318. }
  33319. this.startTime = 0;
  33320. this.endTime = 0;
  33321. this.duration = 0;
  33322. if ( this.input.length ) {
  33323. this.startTime = 100000000;
  33324. this.endTime = -100000000;
  33325. for ( var i = 0; i < this.input.length; i ++ ) {
  33326. this.startTime = Math.min( this.startTime, this.input[ i ] );
  33327. this.endTime = Math.max( this.endTime, this.input[ i ] );
  33328. }
  33329. this.duration = this.endTime - this.startTime;
  33330. }
  33331. };
  33332. Sampler.prototype.getData = function ( type, ndx, member ) {
  33333. var data;
  33334. if ( type === 'matrix' && this.strideOut === 16 ) {
  33335. data = this.output[ ndx ];
  33336. } else if ( this.strideOut > 1 ) {
  33337. data = [];
  33338. ndx *= this.strideOut;
  33339. for ( var i = 0; i < this.strideOut; ++ i ) {
  33340. data[ i ] = this.output[ ndx + i ];
  33341. }
  33342. if ( this.strideOut === 3 ) {
  33343. switch ( type ) {
  33344. case 'rotate':
  33345. case 'translate':
  33346. fixCoords( data, -1 );
  33347. break;
  33348. case 'scale':
  33349. fixCoords( data, 1 );
  33350. break;
  33351. }
  33352. } else if ( this.strideOut === 4 && type === 'matrix' ) {
  33353. fixCoords( data, -1 );
  33354. }
  33355. } else {
  33356. data = this.output[ ndx ];
  33357. if ( member && type === 'translate' ) {
  33358. data = getConvertedTranslation( member, data );
  33359. }
  33360. }
  33361. return data;
  33362. };
  33363. function Key ( time ) {
  33364. this.targets = [];
  33365. this.time = time;
  33366. }
  33367. Key.prototype.addTarget = function ( fullSid, transform, member, data ) {
  33368. this.targets.push( {
  33369. sid: fullSid,
  33370. member: member,
  33371. transform: transform,
  33372. data: data
  33373. } );
  33374. };
  33375. Key.prototype.apply = function ( opt_sid ) {
  33376. for ( var i = 0; i < this.targets.length; ++ i ) {
  33377. var target = this.targets[ i ];
  33378. if ( !opt_sid || target.sid === opt_sid ) {
  33379. target.transform.update( target.data, target.member );
  33380. }
  33381. }
  33382. };
  33383. Key.prototype.getTarget = function ( fullSid ) {
  33384. for ( var i = 0; i < this.targets.length; ++ i ) {
  33385. if ( this.targets[ i ].sid === fullSid ) {
  33386. return this.targets[ i ];
  33387. }
  33388. }
  33389. return null;
  33390. };
  33391. Key.prototype.hasTarget = function ( fullSid ) {
  33392. for ( var i = 0; i < this.targets.length; ++ i ) {
  33393. if ( this.targets[ i ].sid === fullSid ) {
  33394. return true;
  33395. }
  33396. }
  33397. return false;
  33398. };
  33399. // TODO: Currently only doing linear interpolation. Should support full COLLADA spec.
  33400. Key.prototype.interpolate = function ( nextKey, time ) {
  33401. for ( var i = 0, l = this.targets.length; i < l; i ++ ) {
  33402. var target = this.targets[ i ],
  33403. nextTarget = nextKey.getTarget( target.sid ),
  33404. data;
  33405. if ( target.transform.type !== 'matrix' && nextTarget ) {
  33406. var scale = ( time - this.time ) / ( nextKey.time - this.time ),
  33407. nextData = nextTarget.data,
  33408. prevData = target.data;
  33409. if ( scale < 0 ) scale = 0;
  33410. if ( scale > 1 ) scale = 1;
  33411. if ( prevData.length ) {
  33412. data = [];
  33413. for ( var j = 0; j < prevData.length; ++ j ) {
  33414. data[ j ] = prevData[ j ] + ( nextData[ j ] - prevData[ j ] ) * scale;
  33415. }
  33416. } else {
  33417. data = prevData + ( nextData - prevData ) * scale;
  33418. }
  33419. } else {
  33420. data = target.data;
  33421. }
  33422. target.transform.update( data, target.member );
  33423. }
  33424. };
  33425. // Camera
  33426. function Camera() {
  33427. this.id = "";
  33428. this.name = "";
  33429. this.technique = "";
  33430. }
  33431. Camera.prototype.parse = function ( element ) {
  33432. this.id = element.getAttribute( 'id' );
  33433. this.name = element.getAttribute( 'name' );
  33434. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33435. var child = element.childNodes[ i ];
  33436. if ( child.nodeType != 1 ) continue;
  33437. switch ( child.nodeName ) {
  33438. case 'optics':
  33439. this.parseOptics( child );
  33440. break;
  33441. default:
  33442. break;
  33443. }
  33444. }
  33445. return this;
  33446. };
  33447. Camera.prototype.parseOptics = function ( element ) {
  33448. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33449. if ( element.childNodes[ i ].nodeName === 'technique_common' ) {
  33450. var technique = element.childNodes[ i ];
  33451. for ( var j = 0; j < technique.childNodes.length; j ++ ) {
  33452. this.technique = technique.childNodes[ j ].nodeName;
  33453. if ( this.technique === 'perspective' ) {
  33454. var perspective = technique.childNodes[ j ];
  33455. for ( var k = 0; k < perspective.childNodes.length; k ++ ) {
  33456. var param = perspective.childNodes[ k ];
  33457. switch ( param.nodeName ) {
  33458. case 'yfov':
  33459. this.yfov = param.textContent;
  33460. break;
  33461. case 'xfov':
  33462. this.xfov = param.textContent;
  33463. break;
  33464. case 'znear':
  33465. this.znear = param.textContent;
  33466. break;
  33467. case 'zfar':
  33468. this.zfar = param.textContent;
  33469. break;
  33470. case 'aspect_ratio':
  33471. this.aspect_ratio = param.textContent;
  33472. break;
  33473. }
  33474. }
  33475. } else if ( this.technique === 'orthographic' ) {
  33476. var orthographic = technique.childNodes[ j ];
  33477. for ( var k = 0; k < orthographic.childNodes.length; k ++ ) {
  33478. var param = orthographic.childNodes[ k ];
  33479. switch ( param.nodeName ) {
  33480. case 'xmag':
  33481. this.xmag = param.textContent;
  33482. break;
  33483. case 'ymag':
  33484. this.ymag = param.textContent;
  33485. break;
  33486. case 'znear':
  33487. this.znear = param.textContent;
  33488. break;
  33489. case 'zfar':
  33490. this.zfar = param.textContent;
  33491. break;
  33492. case 'aspect_ratio':
  33493. this.aspect_ratio = param.textContent;
  33494. break;
  33495. }
  33496. }
  33497. }
  33498. }
  33499. }
  33500. }
  33501. return this;
  33502. };
  33503. function InstanceCamera() {
  33504. this.url = "";
  33505. }
  33506. InstanceCamera.prototype.parse = function ( element ) {
  33507. this.url = element.getAttribute('url').replace(/^#/, '');
  33508. return this;
  33509. };
  33510. // Light
  33511. function Light() {
  33512. this.id = "";
  33513. this.name = "";
  33514. this.technique = "";
  33515. }
  33516. Light.prototype.parse = function ( element ) {
  33517. this.id = element.getAttribute( 'id' );
  33518. this.name = element.getAttribute( 'name' );
  33519. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33520. var child = element.childNodes[ i ];
  33521. if ( child.nodeType != 1 ) continue;
  33522. switch ( child.nodeName ) {
  33523. case 'technique_common':
  33524. this.parseCommon( child );
  33525. break;
  33526. case 'technique':
  33527. this.parseTechnique( child );
  33528. break;
  33529. default:
  33530. break;
  33531. }
  33532. }
  33533. return this;
  33534. };
  33535. Light.prototype.parseCommon = function ( element ) {
  33536. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33537. switch ( element.childNodes[ i ].nodeName ) {
  33538. case 'directional':
  33539. case 'point':
  33540. case 'spot':
  33541. case 'ambient':
  33542. this.technique = element.childNodes[ i ].nodeName;
  33543. var light = element.childNodes[ i ];
  33544. for ( var j = 0; j < light.childNodes.length; j ++ ) {
  33545. var child = light.childNodes[j];
  33546. switch ( child.nodeName ) {
  33547. case 'color':
  33548. var rgba = _floats( child.textContent );
  33549. this.color = new THREE.Color(0);
  33550. this.color.setRGB( rgba[0], rgba[1], rgba[2] );
  33551. this.color.a = rgba[3];
  33552. break;
  33553. case 'falloff_angle':
  33554. this.falloff_angle = parseFloat( child.textContent );
  33555. break;
  33556. case 'quadratic_attenuation':
  33557. var f = parseFloat( child.textContent );
  33558. this.distance = f ? Math.sqrt( 1 / f ) : 0;
  33559. }
  33560. }
  33561. }
  33562. }
  33563. return this;
  33564. };
  33565. Light.prototype.parseTechnique = function ( element ) {
  33566. this.profile = element.getAttribute( 'profile' );
  33567. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33568. var child = element.childNodes[ i ];
  33569. switch ( child.nodeName ) {
  33570. case 'intensity':
  33571. this.intensity = parseFloat(child.textContent);
  33572. break;
  33573. }
  33574. }
  33575. return this;
  33576. };
  33577. function InstanceLight() {
  33578. this.url = "";
  33579. }
  33580. InstanceLight.prototype.parse = function ( element ) {
  33581. this.url = element.getAttribute('url').replace(/^#/, '');
  33582. return this;
  33583. };
  33584. function KinematicsModel( ) {
  33585. this.id = '';
  33586. this.name = '';
  33587. this.joints = [];
  33588. this.links = [];
  33589. }
  33590. KinematicsModel.prototype.parse = function( element ) {
  33591. this.id = element.getAttribute('id');
  33592. this.name = element.getAttribute('name');
  33593. this.joints = [];
  33594. this.links = [];
  33595. for (var i = 0; i < element.childNodes.length; i ++ ) {
  33596. var child = element.childNodes[ i ];
  33597. if ( child.nodeType != 1 ) continue;
  33598. switch ( child.nodeName ) {
  33599. case 'technique_common':
  33600. this.parseCommon(child);
  33601. break;
  33602. default:
  33603. break;
  33604. }
  33605. }
  33606. return this;
  33607. };
  33608. KinematicsModel.prototype.parseCommon = function( element ) {
  33609. for (var i = 0; i < element.childNodes.length; i ++ ) {
  33610. var child = element.childNodes[ i ];
  33611. if ( child.nodeType != 1 ) continue;
  33612. switch ( element.childNodes[ i ].nodeName ) {
  33613. case 'joint':
  33614. this.joints.push( (new Joint()).parse(child) );
  33615. break;
  33616. case 'link':
  33617. this.links.push( (new Link()).parse(child) );
  33618. break;
  33619. default:
  33620. break;
  33621. }
  33622. }
  33623. return this;
  33624. };
  33625. function Joint( ) {
  33626. this.sid = '';
  33627. this.name = '';
  33628. this.axis = new THREE.Vector3();
  33629. this.limits = {
  33630. min: 0,
  33631. max: 0
  33632. };
  33633. this.type = '';
  33634. this.static = false;
  33635. this.zeroPosition = 0.0;
  33636. this.middlePosition = 0.0;
  33637. }
  33638. Joint.prototype.parse = function( element ) {
  33639. this.sid = element.getAttribute('sid');
  33640. this.name = element.getAttribute('name');
  33641. this.axis = new THREE.Vector3();
  33642. this.limits = {
  33643. min: 0,
  33644. max: 0
  33645. };
  33646. this.type = '';
  33647. this.static = false;
  33648. this.zeroPosition = 0.0;
  33649. this.middlePosition = 0.0;
  33650. var axisElement = element.querySelector('axis');
  33651. var _axis = _floats(axisElement.textContent);
  33652. this.axis = getConvertedVec3(_axis, 0);
  33653. var min = element.querySelector('limits min') ? parseFloat(element.querySelector('limits min').textContent) : -360;
  33654. var max = element.querySelector('limits max') ? parseFloat(element.querySelector('limits max').textContent) : 360;
  33655. this.limits = {
  33656. min: min,
  33657. max: max
  33658. };
  33659. var jointTypes = [ 'prismatic', 'revolute' ];
  33660. for (var i = 0; i < jointTypes.length; i ++ ) {
  33661. var type = jointTypes[ i ];
  33662. var jointElement = element.querySelector(type);
  33663. if ( jointElement ) {
  33664. this.type = type;
  33665. }
  33666. }
  33667. // if the min is equal to or somehow greater than the max, consider the joint static
  33668. if ( this.limits.min >= this.limits.max ) {
  33669. this.static = true;
  33670. }
  33671. this.middlePosition = (this.limits.min + this.limits.max) / 2.0;
  33672. return this;
  33673. };
  33674. function Link( ) {
  33675. this.sid = '';
  33676. this.name = '';
  33677. this.transforms = [];
  33678. this.attachments = [];
  33679. }
  33680. Link.prototype.parse = function( element ) {
  33681. this.sid = element.getAttribute('sid');
  33682. this.name = element.getAttribute('name');
  33683. this.transforms = [];
  33684. this.attachments = [];
  33685. for (var i = 0; i < element.childNodes.length; i ++ ) {
  33686. var child = element.childNodes[ i ];
  33687. if ( child.nodeType != 1 ) continue;
  33688. switch ( child.nodeName ) {
  33689. case 'attachment_full':
  33690. this.attachments.push( (new Attachment()).parse(child) );
  33691. break;
  33692. case 'rotate':
  33693. case 'translate':
  33694. case 'matrix':
  33695. this.transforms.push( (new Transform()).parse(child) );
  33696. break;
  33697. default:
  33698. break;
  33699. }
  33700. }
  33701. return this;
  33702. };
  33703. function Attachment( ) {
  33704. this.joint = '';
  33705. this.transforms = [];
  33706. this.links = [];
  33707. }
  33708. Attachment.prototype.parse = function( element ) {
  33709. this.joint = element.getAttribute('joint').split('/').pop();
  33710. this.links = [];
  33711. for (var i = 0; i < element.childNodes.length; i ++ ) {
  33712. var child = element.childNodes[ i ];
  33713. if ( child.nodeType != 1 ) continue;
  33714. switch ( child.nodeName ) {
  33715. case 'link':
  33716. this.links.push( (new Link()).parse(child) );
  33717. break;
  33718. case 'rotate':
  33719. case 'translate':
  33720. case 'matrix':
  33721. this.transforms.push( (new Transform()).parse(child) );
  33722. break;
  33723. default:
  33724. break;
  33725. }
  33726. }
  33727. return this;
  33728. };
  33729. function _source( element ) {
  33730. var id = element.getAttribute( 'id' );
  33731. if ( sources[ id ] != undefined ) {
  33732. return sources[ id ];
  33733. }
  33734. sources[ id ] = ( new Source(id )).parse( element );
  33735. return sources[ id ];
  33736. }
  33737. function _nsResolver( nsPrefix ) {
  33738. if ( nsPrefix === "dae" ) {
  33739. return "http://www.collada.org/2005/11/COLLADASchema";
  33740. }
  33741. return null;
  33742. }
  33743. function _bools( str ) {
  33744. var raw = _strings( str );
  33745. var data = [];
  33746. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  33747. data.push( (raw[i] === 'true' || raw[i] === '1') ? true : false );
  33748. }
  33749. return data;
  33750. }
  33751. function _floats( str ) {
  33752. var raw = _strings(str);
  33753. var data = [];
  33754. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  33755. data.push( parseFloat( raw[ i ] ) );
  33756. }
  33757. return data;
  33758. }
  33759. function _ints( str ) {
  33760. var raw = _strings( str );
  33761. var data = [];
  33762. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  33763. data.push( parseInt( raw[ i ], 10 ) );
  33764. }
  33765. return data;
  33766. }
  33767. function _strings( str ) {
  33768. return ( str.length > 0 ) ? _trimString( str ).split( /\s+/ ) : [];
  33769. }
  33770. function _trimString( str ) {
  33771. return str.replace( /^\s+/, "" ).replace( /\s+$/, "" );
  33772. }
  33773. function _attr_as_float( element, name, defaultValue ) {
  33774. if ( element.hasAttribute( name ) ) {
  33775. return parseFloat( element.getAttribute( name ) );
  33776. } else {
  33777. return defaultValue;
  33778. }
  33779. }
  33780. function _attr_as_int( element, name, defaultValue ) {
  33781. if ( element.hasAttribute( name ) ) {
  33782. return parseInt( element.getAttribute( name ), 10) ;
  33783. } else {
  33784. return defaultValue;
  33785. }
  33786. }
  33787. function _attr_as_string( element, name, defaultValue ) {
  33788. if ( element.hasAttribute( name ) ) {
  33789. return element.getAttribute( name );
  33790. } else {
  33791. return defaultValue;
  33792. }
  33793. }
  33794. function _format_float( f, num ) {
  33795. if ( f === undefined ) {
  33796. var s = '0.';
  33797. while ( s.length < num + 2 ) {
  33798. s += '0';
  33799. }
  33800. return s;
  33801. }
  33802. num = num || 2;
  33803. var parts = f.toString().split( '.' );
  33804. parts[ 1 ] = parts.length > 1 ? parts[ 1 ].substr( 0, num ) : "0";
  33805. while ( parts[ 1 ].length < num ) {
  33806. parts[ 1 ] += '0';
  33807. }
  33808. return parts.join( '.' );
  33809. }
  33810. function loadTextureImage ( texture, url ) {
  33811. var loader = new THREE.ImageLoader();
  33812. loader.load( url, function ( image ) {
  33813. texture.image = image;
  33814. texture.needsUpdate = true;
  33815. } );
  33816. }
  33817. function extractDoubleSided( obj, element ) {
  33818. obj.doubleSided = false;
  33819. var node = element.querySelectorAll('extra double_sided')[0];
  33820. if ( node ) {
  33821. if ( node && parseInt( node.textContent, 10 ) === 1 ) {
  33822. obj.doubleSided = true;
  33823. }
  33824. }
  33825. }
  33826. // Up axis conversion
  33827. function setUpConversion() {
  33828. if ( options.convertUpAxis !== true || colladaUp === options.upAxis ) {
  33829. upConversion = null;
  33830. } else {
  33831. switch ( colladaUp ) {
  33832. case 'X':
  33833. upConversion = options.upAxis === 'Y' ? 'XtoY' : 'XtoZ';
  33834. break;
  33835. case 'Y':
  33836. upConversion = options.upAxis === 'X' ? 'YtoX' : 'YtoZ';
  33837. break;
  33838. case 'Z':
  33839. upConversion = options.upAxis === 'X' ? 'ZtoX' : 'ZtoY';
  33840. break;
  33841. }
  33842. }
  33843. }
  33844. function fixCoords( data, sign ) {
  33845. if ( options.convertUpAxis !== true || colladaUp === options.upAxis ) {
  33846. return;
  33847. }
  33848. switch ( upConversion ) {
  33849. case 'XtoY':
  33850. var tmp = data[ 0 ];
  33851. data[ 0 ] = sign * data[ 1 ];
  33852. data[ 1 ] = tmp;
  33853. break;
  33854. case 'XtoZ':
  33855. var tmp = data[ 2 ];
  33856. data[ 2 ] = data[ 1 ];
  33857. data[ 1 ] = data[ 0 ];
  33858. data[ 0 ] = tmp;
  33859. break;
  33860. case 'YtoX':
  33861. var tmp = data[ 0 ];
  33862. data[ 0 ] = data[ 1 ];
  33863. data[ 1 ] = sign * tmp;
  33864. break;
  33865. case 'YtoZ':
  33866. var tmp = data[ 1 ];
  33867. data[ 1 ] = sign * data[ 2 ];
  33868. data[ 2 ] = tmp;
  33869. break;
  33870. case 'ZtoX':
  33871. var tmp = data[ 0 ];
  33872. data[ 0 ] = data[ 1 ];
  33873. data[ 1 ] = data[ 2 ];
  33874. data[ 2 ] = tmp;
  33875. break;
  33876. case 'ZtoY':
  33877. var tmp = data[ 1 ];
  33878. data[ 1 ] = data[ 2 ];
  33879. data[ 2 ] = sign * tmp;
  33880. break;
  33881. }
  33882. }
  33883. function getConvertedTranslation( axis, data ) {
  33884. if ( options.convertUpAxis !== true || colladaUp === options.upAxis ) {
  33885. return data;
  33886. }
  33887. switch ( axis ) {
  33888. case 'X':
  33889. data = upConversion === 'XtoY' ? data * -1 : data;
  33890. break;
  33891. case 'Y':
  33892. data = upConversion === 'YtoZ' || upConversion === 'YtoX' ? data * -1 : data;
  33893. break;
  33894. case 'Z':
  33895. data = upConversion === 'ZtoY' ? data * -1 : data ;
  33896. break;
  33897. default:
  33898. break;
  33899. }
  33900. return data;
  33901. }
  33902. function getConvertedVec3( data, offset ) {
  33903. var arr = [ data[ offset ], data[ offset + 1 ], data[ offset + 2 ] ];
  33904. fixCoords( arr, -1 );
  33905. return new THREE.Vector3( arr[ 0 ], arr[ 1 ], arr[ 2 ] );
  33906. }
  33907. function getConvertedMat4( data ) {
  33908. if ( options.convertUpAxis ) {
  33909. // First fix rotation and scale
  33910. // Columns first
  33911. var arr = [ data[ 0 ], data[ 4 ], data[ 8 ] ];
  33912. fixCoords( arr, -1 );
  33913. data[ 0 ] = arr[ 0 ];
  33914. data[ 4 ] = arr[ 1 ];
  33915. data[ 8 ] = arr[ 2 ];
  33916. arr = [ data[ 1 ], data[ 5 ], data[ 9 ] ];
  33917. fixCoords( arr, -1 );
  33918. data[ 1 ] = arr[ 0 ];
  33919. data[ 5 ] = arr[ 1 ];
  33920. data[ 9 ] = arr[ 2 ];
  33921. arr = [ data[ 2 ], data[ 6 ], data[ 10 ] ];
  33922. fixCoords( arr, -1 );
  33923. data[ 2 ] = arr[ 0 ];
  33924. data[ 6 ] = arr[ 1 ];
  33925. data[ 10 ] = arr[ 2 ];
  33926. // Rows second
  33927. arr = [ data[ 0 ], data[ 1 ], data[ 2 ] ];
  33928. fixCoords( arr, -1 );
  33929. data[ 0 ] = arr[ 0 ];
  33930. data[ 1 ] = arr[ 1 ];
  33931. data[ 2 ] = arr[ 2 ];
  33932. arr = [ data[ 4 ], data[ 5 ], data[ 6 ] ];
  33933. fixCoords( arr, -1 );
  33934. data[ 4 ] = arr[ 0 ];
  33935. data[ 5 ] = arr[ 1 ];
  33936. data[ 6 ] = arr[ 2 ];
  33937. arr = [ data[ 8 ], data[ 9 ], data[ 10 ] ];
  33938. fixCoords( arr, -1 );
  33939. data[ 8 ] = arr[ 0 ];
  33940. data[ 9 ] = arr[ 1 ];
  33941. data[ 10 ] = arr[ 2 ];
  33942. // Now fix translation
  33943. arr = [ data[ 3 ], data[ 7 ], data[ 11 ] ];
  33944. fixCoords( arr, -1 );
  33945. data[ 3 ] = arr[ 0 ];
  33946. data[ 7 ] = arr[ 1 ];
  33947. data[ 11 ] = arr[ 2 ];
  33948. }
  33949. return new THREE.Matrix4().set(
  33950. data[0], data[1], data[2], data[3],
  33951. data[4], data[5], data[6], data[7],
  33952. data[8], data[9], data[10], data[11],
  33953. data[12], data[13], data[14], data[15]
  33954. );
  33955. }
  33956. function getConvertedIndex( index ) {
  33957. if ( index > -1 && index < 3 ) {
  33958. var members = [ 'X', 'Y', 'Z' ],
  33959. indices = { X: 0, Y: 1, Z: 2 };
  33960. index = getConvertedMember( members[ index ] );
  33961. index = indices[ index ];
  33962. }
  33963. return index;
  33964. }
  33965. function getConvertedMember( member ) {
  33966. if ( options.convertUpAxis ) {
  33967. switch ( member ) {
  33968. case 'X':
  33969. switch ( upConversion ) {
  33970. case 'XtoY':
  33971. case 'XtoZ':
  33972. case 'YtoX':
  33973. member = 'Y';
  33974. break;
  33975. case 'ZtoX':
  33976. member = 'Z';
  33977. break;
  33978. }
  33979. break;
  33980. case 'Y':
  33981. switch ( upConversion ) {
  33982. case 'XtoY':
  33983. case 'YtoX':
  33984. case 'ZtoX':
  33985. member = 'X';
  33986. break;
  33987. case 'XtoZ':
  33988. case 'YtoZ':
  33989. case 'ZtoY':
  33990. member = 'Z';
  33991. break;
  33992. }
  33993. break;
  33994. case 'Z':
  33995. switch ( upConversion ) {
  33996. case 'XtoZ':
  33997. member = 'X';
  33998. break;
  33999. case 'YtoZ':
  34000. case 'ZtoX':
  34001. case 'ZtoY':
  34002. member = 'Y';
  34003. break;
  34004. }
  34005. break;
  34006. }
  34007. }
  34008. return member;
  34009. }
  34010. return {
  34011. load: load,
  34012. parse: parse,
  34013. setPreferredShading: setPreferredShading,
  34014. applySkin: applySkin,
  34015. geometries : geometries,
  34016. options: options
  34017. };
  34018. };
  34019. },{}],44:[function(_dereq_,module,exports){
  34020. /**
  34021. * @author Rich Tibbett / https://github.com/richtr
  34022. * @author mrdoob / http://mrdoob.com/
  34023. * @author Tony Parisi / http://www.tonyparisi.com/
  34024. * @author Takahiro / https://github.com/takahirox
  34025. */
  34026. THREE.GLTFLoader = ( function () {
  34027. function GLTFLoader( manager ) {
  34028. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  34029. }
  34030. GLTFLoader.prototype = {
  34031. constructor: GLTFLoader,
  34032. load: function ( url, onLoad, onProgress, onError ) {
  34033. var scope = this;
  34034. var path = this.path && ( typeof this.path === "string" ) ? this.path : THREE.Loader.prototype.extractUrlBase( url );
  34035. var loader = new THREE.FileLoader( scope.manager );
  34036. loader.setResponseType( 'arraybuffer' );
  34037. loader.load( url, function ( data ) {
  34038. scope.parse( data, onLoad, path );
  34039. }, onProgress, onError );
  34040. },
  34041. setCrossOrigin: function ( value ) {
  34042. this.crossOrigin = value;
  34043. },
  34044. setPath: function ( value ) {
  34045. this.path = value;
  34046. },
  34047. parse: function ( data, callback, path ) {
  34048. var content;
  34049. var extensions = {};
  34050. var magic = convertUint8ArrayToString( new Uint8Array( data, 0, 4 ) );
  34051. if ( magic === BINARY_EXTENSION_HEADER_DEFAULTS.magic ) {
  34052. extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
  34053. content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content;
  34054. } else {
  34055. content = convertUint8ArrayToString( new Uint8Array( data ) );
  34056. }
  34057. var json = JSON.parse( content );
  34058. if ( json.extensionsUsed && json.extensionsUsed.indexOf( EXTENSIONS.KHR_MATERIALS_COMMON ) >= 0 ) {
  34059. extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ] = new GLTFMaterialsCommonExtension( json );
  34060. }
  34061. console.time( 'GLTFLoader' );
  34062. var parser = new GLTFParser( json, extensions, {
  34063. path: path || this.path,
  34064. crossOrigin: this.crossOrigin
  34065. } );
  34066. parser.parse( function ( scene, scenes, cameras, animations ) {
  34067. console.timeEnd( 'GLTFLoader' );
  34068. var glTF = {
  34069. "scene": scene,
  34070. "scenes": scenes,
  34071. "cameras": cameras,
  34072. "animations": animations
  34073. };
  34074. callback( glTF );
  34075. } );
  34076. }
  34077. };
  34078. /* GLTFREGISTRY */
  34079. function GLTFRegistry() {
  34080. var objects = {};
  34081. return {
  34082. get: function ( key ) {
  34083. return objects[ key ];
  34084. },
  34085. add: function ( key, object ) {
  34086. objects[ key ] = object;
  34087. },
  34088. remove: function ( key ) {
  34089. delete objects[ key ];
  34090. },
  34091. removeAll: function () {
  34092. objects = {};
  34093. },
  34094. update: function ( scene, camera ) {
  34095. // update scene graph
  34096. scene.updateMatrixWorld();
  34097. // update camera matrices and frustum
  34098. camera.updateMatrixWorld();
  34099. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  34100. for ( var name in objects ) {
  34101. var object = objects[ name ];
  34102. if ( object.update ) {
  34103. object.update( scene, camera );
  34104. }
  34105. }
  34106. }
  34107. };
  34108. }
  34109. /* GLTFSHADERS */
  34110. GLTFLoader.Shaders = new GLTFRegistry();
  34111. /* GLTFSHADER */
  34112. function GLTFShader( targetNode, allNodes ) {
  34113. var boundUniforms = {};
  34114. // bind each uniform to its source node
  34115. var uniforms = targetNode.material.uniforms;
  34116. for ( var uniformId in uniforms ) {
  34117. var uniform = uniforms[ uniformId ];
  34118. if ( uniform.semantic ) {
  34119. var sourceNodeRef = uniform.node;
  34120. var sourceNode = targetNode;
  34121. if ( sourceNodeRef ) {
  34122. sourceNode = allNodes[ sourceNodeRef ];
  34123. }
  34124. boundUniforms[ uniformId ] = {
  34125. semantic: uniform.semantic,
  34126. sourceNode: sourceNode,
  34127. targetNode: targetNode,
  34128. uniform: uniform
  34129. };
  34130. }
  34131. }
  34132. this.boundUniforms = boundUniforms;
  34133. this._m4 = new THREE.Matrix4();
  34134. }
  34135. // Update - update all the uniform values
  34136. GLTFShader.prototype.update = function ( scene, camera ) {
  34137. var boundUniforms = this.boundUniforms;
  34138. for ( var name in boundUniforms ) {
  34139. var boundUniform = boundUniforms[ name ];
  34140. switch ( boundUniform.semantic ) {
  34141. case "MODELVIEW":
  34142. var m4 = boundUniform.uniform.value;
  34143. m4.multiplyMatrices( camera.matrixWorldInverse, boundUniform.sourceNode.matrixWorld );
  34144. break;
  34145. case "MODELVIEWINVERSETRANSPOSE":
  34146. var m3 = boundUniform.uniform.value;
  34147. this._m4.multiplyMatrices( camera.matrixWorldInverse, boundUniform.sourceNode.matrixWorld );
  34148. m3.getNormalMatrix( this._m4 );
  34149. break;
  34150. case "PROJECTION":
  34151. var m4 = boundUniform.uniform.value;
  34152. m4.copy( camera.projectionMatrix );
  34153. break;
  34154. case "JOINTMATRIX":
  34155. var m4v = boundUniform.uniform.value;
  34156. for ( var mi = 0; mi < m4v.length; mi ++ ) {
  34157. // So it goes like this:
  34158. // SkinnedMesh world matrix is already baked into MODELVIEW;
  34159. // transform joints to local space,
  34160. // then transform using joint's inverse
  34161. m4v[ mi ]
  34162. .getInverse( boundUniform.sourceNode.matrixWorld )
  34163. .multiply( boundUniform.targetNode.skeleton.bones[ mi ].matrixWorld )
  34164. .multiply( boundUniform.targetNode.skeleton.boneInverses[ mi ] )
  34165. .multiply( boundUniform.targetNode.bindMatrix );
  34166. }
  34167. break;
  34168. default :
  34169. console.warn( "Unhandled shader semantic: " + boundUniform.semantic );
  34170. break;
  34171. }
  34172. }
  34173. };
  34174. /* ANIMATION */
  34175. GLTFLoader.Animations = {
  34176. update: function () {
  34177. console.warn( 'THREE.GLTFLoader.Animation has been deprecated. Use THREE.AnimationMixer instead.' );
  34178. }
  34179. };
  34180. /*********************************/
  34181. /********** EXTENSIONS ***********/
  34182. /*********************************/
  34183. var EXTENSIONS = {
  34184. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  34185. KHR_MATERIALS_COMMON: 'KHR_materials_common'
  34186. };
  34187. /* MATERIALS COMMON EXTENSION */
  34188. function GLTFMaterialsCommonExtension( json ) {
  34189. this.name = EXTENSIONS.KHR_MATERIALS_COMMON;
  34190. this.lights = {};
  34191. var lights = json.extensions && json.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ].lights;
  34192. for ( var lightId in lights ) {
  34193. var light = lights[ lightId ];
  34194. var lightNode;
  34195. var lightParams = light[ light.type ];
  34196. var color = new THREE.Color().fromArray( lightParams.color );
  34197. switch ( light.type ) {
  34198. case "directional":
  34199. lightNode = new THREE.DirectionalLight( color );
  34200. lightNode.position.set( 0, 0, 1 );
  34201. break;
  34202. case "point":
  34203. lightNode = new THREE.PointLight( color );
  34204. break;
  34205. case "spot":
  34206. lightNode = new THREE.SpotLight( color );
  34207. lightNode.position.set( 0, 0, 1 );
  34208. break;
  34209. case "ambient":
  34210. lightNode = new THREE.AmbientLight( color );
  34211. break;
  34212. }
  34213. if ( lightNode ) {
  34214. this.lights[ lightId ] = lightNode;
  34215. }
  34216. }
  34217. }
  34218. /* BINARY EXTENSION */
  34219. var BINARY_EXTENSION_BUFFER_NAME = 'binary_glTF';
  34220. var BINARY_EXTENSION_HEADER_DEFAULTS = { magic: 'glTF', version: 1, contentFormat: 0 };
  34221. var BINARY_EXTENSION_HEADER_LENGTH = 20;
  34222. function GLTFBinaryExtension( data ) {
  34223. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  34224. var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
  34225. var header = {
  34226. magic: convertUint8ArrayToString( new Uint8Array( data.slice( 0, 4 ) ) ),
  34227. version: headerView.getUint32( 4, true ),
  34228. length: headerView.getUint32( 8, true ),
  34229. contentLength: headerView.getUint32( 12, true ),
  34230. contentFormat: headerView.getUint32( 16, true )
  34231. };
  34232. for ( var key in BINARY_EXTENSION_HEADER_DEFAULTS ) {
  34233. var value = BINARY_EXTENSION_HEADER_DEFAULTS[ key ];
  34234. if ( header[ key ] !== value ) {
  34235. throw new Error( 'Unsupported glTF-Binary header: Expected "%s" to be "%s".', key, value );
  34236. }
  34237. }
  34238. var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH, header.contentLength );
  34239. this.header = header;
  34240. this.content = convertUint8ArrayToString( contentArray );
  34241. this.body = data.slice( BINARY_EXTENSION_HEADER_LENGTH + header.contentLength, header.length );
  34242. }
  34243. GLTFBinaryExtension.prototype.loadShader = function ( shader, bufferViews ) {
  34244. var bufferView = bufferViews[ shader.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].bufferView ];
  34245. var array = new Uint8Array( bufferView );
  34246. return convertUint8ArrayToString( array );
  34247. };
  34248. GLTFBinaryExtension.prototype.loadTextureSourceUri = function ( source, bufferViews ) {
  34249. var metadata = source.extensions[ EXTENSIONS.KHR_BINARY_GLTF ];
  34250. var bufferView = bufferViews[ metadata.bufferView ];
  34251. var stringData = convertUint8ArrayToString( new Uint8Array( bufferView ) );
  34252. return 'data:' + metadata.mimeType + ';base64,' + btoa( stringData );
  34253. };
  34254. /*********************************/
  34255. /********** INTERNALS ************/
  34256. /*********************************/
  34257. /* CONSTANTS */
  34258. var WEBGL_CONSTANTS = {
  34259. FLOAT: 5126,
  34260. //FLOAT_MAT2: 35674,
  34261. FLOAT_MAT3: 35675,
  34262. FLOAT_MAT4: 35676,
  34263. FLOAT_VEC2: 35664,
  34264. FLOAT_VEC3: 35665,
  34265. FLOAT_VEC4: 35666,
  34266. LINEAR: 9729,
  34267. REPEAT: 10497,
  34268. SAMPLER_2D: 35678,
  34269. TRIANGLES: 4,
  34270. LINES: 1,
  34271. UNSIGNED_BYTE: 5121,
  34272. UNSIGNED_SHORT: 5123,
  34273. VERTEX_SHADER: 35633,
  34274. FRAGMENT_SHADER: 35632
  34275. };
  34276. var WEBGL_TYPE = {
  34277. 5126: Number,
  34278. //35674: THREE.Matrix2,
  34279. 35675: THREE.Matrix3,
  34280. 35676: THREE.Matrix4,
  34281. 35664: THREE.Vector2,
  34282. 35665: THREE.Vector3,
  34283. 35666: THREE.Vector4,
  34284. 35678: THREE.Texture
  34285. };
  34286. var WEBGL_COMPONENT_TYPES = {
  34287. 5120: Int8Array,
  34288. 5121: Uint8Array,
  34289. 5122: Int16Array,
  34290. 5123: Uint16Array,
  34291. 5125: Uint32Array,
  34292. 5126: Float32Array
  34293. };
  34294. var WEBGL_FILTERS = {
  34295. 9728: THREE.NearestFilter,
  34296. 9729: THREE.LinearFilter,
  34297. 9984: THREE.NearestMipMapNearestFilter,
  34298. 9985: THREE.LinearMipMapNearestFilter,
  34299. 9986: THREE.NearestMipMapLinearFilter,
  34300. 9987: THREE.LinearMipMapLinearFilter
  34301. };
  34302. var WEBGL_WRAPPINGS = {
  34303. 33071: THREE.ClampToEdgeWrapping,
  34304. 33648: THREE.MirroredRepeatWrapping,
  34305. 10497: THREE.RepeatWrapping
  34306. };
  34307. var WEBGL_TEXTURE_FORMATS = {
  34308. 6406: THREE.AlphaFormat,
  34309. 6407: THREE.RGBFormat,
  34310. 6408: THREE.RGBAFormat,
  34311. 6409: THREE.LuminanceFormat,
  34312. 6410: THREE.LuminanceAlphaFormat
  34313. };
  34314. var WEBGL_TEXTURE_DATATYPES = {
  34315. 5121: THREE.UnsignedByteType,
  34316. 32819: THREE.UnsignedShort4444Type,
  34317. 32820: THREE.UnsignedShort5551Type,
  34318. 33635: THREE.UnsignedShort565Type
  34319. };
  34320. var WEBGL_SIDES = {
  34321. 1028: THREE.BackSide, // Culling front
  34322. 1029: THREE.FrontSide // Culling back
  34323. //1032: THREE.NoSide // Culling front and back, what to do?
  34324. };
  34325. var WEBGL_DEPTH_FUNCS = {
  34326. 512: THREE.NeverDepth,
  34327. 513: THREE.LessDepth,
  34328. 514: THREE.EqualDepth,
  34329. 515: THREE.LessEqualDepth,
  34330. 516: THREE.GreaterEqualDepth,
  34331. 517: THREE.NotEqualDepth,
  34332. 518: THREE.GreaterEqualDepth,
  34333. 519: THREE.AlwaysDepth
  34334. };
  34335. var WEBGL_BLEND_EQUATIONS = {
  34336. 32774: THREE.AddEquation,
  34337. 32778: THREE.SubtractEquation,
  34338. 32779: THREE.ReverseSubtractEquation
  34339. };
  34340. var WEBGL_BLEND_FUNCS = {
  34341. 0: THREE.ZeroFactor,
  34342. 1: THREE.OneFactor,
  34343. 768: THREE.SrcColorFactor,
  34344. 769: THREE.OneMinusSrcColorFactor,
  34345. 770: THREE.SrcAlphaFactor,
  34346. 771: THREE.OneMinusSrcAlphaFactor,
  34347. 772: THREE.DstAlphaFactor,
  34348. 773: THREE.OneMinusDstAlphaFactor,
  34349. 774: THREE.DstColorFactor,
  34350. 775: THREE.OneMinusDstColorFactor,
  34351. 776: THREE.SrcAlphaSaturateFactor
  34352. // The followings are not supported by Three.js yet
  34353. //32769: CONSTANT_COLOR,
  34354. //32770: ONE_MINUS_CONSTANT_COLOR,
  34355. //32771: CONSTANT_ALPHA,
  34356. //32772: ONE_MINUS_CONSTANT_COLOR
  34357. };
  34358. var WEBGL_TYPE_SIZES = {
  34359. 'SCALAR': 1,
  34360. 'VEC2': 2,
  34361. 'VEC3': 3,
  34362. 'VEC4': 4,
  34363. 'MAT2': 4,
  34364. 'MAT3': 9,
  34365. 'MAT4': 16
  34366. };
  34367. var PATH_PROPERTIES = {
  34368. scale: 'scale',
  34369. translation: 'position',
  34370. rotation: 'quaternion'
  34371. };
  34372. var INTERPOLATION = {
  34373. LINEAR: THREE.InterpolateLinear,
  34374. STEP: THREE.InterpolateDiscrete
  34375. };
  34376. var STATES_ENABLES = {
  34377. 2884: 'CULL_FACE',
  34378. 2929: 'DEPTH_TEST',
  34379. 3042: 'BLEND',
  34380. 3089: 'SCISSOR_TEST',
  34381. 32823: 'POLYGON_OFFSET_FILL',
  34382. 32926: 'SAMPLE_ALPHA_TO_COVERAGE'
  34383. };
  34384. /* UTILITY FUNCTIONS */
  34385. function _each( object, callback, thisObj ) {
  34386. if ( !object ) {
  34387. return Promise.resolve();
  34388. }
  34389. var results;
  34390. var fns = [];
  34391. if ( Object.prototype.toString.call( object ) === '[object Array]' ) {
  34392. results = [];
  34393. var length = object.length;
  34394. for ( var idx = 0; idx < length; idx ++ ) {
  34395. var value = callback.call( thisObj || this, object[ idx ], idx );
  34396. if ( value ) {
  34397. fns.push( value );
  34398. if ( value instanceof Promise ) {
  34399. value.then( function( key, value ) {
  34400. results[ idx ] = value;
  34401. }.bind( this, key ));
  34402. } else {
  34403. results[ idx ] = value;
  34404. }
  34405. }
  34406. }
  34407. } else {
  34408. results = {};
  34409. for ( var key in object ) {
  34410. if ( object.hasOwnProperty( key ) ) {
  34411. var value = callback.call( thisObj || this, object[ key ], key );
  34412. if ( value ) {
  34413. fns.push( value );
  34414. if ( value instanceof Promise ) {
  34415. value.then( function( key, value ) {
  34416. results[ key ] = value;
  34417. }.bind( this, key ));
  34418. } else {
  34419. results[ key ] = value;
  34420. }
  34421. }
  34422. }
  34423. }
  34424. }
  34425. return Promise.all( fns ).then( function() {
  34426. return results;
  34427. });
  34428. }
  34429. function resolveURL( url, path ) {
  34430. // Invalid URL
  34431. if ( typeof url !== 'string' || url === '' )
  34432. return '';
  34433. // Absolute URL
  34434. if ( /^https?:\/\//i.test( url ) ) {
  34435. return url;
  34436. }
  34437. // Data URI
  34438. if ( /^data:.*,.*$/i.test( url ) ) {
  34439. return url;
  34440. }
  34441. // Relative URL
  34442. return ( path || '' ) + url;
  34443. }
  34444. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  34445. // throws a "maximum call stack size exceeded" error for large arrays.
  34446. function convertUint8ArrayToString( array ) {
  34447. var s = '';
  34448. for ( var i = 0; i < array.length; i ++ ) {
  34449. s += String.fromCharCode( array[ i ] );
  34450. }
  34451. return s;
  34452. }
  34453. // Three.js seems too dependent on attribute names so globally
  34454. // replace those in the shader code
  34455. function replaceTHREEShaderAttributes( shaderText, technique ) {
  34456. // Expected technique attributes
  34457. var attributes = {};
  34458. for ( var attributeId in technique.attributes ) {
  34459. var pname = technique.attributes[ attributeId ];
  34460. var param = technique.parameters[ pname ];
  34461. var atype = param.type;
  34462. var semantic = param.semantic;
  34463. attributes[ attributeId ] = {
  34464. type: atype,
  34465. semantic: semantic
  34466. };
  34467. }
  34468. // Figure out which attributes to change in technique
  34469. var shaderParams = technique.parameters;
  34470. var shaderAttributes = technique.attributes;
  34471. var params = {};
  34472. for ( var attributeId in attributes ) {
  34473. var pname = shaderAttributes[ attributeId ];
  34474. var shaderParam = shaderParams[ pname ];
  34475. var semantic = shaderParam.semantic;
  34476. if ( semantic ) {
  34477. params[ attributeId ] = shaderParam;
  34478. }
  34479. }
  34480. for ( var pname in params ) {
  34481. var param = params[ pname ];
  34482. var semantic = param.semantic;
  34483. var regEx = new RegExp( "\\b" + pname + "\\b", "g" );
  34484. switch ( semantic ) {
  34485. case "POSITION":
  34486. shaderText = shaderText.replace( regEx, 'position' );
  34487. break;
  34488. case "NORMAL":
  34489. shaderText = shaderText.replace( regEx, 'normal' );
  34490. break;
  34491. case 'TEXCOORD_0':
  34492. case 'TEXCOORD0':
  34493. case 'TEXCOORD':
  34494. shaderText = shaderText.replace( regEx, 'uv' );
  34495. break;
  34496. case 'COLOR_0':
  34497. case 'COLOR0':
  34498. case 'COLOR':
  34499. shaderText = shaderText.replace( regEx, 'color' );
  34500. break;
  34501. case "WEIGHT":
  34502. shaderText = shaderText.replace( regEx, 'skinWeight' );
  34503. break;
  34504. case "JOINT":
  34505. shaderText = shaderText.replace( regEx, 'skinIndex' );
  34506. break;
  34507. }
  34508. }
  34509. return shaderText;
  34510. }
  34511. function createDefaultMaterial() {
  34512. return new THREE.MeshPhongMaterial( {
  34513. color: 0x00000,
  34514. emissive: 0x888888,
  34515. specular: 0x000000,
  34516. shininess: 0,
  34517. transparent: false,
  34518. depthTest: true,
  34519. side: THREE.FrontSide
  34520. } );
  34521. }
  34522. // Deferred constructor for RawShaderMaterial types
  34523. function DeferredShaderMaterial( params ) {
  34524. this.isDeferredShaderMaterial = true;
  34525. this.params = params;
  34526. }
  34527. DeferredShaderMaterial.prototype.create = function () {
  34528. var uniforms = THREE.UniformsUtils.clone( this.params.uniforms );
  34529. for ( var uniformId in this.params.uniforms ) {
  34530. var originalUniform = this.params.uniforms[ uniformId ];
  34531. if ( originalUniform.value instanceof THREE.Texture ) {
  34532. uniforms[ uniformId ].value = originalUniform.value;
  34533. uniforms[ uniformId ].value.needsUpdate = true;
  34534. }
  34535. uniforms[ uniformId ].semantic = originalUniform.semantic;
  34536. uniforms[ uniformId ].node = originalUniform.node;
  34537. }
  34538. this.params.uniforms = uniforms;
  34539. return new THREE.RawShaderMaterial( this.params );
  34540. };
  34541. /* GLTF PARSER */
  34542. function GLTFParser( json, extensions, options ) {
  34543. this.json = json || {};
  34544. this.extensions = extensions || {};
  34545. this.options = options || {};
  34546. // loader object cache
  34547. this.cache = new GLTFRegistry();
  34548. }
  34549. GLTFParser.prototype._withDependencies = function ( dependencies ) {
  34550. var _dependencies = {};
  34551. for ( var i = 0; i < dependencies.length; i ++ ) {
  34552. var dependency = dependencies[ i ];
  34553. var fnName = "load" + dependency.charAt( 0 ).toUpperCase() + dependency.slice( 1 );
  34554. var cached = this.cache.get( dependency );
  34555. if ( cached !== undefined ) {
  34556. _dependencies[ dependency ] = cached;
  34557. } else if ( this[ fnName ] ) {
  34558. var fn = this[ fnName ]();
  34559. this.cache.add( dependency, fn );
  34560. _dependencies[ dependency ] = fn;
  34561. }
  34562. }
  34563. return _each( _dependencies, function ( dependency ) {
  34564. return dependency;
  34565. } );
  34566. };
  34567. GLTFParser.prototype.parse = function ( callback ) {
  34568. var json = this.json;
  34569. // Clear the loader cache
  34570. this.cache.removeAll();
  34571. // Fire the callback on complete
  34572. this._withDependencies( [
  34573. "scenes",
  34574. "cameras",
  34575. "animations"
  34576. ] ).then( function ( dependencies ) {
  34577. var scene = dependencies.scenes[ json.scene ];
  34578. var scenes = [];
  34579. for ( var name in dependencies.scenes ) {
  34580. scenes.push( dependencies.scenes[ name ] );
  34581. }
  34582. var cameras = [];
  34583. for ( var name in dependencies.cameras ) {
  34584. var camera = dependencies.cameras[ name ];
  34585. cameras.push( camera );
  34586. }
  34587. var animations = [];
  34588. for ( var name in dependencies.animations ) {
  34589. animations.push( dependencies.animations[ name ] );
  34590. }
  34591. callback( scene, scenes, cameras, animations );
  34592. } );
  34593. };
  34594. GLTFParser.prototype.loadShaders = function () {
  34595. var json = this.json;
  34596. var extensions = this.extensions;
  34597. var options = this.options;
  34598. return this._withDependencies( [
  34599. "bufferViews"
  34600. ] ).then( function ( dependencies ) {
  34601. return _each( json.shaders, function ( shader ) {
  34602. if ( shader.extensions && shader.extensions[ EXTENSIONS.KHR_BINARY_GLTF ] ) {
  34603. return extensions[ EXTENSIONS.KHR_BINARY_GLTF ].loadShader( shader, dependencies.bufferViews );
  34604. }
  34605. return new Promise( function ( resolve ) {
  34606. var loader = new THREE.FileLoader();
  34607. loader.setResponseType( 'text' );
  34608. loader.load( resolveURL( shader.uri, options.path ), function ( shaderText ) {
  34609. resolve( shaderText );
  34610. } );
  34611. } );
  34612. } );
  34613. } );
  34614. };
  34615. GLTFParser.prototype.loadBuffers = function () {
  34616. var json = this.json;
  34617. var extensions = this.extensions;
  34618. var options = this.options;
  34619. return _each( json.buffers, function ( buffer, name ) {
  34620. if ( name === BINARY_EXTENSION_BUFFER_NAME ) {
  34621. return extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body;
  34622. }
  34623. if ( buffer.type === 'arraybuffer' || buffer.type === undefined ) {
  34624. return new Promise( function ( resolve ) {
  34625. var loader = new THREE.FileLoader();
  34626. loader.setResponseType( 'arraybuffer' );
  34627. loader.load( resolveURL( buffer.uri, options.path ), function ( buffer ) {
  34628. resolve( buffer );
  34629. } );
  34630. } );
  34631. } else {
  34632. console.warn( 'THREE.GLTFLoader: ' + buffer.type + ' buffer type is not supported' );
  34633. }
  34634. } );
  34635. };
  34636. GLTFParser.prototype.loadBufferViews = function () {
  34637. var json = this.json;
  34638. return this._withDependencies( [
  34639. "buffers"
  34640. ] ).then( function ( dependencies ) {
  34641. return _each( json.bufferViews, function ( bufferView ) {
  34642. var arraybuffer = dependencies.buffers[ bufferView.buffer ];
  34643. return arraybuffer.slice( bufferView.byteOffset, bufferView.byteOffset + bufferView.byteLength );
  34644. } );
  34645. } );
  34646. };
  34647. GLTFParser.prototype.loadAccessors = function () {
  34648. var json = this.json;
  34649. return this._withDependencies( [
  34650. "bufferViews"
  34651. ] ).then( function ( dependencies ) {
  34652. return _each( json.accessors, function ( accessor ) {
  34653. var arraybuffer = dependencies.bufferViews[ accessor.bufferView ];
  34654. var itemSize = WEBGL_TYPE_SIZES[ accessor.type ];
  34655. var TypedArray = WEBGL_COMPONENT_TYPES[ accessor.componentType ];
  34656. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  34657. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  34658. var itemBytes = elementBytes * itemSize;
  34659. // The buffer is not interleaved if the stride is the item size in bytes.
  34660. if ( accessor.byteStride && accessor.byteStride !== itemBytes ) {
  34661. // Use the full buffer if it's interleaved.
  34662. var array = new TypedArray( arraybuffer );
  34663. // Integer parameters to IB/IBA are in array elements, not bytes.
  34664. var ib = new THREE.InterleavedBuffer( array, accessor.byteStride / elementBytes );
  34665. return new THREE.InterleavedBufferAttribute( ib, itemSize, accessor.byteOffset / elementBytes );
  34666. } else {
  34667. array = new TypedArray( arraybuffer, accessor.byteOffset, accessor.count * itemSize );
  34668. return new THREE.BufferAttribute( array, itemSize );
  34669. }
  34670. } );
  34671. } );
  34672. };
  34673. GLTFParser.prototype.loadTextures = function () {
  34674. var json = this.json;
  34675. var extensions = this.extensions;
  34676. var options = this.options;
  34677. return this._withDependencies( [
  34678. "bufferViews"
  34679. ] ).then( function ( dependencies ) {
  34680. return _each( json.textures, function ( texture ) {
  34681. if ( texture.source ) {
  34682. return new Promise( function ( resolve ) {
  34683. var source = json.images[ texture.source ];
  34684. var sourceUri = source.uri;
  34685. if ( source.extensions && source.extensions[ EXTENSIONS.KHR_BINARY_GLTF ] ) {
  34686. sourceUri = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].loadTextureSourceUri( source, dependencies.bufferViews );
  34687. }
  34688. var textureLoader = THREE.Loader.Handlers.get( sourceUri );
  34689. if ( textureLoader === null ) {
  34690. textureLoader = new THREE.TextureLoader();
  34691. }
  34692. textureLoader.setCrossOrigin( options.crossOrigin );
  34693. textureLoader.load( resolveURL( sourceUri, options.path ), function ( _texture ) {
  34694. _texture.flipY = false;
  34695. if ( texture.name !== undefined ) _texture.name = texture.name;
  34696. _texture.format = texture.format !== undefined ? WEBGL_TEXTURE_FORMATS[ texture.format ] : THREE.RGBAFormat;
  34697. if ( texture.internalFormat !== undefined && _texture.format !== WEBGL_TEXTURE_FORMATS[ texture.internalFormat ] ) {
  34698. console.warn( 'THREE.GLTFLoader: Three.js doesn\'t support texture internalFormat which is different from texture format. ' +
  34699. 'internalFormat will be forced to be the same value as format.' );
  34700. }
  34701. _texture.type = texture.type !== undefined ? WEBGL_TEXTURE_DATATYPES[ texture.type ] : THREE.UnsignedByteType;
  34702. if ( texture.sampler ) {
  34703. var sampler = json.samplers[ texture.sampler ];
  34704. _texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ];
  34705. _texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ];
  34706. _texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ];
  34707. _texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ];
  34708. }
  34709. resolve( _texture );
  34710. }, undefined, function () {
  34711. resolve();
  34712. } );
  34713. } );
  34714. }
  34715. } );
  34716. } );
  34717. };
  34718. GLTFParser.prototype.loadMaterials = function () {
  34719. var json = this.json;
  34720. return this._withDependencies( [
  34721. "shaders",
  34722. "textures"
  34723. ] ).then( function ( dependencies ) {
  34724. return _each( json.materials, function ( material ) {
  34725. var materialType;
  34726. var materialValues = {};
  34727. var materialParams = {};
  34728. var khr_material;
  34729. if ( material.extensions && material.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ] ) {
  34730. khr_material = material.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ];
  34731. }
  34732. if ( khr_material ) {
  34733. switch ( khr_material.technique ) {
  34734. case 'BLINN' :
  34735. case 'PHONG' :
  34736. materialType = THREE.MeshPhongMaterial;
  34737. break;
  34738. case 'LAMBERT' :
  34739. materialType = THREE.MeshLambertMaterial;
  34740. break;
  34741. case 'CONSTANT' :
  34742. default :
  34743. materialType = THREE.MeshBasicMaterial;
  34744. break;
  34745. }
  34746. Object.assign( materialValues, khr_material.values );
  34747. if ( khr_material.doubleSided || materialValues.doubleSided ) {
  34748. materialParams.side = THREE.DoubleSide;
  34749. }
  34750. if ( khr_material.transparent || materialValues.transparent ) {
  34751. materialParams.transparent = true;
  34752. materialParams.opacity = ( materialValues.transparency !== undefined ) ? materialValues.transparency : 1;
  34753. }
  34754. } else if ( material.technique === undefined ) {
  34755. materialType = THREE.MeshPhongMaterial;
  34756. Object.assign( materialValues, material.values );
  34757. } else {
  34758. materialType = DeferredShaderMaterial;
  34759. var technique = json.techniques[ material.technique ];
  34760. materialParams.uniforms = {};
  34761. var program = json.programs[ technique.program ];
  34762. if ( program ) {
  34763. materialParams.fragmentShader = dependencies.shaders[ program.fragmentShader ];
  34764. if ( ! materialParams.fragmentShader ) {
  34765. console.warn( "ERROR: Missing fragment shader definition:", program.fragmentShader );
  34766. materialType = THREE.MeshPhongMaterial;
  34767. }
  34768. var vertexShader = dependencies.shaders[ program.vertexShader ];
  34769. if ( ! vertexShader ) {
  34770. console.warn( "ERROR: Missing vertex shader definition:", program.vertexShader );
  34771. materialType = THREE.MeshPhongMaterial;
  34772. }
  34773. // IMPORTANT: FIX VERTEX SHADER ATTRIBUTE DEFINITIONS
  34774. materialParams.vertexShader = replaceTHREEShaderAttributes( vertexShader, technique );
  34775. var uniforms = technique.uniforms;
  34776. for ( var uniformId in uniforms ) {
  34777. var pname = uniforms[ uniformId ];
  34778. var shaderParam = technique.parameters[ pname ];
  34779. var ptype = shaderParam.type;
  34780. if ( WEBGL_TYPE[ ptype ] ) {
  34781. var pcount = shaderParam.count;
  34782. var value;
  34783. if ( material.values !== undefined ) value = material.values[ pname ];
  34784. var uvalue = new WEBGL_TYPE[ ptype ]();
  34785. var usemantic = shaderParam.semantic;
  34786. var unode = shaderParam.node;
  34787. switch ( ptype ) {
  34788. case WEBGL_CONSTANTS.FLOAT:
  34789. uvalue = shaderParam.value;
  34790. if ( pname == "transparency" ) {
  34791. materialParams.transparent = true;
  34792. }
  34793. if ( value !== undefined ) {
  34794. uvalue = value;
  34795. }
  34796. break;
  34797. case WEBGL_CONSTANTS.FLOAT_VEC2:
  34798. case WEBGL_CONSTANTS.FLOAT_VEC3:
  34799. case WEBGL_CONSTANTS.FLOAT_VEC4:
  34800. case WEBGL_CONSTANTS.FLOAT_MAT3:
  34801. if ( shaderParam && shaderParam.value ) {
  34802. uvalue.fromArray( shaderParam.value );
  34803. }
  34804. if ( value ) {
  34805. uvalue.fromArray( value );
  34806. }
  34807. break;
  34808. case WEBGL_CONSTANTS.FLOAT_MAT2:
  34809. // what to do?
  34810. console.warn( "FLOAT_MAT2 is not a supported uniform type" );
  34811. break;
  34812. case WEBGL_CONSTANTS.FLOAT_MAT4:
  34813. if ( pcount ) {
  34814. uvalue = new Array( pcount );
  34815. for ( var mi = 0; mi < pcount; mi ++ ) {
  34816. uvalue[ mi ] = new WEBGL_TYPE[ ptype ]();
  34817. }
  34818. if ( shaderParam && shaderParam.value ) {
  34819. var m4v = shaderParam.value;
  34820. uvalue.fromArray( m4v );
  34821. }
  34822. if ( value ) {
  34823. uvalue.fromArray( value );
  34824. }
  34825. } else {
  34826. if ( shaderParam && shaderParam.value ) {
  34827. var m4 = shaderParam.value;
  34828. uvalue.fromArray( m4 );
  34829. }
  34830. if ( value ) {
  34831. uvalue.fromArray( value );
  34832. }
  34833. }
  34834. break;
  34835. case WEBGL_CONSTANTS.SAMPLER_2D:
  34836. if ( value !== undefined ) {
  34837. uvalue = dependencies.textures[ value ];
  34838. } else if ( shaderParam.value !== undefined ) {
  34839. uvalue = dependencies.textures[ shaderParam.value ];
  34840. } else {
  34841. uvalue = null;
  34842. }
  34843. break;
  34844. }
  34845. materialParams.uniforms[ uniformId ] = {
  34846. value: uvalue,
  34847. semantic: usemantic,
  34848. node: unode
  34849. };
  34850. } else {
  34851. throw new Error( "Unknown shader uniform param type: " + ptype );
  34852. }
  34853. }
  34854. var states = technique.states || {};
  34855. var enables = states.enable || [];
  34856. var functions = states.functions || {};
  34857. var enableCullFace = false;
  34858. var enableDepthTest = false;
  34859. var enableBlend = false;
  34860. for ( var i = 0, il = enables.length; i < il; i ++ ) {
  34861. var enable = enables[ i ];
  34862. switch ( STATES_ENABLES[ enable ] ) {
  34863. case 'CULL_FACE':
  34864. enableCullFace = true;
  34865. break;
  34866. case 'DEPTH_TEST':
  34867. enableDepthTest = true;
  34868. break;
  34869. case 'BLEND':
  34870. enableBlend = true;
  34871. break;
  34872. // TODO: implement
  34873. case 'SCISSOR_TEST':
  34874. case 'POLYGON_OFFSET_FILL':
  34875. case 'SAMPLE_ALPHA_TO_COVERAGE':
  34876. break;
  34877. default:
  34878. throw new Error( "Unknown technique.states.enable: " + enable );
  34879. }
  34880. }
  34881. if ( enableCullFace ) {
  34882. materialParams.side = functions.cullFace !== undefined ? WEBGL_SIDES[ functions.cullFace ] : THREE.FrontSide;
  34883. } else {
  34884. materialParams.side = THREE.DoubleSide;
  34885. }
  34886. materialParams.depthTest = enableDepthTest;
  34887. materialParams.depthFunc = functions.depthFunc !== undefined ? WEBGL_DEPTH_FUNCS[ functions.depthFunc ] : THREE.LessDepth;
  34888. materialParams.depthWrite = functions.depthMask !== undefined ? functions.depthMask[ 0 ] : true;
  34889. materialParams.blending = enableBlend ? THREE.CustomBlending : THREE.NoBlending;
  34890. materialParams.transparent = enableBlend;
  34891. var blendEquationSeparate = functions.blendEquationSeparate;
  34892. if ( blendEquationSeparate !== undefined ) {
  34893. materialParams.blendEquation = WEBGL_BLEND_EQUATIONS[ blendEquationSeparate[ 0 ] ];
  34894. materialParams.blendEquationAlpha = WEBGL_BLEND_EQUATIONS[ blendEquationSeparate[ 1 ] ];
  34895. } else {
  34896. materialParams.blendEquation = THREE.AddEquation;
  34897. materialParams.blendEquationAlpha = THREE.AddEquation;
  34898. }
  34899. var blendFuncSeparate = functions.blendFuncSeparate;
  34900. if ( blendFuncSeparate !== undefined ) {
  34901. materialParams.blendSrc = WEBGL_BLEND_FUNCS[ blendFuncSeparate[ 0 ] ];
  34902. materialParams.blendDst = WEBGL_BLEND_FUNCS[ blendFuncSeparate[ 1 ] ];
  34903. materialParams.blendSrcAlpha = WEBGL_BLEND_FUNCS[ blendFuncSeparate[ 2 ] ];
  34904. materialParams.blendDstAlpha = WEBGL_BLEND_FUNCS[ blendFuncSeparate[ 3 ] ];
  34905. } else {
  34906. materialParams.blendSrc = THREE.OneFactor;
  34907. materialParams.blendDst = THREE.ZeroFactor;
  34908. materialParams.blendSrcAlpha = THREE.OneFactor;
  34909. materialParams.blendDstAlpha = THREE.ZeroFactor;
  34910. }
  34911. }
  34912. }
  34913. if ( Array.isArray( materialValues.diffuse ) ) {
  34914. materialParams.color = new THREE.Color().fromArray( materialValues.diffuse );
  34915. } else if ( typeof( materialValues.diffuse ) === 'string' ) {
  34916. materialParams.map = dependencies.textures[ materialValues.diffuse ];
  34917. }
  34918. delete materialParams.diffuse;
  34919. if ( typeof( materialValues.reflective ) === 'string' ) {
  34920. materialParams.envMap = dependencies.textures[ materialValues.reflective ];
  34921. }
  34922. if ( typeof( materialValues.bump ) === 'string' ) {
  34923. materialParams.bumpMap = dependencies.textures[ materialValues.bump ];
  34924. }
  34925. if ( Array.isArray( materialValues.emission ) ) {
  34926. if ( materialType === THREE.MeshBasicMaterial ) {
  34927. materialParams.color = new THREE.Color().fromArray( materialValues.emission );
  34928. } else {
  34929. materialParams.emissive = new THREE.Color().fromArray( materialValues.emission );
  34930. }
  34931. } else if ( typeof( materialValues.emission ) === 'string' ) {
  34932. if ( materialType === THREE.MeshBasicMaterial ) {
  34933. materialParams.map = dependencies.textures[ materialValues.emission ];
  34934. } else {
  34935. materialParams.emissiveMap = dependencies.textures[ materialValues.emission ];
  34936. }
  34937. }
  34938. if ( Array.isArray( materialValues.specular ) ) {
  34939. materialParams.specular = new THREE.Color().fromArray( materialValues.specular );
  34940. } else if ( typeof( materialValues.specular ) === 'string' ) {
  34941. materialParams.specularMap = dependencies.textures[ materialValues.specular ];
  34942. }
  34943. if ( materialValues.shininess !== undefined ) {
  34944. materialParams.shininess = materialValues.shininess;
  34945. }
  34946. var _material = new materialType( materialParams );
  34947. if ( material.name !== undefined ) _material.name = material.name;
  34948. return _material;
  34949. } );
  34950. } );
  34951. };
  34952. GLTFParser.prototype.loadMeshes = function () {
  34953. var json = this.json;
  34954. return this._withDependencies( [
  34955. "accessors",
  34956. "materials"
  34957. ] ).then( function ( dependencies ) {
  34958. return _each( json.meshes, function ( mesh ) {
  34959. var group = new THREE.Object3D();
  34960. if ( mesh.name !== undefined ) group.name = mesh.name;
  34961. if ( mesh.extras ) group.userData = mesh.extras;
  34962. var primitives = mesh.primitives;
  34963. for ( var name in primitives ) {
  34964. var primitive = primitives[ name ];
  34965. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === undefined ) {
  34966. var geometry = new THREE.BufferGeometry();
  34967. var attributes = primitive.attributes;
  34968. for ( var attributeId in attributes ) {
  34969. var attributeEntry = attributes[ attributeId ];
  34970. if ( ! attributeEntry ) return;
  34971. var bufferAttribute = dependencies.accessors[ attributeEntry ];
  34972. switch ( attributeId ) {
  34973. case 'POSITION':
  34974. geometry.addAttribute( 'position', bufferAttribute );
  34975. break;
  34976. case 'NORMAL':
  34977. geometry.addAttribute( 'normal', bufferAttribute );
  34978. break;
  34979. case 'TEXCOORD_0':
  34980. case 'TEXCOORD0':
  34981. case 'TEXCOORD':
  34982. geometry.addAttribute( 'uv', bufferAttribute );
  34983. break;
  34984. case 'COLOR_0':
  34985. case 'COLOR0':
  34986. case 'COLOR':
  34987. geometry.addAttribute( 'color', bufferAttribute );
  34988. break;
  34989. case 'WEIGHT':
  34990. geometry.addAttribute( 'skinWeight', bufferAttribute );
  34991. break;
  34992. case 'JOINT':
  34993. geometry.addAttribute( 'skinIndex', bufferAttribute );
  34994. break;
  34995. }
  34996. }
  34997. if ( primitive.indices ) {
  34998. geometry.setIndex( dependencies.accessors[ primitive.indices ] );
  34999. }
  35000. var material = dependencies.materials !== undefined ? dependencies.materials[ primitive.material ] : createDefaultMaterial();
  35001. var meshNode = new THREE.Mesh( geometry, material );
  35002. meshNode.castShadow = true;
  35003. meshNode.name = ( name === "0" ? group.name : group.name + name );
  35004. if ( primitive.extras ) meshNode.userData = primitive.extras;
  35005. group.add( meshNode );
  35006. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  35007. var geometry = new THREE.BufferGeometry();
  35008. var attributes = primitive.attributes;
  35009. for ( var attributeId in attributes ) {
  35010. var attributeEntry = attributes[ attributeId ];
  35011. if ( ! attributeEntry ) return;
  35012. var bufferAttribute = dependencies.accessors[ attributeEntry ];
  35013. switch ( attributeId ) {
  35014. case 'POSITION':
  35015. geometry.addAttribute( 'position', bufferAttribute );
  35016. break;
  35017. case 'COLOR_0':
  35018. case 'COLOR0':
  35019. case 'COLOR':
  35020. geometry.addAttribute( 'color', bufferAttribute );
  35021. break;
  35022. }
  35023. }
  35024. var material = dependencies.materials[ primitive.material ];
  35025. var meshNode;
  35026. if ( primitive.indices ) {
  35027. geometry.setIndex( dependencies.accessors[ primitive.indices ] );
  35028. meshNode = new THREE.LineSegments( geometry, material );
  35029. } else {
  35030. meshNode = new THREE.Line( geometry, material );
  35031. }
  35032. meshNode.name = ( name === "0" ? group.name : group.name + name );
  35033. if ( primitive.extras ) meshNode.userData = primitive.extras;
  35034. group.add( meshNode );
  35035. } else {
  35036. console.warn( "Only triangular and line primitives are supported" );
  35037. }
  35038. }
  35039. return group;
  35040. } );
  35041. } );
  35042. };
  35043. GLTFParser.prototype.loadCameras = function () {
  35044. var json = this.json;
  35045. return _each( json.cameras, function ( camera ) {
  35046. if ( camera.type == "perspective" && camera.perspective ) {
  35047. var yfov = camera.perspective.yfov;
  35048. var xfov = camera.perspective.xfov;
  35049. var aspect_ratio = camera.perspective.aspect_ratio || 1;
  35050. // According to COLLADA spec...
  35051. // aspect_ratio = xfov / yfov
  35052. xfov = ( xfov === undefined && yfov ) ? yfov * aspect_ratio : xfov;
  35053. // According to COLLADA spec...
  35054. // aspect_ratio = xfov / yfov
  35055. // yfov = ( yfov === undefined && xfov ) ? xfov / aspect_ratio : yfov;
  35056. var _camera = new THREE.PerspectiveCamera( THREE.Math.radToDeg( xfov ), aspect_ratio, camera.perspective.znear || 1, camera.perspective.zfar || 2e6 );
  35057. if ( camera.name !== undefined ) _camera.name = camera.name;
  35058. if ( camera.extras ) _camera.userData = camera.extras;
  35059. return _camera;
  35060. } else if ( camera.type == "orthographic" && camera.orthographic ) {
  35061. var _camera = new THREE.OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, camera.orthographic.znear, camera.orthographic.zfar );
  35062. if ( camera.name !== undefined ) _camera.name = camera.name;
  35063. if ( camera.extras ) _camera.userData = camera.extras;
  35064. return _camera;
  35065. }
  35066. } );
  35067. };
  35068. GLTFParser.prototype.loadSkins = function () {
  35069. var json = this.json;
  35070. return this._withDependencies( [
  35071. "accessors"
  35072. ] ).then( function ( dependencies ) {
  35073. return _each( json.skins, function ( skin ) {
  35074. var _skin = {
  35075. bindShapeMatrix: new THREE.Matrix4().fromArray( skin.bindShapeMatrix ),
  35076. jointNames: skin.jointNames,
  35077. inverseBindMatrices: dependencies.accessors[ skin.inverseBindMatrices ]
  35078. };
  35079. return _skin;
  35080. } );
  35081. } );
  35082. };
  35083. GLTFParser.prototype.loadAnimations = function () {
  35084. var json = this.json;
  35085. return this._withDependencies( [
  35086. "accessors",
  35087. "nodes"
  35088. ] ).then( function ( dependencies ) {
  35089. return _each( json.animations, function ( animation, animationId ) {
  35090. var tracks = [];
  35091. for ( var channelId in animation.channels ) {
  35092. var channel = animation.channels[ channelId ];
  35093. var sampler = animation.samplers[ channel.sampler ];
  35094. if ( sampler ) {
  35095. var target = channel.target;
  35096. var name = target.id;
  35097. var input = animation.parameters !== undefined ? animation.parameters[ sampler.input ] : sampler.input;
  35098. var output = animation.parameters !== undefined ? animation.parameters[ sampler.output ] : sampler.output;
  35099. var inputAccessor = dependencies.accessors[ input ];
  35100. var outputAccessor = dependencies.accessors[ output ];
  35101. var node = dependencies.nodes[ name ];
  35102. if ( node ) {
  35103. node.updateMatrix();
  35104. node.matrixAutoUpdate = true;
  35105. var TypedKeyframeTrack = PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.rotation
  35106. ? THREE.QuaternionKeyframeTrack
  35107. : THREE.VectorKeyframeTrack;
  35108. var targetName = node.name ? node.name : node.uuid;
  35109. // KeyframeTrack.optimize() will modify given 'times' and 'values'
  35110. // buffers before creating a truncated copy to keep. Because buffers may
  35111. // be reused by other tracks, make copies here.
  35112. tracks.push( new TypedKeyframeTrack(
  35113. targetName + '.' + PATH_PROPERTIES[ target.path ],
  35114. THREE.AnimationUtils.arraySlice( inputAccessor.array, 0 ),
  35115. THREE.AnimationUtils.arraySlice( outputAccessor.array, 0 ),
  35116. INTERPOLATION[ sampler.interpolation ]
  35117. ) );
  35118. }
  35119. }
  35120. }
  35121. return new THREE.AnimationClip( "animation_" + animationId, undefined, tracks );
  35122. } );
  35123. } );
  35124. };
  35125. GLTFParser.prototype.loadNodes = function () {
  35126. var json = this.json;
  35127. var extensions = this.extensions;
  35128. var scope = this;
  35129. return _each( json.nodes, function ( node ) {
  35130. var matrix = new THREE.Matrix4();
  35131. var _node;
  35132. if ( node.jointName ) {
  35133. _node = new THREE.Bone();
  35134. _node.name = node.name !== undefined ? node.name : node.jointName;
  35135. _node.jointName = node.jointName;
  35136. } else {
  35137. _node = new THREE.Object3D();
  35138. if ( node.name !== undefined ) _node.name = node.name;
  35139. }
  35140. if ( node.extras ) _node.userData = node.extras;
  35141. if ( node.matrix !== undefined ) {
  35142. matrix.fromArray( node.matrix );
  35143. _node.applyMatrix( matrix );
  35144. } else {
  35145. if ( node.translation !== undefined ) {
  35146. _node.position.fromArray( node.translation );
  35147. }
  35148. if ( node.rotation !== undefined ) {
  35149. _node.quaternion.fromArray( node.rotation );
  35150. }
  35151. if ( node.scale !== undefined ) {
  35152. _node.scale.fromArray( node.scale );
  35153. }
  35154. }
  35155. return _node;
  35156. } ).then( function ( __nodes ) {
  35157. return scope._withDependencies( [
  35158. "meshes",
  35159. "skins",
  35160. "cameras"
  35161. ] ).then( function ( dependencies ) {
  35162. return _each( __nodes, function ( _node, nodeId ) {
  35163. var node = json.nodes[ nodeId ];
  35164. if ( node.meshes !== undefined ) {
  35165. for ( var meshId in node.meshes ) {
  35166. var mesh = node.meshes[ meshId ];
  35167. var group = dependencies.meshes[ mesh ];
  35168. if ( group === undefined ) {
  35169. console.warn( 'GLTFLoader: Couldn\'t find node "' + mesh + '".' );
  35170. continue;
  35171. }
  35172. for ( var childrenId in group.children ) {
  35173. var child = group.children[ childrenId ];
  35174. // clone Mesh to add to _node
  35175. var originalMaterial = child.material;
  35176. var originalGeometry = child.geometry;
  35177. var originalUserData = child.userData;
  35178. var originalName = child.name;
  35179. var material;
  35180. if ( originalMaterial.isDeferredShaderMaterial ) {
  35181. originalMaterial = material = originalMaterial.create();
  35182. } else {
  35183. material = originalMaterial;
  35184. }
  35185. switch ( child.type ) {
  35186. case 'LineSegments':
  35187. child = new THREE.LineSegments( originalGeometry, material );
  35188. break;
  35189. case 'Line':
  35190. child = new THREE.Line( originalGeometry, material );
  35191. break;
  35192. default:
  35193. child = new THREE.Mesh( originalGeometry, material );
  35194. }
  35195. child.castShadow = true;
  35196. child.userData = originalUserData;
  35197. child.name = originalName;
  35198. var skinEntry;
  35199. if ( node.skin ) {
  35200. skinEntry = dependencies.skins[ node.skin ];
  35201. }
  35202. // Replace Mesh with SkinnedMesh in library
  35203. if ( skinEntry ) {
  35204. var getJointNode = function ( jointId ) {
  35205. var keys = Object.keys( __nodes );
  35206. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  35207. var n = __nodes[ keys[ i ] ];
  35208. if ( n.jointName === jointId ) return n;
  35209. }
  35210. return null;
  35211. };
  35212. var geometry = originalGeometry;
  35213. var material = originalMaterial;
  35214. material.skinning = true;
  35215. child = new THREE.SkinnedMesh( geometry, material, false );
  35216. child.castShadow = true;
  35217. child.userData = originalUserData;
  35218. child.name = originalName;
  35219. var bones = [];
  35220. var boneInverses = [];
  35221. for ( var i = 0, l = skinEntry.jointNames.length; i < l; i ++ ) {
  35222. var jointId = skinEntry.jointNames[ i ];
  35223. var jointNode = getJointNode( jointId );
  35224. if ( jointNode ) {
  35225. bones.push( jointNode );
  35226. var m = skinEntry.inverseBindMatrices.array;
  35227. var mat = new THREE.Matrix4().fromArray( m, i * 16 );
  35228. boneInverses.push( mat );
  35229. } else {
  35230. console.warn( "WARNING: joint: ''" + jointId + "' could not be found" );
  35231. }
  35232. }
  35233. child.bind( new THREE.Skeleton( bones, boneInverses, false ), skinEntry.bindShapeMatrix );
  35234. var buildBoneGraph = function ( parentJson, parentObject, property ) {
  35235. var children = parentJson[ property ];
  35236. if ( children === undefined ) return;
  35237. for ( var i = 0, il = children.length; i < il; i ++ ) {
  35238. var nodeId = children[ i ];
  35239. var bone = __nodes[ nodeId ];
  35240. var boneJson = json.nodes[ nodeId ];
  35241. if ( bone !== undefined && bone.isBone === true && boneJson !== undefined ) {
  35242. parentObject.add( bone );
  35243. buildBoneGraph( boneJson, bone, 'children' );
  35244. }
  35245. }
  35246. };
  35247. buildBoneGraph( node, child, 'skeletons' );
  35248. }
  35249. _node.add( child );
  35250. }
  35251. }
  35252. }
  35253. if ( node.camera !== undefined ) {
  35254. var camera = dependencies.cameras[ node.camera ];
  35255. _node.add( camera );
  35256. }
  35257. if ( node.extensions
  35258. && node.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ]
  35259. && node.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ].light ) {
  35260. var extensionLights = extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ].lights;
  35261. var light = extensionLights[ node.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ].light ];
  35262. _node.add( light );
  35263. }
  35264. return _node;
  35265. } );
  35266. } );
  35267. } );
  35268. };
  35269. GLTFParser.prototype.loadScenes = function () {
  35270. var json = this.json;
  35271. // scene node hierachy builder
  35272. function buildNodeHierachy( nodeId, parentObject, allNodes ) {
  35273. var _node = allNodes[ nodeId ];
  35274. parentObject.add( _node );
  35275. var node = json.nodes[ nodeId ];
  35276. if ( node.children ) {
  35277. var children = node.children;
  35278. for ( var i = 0, l = children.length; i < l; i ++ ) {
  35279. var child = children[ i ];
  35280. buildNodeHierachy( child, _node, allNodes );
  35281. }
  35282. }
  35283. }
  35284. return this._withDependencies( [
  35285. "nodes"
  35286. ] ).then( function ( dependencies ) {
  35287. return _each( json.scenes, function ( scene ) {
  35288. var _scene = new THREE.Scene();
  35289. if ( scene.name !== undefined ) _scene.name = scene.name;
  35290. if ( scene.extras ) _scene.userData = scene.extras;
  35291. var nodes = scene.nodes;
  35292. for ( var i = 0, l = nodes.length; i < l; i ++ ) {
  35293. var nodeId = nodes[ i ];
  35294. buildNodeHierachy( nodeId, _scene, dependencies.nodes );
  35295. }
  35296. _scene.traverse( function ( child ) {
  35297. // Register raw material meshes with GLTFLoader.Shaders
  35298. if ( child.material && child.material.isRawShaderMaterial ) {
  35299. var xshader = new GLTFShader( child, dependencies.nodes );
  35300. GLTFLoader.Shaders.add( child.uuid, xshader );
  35301. }
  35302. } );
  35303. return _scene;
  35304. } );
  35305. } );
  35306. };
  35307. return GLTFLoader;
  35308. } )();
  35309. },{}],45:[function(_dereq_,module,exports){
  35310. /**
  35311. * Loads a Wavefront .mtl file specifying materials
  35312. *
  35313. * @author angelxuanchang
  35314. */
  35315. THREE.MTLLoader = function ( manager ) {
  35316. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  35317. };
  35318. THREE.MTLLoader.prototype = {
  35319. constructor: THREE.MTLLoader,
  35320. /**
  35321. * Loads and parses a MTL asset from a URL.
  35322. *
  35323. * @param {String} url - URL to the MTL file.
  35324. * @param {Function} [onLoad] - Callback invoked with the loaded object.
  35325. * @param {Function} [onProgress] - Callback for download progress.
  35326. * @param {Function} [onError] - Callback for download errors.
  35327. *
  35328. * @see setPath setTexturePath
  35329. *
  35330. * @note In order for relative texture references to resolve correctly
  35331. * you must call setPath and/or setTexturePath explicitly prior to load.
  35332. */
  35333. load: function ( url, onLoad, onProgress, onError ) {
  35334. var scope = this;
  35335. var loader = new THREE.FileLoader( this.manager );
  35336. loader.setPath( this.path );
  35337. loader.load( url, function ( text ) {
  35338. onLoad( scope.parse( text ) );
  35339. }, onProgress, onError );
  35340. },
  35341. /**
  35342. * Set base path for resolving references.
  35343. * If set this path will be prepended to each loaded and found reference.
  35344. *
  35345. * @see setTexturePath
  35346. * @param {String} path
  35347. *
  35348. * @example
  35349. * mtlLoader.setPath( 'assets/obj/' );
  35350. * mtlLoader.load( 'my.mtl', ... );
  35351. */
  35352. setPath: function ( path ) {
  35353. this.path = path;
  35354. },
  35355. /**
  35356. * Set base path for resolving texture references.
  35357. * If set this path will be prepended found texture reference.
  35358. * If not set and setPath is, it will be used as texture base path.
  35359. *
  35360. * @see setPath
  35361. * @param {String} path
  35362. *
  35363. * @example
  35364. * mtlLoader.setPath( 'assets/obj/' );
  35365. * mtlLoader.setTexturePath( 'assets/textures/' );
  35366. * mtlLoader.load( 'my.mtl', ... );
  35367. */
  35368. setTexturePath: function ( path ) {
  35369. this.texturePath = path;
  35370. },
  35371. setBaseUrl: function ( path ) {
  35372. console.warn( 'THREE.MTLLoader: .setBaseUrl() is deprecated. Use .setTexturePath( path ) for texture path or .setPath( path ) for general base path instead.' );
  35373. this.setTexturePath( path );
  35374. },
  35375. setCrossOrigin: function ( value ) {
  35376. this.crossOrigin = value;
  35377. },
  35378. setMaterialOptions: function ( value ) {
  35379. this.materialOptions = value;
  35380. },
  35381. /**
  35382. * Parses a MTL file.
  35383. *
  35384. * @param {String} text - Content of MTL file
  35385. * @return {THREE.MTLLoader.MaterialCreator}
  35386. *
  35387. * @see setPath setTexturePath
  35388. *
  35389. * @note In order for relative texture references to resolve correctly
  35390. * you must call setPath and/or setTexturePath explicitly prior to parse.
  35391. */
  35392. parse: function ( text ) {
  35393. var lines = text.split( '\n' );
  35394. var info = {};
  35395. var delimiter_pattern = /\s+/;
  35396. var materialsInfo = {};
  35397. for ( var i = 0; i < lines.length; i ++ ) {
  35398. var line = lines[ i ];
  35399. line = line.trim();
  35400. if ( line.length === 0 || line.charAt( 0 ) === '#' ) {
  35401. // Blank line or comment ignore
  35402. continue;
  35403. }
  35404. var pos = line.indexOf( ' ' );
  35405. var key = ( pos >= 0 ) ? line.substring( 0, pos ) : line;
  35406. key = key.toLowerCase();
  35407. var value = ( pos >= 0 ) ? line.substring( pos + 1 ) : '';
  35408. value = value.trim();
  35409. if ( key === 'newmtl' ) {
  35410. // New material
  35411. info = { name: value };
  35412. materialsInfo[ value ] = info;
  35413. } else if ( info ) {
  35414. if ( key === 'ka' || key === 'kd' || key === 'ks' ) {
  35415. var ss = value.split( delimiter_pattern, 3 );
  35416. info[ key ] = [ parseFloat( ss[ 0 ] ), parseFloat( ss[ 1 ] ), parseFloat( ss[ 2 ] ) ];
  35417. } else {
  35418. info[ key ] = value;
  35419. }
  35420. }
  35421. }
  35422. var materialCreator = new THREE.MTLLoader.MaterialCreator( this.texturePath || this.path, this.materialOptions );
  35423. materialCreator.setCrossOrigin( this.crossOrigin );
  35424. materialCreator.setManager( this.manager );
  35425. materialCreator.setMaterials( materialsInfo );
  35426. return materialCreator;
  35427. }
  35428. };
  35429. /**
  35430. * Create a new THREE-MTLLoader.MaterialCreator
  35431. * @param baseUrl - Url relative to which textures are loaded
  35432. * @param options - Set of options on how to construct the materials
  35433. * side: Which side to apply the material
  35434. * THREE.FrontSide (default), THREE.BackSide, THREE.DoubleSide
  35435. * wrap: What type of wrapping to apply for textures
  35436. * THREE.RepeatWrapping (default), THREE.ClampToEdgeWrapping, THREE.MirroredRepeatWrapping
  35437. * normalizeRGB: RGBs need to be normalized to 0-1 from 0-255
  35438. * Default: false, assumed to be already normalized
  35439. * ignoreZeroRGBs: Ignore values of RGBs (Ka,Kd,Ks) that are all 0's
  35440. * Default: false
  35441. * @constructor
  35442. */
  35443. THREE.MTLLoader.MaterialCreator = function ( baseUrl, options ) {
  35444. this.baseUrl = baseUrl || '';
  35445. this.options = options;
  35446. this.materialsInfo = {};
  35447. this.materials = {};
  35448. this.materialsArray = [];
  35449. this.nameLookup = {};
  35450. this.side = ( this.options && this.options.side ) ? this.options.side : THREE.FrontSide;
  35451. this.wrap = ( this.options && this.options.wrap ) ? this.options.wrap : THREE.RepeatWrapping;
  35452. };
  35453. THREE.MTLLoader.MaterialCreator.prototype = {
  35454. constructor: THREE.MTLLoader.MaterialCreator,
  35455. setCrossOrigin: function ( value ) {
  35456. this.crossOrigin = value;
  35457. },
  35458. setManager: function ( value ) {
  35459. this.manager = value;
  35460. },
  35461. setMaterials: function ( materialsInfo ) {
  35462. this.materialsInfo = this.convert( materialsInfo );
  35463. this.materials = {};
  35464. this.materialsArray = [];
  35465. this.nameLookup = {};
  35466. },
  35467. convert: function ( materialsInfo ) {
  35468. if ( ! this.options ) return materialsInfo;
  35469. var converted = {};
  35470. for ( var mn in materialsInfo ) {
  35471. // Convert materials info into normalized form based on options
  35472. var mat = materialsInfo[ mn ];
  35473. var covmat = {};
  35474. converted[ mn ] = covmat;
  35475. for ( var prop in mat ) {
  35476. var save = true;
  35477. var value = mat[ prop ];
  35478. var lprop = prop.toLowerCase();
  35479. switch ( lprop ) {
  35480. case 'kd':
  35481. case 'ka':
  35482. case 'ks':
  35483. // Diffuse color (color under white light) using RGB values
  35484. if ( this.options && this.options.normalizeRGB ) {
  35485. value = [ value[ 0 ] / 255, value[ 1 ] / 255, value[ 2 ] / 255 ];
  35486. }
  35487. if ( this.options && this.options.ignoreZeroRGBs ) {
  35488. if ( value[ 0 ] === 0 && value[ 1 ] === 0 && value[ 2 ] === 0 ) {
  35489. // ignore
  35490. save = false;
  35491. }
  35492. }
  35493. break;
  35494. default:
  35495. break;
  35496. }
  35497. if ( save ) {
  35498. covmat[ lprop ] = value;
  35499. }
  35500. }
  35501. }
  35502. return converted;
  35503. },
  35504. preload: function () {
  35505. for ( var mn in this.materialsInfo ) {
  35506. this.create( mn );
  35507. }
  35508. },
  35509. getIndex: function ( materialName ) {
  35510. return this.nameLookup[ materialName ];
  35511. },
  35512. getAsArray: function () {
  35513. var index = 0;
  35514. for ( var mn in this.materialsInfo ) {
  35515. this.materialsArray[ index ] = this.create( mn );
  35516. this.nameLookup[ mn ] = index;
  35517. index ++;
  35518. }
  35519. return this.materialsArray;
  35520. },
  35521. create: function ( materialName ) {
  35522. if ( this.materials[ materialName ] === undefined ) {
  35523. this.createMaterial_( materialName );
  35524. }
  35525. return this.materials[ materialName ];
  35526. },
  35527. createMaterial_: function ( materialName ) {
  35528. // Create material
  35529. var scope = this;
  35530. var mat = this.materialsInfo[ materialName ];
  35531. var params = {
  35532. name: materialName,
  35533. side: this.side
  35534. };
  35535. function resolveURL( baseUrl, url ) {
  35536. if ( typeof url !== 'string' || url === '' )
  35537. return '';
  35538. // Absolute URL
  35539. if ( /^https?:\/\//i.test( url ) ) return url;
  35540. return baseUrl + url;
  35541. }
  35542. function setMapForType( mapType, value ) {
  35543. if ( params[ mapType ] ) return; // Keep the first encountered texture
  35544. var texParams = scope.getTextureParams( value, params );
  35545. var map = scope.loadTexture( resolveURL( scope.baseUrl, texParams.url ) );
  35546. map.repeat.copy( texParams.scale );
  35547. map.offset.copy( texParams.offset );
  35548. map.wrapS = scope.wrap;
  35549. map.wrapT = scope.wrap;
  35550. params[ mapType ] = map;
  35551. }
  35552. for ( var prop in mat ) {
  35553. var value = mat[ prop ];
  35554. if ( value === '' ) continue;
  35555. switch ( prop.toLowerCase() ) {
  35556. // Ns is material specular exponent
  35557. case 'kd':
  35558. // Diffuse color (color under white light) using RGB values
  35559. params.color = new THREE.Color().fromArray( value );
  35560. break;
  35561. case 'ks':
  35562. // Specular color (color when light is reflected from shiny surface) using RGB values
  35563. params.specular = new THREE.Color().fromArray( value );
  35564. break;
  35565. case 'map_kd':
  35566. // Diffuse texture map
  35567. setMapForType( "map", value );
  35568. break;
  35569. case 'map_ks':
  35570. // Specular map
  35571. setMapForType( "specularMap", value );
  35572. break;
  35573. case 'map_bump':
  35574. case 'bump':
  35575. // Bump texture map
  35576. setMapForType( "bumpMap", value );
  35577. break;
  35578. case 'ns':
  35579. // The specular exponent (defines the focus of the specular highlight)
  35580. // A high exponent results in a tight, concentrated highlight. Ns values normally range from 0 to 1000.
  35581. params.shininess = parseFloat( value );
  35582. break;
  35583. case 'd':
  35584. if ( value < 1 ) {
  35585. params.opacity = value;
  35586. params.transparent = true;
  35587. }
  35588. break;
  35589. case 'Tr':
  35590. if ( value > 0 ) {
  35591. params.opacity = 1 - value;
  35592. params.transparent = true;
  35593. }
  35594. break;
  35595. default:
  35596. break;
  35597. }
  35598. }
  35599. this.materials[ materialName ] = new THREE.MeshPhongMaterial( params );
  35600. return this.materials[ materialName ];
  35601. },
  35602. getTextureParams: function ( value, matParams ) {
  35603. var texParams = {
  35604. scale: new THREE.Vector2( 1, 1 ),
  35605. offset: new THREE.Vector2( 0, 0 )
  35606. };
  35607. var items = value.split( /\s+/ );
  35608. var pos;
  35609. pos = items.indexOf( '-bm' );
  35610. if ( pos >= 0 ) {
  35611. matParams.bumpScale = parseFloat( items[ pos + 1 ] );
  35612. items.splice( pos, 2 );
  35613. }
  35614. pos = items.indexOf( '-s' );
  35615. if ( pos >= 0 ) {
  35616. texParams.scale.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  35617. items.splice( pos, 4 ); // we expect 3 parameters here!
  35618. }
  35619. pos = items.indexOf( '-o' );
  35620. if ( pos >= 0 ) {
  35621. texParams.offset.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  35622. items.splice( pos, 4 ); // we expect 3 parameters here!
  35623. }
  35624. texParams.url = items.join( ' ' ).trim();
  35625. return texParams;
  35626. },
  35627. loadTexture: function ( url, mapping, onLoad, onProgress, onError ) {
  35628. var texture;
  35629. var loader = THREE.Loader.Handlers.get( url );
  35630. var manager = ( this.manager !== undefined ) ? this.manager : THREE.DefaultLoadingManager;
  35631. if ( loader === null ) {
  35632. loader = new THREE.TextureLoader( manager );
  35633. }
  35634. if ( loader.setCrossOrigin ) loader.setCrossOrigin( this.crossOrigin );
  35635. texture = loader.load( url, onLoad, onProgress, onError );
  35636. if ( mapping !== undefined ) texture.mapping = mapping;
  35637. return texture;
  35638. }
  35639. };
  35640. },{}],46:[function(_dereq_,module,exports){
  35641. /**
  35642. * @author mrdoob / http://mrdoob.com/
  35643. */
  35644. THREE.OBJLoader = function ( manager ) {
  35645. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  35646. this.materials = null;
  35647. this.regexp = {
  35648. // v float float float
  35649. vertex_pattern : /^v\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)/,
  35650. // vn float float float
  35651. normal_pattern : /^vn\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)/,
  35652. // vt float float
  35653. uv_pattern : /^vt\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)/,
  35654. // f vertex vertex vertex
  35655. face_vertex : /^f\s+(-?\d+)\s+(-?\d+)\s+(-?\d+)(?:\s+(-?\d+))?/,
  35656. // f vertex/uv vertex/uv vertex/uv
  35657. face_vertex_uv : /^f\s+(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)(?:\s+(-?\d+)\/(-?\d+))?/,
  35658. // f vertex/uv/normal vertex/uv/normal vertex/uv/normal
  35659. face_vertex_uv_normal : /^f\s+(-?\d+)\/(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\/(-?\d+)(?:\s+(-?\d+)\/(-?\d+)\/(-?\d+))?/,
  35660. // f vertex//normal vertex//normal vertex//normal
  35661. face_vertex_normal : /^f\s+(-?\d+)\/\/(-?\d+)\s+(-?\d+)\/\/(-?\d+)\s+(-?\d+)\/\/(-?\d+)(?:\s+(-?\d+)\/\/(-?\d+))?/,
  35662. // o object_name | g group_name
  35663. object_pattern : /^[og]\s*(.+)?/,
  35664. // s boolean
  35665. smoothing_pattern : /^s\s+(\d+|on|off)/,
  35666. // mtllib file_reference
  35667. material_library_pattern : /^mtllib /,
  35668. // usemtl material_name
  35669. material_use_pattern : /^usemtl /
  35670. };
  35671. };
  35672. THREE.OBJLoader.prototype = {
  35673. constructor: THREE.OBJLoader,
  35674. load: function ( url, onLoad, onProgress, onError ) {
  35675. var scope = this;
  35676. var loader = new THREE.FileLoader( scope.manager );
  35677. loader.setPath( this.path );
  35678. loader.load( url, function ( text ) {
  35679. onLoad( scope.parse( text ) );
  35680. }, onProgress, onError );
  35681. },
  35682. setPath: function ( value ) {
  35683. this.path = value;
  35684. },
  35685. setMaterials: function ( materials ) {
  35686. this.materials = materials;
  35687. },
  35688. _createParserState : function () {
  35689. var state = {
  35690. objects : [],
  35691. object : {},
  35692. vertices : [],
  35693. normals : [],
  35694. uvs : [],
  35695. materialLibraries : [],
  35696. startObject: function ( name, fromDeclaration ) {
  35697. // If the current object (initial from reset) is not from a g/o declaration in the parsed
  35698. // file. We need to use it for the first parsed g/o to keep things in sync.
  35699. if ( this.object && this.object.fromDeclaration === false ) {
  35700. this.object.name = name;
  35701. this.object.fromDeclaration = ( fromDeclaration !== false );
  35702. return;
  35703. }
  35704. var previousMaterial = ( this.object && typeof this.object.currentMaterial === 'function' ? this.object.currentMaterial() : undefined );
  35705. if ( this.object && typeof this.object._finalize === 'function' ) {
  35706. this.object._finalize( true );
  35707. }
  35708. this.object = {
  35709. name : name || '',
  35710. fromDeclaration : ( fromDeclaration !== false ),
  35711. geometry : {
  35712. vertices : [],
  35713. normals : [],
  35714. uvs : []
  35715. },
  35716. materials : [],
  35717. smooth : true,
  35718. startMaterial : function( name, libraries ) {
  35719. var previous = this._finalize( false );
  35720. // New usemtl declaration overwrites an inherited material, except if faces were declared
  35721. // after the material, then it must be preserved for proper MultiMaterial continuation.
  35722. if ( previous && ( previous.inherited || previous.groupCount <= 0 ) ) {
  35723. this.materials.splice( previous.index, 1 );
  35724. }
  35725. var material = {
  35726. index : this.materials.length,
  35727. name : name || '',
  35728. mtllib : ( Array.isArray( libraries ) && libraries.length > 0 ? libraries[ libraries.length - 1 ] : '' ),
  35729. smooth : ( previous !== undefined ? previous.smooth : this.smooth ),
  35730. groupStart : ( previous !== undefined ? previous.groupEnd : 0 ),
  35731. groupEnd : -1,
  35732. groupCount : -1,
  35733. inherited : false,
  35734. clone : function( index ) {
  35735. var cloned = {
  35736. index : ( typeof index === 'number' ? index : this.index ),
  35737. name : this.name,
  35738. mtllib : this.mtllib,
  35739. smooth : this.smooth,
  35740. groupStart : 0,
  35741. groupEnd : -1,
  35742. groupCount : -1,
  35743. inherited : false
  35744. };
  35745. cloned.clone = this.clone.bind(cloned);
  35746. return cloned;
  35747. }
  35748. };
  35749. this.materials.push( material );
  35750. return material;
  35751. },
  35752. currentMaterial : function() {
  35753. if ( this.materials.length > 0 ) {
  35754. return this.materials[ this.materials.length - 1 ];
  35755. }
  35756. return undefined;
  35757. },
  35758. _finalize : function( end ) {
  35759. var lastMultiMaterial = this.currentMaterial();
  35760. if ( lastMultiMaterial && lastMultiMaterial.groupEnd === -1 ) {
  35761. lastMultiMaterial.groupEnd = this.geometry.vertices.length / 3;
  35762. lastMultiMaterial.groupCount = lastMultiMaterial.groupEnd - lastMultiMaterial.groupStart;
  35763. lastMultiMaterial.inherited = false;
  35764. }
  35765. // Ignore objects tail materials if no face declarations followed them before a new o/g started.
  35766. if ( end && this.materials.length > 1 ) {
  35767. for ( var mi = this.materials.length - 1; mi >= 0; mi-- ) {
  35768. if ( this.materials[mi].groupCount <= 0 ) {
  35769. this.materials.splice( mi, 1 );
  35770. }
  35771. }
  35772. }
  35773. // Guarantee at least one empty material, this makes the creation later more straight forward.
  35774. if ( end && this.materials.length === 0 ) {
  35775. this.materials.push({
  35776. name : '',
  35777. smooth : this.smooth
  35778. });
  35779. }
  35780. return lastMultiMaterial;
  35781. }
  35782. };
  35783. // Inherit previous objects material.
  35784. // Spec tells us that a declared material must be set to all objects until a new material is declared.
  35785. // If a usemtl declaration is encountered while this new object is being parsed, it will
  35786. // overwrite the inherited material. Exception being that there was already face declarations
  35787. // to the inherited material, then it will be preserved for proper MultiMaterial continuation.
  35788. if ( previousMaterial && previousMaterial.name && typeof previousMaterial.clone === "function" ) {
  35789. var declared = previousMaterial.clone( 0 );
  35790. declared.inherited = true;
  35791. this.object.materials.push( declared );
  35792. }
  35793. this.objects.push( this.object );
  35794. },
  35795. finalize : function() {
  35796. if ( this.object && typeof this.object._finalize === 'function' ) {
  35797. this.object._finalize( true );
  35798. }
  35799. },
  35800. parseVertexIndex: function ( value, len ) {
  35801. var index = parseInt( value, 10 );
  35802. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  35803. },
  35804. parseNormalIndex: function ( value, len ) {
  35805. var index = parseInt( value, 10 );
  35806. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  35807. },
  35808. parseUVIndex: function ( value, len ) {
  35809. var index = parseInt( value, 10 );
  35810. return ( index >= 0 ? index - 1 : index + len / 2 ) * 2;
  35811. },
  35812. addVertex: function ( a, b, c ) {
  35813. var src = this.vertices;
  35814. var dst = this.object.geometry.vertices;
  35815. dst.push( src[ a + 0 ] );
  35816. dst.push( src[ a + 1 ] );
  35817. dst.push( src[ a + 2 ] );
  35818. dst.push( src[ b + 0 ] );
  35819. dst.push( src[ b + 1 ] );
  35820. dst.push( src[ b + 2 ] );
  35821. dst.push( src[ c + 0 ] );
  35822. dst.push( src[ c + 1 ] );
  35823. dst.push( src[ c + 2 ] );
  35824. },
  35825. addVertexLine: function ( a ) {
  35826. var src = this.vertices;
  35827. var dst = this.object.geometry.vertices;
  35828. dst.push( src[ a + 0 ] );
  35829. dst.push( src[ a + 1 ] );
  35830. dst.push( src[ a + 2 ] );
  35831. },
  35832. addNormal : function ( a, b, c ) {
  35833. var src = this.normals;
  35834. var dst = this.object.geometry.normals;
  35835. dst.push( src[ a + 0 ] );
  35836. dst.push( src[ a + 1 ] );
  35837. dst.push( src[ a + 2 ] );
  35838. dst.push( src[ b + 0 ] );
  35839. dst.push( src[ b + 1 ] );
  35840. dst.push( src[ b + 2 ] );
  35841. dst.push( src[ c + 0 ] );
  35842. dst.push( src[ c + 1 ] );
  35843. dst.push( src[ c + 2 ] );
  35844. },
  35845. addUV: function ( a, b, c ) {
  35846. var src = this.uvs;
  35847. var dst = this.object.geometry.uvs;
  35848. dst.push( src[ a + 0 ] );
  35849. dst.push( src[ a + 1 ] );
  35850. dst.push( src[ b + 0 ] );
  35851. dst.push( src[ b + 1 ] );
  35852. dst.push( src[ c + 0 ] );
  35853. dst.push( src[ c + 1 ] );
  35854. },
  35855. addUVLine: function ( a ) {
  35856. var src = this.uvs;
  35857. var dst = this.object.geometry.uvs;
  35858. dst.push( src[ a + 0 ] );
  35859. dst.push( src[ a + 1 ] );
  35860. },
  35861. addFace: function ( a, b, c, d, ua, ub, uc, ud, na, nb, nc, nd ) {
  35862. var vLen = this.vertices.length;
  35863. var ia = this.parseVertexIndex( a, vLen );
  35864. var ib = this.parseVertexIndex( b, vLen );
  35865. var ic = this.parseVertexIndex( c, vLen );
  35866. var id;
  35867. if ( d === undefined ) {
  35868. this.addVertex( ia, ib, ic );
  35869. } else {
  35870. id = this.parseVertexIndex( d, vLen );
  35871. this.addVertex( ia, ib, id );
  35872. this.addVertex( ib, ic, id );
  35873. }
  35874. if ( ua !== undefined ) {
  35875. var uvLen = this.uvs.length;
  35876. ia = this.parseUVIndex( ua, uvLen );
  35877. ib = this.parseUVIndex( ub, uvLen );
  35878. ic = this.parseUVIndex( uc, uvLen );
  35879. if ( d === undefined ) {
  35880. this.addUV( ia, ib, ic );
  35881. } else {
  35882. id = this.parseUVIndex( ud, uvLen );
  35883. this.addUV( ia, ib, id );
  35884. this.addUV( ib, ic, id );
  35885. }
  35886. }
  35887. if ( na !== undefined ) {
  35888. // Normals are many times the same. If so, skip function call and parseInt.
  35889. var nLen = this.normals.length;
  35890. ia = this.parseNormalIndex( na, nLen );
  35891. ib = na === nb ? ia : this.parseNormalIndex( nb, nLen );
  35892. ic = na === nc ? ia : this.parseNormalIndex( nc, nLen );
  35893. if ( d === undefined ) {
  35894. this.addNormal( ia, ib, ic );
  35895. } else {
  35896. id = this.parseNormalIndex( nd, nLen );
  35897. this.addNormal( ia, ib, id );
  35898. this.addNormal( ib, ic, id );
  35899. }
  35900. }
  35901. },
  35902. addLineGeometry: function ( vertices, uvs ) {
  35903. this.object.geometry.type = 'Line';
  35904. var vLen = this.vertices.length;
  35905. var uvLen = this.uvs.length;
  35906. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  35907. this.addVertexLine( this.parseVertexIndex( vertices[ vi ], vLen ) );
  35908. }
  35909. for ( var uvi = 0, l = uvs.length; uvi < l; uvi ++ ) {
  35910. this.addUVLine( this.parseUVIndex( uvs[ uvi ], uvLen ) );
  35911. }
  35912. }
  35913. };
  35914. state.startObject( '', false );
  35915. return state;
  35916. },
  35917. parse: function ( text ) {
  35918. console.time( 'OBJLoader' );
  35919. var state = this._createParserState();
  35920. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  35921. // This is faster than String.split with regex that splits on both
  35922. text = text.replace( /\r\n/g, '\n' );
  35923. }
  35924. if ( text.indexOf( '\\\n' ) !== - 1) {
  35925. // join lines separated by a line continuation character (\)
  35926. text = text.replace( /\\\n/g, '' );
  35927. }
  35928. var lines = text.split( '\n' );
  35929. var line = '', lineFirstChar = '', lineSecondChar = '';
  35930. var lineLength = 0;
  35931. var result = [];
  35932. // Faster to just trim left side of the line. Use if available.
  35933. var trimLeft = ( typeof ''.trimLeft === 'function' );
  35934. for ( var i = 0, l = lines.length; i < l; i ++ ) {
  35935. line = lines[ i ];
  35936. line = trimLeft ? line.trimLeft() : line.trim();
  35937. lineLength = line.length;
  35938. if ( lineLength === 0 ) continue;
  35939. lineFirstChar = line.charAt( 0 );
  35940. // @todo invoke passed in handler if any
  35941. if ( lineFirstChar === '#' ) continue;
  35942. if ( lineFirstChar === 'v' ) {
  35943. lineSecondChar = line.charAt( 1 );
  35944. if ( lineSecondChar === ' ' && ( result = this.regexp.vertex_pattern.exec( line ) ) !== null ) {
  35945. // 0 1 2 3
  35946. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  35947. state.vertices.push(
  35948. parseFloat( result[ 1 ] ),
  35949. parseFloat( result[ 2 ] ),
  35950. parseFloat( result[ 3 ] )
  35951. );
  35952. } else if ( lineSecondChar === 'n' && ( result = this.regexp.normal_pattern.exec( line ) ) !== null ) {
  35953. // 0 1 2 3
  35954. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  35955. state.normals.push(
  35956. parseFloat( result[ 1 ] ),
  35957. parseFloat( result[ 2 ] ),
  35958. parseFloat( result[ 3 ] )
  35959. );
  35960. } else if ( lineSecondChar === 't' && ( result = this.regexp.uv_pattern.exec( line ) ) !== null ) {
  35961. // 0 1 2
  35962. // ["vt 0.1 0.2", "0.1", "0.2"]
  35963. state.uvs.push(
  35964. parseFloat( result[ 1 ] ),
  35965. parseFloat( result[ 2 ] )
  35966. );
  35967. } else {
  35968. throw new Error( "Unexpected vertex/normal/uv line: '" + line + "'" );
  35969. }
  35970. } else if ( lineFirstChar === "f" ) {
  35971. if ( ( result = this.regexp.face_vertex_uv_normal.exec( line ) ) !== null ) {
  35972. // f vertex/uv/normal vertex/uv/normal vertex/uv/normal
  35973. // 0 1 2 3 4 5 6 7 8 9 10 11 12
  35974. // ["f 1/1/1 2/2/2 3/3/3", "1", "1", "1", "2", "2", "2", "3", "3", "3", undefined, undefined, undefined]
  35975. state.addFace(
  35976. result[ 1 ], result[ 4 ], result[ 7 ], result[ 10 ],
  35977. result[ 2 ], result[ 5 ], result[ 8 ], result[ 11 ],
  35978. result[ 3 ], result[ 6 ], result[ 9 ], result[ 12 ]
  35979. );
  35980. } else if ( ( result = this.regexp.face_vertex_uv.exec( line ) ) !== null ) {
  35981. // f vertex/uv vertex/uv vertex/uv
  35982. // 0 1 2 3 4 5 6 7 8
  35983. // ["f 1/1 2/2 3/3", "1", "1", "2", "2", "3", "3", undefined, undefined]
  35984. state.addFace(
  35985. result[ 1 ], result[ 3 ], result[ 5 ], result[ 7 ],
  35986. result[ 2 ], result[ 4 ], result[ 6 ], result[ 8 ]
  35987. );
  35988. } else if ( ( result = this.regexp.face_vertex_normal.exec( line ) ) !== null ) {
  35989. // f vertex//normal vertex//normal vertex//normal
  35990. // 0 1 2 3 4 5 6 7 8
  35991. // ["f 1//1 2//2 3//3", "1", "1", "2", "2", "3", "3", undefined, undefined]
  35992. state.addFace(
  35993. result[ 1 ], result[ 3 ], result[ 5 ], result[ 7 ],
  35994. undefined, undefined, undefined, undefined,
  35995. result[ 2 ], result[ 4 ], result[ 6 ], result[ 8 ]
  35996. );
  35997. } else if ( ( result = this.regexp.face_vertex.exec( line ) ) !== null ) {
  35998. // f vertex vertex vertex
  35999. // 0 1 2 3 4
  36000. // ["f 1 2 3", "1", "2", "3", undefined]
  36001. state.addFace(
  36002. result[ 1 ], result[ 2 ], result[ 3 ], result[ 4 ]
  36003. );
  36004. } else {
  36005. throw new Error( "Unexpected face line: '" + line + "'" );
  36006. }
  36007. } else if ( lineFirstChar === "l" ) {
  36008. var lineParts = line.substring( 1 ).trim().split( " " );
  36009. var lineVertices = [], lineUVs = [];
  36010. if ( line.indexOf( "/" ) === - 1 ) {
  36011. lineVertices = lineParts;
  36012. } else {
  36013. for ( var li = 0, llen = lineParts.length; li < llen; li ++ ) {
  36014. var parts = lineParts[ li ].split( "/" );
  36015. if ( parts[ 0 ] !== "" ) lineVertices.push( parts[ 0 ] );
  36016. if ( parts[ 1 ] !== "" ) lineUVs.push( parts[ 1 ] );
  36017. }
  36018. }
  36019. state.addLineGeometry( lineVertices, lineUVs );
  36020. } else if ( ( result = this.regexp.object_pattern.exec( line ) ) !== null ) {
  36021. // o object_name
  36022. // or
  36023. // g group_name
  36024. // WORKAROUND: https://bugs.chromium.org/p/v8/issues/detail?id=2869
  36025. // var name = result[ 0 ].substr( 1 ).trim();
  36026. var name = ( " " + result[ 0 ].substr( 1 ).trim() ).substr( 1 );
  36027. state.startObject( name );
  36028. } else if ( this.regexp.material_use_pattern.test( line ) ) {
  36029. // material
  36030. state.object.startMaterial( line.substring( 7 ).trim(), state.materialLibraries );
  36031. } else if ( this.regexp.material_library_pattern.test( line ) ) {
  36032. // mtl file
  36033. state.materialLibraries.push( line.substring( 7 ).trim() );
  36034. } else if ( ( result = this.regexp.smoothing_pattern.exec( line ) ) !== null ) {
  36035. // smooth shading
  36036. // @todo Handle files that have varying smooth values for a set of faces inside one geometry,
  36037. // but does not define a usemtl for each face set.
  36038. // This should be detected and a dummy material created (later MultiMaterial and geometry groups).
  36039. // This requires some care to not create extra material on each smooth value for "normal" obj files.
  36040. // where explicit usemtl defines geometry groups.
  36041. // Example asset: examples/models/obj/cerberus/Cerberus.obj
  36042. var value = result[ 1 ].trim().toLowerCase();
  36043. state.object.smooth = ( value === '1' || value === 'on' );
  36044. var material = state.object.currentMaterial();
  36045. if ( material ) {
  36046. material.smooth = state.object.smooth;
  36047. }
  36048. } else {
  36049. // Handle null terminated files without exception
  36050. if ( line === '\0' ) continue;
  36051. throw new Error( "Unexpected line: '" + line + "'" );
  36052. }
  36053. }
  36054. state.finalize();
  36055. var container = new THREE.Group();
  36056. container.materialLibraries = [].concat( state.materialLibraries );
  36057. for ( var i = 0, l = state.objects.length; i < l; i ++ ) {
  36058. var object = state.objects[ i ];
  36059. var geometry = object.geometry;
  36060. var materials = object.materials;
  36061. var isLine = ( geometry.type === 'Line' );
  36062. // Skip o/g line declarations that did not follow with any faces
  36063. if ( geometry.vertices.length === 0 ) continue;
  36064. var buffergeometry = new THREE.BufferGeometry();
  36065. buffergeometry.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( geometry.vertices ), 3 ) );
  36066. if ( geometry.normals.length > 0 ) {
  36067. buffergeometry.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( geometry.normals ), 3 ) );
  36068. } else {
  36069. buffergeometry.computeVertexNormals();
  36070. }
  36071. if ( geometry.uvs.length > 0 ) {
  36072. buffergeometry.addAttribute( 'uv', new THREE.BufferAttribute( new Float32Array( geometry.uvs ), 2 ) );
  36073. }
  36074. // Create materials
  36075. var createdMaterials = [];
  36076. for ( var mi = 0, miLen = materials.length; mi < miLen ; mi++ ) {
  36077. var sourceMaterial = materials[mi];
  36078. var material = undefined;
  36079. if ( this.materials !== null ) {
  36080. material = this.materials.create( sourceMaterial.name );
  36081. // mtl etc. loaders probably can't create line materials correctly, copy properties to a line material.
  36082. if ( isLine && material && ! ( material instanceof THREE.LineBasicMaterial ) ) {
  36083. var materialLine = new THREE.LineBasicMaterial();
  36084. materialLine.copy( material );
  36085. material = materialLine;
  36086. }
  36087. }
  36088. if ( ! material ) {
  36089. material = ( ! isLine ? new THREE.MeshPhongMaterial() : new THREE.LineBasicMaterial() );
  36090. material.name = sourceMaterial.name;
  36091. }
  36092. material.shading = sourceMaterial.smooth ? THREE.SmoothShading : THREE.FlatShading;
  36093. createdMaterials.push(material);
  36094. }
  36095. // Create mesh
  36096. var mesh;
  36097. if ( createdMaterials.length > 1 ) {
  36098. for ( var mi = 0, miLen = materials.length; mi < miLen ; mi++ ) {
  36099. var sourceMaterial = materials[mi];
  36100. buffergeometry.addGroup( sourceMaterial.groupStart, sourceMaterial.groupCount, mi );
  36101. }
  36102. var multiMaterial = new THREE.MultiMaterial( createdMaterials );
  36103. mesh = ( ! isLine ? new THREE.Mesh( buffergeometry, multiMaterial ) : new THREE.LineSegments( buffergeometry, multiMaterial ) );
  36104. } else {
  36105. mesh = ( ! isLine ? new THREE.Mesh( buffergeometry, createdMaterials[ 0 ] ) : new THREE.LineSegments( buffergeometry, createdMaterials[ 0 ] ) );
  36106. }
  36107. mesh.name = object.name;
  36108. container.add( mesh );
  36109. }
  36110. console.timeEnd( 'OBJLoader' );
  36111. return container;
  36112. }
  36113. };
  36114. },{}],47:[function(_dereq_,module,exports){
  36115. exports = module.exports = trim;
  36116. function trim(str){
  36117. return str.replace(/^\s*|\s*$/g, '');
  36118. }
  36119. exports.left = function(str){
  36120. return str.replace(/^\s*/, '');
  36121. };
  36122. exports.right = function(str){
  36123. return str.replace(/\s*$/, '');
  36124. };
  36125. },{}],48:[function(_dereq_,module,exports){
  36126. module.exports={
  36127. "_args": [
  36128. [
  36129. {
  36130. "raw": "webvr-polyfill@^0.9.36",
  36131. "scope": null,
  36132. "escapedName": "webvr-polyfill",
  36133. "name": "webvr-polyfill",
  36134. "rawSpec": "^0.9.36",
  36135. "spec": ">=0.9.36 <0.10.0",
  36136. "type": "range"
  36137. },
  36138. "/home/ubuntu/a-frobot/aframe"
  36139. ]
  36140. ],
  36141. "_from": "webvr-polyfill@>=0.9.36 <0.10.0",
  36142. "_id": "webvr-polyfill@0.9.36",
  36143. "_inCache": true,
  36144. "_location": "/webvr-polyfill",
  36145. "_nodeVersion": "4.8.4",
  36146. "_npmOperationalInternal": {
  36147. "host": "s3://npm-registry-packages",
  36148. "tmp": "tmp/webvr-polyfill-0.9.36.tgz_1499892972378_0.10267087002284825"
  36149. },
  36150. "_npmUser": {
  36151. "name": "jsantell",
  36152. "email": "jsantell@gmail.com"
  36153. },
  36154. "_npmVersion": "2.15.11",
  36155. "_phantomChildren": {},
  36156. "_requested": {
  36157. "raw": "webvr-polyfill@^0.9.36",
  36158. "scope": null,
  36159. "escapedName": "webvr-polyfill",
  36160. "name": "webvr-polyfill",
  36161. "rawSpec": "^0.9.36",
  36162. "spec": ">=0.9.36 <0.10.0",
  36163. "type": "range"
  36164. },
  36165. "_requiredBy": [
  36166. "/"
  36167. ],
  36168. "_resolved": "https://registry.npmjs.org/webvr-polyfill/-/webvr-polyfill-0.9.36.tgz",
  36169. "_shasum": "4b1e1556667e804beb0c8c2e67fdfcba3371e8c6",
  36170. "_shrinkwrap": null,
  36171. "_spec": "webvr-polyfill@^0.9.36",
  36172. "_where": "/home/ubuntu/a-frobot/aframe",
  36173. "authors": [
  36174. "Boris Smus <boris@smus.com>",
  36175. "Brandon Jones <tojiro@gmail.com>",
  36176. "Jordan Santell <jordan@jsantell.com>"
  36177. ],
  36178. "bugs": {
  36179. "url": "https://github.com/googlevr/webvr-polyfill/issues"
  36180. },
  36181. "dependencies": {},
  36182. "description": "Use WebVR today, on mobile or desktop, without requiring a special browser build.",
  36183. "devDependencies": {
  36184. "chai": "^3.5.0",
  36185. "jsdom": "^9.12.0",
  36186. "mocha": "^3.2.0",
  36187. "semver": "^5.3.0",
  36188. "webpack": "^2.6.1",
  36189. "webpack-dev-server": "^2.4.5"
  36190. },
  36191. "directories": {},
  36192. "dist": {
  36193. "shasum": "4b1e1556667e804beb0c8c2e67fdfcba3371e8c6",
  36194. "tarball": "https://registry.npmjs.org/webvr-polyfill/-/webvr-polyfill-0.9.36.tgz"
  36195. },
  36196. "gitHead": "5f8693a9053ee1dea425e96d14cd1f2bef7a284c",
  36197. "homepage": "https://github.com/googlevr/webvr-polyfill",
  36198. "keywords": [
  36199. "vr",
  36200. "webvr"
  36201. ],
  36202. "license": "Apache-2.0",
  36203. "main": "src/node-entry",
  36204. "maintainers": [
  36205. {
  36206. "name": "jsantell",
  36207. "email": "jsantell@gmail.com"
  36208. },
  36209. {
  36210. "name": "toji",
  36211. "email": "tojiro@gmail.com"
  36212. },
  36213. {
  36214. "name": "smus",
  36215. "email": "boris@smus.com"
  36216. }
  36217. ],
  36218. "name": "webvr-polyfill",
  36219. "optionalDependencies": {},
  36220. "readme": "ERROR: No README data found!",
  36221. "repository": {
  36222. "type": "git",
  36223. "url": "git+https://github.com/googlevr/webvr-polyfill.git"
  36224. },
  36225. "scripts": {
  36226. "build": "webpack",
  36227. "start": "npm run watch",
  36228. "test": "mocha",
  36229. "watch": "webpack-dev-server"
  36230. },
  36231. "version": "0.9.36"
  36232. }
  36233. },{}],49:[function(_dereq_,module,exports){
  36234. /*
  36235. * Copyright 2015 Google Inc. All Rights Reserved.
  36236. * Licensed under the Apache License, Version 2.0 (the "License");
  36237. * you may not use this file except in compliance with the License.
  36238. * You may obtain a copy of the License at
  36239. *
  36240. * http://www.apache.org/licenses/LICENSE-2.0
  36241. *
  36242. * Unless required by applicable law or agreed to in writing, software
  36243. * distributed under the License is distributed on an "AS IS" BASIS,
  36244. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  36245. * See the License for the specific language governing permissions and
  36246. * limitations under the License.
  36247. */
  36248. var Util = _dereq_('./util.js');
  36249. var WakeLock = _dereq_('./wakelock.js');
  36250. // Start at a higher number to reduce chance of conflict.
  36251. var nextDisplayId = 1000;
  36252. var hasShowDeprecationWarning = false;
  36253. var defaultLeftBounds = [0, 0, 0.5, 1];
  36254. var defaultRightBounds = [0.5, 0, 0.5, 1];
  36255. /**
  36256. * The base class for all VR frame data.
  36257. */
  36258. function VRFrameData() {
  36259. this.leftProjectionMatrix = new Float32Array(16);
  36260. this.leftViewMatrix = new Float32Array(16);
  36261. this.rightProjectionMatrix = new Float32Array(16);
  36262. this.rightViewMatrix = new Float32Array(16);
  36263. this.pose = null;
  36264. };
  36265. /**
  36266. * The base class for all VR displays.
  36267. */
  36268. function VRDisplay() {
  36269. this.isPolyfilled = true;
  36270. this.displayId = nextDisplayId++;
  36271. this.displayName = 'webvr-polyfill displayName';
  36272. this.depthNear = 0.01;
  36273. this.depthFar = 10000.0;
  36274. this.isConnected = true;
  36275. this.isPresenting = false;
  36276. this.capabilities = {
  36277. hasPosition: false,
  36278. hasOrientation: false,
  36279. hasExternalDisplay: false,
  36280. canPresent: false,
  36281. maxLayers: 1
  36282. };
  36283. this.stageParameters = null;
  36284. // "Private" members.
  36285. this.waitingForPresent_ = false;
  36286. this.layer_ = null;
  36287. this.fullscreenElement_ = null;
  36288. this.fullscreenWrapper_ = null;
  36289. this.fullscreenElementCachedStyle_ = null;
  36290. this.fullscreenEventTarget_ = null;
  36291. this.fullscreenChangeHandler_ = null;
  36292. this.fullscreenErrorHandler_ = null;
  36293. this.wakelock_ = new WakeLock();
  36294. }
  36295. VRDisplay.prototype.getFrameData = function(frameData) {
  36296. // TODO: Technically this should retain it's value for the duration of a frame
  36297. // but I doubt that's practical to do in javascript.
  36298. return Util.frameDataFromPose(frameData, this.getPose(), this);
  36299. };
  36300. VRDisplay.prototype.getPose = function() {
  36301. // TODO: Technically this should retain it's value for the duration of a frame
  36302. // but I doubt that's practical to do in javascript.
  36303. return this.getImmediatePose();
  36304. };
  36305. VRDisplay.prototype.requestAnimationFrame = function(callback) {
  36306. return window.requestAnimationFrame(callback);
  36307. };
  36308. VRDisplay.prototype.cancelAnimationFrame = function(id) {
  36309. return window.cancelAnimationFrame(id);
  36310. };
  36311. VRDisplay.prototype.wrapForFullscreen = function(element) {
  36312. // Don't wrap in iOS.
  36313. if (Util.isIOS()) {
  36314. return element;
  36315. }
  36316. if (!this.fullscreenWrapper_) {
  36317. this.fullscreenWrapper_ = document.createElement('div');
  36318. var cssProperties = [
  36319. 'height: ' + Math.min(screen.height, screen.width) + 'px !important',
  36320. 'top: 0 !important',
  36321. 'left: 0 !important',
  36322. 'right: 0 !important',
  36323. 'border: 0',
  36324. 'margin: 0',
  36325. 'padding: 0',
  36326. 'z-index: 999999 !important',
  36327. 'position: fixed',
  36328. ];
  36329. this.fullscreenWrapper_.setAttribute('style', cssProperties.join('; ') + ';');
  36330. this.fullscreenWrapper_.classList.add('webvr-polyfill-fullscreen-wrapper');
  36331. }
  36332. if (this.fullscreenElement_ == element) {
  36333. return this.fullscreenWrapper_;
  36334. }
  36335. // Remove any previously applied wrappers
  36336. this.removeFullscreenWrapper();
  36337. this.fullscreenElement_ = element;
  36338. var parent = this.fullscreenElement_.parentElement;
  36339. parent.insertBefore(this.fullscreenWrapper_, this.fullscreenElement_);
  36340. parent.removeChild(this.fullscreenElement_);
  36341. this.fullscreenWrapper_.insertBefore(this.fullscreenElement_, this.fullscreenWrapper_.firstChild);
  36342. this.fullscreenElementCachedStyle_ = this.fullscreenElement_.getAttribute('style');
  36343. var self = this;
  36344. function applyFullscreenElementStyle() {
  36345. if (!self.fullscreenElement_) {
  36346. return;
  36347. }
  36348. var cssProperties = [
  36349. 'position: absolute',
  36350. 'top: 0',
  36351. 'left: 0',
  36352. 'width: ' + Math.max(screen.width, screen.height) + 'px',
  36353. 'height: ' + Math.min(screen.height, screen.width) + 'px',
  36354. 'border: 0',
  36355. 'margin: 0',
  36356. 'padding: 0',
  36357. ];
  36358. self.fullscreenElement_.setAttribute('style', cssProperties.join('; ') + ';');
  36359. }
  36360. applyFullscreenElementStyle();
  36361. return this.fullscreenWrapper_;
  36362. };
  36363. VRDisplay.prototype.removeFullscreenWrapper = function() {
  36364. if (!this.fullscreenElement_) {
  36365. return;
  36366. }
  36367. var element = this.fullscreenElement_;
  36368. if (this.fullscreenElementCachedStyle_) {
  36369. element.setAttribute('style', this.fullscreenElementCachedStyle_);
  36370. } else {
  36371. element.removeAttribute('style');
  36372. }
  36373. this.fullscreenElement_ = null;
  36374. this.fullscreenElementCachedStyle_ = null;
  36375. var parent = this.fullscreenWrapper_.parentElement;
  36376. this.fullscreenWrapper_.removeChild(element);
  36377. parent.insertBefore(element, this.fullscreenWrapper_);
  36378. parent.removeChild(this.fullscreenWrapper_);
  36379. return element;
  36380. };
  36381. VRDisplay.prototype.requestPresent = function(layers) {
  36382. var wasPresenting = this.isPresenting;
  36383. var self = this;
  36384. if (!(layers instanceof Array)) {
  36385. if (!hasShowDeprecationWarning) {
  36386. console.warn("Using a deprecated form of requestPresent. Should pass in an array of VRLayers.");
  36387. hasShowDeprecationWarning = true;
  36388. }
  36389. layers = [layers];
  36390. }
  36391. return new Promise(function(resolve, reject) {
  36392. if (!self.capabilities.canPresent) {
  36393. reject(new Error('VRDisplay is not capable of presenting.'));
  36394. return;
  36395. }
  36396. if (layers.length == 0 || layers.length > self.capabilities.maxLayers) {
  36397. reject(new Error('Invalid number of layers.'));
  36398. return;
  36399. }
  36400. var incomingLayer = layers[0];
  36401. if (!incomingLayer.source) {
  36402. /*
  36403. todo: figure out the correct behavior if the source is not provided.
  36404. see https://github.com/w3c/webvr/issues/58
  36405. */
  36406. resolve();
  36407. return;
  36408. }
  36409. var leftBounds = incomingLayer.leftBounds || defaultLeftBounds;
  36410. var rightBounds = incomingLayer.rightBounds || defaultRightBounds;
  36411. if (wasPresenting) {
  36412. // Already presenting, just changing configuration
  36413. var layer = self.layer_;
  36414. if (layer.source !== incomingLayer.source) {
  36415. layer.source = incomingLayer.source;
  36416. }
  36417. for (var i = 0; i < 4; i++) {
  36418. layer.leftBounds[i] = leftBounds[i];
  36419. layer.rightBounds[i] = rightBounds[i];
  36420. }
  36421. resolve();
  36422. return;
  36423. }
  36424. // Was not already presenting.
  36425. self.layer_ = {
  36426. predistorted: incomingLayer.predistorted,
  36427. source: incomingLayer.source,
  36428. leftBounds: leftBounds.slice(0),
  36429. rightBounds: rightBounds.slice(0)
  36430. };
  36431. self.waitingForPresent_ = false;
  36432. if (self.layer_ && self.layer_.source) {
  36433. var fullscreenElement = self.wrapForFullscreen(self.layer_.source);
  36434. var onFullscreenChange = function() {
  36435. var actualFullscreenElement = Util.getFullscreenElement();
  36436. self.isPresenting = (fullscreenElement === actualFullscreenElement);
  36437. if (self.isPresenting) {
  36438. if (screen.orientation && screen.orientation.lock) {
  36439. screen.orientation.lock('landscape-primary').catch(function(error){
  36440. console.error('screen.orientation.lock() failed due to', error.message)
  36441. });
  36442. }
  36443. self.waitingForPresent_ = false;
  36444. self.beginPresent_();
  36445. resolve();
  36446. } else {
  36447. if (screen.orientation && screen.orientation.unlock) {
  36448. screen.orientation.unlock();
  36449. }
  36450. self.removeFullscreenWrapper();
  36451. self.wakelock_.release();
  36452. self.endPresent_();
  36453. self.removeFullscreenListeners_();
  36454. }
  36455. self.fireVRDisplayPresentChange_();
  36456. }
  36457. var onFullscreenError = function() {
  36458. if (!self.waitingForPresent_) {
  36459. return;
  36460. }
  36461. self.removeFullscreenWrapper();
  36462. self.removeFullscreenListeners_();
  36463. self.wakelock_.release();
  36464. self.waitingForPresent_ = false;
  36465. self.isPresenting = false;
  36466. reject(new Error('Unable to present.'));
  36467. }
  36468. self.addFullscreenListeners_(fullscreenElement,
  36469. onFullscreenChange, onFullscreenError);
  36470. if (Util.requestFullscreen(fullscreenElement)) {
  36471. self.wakelock_.request();
  36472. self.waitingForPresent_ = true;
  36473. } else if (Util.isIOS() || Util.isWebViewAndroid()) {
  36474. // *sigh* Just fake it.
  36475. self.wakelock_.request();
  36476. self.isPresenting = true;
  36477. self.beginPresent_();
  36478. self.fireVRDisplayPresentChange_();
  36479. resolve();
  36480. }
  36481. }
  36482. if (!self.waitingForPresent_ && !Util.isIOS()) {
  36483. Util.exitFullscreen();
  36484. reject(new Error('Unable to present.'));
  36485. }
  36486. });
  36487. };
  36488. VRDisplay.prototype.exitPresent = function() {
  36489. var wasPresenting = this.isPresenting;
  36490. var self = this;
  36491. this.isPresenting = false;
  36492. this.layer_ = null;
  36493. this.wakelock_.release();
  36494. return new Promise(function(resolve, reject) {
  36495. if (wasPresenting) {
  36496. if (!Util.exitFullscreen() && Util.isIOS()) {
  36497. self.endPresent_();
  36498. self.fireVRDisplayPresentChange_();
  36499. }
  36500. if (Util.isWebViewAndroid()) {
  36501. self.removeFullscreenWrapper();
  36502. self.removeFullscreenListeners_();
  36503. self.endPresent_();
  36504. self.fireVRDisplayPresentChange_();
  36505. }
  36506. resolve();
  36507. } else {
  36508. reject(new Error('Was not presenting to VRDisplay.'));
  36509. }
  36510. });
  36511. };
  36512. VRDisplay.prototype.getLayers = function() {
  36513. if (this.layer_) {
  36514. return [this.layer_];
  36515. }
  36516. return [];
  36517. };
  36518. VRDisplay.prototype.fireVRDisplayPresentChange_ = function() {
  36519. // Important: unfortunately we cannot have full spec compliance here.
  36520. // CustomEvent custom fields all go under e.detail (so the VRDisplay ends up
  36521. // being e.detail.display, instead of e.display as per WebVR spec).
  36522. var event = new CustomEvent('vrdisplaypresentchange', {detail: {display: this}});
  36523. window.dispatchEvent(event);
  36524. };
  36525. VRDisplay.prototype.fireVRDisplayConnect_ = function() {
  36526. // Important: unfortunately we cannot have full spec compliance here.
  36527. // CustomEvent custom fields all go under e.detail (so the VRDisplay ends up
  36528. // being e.detail.display, instead of e.display as per WebVR spec).
  36529. var event = new CustomEvent('vrdisplayconnect', {detail: {display: this}});
  36530. window.dispatchEvent(event);
  36531. };
  36532. VRDisplay.prototype.addFullscreenListeners_ = function(element, changeHandler, errorHandler) {
  36533. this.removeFullscreenListeners_();
  36534. this.fullscreenEventTarget_ = element;
  36535. this.fullscreenChangeHandler_ = changeHandler;
  36536. this.fullscreenErrorHandler_ = errorHandler;
  36537. if (changeHandler) {
  36538. if (document.fullscreenEnabled) {
  36539. element.addEventListener('fullscreenchange', changeHandler, false);
  36540. } else if (document.webkitFullscreenEnabled) {
  36541. element.addEventListener('webkitfullscreenchange', changeHandler, false);
  36542. } else if (document.mozFullScreenEnabled) {
  36543. document.addEventListener('mozfullscreenchange', changeHandler, false);
  36544. } else if (document.msFullscreenEnabled) {
  36545. element.addEventListener('msfullscreenchange', changeHandler, false);
  36546. }
  36547. }
  36548. if (errorHandler) {
  36549. if (document.fullscreenEnabled) {
  36550. element.addEventListener('fullscreenerror', errorHandler, false);
  36551. } else if (document.webkitFullscreenEnabled) {
  36552. element.addEventListener('webkitfullscreenerror', errorHandler, false);
  36553. } else if (document.mozFullScreenEnabled) {
  36554. document.addEventListener('mozfullscreenerror', errorHandler, false);
  36555. } else if (document.msFullscreenEnabled) {
  36556. element.addEventListener('msfullscreenerror', errorHandler, false);
  36557. }
  36558. }
  36559. };
  36560. VRDisplay.prototype.removeFullscreenListeners_ = function() {
  36561. if (!this.fullscreenEventTarget_)
  36562. return;
  36563. var element = this.fullscreenEventTarget_;
  36564. if (this.fullscreenChangeHandler_) {
  36565. var changeHandler = this.fullscreenChangeHandler_;
  36566. element.removeEventListener('fullscreenchange', changeHandler, false);
  36567. element.removeEventListener('webkitfullscreenchange', changeHandler, false);
  36568. document.removeEventListener('mozfullscreenchange', changeHandler, false);
  36569. element.removeEventListener('msfullscreenchange', changeHandler, false);
  36570. }
  36571. if (this.fullscreenErrorHandler_) {
  36572. var errorHandler = this.fullscreenErrorHandler_;
  36573. element.removeEventListener('fullscreenerror', errorHandler, false);
  36574. element.removeEventListener('webkitfullscreenerror', errorHandler, false);
  36575. document.removeEventListener('mozfullscreenerror', errorHandler, false);
  36576. element.removeEventListener('msfullscreenerror', errorHandler, false);
  36577. }
  36578. this.fullscreenEventTarget_ = null;
  36579. this.fullscreenChangeHandler_ = null;
  36580. this.fullscreenErrorHandler_ = null;
  36581. };
  36582. VRDisplay.prototype.beginPresent_ = function() {
  36583. // Override to add custom behavior when presentation begins.
  36584. };
  36585. VRDisplay.prototype.endPresent_ = function() {
  36586. // Override to add custom behavior when presentation ends.
  36587. };
  36588. VRDisplay.prototype.submitFrame = function(pose) {
  36589. // Override to add custom behavior for frame submission.
  36590. };
  36591. VRDisplay.prototype.getEyeParameters = function(whichEye) {
  36592. // Override to return accurate eye parameters if canPresent is true.
  36593. return null;
  36594. };
  36595. /*
  36596. * Deprecated classes
  36597. */
  36598. /**
  36599. * The base class for all VR devices. (Deprecated)
  36600. */
  36601. function VRDevice() {
  36602. this.isPolyfilled = true;
  36603. this.hardwareUnitId = 'webvr-polyfill hardwareUnitId';
  36604. this.deviceId = 'webvr-polyfill deviceId';
  36605. this.deviceName = 'webvr-polyfill deviceName';
  36606. }
  36607. /**
  36608. * The base class for all VR HMD devices. (Deprecated)
  36609. */
  36610. function HMDVRDevice() {
  36611. }
  36612. HMDVRDevice.prototype = new VRDevice();
  36613. /**
  36614. * The base class for all VR position sensor devices. (Deprecated)
  36615. */
  36616. function PositionSensorVRDevice() {
  36617. }
  36618. PositionSensorVRDevice.prototype = new VRDevice();
  36619. module.exports.VRFrameData = VRFrameData;
  36620. module.exports.VRDisplay = VRDisplay;
  36621. module.exports.VRDevice = VRDevice;
  36622. module.exports.HMDVRDevice = HMDVRDevice;
  36623. module.exports.PositionSensorVRDevice = PositionSensorVRDevice;
  36624. },{"./util.js":69,"./wakelock.js":71}],50:[function(_dereq_,module,exports){
  36625. /*
  36626. * Copyright 2016 Google Inc. All Rights Reserved.
  36627. * Licensed under the Apache License, Version 2.0 (the "License");
  36628. * you may not use this file except in compliance with the License.
  36629. * You may obtain a copy of the License at
  36630. *
  36631. * http://www.apache.org/licenses/LICENSE-2.0
  36632. *
  36633. * Unless required by applicable law or agreed to in writing, software
  36634. * distributed under the License is distributed on an "AS IS" BASIS,
  36635. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  36636. * See the License for the specific language governing permissions and
  36637. * limitations under the License.
  36638. */
  36639. var CardboardUI = _dereq_('./cardboard-ui.js');
  36640. var Util = _dereq_('./util.js');
  36641. var WGLUPreserveGLState = _dereq_('./deps/wglu-preserve-state.js');
  36642. var distortionVS = [
  36643. 'attribute vec2 position;',
  36644. 'attribute vec3 texCoord;',
  36645. 'varying vec2 vTexCoord;',
  36646. 'uniform vec4 viewportOffsetScale[2];',
  36647. 'void main() {',
  36648. ' vec4 viewport = viewportOffsetScale[int(texCoord.z)];',
  36649. ' vTexCoord = (texCoord.xy * viewport.zw) + viewport.xy;',
  36650. ' gl_Position = vec4( position, 1.0, 1.0 );',
  36651. '}',
  36652. ].join('\n');
  36653. var distortionFS = [
  36654. 'precision mediump float;',
  36655. 'uniform sampler2D diffuse;',
  36656. 'varying vec2 vTexCoord;',
  36657. 'void main() {',
  36658. ' gl_FragColor = texture2D(diffuse, vTexCoord);',
  36659. '}',
  36660. ].join('\n');
  36661. /**
  36662. * A mesh-based distorter.
  36663. */
  36664. function CardboardDistorter(gl) {
  36665. this.gl = gl;
  36666. this.ctxAttribs = gl.getContextAttributes();
  36667. this.meshWidth = 20;
  36668. this.meshHeight = 20;
  36669. this.bufferScale = window.WebVRConfig.BUFFER_SCALE;
  36670. this.bufferWidth = gl.drawingBufferWidth;
  36671. this.bufferHeight = gl.drawingBufferHeight;
  36672. // Patching support
  36673. this.realBindFramebuffer = gl.bindFramebuffer;
  36674. this.realEnable = gl.enable;
  36675. this.realDisable = gl.disable;
  36676. this.realColorMask = gl.colorMask;
  36677. this.realClearColor = gl.clearColor;
  36678. this.realViewport = gl.viewport;
  36679. if (!Util.isIOS()) {
  36680. this.realCanvasWidth = Object.getOwnPropertyDescriptor(gl.canvas.__proto__, 'width');
  36681. this.realCanvasHeight = Object.getOwnPropertyDescriptor(gl.canvas.__proto__, 'height');
  36682. }
  36683. this.isPatched = false;
  36684. // State tracking
  36685. this.lastBoundFramebuffer = null;
  36686. this.cullFace = false;
  36687. this.depthTest = false;
  36688. this.blend = false;
  36689. this.scissorTest = false;
  36690. this.stencilTest = false;
  36691. this.viewport = [0, 0, 0, 0];
  36692. this.colorMask = [true, true, true, true];
  36693. this.clearColor = [0, 0, 0, 0];
  36694. this.attribs = {
  36695. position: 0,
  36696. texCoord: 1
  36697. };
  36698. this.program = Util.linkProgram(gl, distortionVS, distortionFS, this.attribs);
  36699. this.uniforms = Util.getProgramUniforms(gl, this.program);
  36700. this.viewportOffsetScale = new Float32Array(8);
  36701. this.setTextureBounds();
  36702. this.vertexBuffer = gl.createBuffer();
  36703. this.indexBuffer = gl.createBuffer();
  36704. this.indexCount = 0;
  36705. this.renderTarget = gl.createTexture();
  36706. this.framebuffer = gl.createFramebuffer();
  36707. this.depthStencilBuffer = null;
  36708. this.depthBuffer = null;
  36709. this.stencilBuffer = null;
  36710. if (this.ctxAttribs.depth && this.ctxAttribs.stencil) {
  36711. this.depthStencilBuffer = gl.createRenderbuffer();
  36712. } else if (this.ctxAttribs.depth) {
  36713. this.depthBuffer = gl.createRenderbuffer();
  36714. } else if (this.ctxAttribs.stencil) {
  36715. this.stencilBuffer = gl.createRenderbuffer();
  36716. }
  36717. this.patch();
  36718. this.onResize();
  36719. if (!window.WebVRConfig.CARDBOARD_UI_DISABLED) {
  36720. this.cardboardUI = new CardboardUI(gl);
  36721. }
  36722. };
  36723. /**
  36724. * Tears down all the resources created by the distorter and removes any
  36725. * patches.
  36726. */
  36727. CardboardDistorter.prototype.destroy = function() {
  36728. var gl = this.gl;
  36729. this.unpatch();
  36730. gl.deleteProgram(this.program);
  36731. gl.deleteBuffer(this.vertexBuffer);
  36732. gl.deleteBuffer(this.indexBuffer);
  36733. gl.deleteTexture(this.renderTarget);
  36734. gl.deleteFramebuffer(this.framebuffer);
  36735. if (this.depthStencilBuffer) {
  36736. gl.deleteRenderbuffer(this.depthStencilBuffer);
  36737. }
  36738. if (this.depthBuffer) {
  36739. gl.deleteRenderbuffer(this.depthBuffer);
  36740. }
  36741. if (this.stencilBuffer) {
  36742. gl.deleteRenderbuffer(this.stencilBuffer);
  36743. }
  36744. if (this.cardboardUI) {
  36745. this.cardboardUI.destroy();
  36746. }
  36747. };
  36748. /**
  36749. * Resizes the backbuffer to match the canvas width and height.
  36750. */
  36751. CardboardDistorter.prototype.onResize = function() {
  36752. var gl = this.gl;
  36753. var self = this;
  36754. var glState = [
  36755. gl.RENDERBUFFER_BINDING,
  36756. gl.TEXTURE_BINDING_2D, gl.TEXTURE0
  36757. ];
  36758. WGLUPreserveGLState(gl, glState, function(gl) {
  36759. // Bind real backbuffer and clear it once. We don't need to clear it again
  36760. // after that because we're overwriting the same area every frame.
  36761. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, null);
  36762. // Put things in a good state
  36763. if (self.scissorTest) { self.realDisable.call(gl, gl.SCISSOR_TEST); }
  36764. self.realColorMask.call(gl, true, true, true, true);
  36765. self.realViewport.call(gl, 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  36766. self.realClearColor.call(gl, 0, 0, 0, 1);
  36767. gl.clear(gl.COLOR_BUFFER_BIT);
  36768. // Now bind and resize the fake backbuffer
  36769. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.framebuffer);
  36770. gl.bindTexture(gl.TEXTURE_2D, self.renderTarget);
  36771. gl.texImage2D(gl.TEXTURE_2D, 0, self.ctxAttribs.alpha ? gl.RGBA : gl.RGB,
  36772. self.bufferWidth, self.bufferHeight, 0,
  36773. self.ctxAttribs.alpha ? gl.RGBA : gl.RGB, gl.UNSIGNED_BYTE, null);
  36774. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  36775. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  36776. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  36777. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  36778. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, self.renderTarget, 0);
  36779. if (self.ctxAttribs.depth && self.ctxAttribs.stencil) {
  36780. gl.bindRenderbuffer(gl.RENDERBUFFER, self.depthStencilBuffer);
  36781. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL,
  36782. self.bufferWidth, self.bufferHeight);
  36783. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT,
  36784. gl.RENDERBUFFER, self.depthStencilBuffer);
  36785. } else if (self.ctxAttribs.depth) {
  36786. gl.bindRenderbuffer(gl.RENDERBUFFER, self.depthBuffer);
  36787. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16,
  36788. self.bufferWidth, self.bufferHeight);
  36789. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT,
  36790. gl.RENDERBUFFER, self.depthBuffer);
  36791. } else if (self.ctxAttribs.stencil) {
  36792. gl.bindRenderbuffer(gl.RENDERBUFFER, self.stencilBuffer);
  36793. gl.renderbufferStorage(gl.RENDERBUFFER, gl.STENCIL_INDEX8,
  36794. self.bufferWidth, self.bufferHeight);
  36795. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT,
  36796. gl.RENDERBUFFER, self.stencilBuffer);
  36797. }
  36798. if (!gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE) {
  36799. console.error('Framebuffer incomplete!');
  36800. }
  36801. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.lastBoundFramebuffer);
  36802. if (self.scissorTest) { self.realEnable.call(gl, gl.SCISSOR_TEST); }
  36803. self.realColorMask.apply(gl, self.colorMask);
  36804. self.realViewport.apply(gl, self.viewport);
  36805. self.realClearColor.apply(gl, self.clearColor);
  36806. });
  36807. if (this.cardboardUI) {
  36808. this.cardboardUI.onResize();
  36809. }
  36810. };
  36811. CardboardDistorter.prototype.patch = function() {
  36812. if (this.isPatched) {
  36813. return;
  36814. }
  36815. var self = this;
  36816. var canvas = this.gl.canvas;
  36817. var gl = this.gl;
  36818. if (!Util.isIOS()) {
  36819. canvas.width = Util.getScreenWidth() * this.bufferScale;
  36820. canvas.height = Util.getScreenHeight() * this.bufferScale;
  36821. Object.defineProperty(canvas, 'width', {
  36822. configurable: true,
  36823. enumerable: true,
  36824. get: function() {
  36825. return self.bufferWidth;
  36826. },
  36827. set: function(value) {
  36828. self.bufferWidth = value;
  36829. self.realCanvasWidth.set.call(canvas, value);
  36830. self.onResize();
  36831. }
  36832. });
  36833. Object.defineProperty(canvas, 'height', {
  36834. configurable: true,
  36835. enumerable: true,
  36836. get: function() {
  36837. return self.bufferHeight;
  36838. },
  36839. set: function(value) {
  36840. self.bufferHeight = value;
  36841. self.realCanvasHeight.set.call(canvas, value);
  36842. self.onResize();
  36843. }
  36844. });
  36845. }
  36846. this.lastBoundFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);
  36847. if (this.lastBoundFramebuffer == null) {
  36848. this.lastBoundFramebuffer = this.framebuffer;
  36849. this.gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer);
  36850. }
  36851. this.gl.bindFramebuffer = function(target, framebuffer) {
  36852. self.lastBoundFramebuffer = framebuffer ? framebuffer : self.framebuffer;
  36853. // Silently make calls to bind the default framebuffer bind ours instead.
  36854. self.realBindFramebuffer.call(gl, target, self.lastBoundFramebuffer);
  36855. };
  36856. this.cullFace = gl.getParameter(gl.CULL_FACE);
  36857. this.depthTest = gl.getParameter(gl.DEPTH_TEST);
  36858. this.blend = gl.getParameter(gl.BLEND);
  36859. this.scissorTest = gl.getParameter(gl.SCISSOR_TEST);
  36860. this.stencilTest = gl.getParameter(gl.STENCIL_TEST);
  36861. gl.enable = function(pname) {
  36862. switch (pname) {
  36863. case gl.CULL_FACE: self.cullFace = true; break;
  36864. case gl.DEPTH_TEST: self.depthTest = true; break;
  36865. case gl.BLEND: self.blend = true; break;
  36866. case gl.SCISSOR_TEST: self.scissorTest = true; break;
  36867. case gl.STENCIL_TEST: self.stencilTest = true; break;
  36868. }
  36869. self.realEnable.call(gl, pname);
  36870. };
  36871. gl.disable = function(pname) {
  36872. switch (pname) {
  36873. case gl.CULL_FACE: self.cullFace = false; break;
  36874. case gl.DEPTH_TEST: self.depthTest = false; break;
  36875. case gl.BLEND: self.blend = false; break;
  36876. case gl.SCISSOR_TEST: self.scissorTest = false; break;
  36877. case gl.STENCIL_TEST: self.stencilTest = false; break;
  36878. }
  36879. self.realDisable.call(gl, pname);
  36880. };
  36881. this.colorMask = gl.getParameter(gl.COLOR_WRITEMASK);
  36882. gl.colorMask = function(r, g, b, a) {
  36883. self.colorMask[0] = r;
  36884. self.colorMask[1] = g;
  36885. self.colorMask[2] = b;
  36886. self.colorMask[3] = a;
  36887. self.realColorMask.call(gl, r, g, b, a);
  36888. };
  36889. this.clearColor = gl.getParameter(gl.COLOR_CLEAR_VALUE);
  36890. gl.clearColor = function(r, g, b, a) {
  36891. self.clearColor[0] = r;
  36892. self.clearColor[1] = g;
  36893. self.clearColor[2] = b;
  36894. self.clearColor[3] = a;
  36895. self.realClearColor.call(gl, r, g, b, a);
  36896. };
  36897. this.viewport = gl.getParameter(gl.VIEWPORT);
  36898. gl.viewport = function(x, y, w, h) {
  36899. self.viewport[0] = x;
  36900. self.viewport[1] = y;
  36901. self.viewport[2] = w;
  36902. self.viewport[3] = h;
  36903. self.realViewport.call(gl, x, y, w, h);
  36904. };
  36905. this.isPatched = true;
  36906. Util.safariCssSizeWorkaround(canvas);
  36907. };
  36908. CardboardDistorter.prototype.unpatch = function() {
  36909. if (!this.isPatched) {
  36910. return;
  36911. }
  36912. var gl = this.gl;
  36913. var canvas = this.gl.canvas;
  36914. if (!Util.isIOS()) {
  36915. Object.defineProperty(canvas, 'width', this.realCanvasWidth);
  36916. Object.defineProperty(canvas, 'height', this.realCanvasHeight);
  36917. }
  36918. canvas.width = this.bufferWidth;
  36919. canvas.height = this.bufferHeight;
  36920. gl.bindFramebuffer = this.realBindFramebuffer;
  36921. gl.enable = this.realEnable;
  36922. gl.disable = this.realDisable;
  36923. gl.colorMask = this.realColorMask;
  36924. gl.clearColor = this.realClearColor;
  36925. gl.viewport = this.realViewport;
  36926. // Check to see if our fake backbuffer is bound and bind the real backbuffer
  36927. // if that's the case.
  36928. if (this.lastBoundFramebuffer == this.framebuffer) {
  36929. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  36930. }
  36931. this.isPatched = false;
  36932. setTimeout(function() {
  36933. Util.safariCssSizeWorkaround(canvas);
  36934. }, 1);
  36935. };
  36936. CardboardDistorter.prototype.setTextureBounds = function(leftBounds, rightBounds) {
  36937. if (!leftBounds) {
  36938. leftBounds = [0, 0, 0.5, 1];
  36939. }
  36940. if (!rightBounds) {
  36941. rightBounds = [0.5, 0, 0.5, 1];
  36942. }
  36943. // Left eye
  36944. this.viewportOffsetScale[0] = leftBounds[0]; // X
  36945. this.viewportOffsetScale[1] = leftBounds[1]; // Y
  36946. this.viewportOffsetScale[2] = leftBounds[2]; // Width
  36947. this.viewportOffsetScale[3] = leftBounds[3]; // Height
  36948. // Right eye
  36949. this.viewportOffsetScale[4] = rightBounds[0]; // X
  36950. this.viewportOffsetScale[5] = rightBounds[1]; // Y
  36951. this.viewportOffsetScale[6] = rightBounds[2]; // Width
  36952. this.viewportOffsetScale[7] = rightBounds[3]; // Height
  36953. };
  36954. /**
  36955. * Performs distortion pass on the injected backbuffer, rendering it to the real
  36956. * backbuffer.
  36957. */
  36958. CardboardDistorter.prototype.submitFrame = function() {
  36959. var gl = this.gl;
  36960. var self = this;
  36961. var glState = [];
  36962. if (!window.WebVRConfig.DIRTY_SUBMIT_FRAME_BINDINGS) {
  36963. glState.push(
  36964. gl.CURRENT_PROGRAM,
  36965. gl.ARRAY_BUFFER_BINDING,
  36966. gl.ELEMENT_ARRAY_BUFFER_BINDING,
  36967. gl.TEXTURE_BINDING_2D, gl.TEXTURE0
  36968. );
  36969. }
  36970. WGLUPreserveGLState(gl, glState, function(gl) {
  36971. // Bind the real default framebuffer
  36972. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, null);
  36973. // Make sure the GL state is in a good place
  36974. if (self.cullFace) { self.realDisable.call(gl, gl.CULL_FACE); }
  36975. if (self.depthTest) { self.realDisable.call(gl, gl.DEPTH_TEST); }
  36976. if (self.blend) { self.realDisable.call(gl, gl.BLEND); }
  36977. if (self.scissorTest) { self.realDisable.call(gl, gl.SCISSOR_TEST); }
  36978. if (self.stencilTest) { self.realDisable.call(gl, gl.STENCIL_TEST); }
  36979. self.realColorMask.call(gl, true, true, true, true);
  36980. self.realViewport.call(gl, 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  36981. // If the backbuffer has an alpha channel clear every frame so the page
  36982. // doesn't show through.
  36983. if (self.ctxAttribs.alpha || Util.isIOS()) {
  36984. self.realClearColor.call(gl, 0, 0, 0, 1);
  36985. gl.clear(gl.COLOR_BUFFER_BIT);
  36986. }
  36987. // Bind distortion program and mesh
  36988. gl.useProgram(self.program);
  36989. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, self.indexBuffer);
  36990. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  36991. gl.enableVertexAttribArray(self.attribs.position);
  36992. gl.enableVertexAttribArray(self.attribs.texCoord);
  36993. gl.vertexAttribPointer(self.attribs.position, 2, gl.FLOAT, false, 20, 0);
  36994. gl.vertexAttribPointer(self.attribs.texCoord, 3, gl.FLOAT, false, 20, 8);
  36995. gl.activeTexture(gl.TEXTURE0);
  36996. gl.uniform1i(self.uniforms.diffuse, 0);
  36997. gl.bindTexture(gl.TEXTURE_2D, self.renderTarget);
  36998. gl.uniform4fv(self.uniforms.viewportOffsetScale, self.viewportOffsetScale);
  36999. // Draws both eyes
  37000. gl.drawElements(gl.TRIANGLES, self.indexCount, gl.UNSIGNED_SHORT, 0);
  37001. if (self.cardboardUI) {
  37002. self.cardboardUI.renderNoState();
  37003. }
  37004. // Bind the fake default framebuffer again
  37005. self.realBindFramebuffer.call(self.gl, gl.FRAMEBUFFER, self.framebuffer);
  37006. // If preserveDrawingBuffer == false clear the framebuffer
  37007. if (!self.ctxAttribs.preserveDrawingBuffer) {
  37008. self.realClearColor.call(gl, 0, 0, 0, 0);
  37009. gl.clear(gl.COLOR_BUFFER_BIT);
  37010. }
  37011. if (!window.WebVRConfig.DIRTY_SUBMIT_FRAME_BINDINGS) {
  37012. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.lastBoundFramebuffer);
  37013. }
  37014. // Restore state
  37015. if (self.cullFace) { self.realEnable.call(gl, gl.CULL_FACE); }
  37016. if (self.depthTest) { self.realEnable.call(gl, gl.DEPTH_TEST); }
  37017. if (self.blend) { self.realEnable.call(gl, gl.BLEND); }
  37018. if (self.scissorTest) { self.realEnable.call(gl, gl.SCISSOR_TEST); }
  37019. if (self.stencilTest) { self.realEnable.call(gl, gl.STENCIL_TEST); }
  37020. self.realColorMask.apply(gl, self.colorMask);
  37021. self.realViewport.apply(gl, self.viewport);
  37022. if (self.ctxAttribs.alpha || !self.ctxAttribs.preserveDrawingBuffer) {
  37023. self.realClearColor.apply(gl, self.clearColor);
  37024. }
  37025. });
  37026. // Workaround for the fact that Safari doesn't allow us to patch the canvas
  37027. // width and height correctly. After each submit frame check to see what the
  37028. // real backbuffer size has been set to and resize the fake backbuffer size
  37029. // to match.
  37030. if (Util.isIOS()) {
  37031. var canvas = gl.canvas;
  37032. if (canvas.width != self.bufferWidth || canvas.height != self.bufferHeight) {
  37033. self.bufferWidth = canvas.width;
  37034. self.bufferHeight = canvas.height;
  37035. self.onResize();
  37036. }
  37037. }
  37038. };
  37039. /**
  37040. * Call when the deviceInfo has changed. At this point we need
  37041. * to re-calculate the distortion mesh.
  37042. */
  37043. CardboardDistorter.prototype.updateDeviceInfo = function(deviceInfo) {
  37044. var gl = this.gl;
  37045. var self = this;
  37046. var glState = [gl.ARRAY_BUFFER_BINDING, gl.ELEMENT_ARRAY_BUFFER_BINDING];
  37047. WGLUPreserveGLState(gl, glState, function(gl) {
  37048. var vertices = self.computeMeshVertices_(self.meshWidth, self.meshHeight, deviceInfo);
  37049. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  37050. gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
  37051. // Indices don't change based on device parameters, so only compute once.
  37052. if (!self.indexCount) {
  37053. var indices = self.computeMeshIndices_(self.meshWidth, self.meshHeight);
  37054. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, self.indexBuffer);
  37055. gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);
  37056. self.indexCount = indices.length;
  37057. }
  37058. });
  37059. };
  37060. /**
  37061. * Build the distortion mesh vertices.
  37062. * Based on code from the Unity cardboard plugin.
  37063. */
  37064. CardboardDistorter.prototype.computeMeshVertices_ = function(width, height, deviceInfo) {
  37065. var vertices = new Float32Array(2 * width * height * 5);
  37066. var lensFrustum = deviceInfo.getLeftEyeVisibleTanAngles();
  37067. var noLensFrustum = deviceInfo.getLeftEyeNoLensTanAngles();
  37068. var viewport = deviceInfo.getLeftEyeVisibleScreenRect(noLensFrustum);
  37069. var vidx = 0;
  37070. var iidx = 0;
  37071. for (var e = 0; e < 2; e++) {
  37072. for (var j = 0; j < height; j++) {
  37073. for (var i = 0; i < width; i++, vidx++) {
  37074. var u = i / (width - 1);
  37075. var v = j / (height - 1);
  37076. // Grid points regularly spaced in StreoScreen, and barrel distorted in
  37077. // the mesh.
  37078. var s = u;
  37079. var t = v;
  37080. var x = Util.lerp(lensFrustum[0], lensFrustum[2], u);
  37081. var y = Util.lerp(lensFrustum[3], lensFrustum[1], v);
  37082. var d = Math.sqrt(x * x + y * y);
  37083. var r = deviceInfo.distortion.distortInverse(d);
  37084. var p = x * r / d;
  37085. var q = y * r / d;
  37086. u = (p - noLensFrustum[0]) / (noLensFrustum[2] - noLensFrustum[0]);
  37087. v = (q - noLensFrustum[3]) / (noLensFrustum[1] - noLensFrustum[3]);
  37088. // Convert u,v to mesh screen coordinates.
  37089. var aspect = deviceInfo.device.widthMeters / deviceInfo.device.heightMeters;
  37090. // FIXME: The original Unity plugin multiplied U by the aspect ratio
  37091. // and didn't multiply either value by 2, but that seems to get it
  37092. // really close to correct looking for me. I hate this kind of "Don't
  37093. // know why it works" code though, and wold love a more logical
  37094. // explanation of what needs to happen here.
  37095. u = (viewport.x + u * viewport.width - 0.5) * 2.0; //* aspect;
  37096. v = (viewport.y + v * viewport.height - 0.5) * 2.0;
  37097. vertices[(vidx * 5) + 0] = u; // position.x
  37098. vertices[(vidx * 5) + 1] = v; // position.y
  37099. vertices[(vidx * 5) + 2] = s; // texCoord.x
  37100. vertices[(vidx * 5) + 3] = t; // texCoord.y
  37101. vertices[(vidx * 5) + 4] = e; // texCoord.z (viewport index)
  37102. }
  37103. }
  37104. var w = lensFrustum[2] - lensFrustum[0];
  37105. lensFrustum[0] = -(w + lensFrustum[0]);
  37106. lensFrustum[2] = w - lensFrustum[2];
  37107. w = noLensFrustum[2] - noLensFrustum[0];
  37108. noLensFrustum[0] = -(w + noLensFrustum[0]);
  37109. noLensFrustum[2] = w - noLensFrustum[2];
  37110. viewport.x = 1 - (viewport.x + viewport.width);
  37111. }
  37112. return vertices;
  37113. }
  37114. /**
  37115. * Build the distortion mesh indices.
  37116. * Based on code from the Unity cardboard plugin.
  37117. */
  37118. CardboardDistorter.prototype.computeMeshIndices_ = function(width, height) {
  37119. var indices = new Uint16Array(2 * (width - 1) * (height - 1) * 6);
  37120. var halfwidth = width / 2;
  37121. var halfheight = height / 2;
  37122. var vidx = 0;
  37123. var iidx = 0;
  37124. for (var e = 0; e < 2; e++) {
  37125. for (var j = 0; j < height; j++) {
  37126. for (var i = 0; i < width; i++, vidx++) {
  37127. if (i == 0 || j == 0)
  37128. continue;
  37129. // Build a quad. Lower right and upper left quadrants have quads with
  37130. // the triangle diagonal flipped to get the vignette to interpolate
  37131. // correctly.
  37132. if ((i <= halfwidth) == (j <= halfheight)) {
  37133. // Quad diagonal lower left to upper right.
  37134. indices[iidx++] = vidx;
  37135. indices[iidx++] = vidx - width - 1;
  37136. indices[iidx++] = vidx - width;
  37137. indices[iidx++] = vidx - width - 1;
  37138. indices[iidx++] = vidx;
  37139. indices[iidx++] = vidx - 1;
  37140. } else {
  37141. // Quad diagonal upper left to lower right.
  37142. indices[iidx++] = vidx - 1;
  37143. indices[iidx++] = vidx - width;
  37144. indices[iidx++] = vidx;
  37145. indices[iidx++] = vidx - width;
  37146. indices[iidx++] = vidx - 1;
  37147. indices[iidx++] = vidx - width - 1;
  37148. }
  37149. }
  37150. }
  37151. }
  37152. return indices;
  37153. };
  37154. CardboardDistorter.prototype.getOwnPropertyDescriptor_ = function(proto, attrName) {
  37155. var descriptor = Object.getOwnPropertyDescriptor(proto, attrName);
  37156. // In some cases (ahem... Safari), the descriptor returns undefined get and
  37157. // set fields. In this case, we need to create a synthetic property
  37158. // descriptor. This works around some of the issues in
  37159. // https://github.com/borismus/webvr-polyfill/issues/46
  37160. if (descriptor.get === undefined || descriptor.set === undefined) {
  37161. descriptor.configurable = true;
  37162. descriptor.enumerable = true;
  37163. descriptor.get = function() {
  37164. return this.getAttribute(attrName);
  37165. };
  37166. descriptor.set = function(val) {
  37167. this.setAttribute(attrName, val);
  37168. };
  37169. }
  37170. return descriptor;
  37171. };
  37172. module.exports = CardboardDistorter;
  37173. },{"./cardboard-ui.js":51,"./deps/wglu-preserve-state.js":53,"./util.js":69}],51:[function(_dereq_,module,exports){
  37174. /*
  37175. * Copyright 2016 Google Inc. All Rights Reserved.
  37176. * Licensed under the Apache License, Version 2.0 (the "License");
  37177. * you may not use this file except in compliance with the License.
  37178. * You may obtain a copy of the License at
  37179. *
  37180. * http://www.apache.org/licenses/LICENSE-2.0
  37181. *
  37182. * Unless required by applicable law or agreed to in writing, software
  37183. * distributed under the License is distributed on an "AS IS" BASIS,
  37184. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  37185. * See the License for the specific language governing permissions and
  37186. * limitations under the License.
  37187. */
  37188. var Util = _dereq_('./util.js');
  37189. var WGLUPreserveGLState = _dereq_('./deps/wglu-preserve-state.js');
  37190. var uiVS = [
  37191. 'attribute vec2 position;',
  37192. 'uniform mat4 projectionMat;',
  37193. 'void main() {',
  37194. ' gl_Position = projectionMat * vec4( position, -1.0, 1.0 );',
  37195. '}',
  37196. ].join('\n');
  37197. var uiFS = [
  37198. 'precision mediump float;',
  37199. 'uniform vec4 color;',
  37200. 'void main() {',
  37201. ' gl_FragColor = color;',
  37202. '}',
  37203. ].join('\n');
  37204. var DEG2RAD = Math.PI/180.0;
  37205. // The gear has 6 identical sections, each spanning 60 degrees.
  37206. var kAnglePerGearSection = 60;
  37207. // Half-angle of the span of the outer rim.
  37208. var kOuterRimEndAngle = 12;
  37209. // Angle between the middle of the outer rim and the start of the inner rim.
  37210. var kInnerRimBeginAngle = 20;
  37211. // Distance from center to outer rim, normalized so that the entire model
  37212. // fits in a [-1, 1] x [-1, 1] square.
  37213. var kOuterRadius = 1;
  37214. // Distance from center to depressed rim, in model units.
  37215. var kMiddleRadius = 0.75;
  37216. // Radius of the inner hollow circle, in model units.
  37217. var kInnerRadius = 0.3125;
  37218. // Center line thickness in DP.
  37219. var kCenterLineThicknessDp = 4;
  37220. // Button width in DP.
  37221. var kButtonWidthDp = 28;
  37222. // Factor to scale the touch area that responds to the touch.
  37223. var kTouchSlopFactor = 1.5;
  37224. var Angles = [
  37225. 0, kOuterRimEndAngle, kInnerRimBeginAngle,
  37226. kAnglePerGearSection - kInnerRimBeginAngle,
  37227. kAnglePerGearSection - kOuterRimEndAngle
  37228. ];
  37229. /**
  37230. * Renders the alignment line and "options" gear. It is assumed that the canvas
  37231. * this is rendered into covers the entire screen (or close to it.)
  37232. */
  37233. function CardboardUI(gl) {
  37234. this.gl = gl;
  37235. this.attribs = {
  37236. position: 0
  37237. };
  37238. this.program = Util.linkProgram(gl, uiVS, uiFS, this.attribs);
  37239. this.uniforms = Util.getProgramUniforms(gl, this.program);
  37240. this.vertexBuffer = gl.createBuffer();
  37241. this.gearOffset = 0;
  37242. this.gearVertexCount = 0;
  37243. this.arrowOffset = 0;
  37244. this.arrowVertexCount = 0;
  37245. this.projMat = new Float32Array(16);
  37246. this.listener = null;
  37247. this.onResize();
  37248. };
  37249. /**
  37250. * Tears down all the resources created by the UI renderer.
  37251. */
  37252. CardboardUI.prototype.destroy = function() {
  37253. var gl = this.gl;
  37254. if (this.listener) {
  37255. gl.canvas.removeEventListener('click', this.listener, false);
  37256. }
  37257. gl.deleteProgram(this.program);
  37258. gl.deleteBuffer(this.vertexBuffer);
  37259. };
  37260. /**
  37261. * Adds a listener to clicks on the gear and back icons
  37262. */
  37263. CardboardUI.prototype.listen = function(optionsCallback, backCallback) {
  37264. var canvas = this.gl.canvas;
  37265. this.listener = function(event) {
  37266. var midline = canvas.clientWidth / 2;
  37267. var buttonSize = kButtonWidthDp * kTouchSlopFactor;
  37268. // Check to see if the user clicked on (or around) the gear icon
  37269. if (event.clientX > midline - buttonSize &&
  37270. event.clientX < midline + buttonSize &&
  37271. event.clientY > canvas.clientHeight - buttonSize) {
  37272. optionsCallback(event);
  37273. }
  37274. // Check to see if the user clicked on (or around) the back icon
  37275. else if (event.clientX < buttonSize && event.clientY < buttonSize) {
  37276. backCallback(event);
  37277. }
  37278. };
  37279. canvas.addEventListener('click', this.listener, false);
  37280. };
  37281. /**
  37282. * Builds the UI mesh.
  37283. */
  37284. CardboardUI.prototype.onResize = function() {
  37285. var gl = this.gl;
  37286. var self = this;
  37287. var glState = [
  37288. gl.ARRAY_BUFFER_BINDING
  37289. ];
  37290. WGLUPreserveGLState(gl, glState, function(gl) {
  37291. var vertices = [];
  37292. var midline = gl.drawingBufferWidth / 2;
  37293. // The gl buffer size will likely be smaller than the physical pixel count.
  37294. // So we need to scale the dps down based on the actual buffer size vs physical pixel count.
  37295. // This will properly size the ui elements no matter what the gl buffer resolution is
  37296. var physicalPixels = Math.max(screen.width, screen.height) * window.devicePixelRatio;
  37297. var scalingRatio = gl.drawingBufferWidth / physicalPixels;
  37298. var dps = scalingRatio * window.devicePixelRatio;
  37299. var lineWidth = kCenterLineThicknessDp * dps / 2;
  37300. var buttonSize = kButtonWidthDp * kTouchSlopFactor * dps;
  37301. var buttonScale = kButtonWidthDp * dps / 2;
  37302. var buttonBorder = ((kButtonWidthDp * kTouchSlopFactor) - kButtonWidthDp) * dps;
  37303. // Build centerline
  37304. vertices.push(midline - lineWidth, buttonSize);
  37305. vertices.push(midline - lineWidth, gl.drawingBufferHeight);
  37306. vertices.push(midline + lineWidth, buttonSize);
  37307. vertices.push(midline + lineWidth, gl.drawingBufferHeight);
  37308. // Build gear
  37309. self.gearOffset = (vertices.length / 2);
  37310. function addGearSegment(theta, r) {
  37311. var angle = (90 - theta) * DEG2RAD;
  37312. var x = Math.cos(angle);
  37313. var y = Math.sin(angle);
  37314. vertices.push(kInnerRadius * x * buttonScale + midline, kInnerRadius * y * buttonScale + buttonScale);
  37315. vertices.push(r * x * buttonScale + midline, r * y * buttonScale + buttonScale);
  37316. }
  37317. for (var i = 0; i <= 6; i++) {
  37318. var segmentTheta = i * kAnglePerGearSection;
  37319. addGearSegment(segmentTheta, kOuterRadius);
  37320. addGearSegment(segmentTheta + kOuterRimEndAngle, kOuterRadius);
  37321. addGearSegment(segmentTheta + kInnerRimBeginAngle, kMiddleRadius);
  37322. addGearSegment(segmentTheta + (kAnglePerGearSection - kInnerRimBeginAngle), kMiddleRadius);
  37323. addGearSegment(segmentTheta + (kAnglePerGearSection - kOuterRimEndAngle), kOuterRadius);
  37324. }
  37325. self.gearVertexCount = (vertices.length / 2) - self.gearOffset;
  37326. // Build back arrow
  37327. self.arrowOffset = (vertices.length / 2);
  37328. function addArrowVertex(x, y) {
  37329. vertices.push(buttonBorder + x, gl.drawingBufferHeight - buttonBorder - y);
  37330. }
  37331. var angledLineWidth = lineWidth / Math.sin(45 * DEG2RAD);
  37332. addArrowVertex(0, buttonScale);
  37333. addArrowVertex(buttonScale, 0);
  37334. addArrowVertex(buttonScale + angledLineWidth, angledLineWidth);
  37335. addArrowVertex(angledLineWidth, buttonScale + angledLineWidth);
  37336. addArrowVertex(angledLineWidth, buttonScale - angledLineWidth);
  37337. addArrowVertex(0, buttonScale);
  37338. addArrowVertex(buttonScale, buttonScale * 2);
  37339. addArrowVertex(buttonScale + angledLineWidth, (buttonScale * 2) - angledLineWidth);
  37340. addArrowVertex(angledLineWidth, buttonScale - angledLineWidth);
  37341. addArrowVertex(0, buttonScale);
  37342. addArrowVertex(angledLineWidth, buttonScale - lineWidth);
  37343. addArrowVertex(kButtonWidthDp * dps, buttonScale - lineWidth);
  37344. addArrowVertex(angledLineWidth, buttonScale + lineWidth);
  37345. addArrowVertex(kButtonWidthDp * dps, buttonScale + lineWidth);
  37346. self.arrowVertexCount = (vertices.length / 2) - self.arrowOffset;
  37347. // Buffer data
  37348. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  37349. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
  37350. });
  37351. };
  37352. /**
  37353. * Performs distortion pass on the injected backbuffer, rendering it to the real
  37354. * backbuffer.
  37355. */
  37356. CardboardUI.prototype.render = function() {
  37357. var gl = this.gl;
  37358. var self = this;
  37359. var glState = [
  37360. gl.CULL_FACE,
  37361. gl.DEPTH_TEST,
  37362. gl.BLEND,
  37363. gl.SCISSOR_TEST,
  37364. gl.STENCIL_TEST,
  37365. gl.COLOR_WRITEMASK,
  37366. gl.VIEWPORT,
  37367. gl.CURRENT_PROGRAM,
  37368. gl.ARRAY_BUFFER_BINDING
  37369. ];
  37370. WGLUPreserveGLState(gl, glState, function(gl) {
  37371. // Make sure the GL state is in a good place
  37372. gl.disable(gl.CULL_FACE);
  37373. gl.disable(gl.DEPTH_TEST);
  37374. gl.disable(gl.BLEND);
  37375. gl.disable(gl.SCISSOR_TEST);
  37376. gl.disable(gl.STENCIL_TEST);
  37377. gl.colorMask(true, true, true, true);
  37378. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  37379. self.renderNoState();
  37380. });
  37381. };
  37382. CardboardUI.prototype.renderNoState = function() {
  37383. var gl = this.gl;
  37384. // Bind distortion program and mesh
  37385. gl.useProgram(this.program);
  37386. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  37387. gl.enableVertexAttribArray(this.attribs.position);
  37388. gl.vertexAttribPointer(this.attribs.position, 2, gl.FLOAT, false, 8, 0);
  37389. gl.uniform4f(this.uniforms.color, 1.0, 1.0, 1.0, 1.0);
  37390. Util.orthoMatrix(this.projMat, 0, gl.drawingBufferWidth, 0, gl.drawingBufferHeight, 0.1, 1024.0);
  37391. gl.uniformMatrix4fv(this.uniforms.projectionMat, false, this.projMat);
  37392. // Draws UI element
  37393. gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  37394. gl.drawArrays(gl.TRIANGLE_STRIP, this.gearOffset, this.gearVertexCount);
  37395. gl.drawArrays(gl.TRIANGLE_STRIP, this.arrowOffset, this.arrowVertexCount);
  37396. };
  37397. module.exports = CardboardUI;
  37398. },{"./deps/wglu-preserve-state.js":53,"./util.js":69}],52:[function(_dereq_,module,exports){
  37399. /*
  37400. * Copyright 2016 Google Inc. All Rights Reserved.
  37401. * Licensed under the Apache License, Version 2.0 (the "License");
  37402. * you may not use this file except in compliance with the License.
  37403. * You may obtain a copy of the License at
  37404. *
  37405. * http://www.apache.org/licenses/LICENSE-2.0
  37406. *
  37407. * Unless required by applicable law or agreed to in writing, software
  37408. * distributed under the License is distributed on an "AS IS" BASIS,
  37409. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  37410. * See the License for the specific language governing permissions and
  37411. * limitations under the License.
  37412. */
  37413. var CardboardDistorter = _dereq_('./cardboard-distorter.js');
  37414. var CardboardUI = _dereq_('./cardboard-ui.js');
  37415. var DeviceInfo = _dereq_('./device-info.js');
  37416. var Dpdb = _dereq_('./dpdb/dpdb.js');
  37417. var FusionPoseSensor = _dereq_('./sensor-fusion/fusion-pose-sensor.js');
  37418. var RotateInstructions = _dereq_('./rotate-instructions.js');
  37419. var ViewerSelector = _dereq_('./viewer-selector.js');
  37420. var VRDisplay = _dereq_('./base.js').VRDisplay;
  37421. var Util = _dereq_('./util.js');
  37422. var Eye = {
  37423. LEFT: 'left',
  37424. RIGHT: 'right'
  37425. };
  37426. /**
  37427. * VRDisplay based on mobile device parameters and DeviceMotion APIs.
  37428. */
  37429. function CardboardVRDisplay() {
  37430. this.displayName = 'Cardboard VRDisplay (webvr-polyfill)';
  37431. this.capabilities.hasOrientation = true;
  37432. this.capabilities.canPresent = true;
  37433. // "Private" members.
  37434. this.bufferScale_ = window.WebVRConfig.BUFFER_SCALE;
  37435. this.poseSensor_ = new FusionPoseSensor();
  37436. this.distorter_ = null;
  37437. this.cardboardUI_ = null;
  37438. this.dpdb_ = new Dpdb(true, this.onDeviceParamsUpdated_.bind(this));
  37439. this.deviceInfo_ = new DeviceInfo(this.dpdb_.getDeviceParams());
  37440. this.viewerSelector_ = new ViewerSelector();
  37441. this.viewerSelector_.onChange(this.onViewerChanged_.bind(this));
  37442. // Set the correct initial viewer.
  37443. this.deviceInfo_.setViewer(this.viewerSelector_.getCurrentViewer());
  37444. if (!window.WebVRConfig.ROTATE_INSTRUCTIONS_DISABLED) {
  37445. this.rotateInstructions_ = new RotateInstructions();
  37446. }
  37447. if (Util.isIOS()) {
  37448. // Listen for resize events to workaround this awful Safari bug.
  37449. window.addEventListener('resize', this.onResize_.bind(this));
  37450. }
  37451. }
  37452. CardboardVRDisplay.prototype = new VRDisplay();
  37453. CardboardVRDisplay.prototype.getImmediatePose = function() {
  37454. return {
  37455. position: this.poseSensor_.getPosition(),
  37456. orientation: this.poseSensor_.getOrientation(),
  37457. linearVelocity: null,
  37458. linearAcceleration: null,
  37459. angularVelocity: null,
  37460. angularAcceleration: null
  37461. };
  37462. };
  37463. CardboardVRDisplay.prototype.resetPose = function() {
  37464. this.poseSensor_.resetPose();
  37465. };
  37466. CardboardVRDisplay.prototype.getEyeParameters = function(whichEye) {
  37467. var offset = [this.deviceInfo_.viewer.interLensDistance * 0.5, 0.0, 0.0];
  37468. var fieldOfView;
  37469. // TODO: FoV can be a little expensive to compute. Cache when device params change.
  37470. if (whichEye == Eye.LEFT) {
  37471. offset[0] *= -1.0;
  37472. fieldOfView = this.deviceInfo_.getFieldOfViewLeftEye();
  37473. } else if (whichEye == Eye.RIGHT) {
  37474. fieldOfView = this.deviceInfo_.getFieldOfViewRightEye();
  37475. } else {
  37476. console.error('Invalid eye provided: %s', whichEye);
  37477. return null;
  37478. }
  37479. return {
  37480. fieldOfView: fieldOfView,
  37481. offset: offset,
  37482. // TODO: Should be able to provide better values than these.
  37483. renderWidth: this.deviceInfo_.device.width * 0.5 * this.bufferScale_,
  37484. renderHeight: this.deviceInfo_.device.height * this.bufferScale_,
  37485. };
  37486. };
  37487. CardboardVRDisplay.prototype.onDeviceParamsUpdated_ = function(newParams) {
  37488. if (Util.isDebug()) {
  37489. console.log('DPDB reported that device params were updated.');
  37490. }
  37491. this.deviceInfo_.updateDeviceParams(newParams);
  37492. if (this.distorter_) {
  37493. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  37494. }
  37495. };
  37496. CardboardVRDisplay.prototype.updateBounds_ = function () {
  37497. if (this.layer_ && this.distorter_ && (this.layer_.leftBounds || this.layer_.rightBounds)) {
  37498. this.distorter_.setTextureBounds(this.layer_.leftBounds, this.layer_.rightBounds);
  37499. }
  37500. };
  37501. CardboardVRDisplay.prototype.beginPresent_ = function() {
  37502. var gl = this.layer_.source.getContext('webgl');
  37503. if (!gl)
  37504. gl = this.layer_.source.getContext('experimental-webgl');
  37505. if (!gl)
  37506. gl = this.layer_.source.getContext('webgl2');
  37507. if (!gl)
  37508. return; // Can't do distortion without a WebGL context.
  37509. // Provides a way to opt out of distortion
  37510. if (this.layer_.predistorted) {
  37511. if (!window.WebVRConfig.CARDBOARD_UI_DISABLED) {
  37512. gl.canvas.width = Util.getScreenWidth() * this.bufferScale_;
  37513. gl.canvas.height = Util.getScreenHeight() * this.bufferScale_;
  37514. this.cardboardUI_ = new CardboardUI(gl);
  37515. }
  37516. } else {
  37517. // Create a new distorter for the target context
  37518. this.distorter_ = new CardboardDistorter(gl);
  37519. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  37520. this.cardboardUI_ = this.distorter_.cardboardUI;
  37521. }
  37522. if (this.cardboardUI_) {
  37523. this.cardboardUI_.listen(function(e) {
  37524. // Options clicked.
  37525. this.viewerSelector_.show(this.layer_.source.parentElement);
  37526. e.stopPropagation();
  37527. e.preventDefault();
  37528. }.bind(this), function(e) {
  37529. // Back clicked.
  37530. this.exitPresent();
  37531. e.stopPropagation();
  37532. e.preventDefault();
  37533. }.bind(this));
  37534. }
  37535. if (this.rotateInstructions_) {
  37536. if (Util.isLandscapeMode() && Util.isMobile()) {
  37537. // In landscape mode, temporarily show the "put into Cardboard"
  37538. // interstitial. Otherwise, do the default thing.
  37539. this.rotateInstructions_.showTemporarily(3000, this.layer_.source.parentElement);
  37540. } else {
  37541. this.rotateInstructions_.update();
  37542. }
  37543. }
  37544. // Listen for orientation change events in order to show interstitial.
  37545. this.orientationHandler = this.onOrientationChange_.bind(this);
  37546. window.addEventListener('orientationchange', this.orientationHandler);
  37547. // Listen for present display change events in order to update distorter dimensions
  37548. this.vrdisplaypresentchangeHandler = this.updateBounds_.bind(this);
  37549. window.addEventListener('vrdisplaypresentchange', this.vrdisplaypresentchangeHandler);
  37550. // Fire this event initially, to give geometry-distortion clients the chance
  37551. // to do something custom.
  37552. this.fireVRDisplayDeviceParamsChange_();
  37553. };
  37554. CardboardVRDisplay.prototype.endPresent_ = function() {
  37555. if (this.distorter_) {
  37556. this.distorter_.destroy();
  37557. this.distorter_ = null;
  37558. }
  37559. if (this.cardboardUI_) {
  37560. this.cardboardUI_.destroy();
  37561. this.cardboardUI_ = null;
  37562. }
  37563. if (this.rotateInstructions_) {
  37564. this.rotateInstructions_.hide();
  37565. }
  37566. this.viewerSelector_.hide();
  37567. window.removeEventListener('orientationchange', this.orientationHandler);
  37568. window.removeEventListener('vrdisplaypresentchange', this.vrdisplaypresentchangeHandler);
  37569. };
  37570. CardboardVRDisplay.prototype.submitFrame = function(pose) {
  37571. if (this.distorter_) {
  37572. this.updateBounds_();
  37573. this.distorter_.submitFrame();
  37574. } else if (this.cardboardUI_ && this.layer_) {
  37575. // Hack for predistorted: true.
  37576. var canvas = this.layer_.source.getContext('webgl').canvas;
  37577. if (canvas.width != this.lastWidth || canvas.height != this.lastHeight) {
  37578. this.cardboardUI_.onResize();
  37579. }
  37580. this.lastWidth = canvas.width;
  37581. this.lastHeight = canvas.height;
  37582. // Render the Cardboard UI.
  37583. this.cardboardUI_.render();
  37584. }
  37585. };
  37586. CardboardVRDisplay.prototype.onOrientationChange_ = function(e) {
  37587. // Hide the viewer selector.
  37588. this.viewerSelector_.hide();
  37589. // Update the rotate instructions.
  37590. if (this.rotateInstructions_) {
  37591. this.rotateInstructions_.update();
  37592. }
  37593. this.onResize_();
  37594. };
  37595. CardboardVRDisplay.prototype.onResize_ = function(e) {
  37596. if (this.layer_) {
  37597. var gl = this.layer_.source.getContext('webgl');
  37598. // Size the CSS canvas.
  37599. // Added padding on right and bottom because iPhone 5 will not
  37600. // hide the URL bar unless content is bigger than the screen.
  37601. // This will not be visible as long as the container element (e.g. body)
  37602. // is set to 'overflow: hidden'.
  37603. // Additionally, 'box-sizing: content-box' ensures renderWidth = width + padding.
  37604. // This is required when 'box-sizing: border-box' is used elsewhere in the page.
  37605. var cssProperties = [
  37606. 'position: absolute',
  37607. 'top: 0',
  37608. 'left: 0',
  37609. 'width: ' + Math.max(screen.width, screen.height) + 'px',
  37610. 'height: ' + Math.min(screen.height, screen.width) + 'px',
  37611. 'border: 0',
  37612. 'margin: 0',
  37613. 'padding: 0 10px 10px 0',
  37614. 'box-sizing: content-box',
  37615. ];
  37616. gl.canvas.setAttribute('style', cssProperties.join('; ') + ';');
  37617. Util.safariCssSizeWorkaround(gl.canvas);
  37618. }
  37619. };
  37620. CardboardVRDisplay.prototype.onViewerChanged_ = function(viewer) {
  37621. this.deviceInfo_.setViewer(viewer);
  37622. if (this.distorter_) {
  37623. // Update the distortion appropriately.
  37624. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  37625. }
  37626. // Fire a new event containing viewer and device parameters for clients that
  37627. // want to implement their own geometry-based distortion.
  37628. this.fireVRDisplayDeviceParamsChange_();
  37629. };
  37630. CardboardVRDisplay.prototype.fireVRDisplayDeviceParamsChange_ = function() {
  37631. var event = new CustomEvent('vrdisplaydeviceparamschange', {
  37632. detail: {
  37633. vrdisplay: this,
  37634. deviceInfo: this.deviceInfo_,
  37635. }
  37636. });
  37637. window.dispatchEvent(event);
  37638. };
  37639. module.exports = CardboardVRDisplay;
  37640. },{"./base.js":49,"./cardboard-distorter.js":50,"./cardboard-ui.js":51,"./device-info.js":54,"./dpdb/dpdb.js":58,"./rotate-instructions.js":63,"./sensor-fusion/fusion-pose-sensor.js":65,"./util.js":69,"./viewer-selector.js":70}],53:[function(_dereq_,module,exports){
  37641. /**
  37642. * Copyright (c) 2016, Brandon Jones.
  37643. * https://github.com/toji/webgl-utils/blob/master/src/wglu-preserve-state.js
  37644. * LICENSE: https://github.com/toji/webgl-utils/blob/master/LICENSE.md
  37645. */
  37646. function WGLUPreserveGLState(gl, bindings, callback) {
  37647. if (!bindings) {
  37648. callback(gl);
  37649. return;
  37650. }
  37651. var boundValues = [];
  37652. var activeTexture = null;
  37653. for (var i = 0; i < bindings.length; ++i) {
  37654. var binding = bindings[i];
  37655. switch (binding) {
  37656. case gl.TEXTURE_BINDING_2D:
  37657. case gl.TEXTURE_BINDING_CUBE_MAP:
  37658. var textureUnit = bindings[++i];
  37659. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31) {
  37660. console.error("TEXTURE_BINDING_2D or TEXTURE_BINDING_CUBE_MAP must be followed by a valid texture unit");
  37661. boundValues.push(null, null);
  37662. break;
  37663. }
  37664. if (!activeTexture) {
  37665. activeTexture = gl.getParameter(gl.ACTIVE_TEXTURE);
  37666. }
  37667. gl.activeTexture(textureUnit);
  37668. boundValues.push(gl.getParameter(binding), null);
  37669. break;
  37670. case gl.ACTIVE_TEXTURE:
  37671. activeTexture = gl.getParameter(gl.ACTIVE_TEXTURE);
  37672. boundValues.push(null);
  37673. break;
  37674. default:
  37675. boundValues.push(gl.getParameter(binding));
  37676. break;
  37677. }
  37678. }
  37679. callback(gl);
  37680. for (var i = 0; i < bindings.length; ++i) {
  37681. var binding = bindings[i];
  37682. var boundValue = boundValues[i];
  37683. switch (binding) {
  37684. case gl.ACTIVE_TEXTURE:
  37685. break; // Ignore this binding, since we special-case it to happen last.
  37686. case gl.ARRAY_BUFFER_BINDING:
  37687. gl.bindBuffer(gl.ARRAY_BUFFER, boundValue);
  37688. break;
  37689. case gl.COLOR_CLEAR_VALUE:
  37690. gl.clearColor(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  37691. break;
  37692. case gl.COLOR_WRITEMASK:
  37693. gl.colorMask(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  37694. break;
  37695. case gl.CURRENT_PROGRAM:
  37696. gl.useProgram(boundValue);
  37697. break;
  37698. case gl.ELEMENT_ARRAY_BUFFER_BINDING:
  37699. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, boundValue);
  37700. break;
  37701. case gl.FRAMEBUFFER_BINDING:
  37702. gl.bindFramebuffer(gl.FRAMEBUFFER, boundValue);
  37703. break;
  37704. case gl.RENDERBUFFER_BINDING:
  37705. gl.bindRenderbuffer(gl.RENDERBUFFER, boundValue);
  37706. break;
  37707. case gl.TEXTURE_BINDING_2D:
  37708. var textureUnit = bindings[++i];
  37709. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31)
  37710. break;
  37711. gl.activeTexture(textureUnit);
  37712. gl.bindTexture(gl.TEXTURE_2D, boundValue);
  37713. break;
  37714. case gl.TEXTURE_BINDING_CUBE_MAP:
  37715. var textureUnit = bindings[++i];
  37716. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31)
  37717. break;
  37718. gl.activeTexture(textureUnit);
  37719. gl.bindTexture(gl.TEXTURE_CUBE_MAP, boundValue);
  37720. break;
  37721. case gl.VIEWPORT:
  37722. gl.viewport(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  37723. break;
  37724. case gl.BLEND:
  37725. case gl.CULL_FACE:
  37726. case gl.DEPTH_TEST:
  37727. case gl.SCISSOR_TEST:
  37728. case gl.STENCIL_TEST:
  37729. if (boundValue) {
  37730. gl.enable(binding);
  37731. } else {
  37732. gl.disable(binding);
  37733. }
  37734. break;
  37735. default:
  37736. console.log("No GL restore behavior for 0x" + binding.toString(16));
  37737. break;
  37738. }
  37739. if (activeTexture) {
  37740. gl.activeTexture(activeTexture);
  37741. }
  37742. }
  37743. }
  37744. module.exports = WGLUPreserveGLState;
  37745. },{}],54:[function(_dereq_,module,exports){
  37746. /*
  37747. * Copyright 2015 Google Inc. All Rights Reserved.
  37748. * Licensed under the Apache License, Version 2.0 (the "License");
  37749. * you may not use this file except in compliance with the License.
  37750. * You may obtain a copy of the License at
  37751. *
  37752. * http://www.apache.org/licenses/LICENSE-2.0
  37753. *
  37754. * Unless required by applicable law or agreed to in writing, software
  37755. * distributed under the License is distributed on an "AS IS" BASIS,
  37756. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  37757. * See the License for the specific language governing permissions and
  37758. * limitations under the License.
  37759. */
  37760. var Distortion = _dereq_('./distortion/distortion.js');
  37761. var MathUtil = _dereq_('./math-util.js');
  37762. var Util = _dereq_('./util.js');
  37763. function Device(params) {
  37764. this.width = params.width || Util.getScreenWidth();
  37765. this.height = params.height || Util.getScreenHeight();
  37766. this.widthMeters = params.widthMeters;
  37767. this.heightMeters = params.heightMeters;
  37768. this.bevelMeters = params.bevelMeters;
  37769. }
  37770. // Fallback Android device (based on Nexus 5 measurements) for use when
  37771. // we can't recognize an Android device.
  37772. var DEFAULT_ANDROID = new Device({
  37773. widthMeters: 0.110,
  37774. heightMeters: 0.062,
  37775. bevelMeters: 0.004
  37776. });
  37777. // Fallback iOS device (based on iPhone6) for use when
  37778. // we can't recognize an Android device.
  37779. var DEFAULT_IOS = new Device({
  37780. widthMeters: 0.1038,
  37781. heightMeters: 0.0584,
  37782. bevelMeters: 0.004
  37783. });
  37784. var Viewers = {
  37785. CardboardV1: new CardboardViewer({
  37786. id: 'CardboardV1',
  37787. label: 'Cardboard I/O 2014',
  37788. fov: 40,
  37789. interLensDistance: 0.060,
  37790. baselineLensDistance: 0.035,
  37791. screenLensDistance: 0.042,
  37792. distortionCoefficients: [0.441, 0.156],
  37793. inverseCoefficients: [-0.4410035, 0.42756155, -0.4804439, 0.5460139,
  37794. -0.58821183, 0.5733938, -0.48303202, 0.33299083, -0.17573841,
  37795. 0.0651772, -0.01488963, 0.001559834]
  37796. }),
  37797. CardboardV2: new CardboardViewer({
  37798. id: 'CardboardV2',
  37799. label: 'Cardboard I/O 2015',
  37800. fov: 60,
  37801. interLensDistance: 0.064,
  37802. baselineLensDistance: 0.035,
  37803. screenLensDistance: 0.039,
  37804. distortionCoefficients: [0.34, 0.55],
  37805. inverseCoefficients: [-0.33836704, -0.18162185, 0.862655, -1.2462051,
  37806. 1.0560602, -0.58208317, 0.21609078, -0.05444823, 0.009177956,
  37807. -9.904169E-4, 6.183535E-5, -1.6981803E-6]
  37808. })
  37809. };
  37810. var DEFAULT_LEFT_CENTER = {x: 0.5, y: 0.5};
  37811. var DEFAULT_RIGHT_CENTER = {x: 0.5, y: 0.5};
  37812. /**
  37813. * Manages information about the device and the viewer.
  37814. *
  37815. * deviceParams indicates the parameters of the device to use (generally
  37816. * obtained from dpdb.getDeviceParams()). Can be null to mean no device
  37817. * params were found.
  37818. */
  37819. function DeviceInfo(deviceParams) {
  37820. this.viewer = Viewers.CardboardV2;
  37821. this.updateDeviceParams(deviceParams);
  37822. this.distortion = new Distortion(this.viewer.distortionCoefficients);
  37823. }
  37824. DeviceInfo.prototype.updateDeviceParams = function(deviceParams) {
  37825. this.device = this.determineDevice_(deviceParams) || this.device;
  37826. };
  37827. DeviceInfo.prototype.getDevice = function() {
  37828. return this.device;
  37829. };
  37830. DeviceInfo.prototype.setViewer = function(viewer) {
  37831. this.viewer = viewer;
  37832. this.distortion = new Distortion(this.viewer.distortionCoefficients);
  37833. };
  37834. DeviceInfo.prototype.determineDevice_ = function(deviceParams) {
  37835. if (!deviceParams) {
  37836. // No parameters, so use a default.
  37837. if (Util.isIOS()) {
  37838. console.warn('Using fallback iOS device measurements.');
  37839. return DEFAULT_IOS;
  37840. } else {
  37841. console.warn('Using fallback Android device measurements.');
  37842. return DEFAULT_ANDROID;
  37843. }
  37844. }
  37845. // Compute device screen dimensions based on deviceParams.
  37846. var METERS_PER_INCH = 0.0254;
  37847. var metersPerPixelX = METERS_PER_INCH / deviceParams.xdpi;
  37848. var metersPerPixelY = METERS_PER_INCH / deviceParams.ydpi;
  37849. var width = Util.getScreenWidth();
  37850. var height = Util.getScreenHeight();
  37851. return new Device({
  37852. widthMeters: metersPerPixelX * width,
  37853. heightMeters: metersPerPixelY * height,
  37854. bevelMeters: deviceParams.bevelMm * 0.001,
  37855. });
  37856. };
  37857. /**
  37858. * Calculates field of view for the left eye.
  37859. */
  37860. DeviceInfo.prototype.getDistortedFieldOfViewLeftEye = function() {
  37861. var viewer = this.viewer;
  37862. var device = this.device;
  37863. var distortion = this.distortion;
  37864. // Device.height and device.width for device in portrait mode, so transpose.
  37865. var eyeToScreenDistance = viewer.screenLensDistance;
  37866. var outerDist = (device.widthMeters - viewer.interLensDistance) / 2;
  37867. var innerDist = viewer.interLensDistance / 2;
  37868. var bottomDist = viewer.baselineLensDistance - device.bevelMeters;
  37869. var topDist = device.heightMeters - bottomDist;
  37870. var outerAngle = MathUtil.radToDeg * Math.atan(
  37871. distortion.distort(outerDist / eyeToScreenDistance));
  37872. var innerAngle = MathUtil.radToDeg * Math.atan(
  37873. distortion.distort(innerDist / eyeToScreenDistance));
  37874. var bottomAngle = MathUtil.radToDeg * Math.atan(
  37875. distortion.distort(bottomDist / eyeToScreenDistance));
  37876. var topAngle = MathUtil.radToDeg * Math.atan(
  37877. distortion.distort(topDist / eyeToScreenDistance));
  37878. return {
  37879. leftDegrees: Math.min(outerAngle, viewer.fov),
  37880. rightDegrees: Math.min(innerAngle, viewer.fov),
  37881. downDegrees: Math.min(bottomAngle, viewer.fov),
  37882. upDegrees: Math.min(topAngle, viewer.fov)
  37883. };
  37884. };
  37885. /**
  37886. * Calculates the tan-angles from the maximum FOV for the left eye for the
  37887. * current device and screen parameters.
  37888. */
  37889. DeviceInfo.prototype.getLeftEyeVisibleTanAngles = function() {
  37890. var viewer = this.viewer;
  37891. var device = this.device;
  37892. var distortion = this.distortion;
  37893. // Tan-angles from the max FOV.
  37894. var fovLeft = Math.tan(-MathUtil.degToRad * viewer.fov);
  37895. var fovTop = Math.tan(MathUtil.degToRad * viewer.fov);
  37896. var fovRight = Math.tan(MathUtil.degToRad * viewer.fov);
  37897. var fovBottom = Math.tan(-MathUtil.degToRad * viewer.fov);
  37898. // Viewport size.
  37899. var halfWidth = device.widthMeters / 4;
  37900. var halfHeight = device.heightMeters / 2;
  37901. // Viewport center, measured from left lens position.
  37902. var verticalLensOffset = (viewer.baselineLensDistance - device.bevelMeters - halfHeight);
  37903. var centerX = viewer.interLensDistance / 2 - halfWidth;
  37904. var centerY = -verticalLensOffset;
  37905. var centerZ = viewer.screenLensDistance;
  37906. // Tan-angles of the viewport edges, as seen through the lens.
  37907. var screenLeft = distortion.distort((centerX - halfWidth) / centerZ);
  37908. var screenTop = distortion.distort((centerY + halfHeight) / centerZ);
  37909. var screenRight = distortion.distort((centerX + halfWidth) / centerZ);
  37910. var screenBottom = distortion.distort((centerY - halfHeight) / centerZ);
  37911. // Compare the two sets of tan-angles and take the value closer to zero on each side.
  37912. var result = new Float32Array(4);
  37913. result[0] = Math.max(fovLeft, screenLeft);
  37914. result[1] = Math.min(fovTop, screenTop);
  37915. result[2] = Math.min(fovRight, screenRight);
  37916. result[3] = Math.max(fovBottom, screenBottom);
  37917. return result;
  37918. };
  37919. /**
  37920. * Calculates the tan-angles from the maximum FOV for the left eye for the
  37921. * current device and screen parameters, assuming no lenses.
  37922. */
  37923. DeviceInfo.prototype.getLeftEyeNoLensTanAngles = function() {
  37924. var viewer = this.viewer;
  37925. var device = this.device;
  37926. var distortion = this.distortion;
  37927. var result = new Float32Array(4);
  37928. // Tan-angles from the max FOV.
  37929. var fovLeft = distortion.distortInverse(Math.tan(-MathUtil.degToRad * viewer.fov));
  37930. var fovTop = distortion.distortInverse(Math.tan(MathUtil.degToRad * viewer.fov));
  37931. var fovRight = distortion.distortInverse(Math.tan(MathUtil.degToRad * viewer.fov));
  37932. var fovBottom = distortion.distortInverse(Math.tan(-MathUtil.degToRad * viewer.fov));
  37933. // Viewport size.
  37934. var halfWidth = device.widthMeters / 4;
  37935. var halfHeight = device.heightMeters / 2;
  37936. // Viewport center, measured from left lens position.
  37937. var verticalLensOffset = (viewer.baselineLensDistance - device.bevelMeters - halfHeight);
  37938. var centerX = viewer.interLensDistance / 2 - halfWidth;
  37939. var centerY = -verticalLensOffset;
  37940. var centerZ = viewer.screenLensDistance;
  37941. // Tan-angles of the viewport edges, as seen through the lens.
  37942. var screenLeft = (centerX - halfWidth) / centerZ;
  37943. var screenTop = (centerY + halfHeight) / centerZ;
  37944. var screenRight = (centerX + halfWidth) / centerZ;
  37945. var screenBottom = (centerY - halfHeight) / centerZ;
  37946. // Compare the two sets of tan-angles and take the value closer to zero on each side.
  37947. result[0] = Math.max(fovLeft, screenLeft);
  37948. result[1] = Math.min(fovTop, screenTop);
  37949. result[2] = Math.min(fovRight, screenRight);
  37950. result[3] = Math.max(fovBottom, screenBottom);
  37951. return result;
  37952. };
  37953. /**
  37954. * Calculates the screen rectangle visible from the left eye for the
  37955. * current device and screen parameters.
  37956. */
  37957. DeviceInfo.prototype.getLeftEyeVisibleScreenRect = function(undistortedFrustum) {
  37958. var viewer = this.viewer;
  37959. var device = this.device;
  37960. var dist = viewer.screenLensDistance;
  37961. var eyeX = (device.widthMeters - viewer.interLensDistance) / 2;
  37962. var eyeY = viewer.baselineLensDistance - device.bevelMeters;
  37963. var left = (undistortedFrustum[0] * dist + eyeX) / device.widthMeters;
  37964. var top = (undistortedFrustum[1] * dist + eyeY) / device.heightMeters;
  37965. var right = (undistortedFrustum[2] * dist + eyeX) / device.widthMeters;
  37966. var bottom = (undistortedFrustum[3] * dist + eyeY) / device.heightMeters;
  37967. return {
  37968. x: left,
  37969. y: bottom,
  37970. width: right - left,
  37971. height: top - bottom
  37972. };
  37973. };
  37974. DeviceInfo.prototype.getFieldOfViewLeftEye = function(opt_isUndistorted) {
  37975. return opt_isUndistorted ? this.getUndistortedFieldOfViewLeftEye() :
  37976. this.getDistortedFieldOfViewLeftEye();
  37977. };
  37978. DeviceInfo.prototype.getFieldOfViewRightEye = function(opt_isUndistorted) {
  37979. var fov = this.getFieldOfViewLeftEye(opt_isUndistorted);
  37980. return {
  37981. leftDegrees: fov.rightDegrees,
  37982. rightDegrees: fov.leftDegrees,
  37983. upDegrees: fov.upDegrees,
  37984. downDegrees: fov.downDegrees
  37985. };
  37986. };
  37987. /**
  37988. * Calculates undistorted field of view for the left eye.
  37989. */
  37990. DeviceInfo.prototype.getUndistortedFieldOfViewLeftEye = function() {
  37991. var p = this.getUndistortedParams_();
  37992. return {
  37993. leftDegrees: MathUtil.radToDeg * Math.atan(p.outerDist),
  37994. rightDegrees: MathUtil.radToDeg * Math.atan(p.innerDist),
  37995. downDegrees: MathUtil.radToDeg * Math.atan(p.bottomDist),
  37996. upDegrees: MathUtil.radToDeg * Math.atan(p.topDist)
  37997. };
  37998. };
  37999. DeviceInfo.prototype.getUndistortedViewportLeftEye = function() {
  38000. var p = this.getUndistortedParams_();
  38001. var viewer = this.viewer;
  38002. var device = this.device;
  38003. // Distances stored in local variables are in tan-angle units unless otherwise
  38004. // noted.
  38005. var eyeToScreenDistance = viewer.screenLensDistance;
  38006. var screenWidth = device.widthMeters / eyeToScreenDistance;
  38007. var screenHeight = device.heightMeters / eyeToScreenDistance;
  38008. var xPxPerTanAngle = device.width / screenWidth;
  38009. var yPxPerTanAngle = device.height / screenHeight;
  38010. var x = Math.round((p.eyePosX - p.outerDist) * xPxPerTanAngle);
  38011. var y = Math.round((p.eyePosY - p.bottomDist) * yPxPerTanAngle);
  38012. return {
  38013. x: x,
  38014. y: y,
  38015. width: Math.round((p.eyePosX + p.innerDist) * xPxPerTanAngle) - x,
  38016. height: Math.round((p.eyePosY + p.topDist) * yPxPerTanAngle) - y
  38017. };
  38018. };
  38019. DeviceInfo.prototype.getUndistortedParams_ = function() {
  38020. var viewer = this.viewer;
  38021. var device = this.device;
  38022. var distortion = this.distortion;
  38023. // Most of these variables in tan-angle units.
  38024. var eyeToScreenDistance = viewer.screenLensDistance;
  38025. var halfLensDistance = viewer.interLensDistance / 2 / eyeToScreenDistance;
  38026. var screenWidth = device.widthMeters / eyeToScreenDistance;
  38027. var screenHeight = device.heightMeters / eyeToScreenDistance;
  38028. var eyePosX = screenWidth / 2 - halfLensDistance;
  38029. var eyePosY = (viewer.baselineLensDistance - device.bevelMeters) / eyeToScreenDistance;
  38030. var maxFov = viewer.fov;
  38031. var viewerMax = distortion.distortInverse(Math.tan(MathUtil.degToRad * maxFov));
  38032. var outerDist = Math.min(eyePosX, viewerMax);
  38033. var innerDist = Math.min(halfLensDistance, viewerMax);
  38034. var bottomDist = Math.min(eyePosY, viewerMax);
  38035. var topDist = Math.min(screenHeight - eyePosY, viewerMax);
  38036. return {
  38037. outerDist: outerDist,
  38038. innerDist: innerDist,
  38039. topDist: topDist,
  38040. bottomDist: bottomDist,
  38041. eyePosX: eyePosX,
  38042. eyePosY: eyePosY
  38043. };
  38044. };
  38045. function CardboardViewer(params) {
  38046. // A machine readable ID.
  38047. this.id = params.id;
  38048. // A human readable label.
  38049. this.label = params.label;
  38050. // Field of view in degrees (per side).
  38051. this.fov = params.fov;
  38052. // Distance between lens centers in meters.
  38053. this.interLensDistance = params.interLensDistance;
  38054. // Distance between viewer baseline and lens center in meters.
  38055. this.baselineLensDistance = params.baselineLensDistance;
  38056. // Screen-to-lens distance in meters.
  38057. this.screenLensDistance = params.screenLensDistance;
  38058. // Distortion coefficients.
  38059. this.distortionCoefficients = params.distortionCoefficients;
  38060. // Inverse distortion coefficients.
  38061. // TODO: Calculate these from distortionCoefficients in the future.
  38062. this.inverseCoefficients = params.inverseCoefficients;
  38063. }
  38064. // Export viewer information.
  38065. DeviceInfo.Viewers = Viewers;
  38066. module.exports = DeviceInfo;
  38067. },{"./distortion/distortion.js":56,"./math-util.js":60,"./util.js":69}],55:[function(_dereq_,module,exports){
  38068. /*
  38069. * Copyright 2016 Google Inc. All Rights Reserved.
  38070. * Licensed under the Apache License, Version 2.0 (the "License");
  38071. * you may not use this file except in compliance with the License.
  38072. * You may obtain a copy of the License at
  38073. *
  38074. * http://www.apache.org/licenses/LICENSE-2.0
  38075. *
  38076. * Unless required by applicable law or agreed to in writing, software
  38077. * distributed under the License is distributed on an "AS IS" BASIS,
  38078. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  38079. * See the License for the specific language governing permissions and
  38080. * limitations under the License.
  38081. */
  38082. var VRDisplay = _dereq_('./base.js').VRDisplay;
  38083. var HMDVRDevice = _dereq_('./base.js').HMDVRDevice;
  38084. var PositionSensorVRDevice = _dereq_('./base.js').PositionSensorVRDevice;
  38085. /**
  38086. * Wraps a VRDisplay and exposes it as a HMDVRDevice
  38087. */
  38088. function VRDisplayHMDDevice(display) {
  38089. this.display = display;
  38090. this.hardwareUnitId = display.displayId;
  38091. this.deviceId = 'webvr-polyfill:HMD:' + display.displayId;
  38092. this.deviceName = display.displayName + ' (HMD)';
  38093. }
  38094. VRDisplayHMDDevice.prototype = new HMDVRDevice();
  38095. VRDisplayHMDDevice.prototype.getEyeParameters = function(whichEye) {
  38096. var eyeParameters = this.display.getEyeParameters(whichEye);
  38097. return {
  38098. currentFieldOfView: eyeParameters.fieldOfView,
  38099. maximumFieldOfView: eyeParameters.fieldOfView,
  38100. minimumFieldOfView: eyeParameters.fieldOfView,
  38101. recommendedFieldOfView: eyeParameters.fieldOfView,
  38102. eyeTranslation: { x: eyeParameters.offset[0], y: eyeParameters.offset[1], z: eyeParameters.offset[2] },
  38103. renderRect: {
  38104. x: (whichEye == 'right') ? eyeParameters.renderWidth : 0,
  38105. y: 0,
  38106. width: eyeParameters.renderWidth,
  38107. height: eyeParameters.renderHeight
  38108. }
  38109. };
  38110. };
  38111. VRDisplayHMDDevice.prototype.setFieldOfView =
  38112. function(opt_fovLeft, opt_fovRight, opt_zNear, opt_zFar) {
  38113. // Not supported. getEyeParameters reports that the min, max, and recommended
  38114. // FoV is all the same, so no adjustment can be made.
  38115. };
  38116. // TODO: Need to hook requestFullscreen to see if a wrapped VRDisplay was passed
  38117. // in as an option. If so we should prevent the default fullscreen behavior and
  38118. // call VRDisplay.requestPresent instead.
  38119. /**
  38120. * Wraps a VRDisplay and exposes it as a PositionSensorVRDevice
  38121. */
  38122. function VRDisplayPositionSensorDevice(display) {
  38123. this.display = display;
  38124. this.hardwareUnitId = display.displayId;
  38125. this.deviceId = 'webvr-polyfill:PositionSensor: ' + display.displayId;
  38126. this.deviceName = display.displayName + ' (PositionSensor)';
  38127. }
  38128. VRDisplayPositionSensorDevice.prototype = new PositionSensorVRDevice();
  38129. VRDisplayPositionSensorDevice.prototype.getState = function() {
  38130. var pose = this.display.getPose();
  38131. return {
  38132. position: pose.position ? { x: pose.position[0], y: pose.position[1], z: pose.position[2] } : null,
  38133. orientation: pose.orientation ? { x: pose.orientation[0], y: pose.orientation[1], z: pose.orientation[2], w: pose.orientation[3] } : null,
  38134. linearVelocity: null,
  38135. linearAcceleration: null,
  38136. angularVelocity: null,
  38137. angularAcceleration: null
  38138. };
  38139. };
  38140. VRDisplayPositionSensorDevice.prototype.resetState = function() {
  38141. return this.positionDevice.resetPose();
  38142. };
  38143. module.exports.VRDisplayHMDDevice = VRDisplayHMDDevice;
  38144. module.exports.VRDisplayPositionSensorDevice = VRDisplayPositionSensorDevice;
  38145. },{"./base.js":49}],56:[function(_dereq_,module,exports){
  38146. /**
  38147. * TODO(smus): Implement coefficient inversion.
  38148. */
  38149. function Distortion(coefficients) {
  38150. this.coefficients = coefficients;
  38151. }
  38152. /**
  38153. * Calculates the inverse distortion for a radius.
  38154. * </p><p>
  38155. * Allows to compute the original undistorted radius from a distorted one.
  38156. * See also getApproximateInverseDistortion() for a faster but potentially
  38157. * less accurate method.
  38158. *
  38159. * @param {Number} radius Distorted radius from the lens center in tan-angle units.
  38160. * @return {Number} The undistorted radius in tan-angle units.
  38161. */
  38162. Distortion.prototype.distortInverse = function(radius) {
  38163. // Secant method.
  38164. var r0 = 0;
  38165. var r1 = 1;
  38166. var dr0 = radius - this.distort(r0);
  38167. while (Math.abs(r1 - r0) > 0.0001 /** 0.1mm */) {
  38168. var dr1 = radius - this.distort(r1);
  38169. var r2 = r1 - dr1 * ((r1 - r0) / (dr1 - dr0));
  38170. r0 = r1;
  38171. r1 = r2;
  38172. dr0 = dr1;
  38173. }
  38174. return r1;
  38175. };
  38176. /**
  38177. * Distorts a radius by its distortion factor from the center of the lenses.
  38178. *
  38179. * @param {Number} radius Radius from the lens center in tan-angle units.
  38180. * @return {Number} The distorted radius in tan-angle units.
  38181. */
  38182. Distortion.prototype.distort = function(radius) {
  38183. var r2 = radius * radius;
  38184. var ret = 0;
  38185. for (var i = 0; i < this.coefficients.length; i++) {
  38186. ret = r2 * (ret + this.coefficients[i]);
  38187. }
  38188. return (ret + 1) * radius;
  38189. };
  38190. module.exports = Distortion;
  38191. },{}],57:[function(_dereq_,module,exports){
  38192. module.exports={
  38193. "format": 1,
  38194. "last_updated": "2017-06-01T22:33:42Z",
  38195. "devices": [
  38196. {
  38197. "type": "android",
  38198. "rules": [
  38199. {
  38200. "mdmh": "asus/*/Nexus 7/*"
  38201. },
  38202. {
  38203. "ua": "Nexus 7"
  38204. }
  38205. ],
  38206. "dpi": [
  38207. 320.8,
  38208. 323
  38209. ],
  38210. "bw": 3,
  38211. "ac": 500
  38212. },
  38213. {
  38214. "type": "android",
  38215. "rules": [
  38216. {
  38217. "mdmh": "asus/*/ASUS_Z00AD/*"
  38218. },
  38219. {
  38220. "ua": "ASUS_Z00AD"
  38221. }
  38222. ],
  38223. "dpi": [
  38224. 403,
  38225. 404.6
  38226. ],
  38227. "bw": 3,
  38228. "ac": 1000
  38229. },
  38230. {
  38231. "type": "android",
  38232. "rules": [
  38233. {
  38234. "mdmh": "Google/*/Pixel XL/*"
  38235. },
  38236. {
  38237. "ua": "Pixel XL"
  38238. }
  38239. ],
  38240. "dpi": [
  38241. 537.9,
  38242. 533
  38243. ],
  38244. "bw": 3,
  38245. "ac": 1000
  38246. },
  38247. {
  38248. "type": "android",
  38249. "rules": [
  38250. {
  38251. "mdmh": "Google/*/Pixel/*"
  38252. },
  38253. {
  38254. "ua": "Pixel"
  38255. }
  38256. ],
  38257. "dpi": [
  38258. 432.6,
  38259. 436.7
  38260. ],
  38261. "bw": 3,
  38262. "ac": 1000
  38263. },
  38264. {
  38265. "type": "android",
  38266. "rules": [
  38267. {
  38268. "mdmh": "HTC/*/HTC6435LVW/*"
  38269. },
  38270. {
  38271. "ua": "HTC6435LVW"
  38272. }
  38273. ],
  38274. "dpi": [
  38275. 449.7,
  38276. 443.3
  38277. ],
  38278. "bw": 3,
  38279. "ac": 1000
  38280. },
  38281. {
  38282. "type": "android",
  38283. "rules": [
  38284. {
  38285. "mdmh": "HTC/*/HTC One XL/*"
  38286. },
  38287. {
  38288. "ua": "HTC One XL"
  38289. }
  38290. ],
  38291. "dpi": [
  38292. 315.3,
  38293. 314.6
  38294. ],
  38295. "bw": 3,
  38296. "ac": 1000
  38297. },
  38298. {
  38299. "type": "android",
  38300. "rules": [
  38301. {
  38302. "mdmh": "htc/*/Nexus 9/*"
  38303. },
  38304. {
  38305. "ua": "Nexus 9"
  38306. }
  38307. ],
  38308. "dpi": 289,
  38309. "bw": 3,
  38310. "ac": 500
  38311. },
  38312. {
  38313. "type": "android",
  38314. "rules": [
  38315. {
  38316. "mdmh": "HTC/*/HTC One M9/*"
  38317. },
  38318. {
  38319. "ua": "HTC One M9"
  38320. }
  38321. ],
  38322. "dpi": [
  38323. 442.5,
  38324. 443.3
  38325. ],
  38326. "bw": 3,
  38327. "ac": 500
  38328. },
  38329. {
  38330. "type": "android",
  38331. "rules": [
  38332. {
  38333. "mdmh": "HTC/*/HTC One_M8/*"
  38334. },
  38335. {
  38336. "ua": "HTC One_M8"
  38337. }
  38338. ],
  38339. "dpi": [
  38340. 449.7,
  38341. 447.4
  38342. ],
  38343. "bw": 3,
  38344. "ac": 500
  38345. },
  38346. {
  38347. "type": "android",
  38348. "rules": [
  38349. {
  38350. "mdmh": "HTC/*/HTC One/*"
  38351. },
  38352. {
  38353. "ua": "HTC One"
  38354. }
  38355. ],
  38356. "dpi": 472.8,
  38357. "bw": 3,
  38358. "ac": 1000
  38359. },
  38360. {
  38361. "type": "android",
  38362. "rules": [
  38363. {
  38364. "mdmh": "Huawei/*/Nexus 6P/*"
  38365. },
  38366. {
  38367. "ua": "Nexus 6P"
  38368. }
  38369. ],
  38370. "dpi": [
  38371. 515.1,
  38372. 518
  38373. ],
  38374. "bw": 3,
  38375. "ac": 1000
  38376. },
  38377. {
  38378. "type": "android",
  38379. "rules": [
  38380. {
  38381. "mdmh": "LGE/*/Nexus 5X/*"
  38382. },
  38383. {
  38384. "ua": "Nexus 5X"
  38385. }
  38386. ],
  38387. "dpi": [
  38388. 422,
  38389. 419.9
  38390. ],
  38391. "bw": 3,
  38392. "ac": 1000
  38393. },
  38394. {
  38395. "type": "android",
  38396. "rules": [
  38397. {
  38398. "mdmh": "LGE/*/LGMS345/*"
  38399. },
  38400. {
  38401. "ua": "LGMS345"
  38402. }
  38403. ],
  38404. "dpi": [
  38405. 221.7,
  38406. 219.1
  38407. ],
  38408. "bw": 3,
  38409. "ac": 500
  38410. },
  38411. {
  38412. "type": "android",
  38413. "rules": [
  38414. {
  38415. "mdmh": "LGE/*/LG-D800/*"
  38416. },
  38417. {
  38418. "ua": "LG-D800"
  38419. }
  38420. ],
  38421. "dpi": [
  38422. 422,
  38423. 424.1
  38424. ],
  38425. "bw": 3,
  38426. "ac": 500
  38427. },
  38428. {
  38429. "type": "android",
  38430. "rules": [
  38431. {
  38432. "mdmh": "LGE/*/LG-D850/*"
  38433. },
  38434. {
  38435. "ua": "LG-D850"
  38436. }
  38437. ],
  38438. "dpi": [
  38439. 537.9,
  38440. 541.9
  38441. ],
  38442. "bw": 3,
  38443. "ac": 500
  38444. },
  38445. {
  38446. "type": "android",
  38447. "rules": [
  38448. {
  38449. "mdmh": "LGE/*/VS985 4G/*"
  38450. },
  38451. {
  38452. "ua": "VS985 4G"
  38453. }
  38454. ],
  38455. "dpi": [
  38456. 537.9,
  38457. 535.6
  38458. ],
  38459. "bw": 3,
  38460. "ac": 1000
  38461. },
  38462. {
  38463. "type": "android",
  38464. "rules": [
  38465. {
  38466. "mdmh": "LGE/*/Nexus 5/*"
  38467. },
  38468. {
  38469. "ua": "Nexus 5 B"
  38470. }
  38471. ],
  38472. "dpi": [
  38473. 442.4,
  38474. 444.8
  38475. ],
  38476. "bw": 3,
  38477. "ac": 1000
  38478. },
  38479. {
  38480. "type": "android",
  38481. "rules": [
  38482. {
  38483. "mdmh": "LGE/*/Nexus 4/*"
  38484. },
  38485. {
  38486. "ua": "Nexus 4"
  38487. }
  38488. ],
  38489. "dpi": [
  38490. 319.8,
  38491. 318.4
  38492. ],
  38493. "bw": 3,
  38494. "ac": 1000
  38495. },
  38496. {
  38497. "type": "android",
  38498. "rules": [
  38499. {
  38500. "mdmh": "LGE/*/LG-P769/*"
  38501. },
  38502. {
  38503. "ua": "LG-P769"
  38504. }
  38505. ],
  38506. "dpi": [
  38507. 240.6,
  38508. 247.5
  38509. ],
  38510. "bw": 3,
  38511. "ac": 1000
  38512. },
  38513. {
  38514. "type": "android",
  38515. "rules": [
  38516. {
  38517. "mdmh": "LGE/*/LGMS323/*"
  38518. },
  38519. {
  38520. "ua": "LGMS323"
  38521. }
  38522. ],
  38523. "dpi": [
  38524. 206.6,
  38525. 204.6
  38526. ],
  38527. "bw": 3,
  38528. "ac": 1000
  38529. },
  38530. {
  38531. "type": "android",
  38532. "rules": [
  38533. {
  38534. "mdmh": "LGE/*/LGLS996/*"
  38535. },
  38536. {
  38537. "ua": "LGLS996"
  38538. }
  38539. ],
  38540. "dpi": [
  38541. 403.4,
  38542. 401.5
  38543. ],
  38544. "bw": 3,
  38545. "ac": 1000
  38546. },
  38547. {
  38548. "type": "android",
  38549. "rules": [
  38550. {
  38551. "mdmh": "Micromax/*/4560MMX/*"
  38552. },
  38553. {
  38554. "ua": "4560MMX"
  38555. }
  38556. ],
  38557. "dpi": [
  38558. 240,
  38559. 219.4
  38560. ],
  38561. "bw": 3,
  38562. "ac": 1000
  38563. },
  38564. {
  38565. "type": "android",
  38566. "rules": [
  38567. {
  38568. "mdmh": "Micromax/*/A250/*"
  38569. },
  38570. {
  38571. "ua": "Micromax A250"
  38572. }
  38573. ],
  38574. "dpi": [
  38575. 480,
  38576. 446.4
  38577. ],
  38578. "bw": 3,
  38579. "ac": 1000
  38580. },
  38581. {
  38582. "type": "android",
  38583. "rules": [
  38584. {
  38585. "mdmh": "Micromax/*/Micromax AQ4501/*"
  38586. },
  38587. {
  38588. "ua": "Micromax AQ4501"
  38589. }
  38590. ],
  38591. "dpi": 240,
  38592. "bw": 3,
  38593. "ac": 500
  38594. },
  38595. {
  38596. "type": "android",
  38597. "rules": [
  38598. {
  38599. "mdmh": "motorola/*/DROID RAZR/*"
  38600. },
  38601. {
  38602. "ua": "DROID RAZR"
  38603. }
  38604. ],
  38605. "dpi": [
  38606. 368.1,
  38607. 256.7
  38608. ],
  38609. "bw": 3,
  38610. "ac": 1000
  38611. },
  38612. {
  38613. "type": "android",
  38614. "rules": [
  38615. {
  38616. "mdmh": "motorola/*/XT830C/*"
  38617. },
  38618. {
  38619. "ua": "XT830C"
  38620. }
  38621. ],
  38622. "dpi": [
  38623. 254,
  38624. 255.9
  38625. ],
  38626. "bw": 3,
  38627. "ac": 1000
  38628. },
  38629. {
  38630. "type": "android",
  38631. "rules": [
  38632. {
  38633. "mdmh": "motorola/*/XT1021/*"
  38634. },
  38635. {
  38636. "ua": "XT1021"
  38637. }
  38638. ],
  38639. "dpi": [
  38640. 254,
  38641. 256.7
  38642. ],
  38643. "bw": 3,
  38644. "ac": 500
  38645. },
  38646. {
  38647. "type": "android",
  38648. "rules": [
  38649. {
  38650. "mdmh": "motorola/*/XT1023/*"
  38651. },
  38652. {
  38653. "ua": "XT1023"
  38654. }
  38655. ],
  38656. "dpi": [
  38657. 254,
  38658. 256.7
  38659. ],
  38660. "bw": 3,
  38661. "ac": 500
  38662. },
  38663. {
  38664. "type": "android",
  38665. "rules": [
  38666. {
  38667. "mdmh": "motorola/*/XT1028/*"
  38668. },
  38669. {
  38670. "ua": "XT1028"
  38671. }
  38672. ],
  38673. "dpi": [
  38674. 326.6,
  38675. 327.6
  38676. ],
  38677. "bw": 3,
  38678. "ac": 1000
  38679. },
  38680. {
  38681. "type": "android",
  38682. "rules": [
  38683. {
  38684. "mdmh": "motorola/*/XT1034/*"
  38685. },
  38686. {
  38687. "ua": "XT1034"
  38688. }
  38689. ],
  38690. "dpi": [
  38691. 326.6,
  38692. 328.4
  38693. ],
  38694. "bw": 3,
  38695. "ac": 500
  38696. },
  38697. {
  38698. "type": "android",
  38699. "rules": [
  38700. {
  38701. "mdmh": "motorola/*/XT1053/*"
  38702. },
  38703. {
  38704. "ua": "XT1053"
  38705. }
  38706. ],
  38707. "dpi": [
  38708. 315.3,
  38709. 316.1
  38710. ],
  38711. "bw": 3,
  38712. "ac": 1000
  38713. },
  38714. {
  38715. "type": "android",
  38716. "rules": [
  38717. {
  38718. "mdmh": "motorola/*/XT1562/*"
  38719. },
  38720. {
  38721. "ua": "XT1562"
  38722. }
  38723. ],
  38724. "dpi": [
  38725. 403.4,
  38726. 402.7
  38727. ],
  38728. "bw": 3,
  38729. "ac": 1000
  38730. },
  38731. {
  38732. "type": "android",
  38733. "rules": [
  38734. {
  38735. "mdmh": "motorola/*/Nexus 6/*"
  38736. },
  38737. {
  38738. "ua": "Nexus 6 B"
  38739. }
  38740. ],
  38741. "dpi": [
  38742. 494.3,
  38743. 489.7
  38744. ],
  38745. "bw": 3,
  38746. "ac": 1000
  38747. },
  38748. {
  38749. "type": "android",
  38750. "rules": [
  38751. {
  38752. "mdmh": "motorola/*/XT1063/*"
  38753. },
  38754. {
  38755. "ua": "XT1063"
  38756. }
  38757. ],
  38758. "dpi": [
  38759. 295,
  38760. 296.6
  38761. ],
  38762. "bw": 3,
  38763. "ac": 1000
  38764. },
  38765. {
  38766. "type": "android",
  38767. "rules": [
  38768. {
  38769. "mdmh": "motorola/*/XT1064/*"
  38770. },
  38771. {
  38772. "ua": "XT1064"
  38773. }
  38774. ],
  38775. "dpi": [
  38776. 295,
  38777. 295.6
  38778. ],
  38779. "bw": 3,
  38780. "ac": 500
  38781. },
  38782. {
  38783. "type": "android",
  38784. "rules": [
  38785. {
  38786. "mdmh": "motorola/*/XT1092/*"
  38787. },
  38788. {
  38789. "ua": "XT1092"
  38790. }
  38791. ],
  38792. "dpi": [
  38793. 422,
  38794. 424.1
  38795. ],
  38796. "bw": 3,
  38797. "ac": 500
  38798. },
  38799. {
  38800. "type": "android",
  38801. "rules": [
  38802. {
  38803. "mdmh": "motorola/*/XT1095/*"
  38804. },
  38805. {
  38806. "ua": "XT1095"
  38807. }
  38808. ],
  38809. "dpi": [
  38810. 422,
  38811. 423.4
  38812. ],
  38813. "bw": 3,
  38814. "ac": 1000
  38815. },
  38816. {
  38817. "type": "android",
  38818. "rules": [
  38819. {
  38820. "mdmh": "motorola/*/G4/*"
  38821. },
  38822. {
  38823. "ua": "Moto G (4)"
  38824. }
  38825. ],
  38826. "dpi": 401,
  38827. "bw": 4,
  38828. "ac": 1000
  38829. },
  38830. {
  38831. "type": "android",
  38832. "rules": [
  38833. {
  38834. "mdmh": "OnePlus/*/A0001/*"
  38835. },
  38836. {
  38837. "ua": "A0001"
  38838. }
  38839. ],
  38840. "dpi": [
  38841. 403.4,
  38842. 401
  38843. ],
  38844. "bw": 3,
  38845. "ac": 1000
  38846. },
  38847. {
  38848. "type": "android",
  38849. "rules": [
  38850. {
  38851. "mdmh": "OnePlus/*/ONE E1005/*"
  38852. },
  38853. {
  38854. "ua": "ONE E1005"
  38855. }
  38856. ],
  38857. "dpi": [
  38858. 442.4,
  38859. 441.4
  38860. ],
  38861. "bw": 3,
  38862. "ac": 1000
  38863. },
  38864. {
  38865. "type": "android",
  38866. "rules": [
  38867. {
  38868. "mdmh": "OnePlus/*/ONE A2005/*"
  38869. },
  38870. {
  38871. "ua": "ONE A2005"
  38872. }
  38873. ],
  38874. "dpi": [
  38875. 391.9,
  38876. 405.4
  38877. ],
  38878. "bw": 3,
  38879. "ac": 1000
  38880. },
  38881. {
  38882. "type": "android",
  38883. "rules": [
  38884. {
  38885. "mdmh": "OPPO/*/X909/*"
  38886. },
  38887. {
  38888. "ua": "X909"
  38889. }
  38890. ],
  38891. "dpi": [
  38892. 442.4,
  38893. 444.1
  38894. ],
  38895. "bw": 3,
  38896. "ac": 1000
  38897. },
  38898. {
  38899. "type": "android",
  38900. "rules": [
  38901. {
  38902. "mdmh": "samsung/*/GT-I9082/*"
  38903. },
  38904. {
  38905. "ua": "GT-I9082"
  38906. }
  38907. ],
  38908. "dpi": [
  38909. 184.7,
  38910. 185.4
  38911. ],
  38912. "bw": 3,
  38913. "ac": 1000
  38914. },
  38915. {
  38916. "type": "android",
  38917. "rules": [
  38918. {
  38919. "mdmh": "samsung/*/SM-G360P/*"
  38920. },
  38921. {
  38922. "ua": "SM-G360P"
  38923. }
  38924. ],
  38925. "dpi": [
  38926. 196.7,
  38927. 205.4
  38928. ],
  38929. "bw": 3,
  38930. "ac": 1000
  38931. },
  38932. {
  38933. "type": "android",
  38934. "rules": [
  38935. {
  38936. "mdmh": "samsung/*/Nexus S/*"
  38937. },
  38938. {
  38939. "ua": "Nexus S"
  38940. }
  38941. ],
  38942. "dpi": [
  38943. 234.5,
  38944. 229.8
  38945. ],
  38946. "bw": 3,
  38947. "ac": 1000
  38948. },
  38949. {
  38950. "type": "android",
  38951. "rules": [
  38952. {
  38953. "mdmh": "samsung/*/GT-I9300/*"
  38954. },
  38955. {
  38956. "ua": "GT-I9300"
  38957. }
  38958. ],
  38959. "dpi": [
  38960. 304.8,
  38961. 303.9
  38962. ],
  38963. "bw": 5,
  38964. "ac": 500
  38965. },
  38966. {
  38967. "type": "android",
  38968. "rules": [
  38969. {
  38970. "mdmh": "samsung/*/SM-T230NU/*"
  38971. },
  38972. {
  38973. "ua": "SM-T230NU"
  38974. }
  38975. ],
  38976. "dpi": 216,
  38977. "bw": 3,
  38978. "ac": 500
  38979. },
  38980. {
  38981. "type": "android",
  38982. "rules": [
  38983. {
  38984. "mdmh": "samsung/*/SGH-T399/*"
  38985. },
  38986. {
  38987. "ua": "SGH-T399"
  38988. }
  38989. ],
  38990. "dpi": [
  38991. 217.7,
  38992. 231.4
  38993. ],
  38994. "bw": 3,
  38995. "ac": 1000
  38996. },
  38997. {
  38998. "type": "android",
  38999. "rules": [
  39000. {
  39001. "mdmh": "samsung/*/SGH-M919/*"
  39002. },
  39003. {
  39004. "ua": "SGH-M919"
  39005. }
  39006. ],
  39007. "dpi": [
  39008. 440.8,
  39009. 437.7
  39010. ],
  39011. "bw": 3,
  39012. "ac": 1000
  39013. },
  39014. {
  39015. "type": "android",
  39016. "rules": [
  39017. {
  39018. "mdmh": "samsung/*/SM-N9005/*"
  39019. },
  39020. {
  39021. "ua": "SM-N9005"
  39022. }
  39023. ],
  39024. "dpi": [
  39025. 386.4,
  39026. 387
  39027. ],
  39028. "bw": 3,
  39029. "ac": 500
  39030. },
  39031. {
  39032. "type": "android",
  39033. "rules": [
  39034. {
  39035. "mdmh": "samsung/*/SAMSUNG-SM-N900A/*"
  39036. },
  39037. {
  39038. "ua": "SAMSUNG-SM-N900A"
  39039. }
  39040. ],
  39041. "dpi": [
  39042. 386.4,
  39043. 387.7
  39044. ],
  39045. "bw": 3,
  39046. "ac": 1000
  39047. },
  39048. {
  39049. "type": "android",
  39050. "rules": [
  39051. {
  39052. "mdmh": "samsung/*/GT-I9500/*"
  39053. },
  39054. {
  39055. "ua": "GT-I9500"
  39056. }
  39057. ],
  39058. "dpi": [
  39059. 442.5,
  39060. 443.3
  39061. ],
  39062. "bw": 3,
  39063. "ac": 500
  39064. },
  39065. {
  39066. "type": "android",
  39067. "rules": [
  39068. {
  39069. "mdmh": "samsung/*/GT-I9505/*"
  39070. },
  39071. {
  39072. "ua": "GT-I9505"
  39073. }
  39074. ],
  39075. "dpi": 439.4,
  39076. "bw": 4,
  39077. "ac": 1000
  39078. },
  39079. {
  39080. "type": "android",
  39081. "rules": [
  39082. {
  39083. "mdmh": "samsung/*/SM-G900F/*"
  39084. },
  39085. {
  39086. "ua": "SM-G900F"
  39087. }
  39088. ],
  39089. "dpi": [
  39090. 415.6,
  39091. 431.6
  39092. ],
  39093. "bw": 5,
  39094. "ac": 1000
  39095. },
  39096. {
  39097. "type": "android",
  39098. "rules": [
  39099. {
  39100. "mdmh": "samsung/*/SM-G900M/*"
  39101. },
  39102. {
  39103. "ua": "SM-G900M"
  39104. }
  39105. ],
  39106. "dpi": [
  39107. 415.6,
  39108. 431.6
  39109. ],
  39110. "bw": 5,
  39111. "ac": 1000
  39112. },
  39113. {
  39114. "type": "android",
  39115. "rules": [
  39116. {
  39117. "mdmh": "samsung/*/SM-G800F/*"
  39118. },
  39119. {
  39120. "ua": "SM-G800F"
  39121. }
  39122. ],
  39123. "dpi": 326.8,
  39124. "bw": 3,
  39125. "ac": 1000
  39126. },
  39127. {
  39128. "type": "android",
  39129. "rules": [
  39130. {
  39131. "mdmh": "samsung/*/SM-G906S/*"
  39132. },
  39133. {
  39134. "ua": "SM-G906S"
  39135. }
  39136. ],
  39137. "dpi": [
  39138. 562.7,
  39139. 572.4
  39140. ],
  39141. "bw": 3,
  39142. "ac": 1000
  39143. },
  39144. {
  39145. "type": "android",
  39146. "rules": [
  39147. {
  39148. "mdmh": "samsung/*/GT-I9300/*"
  39149. },
  39150. {
  39151. "ua": "GT-I9300"
  39152. }
  39153. ],
  39154. "dpi": [
  39155. 306.7,
  39156. 304.8
  39157. ],
  39158. "bw": 5,
  39159. "ac": 1000
  39160. },
  39161. {
  39162. "type": "android",
  39163. "rules": [
  39164. {
  39165. "mdmh": "samsung/*/SM-T535/*"
  39166. },
  39167. {
  39168. "ua": "SM-T535"
  39169. }
  39170. ],
  39171. "dpi": [
  39172. 142.6,
  39173. 136.4
  39174. ],
  39175. "bw": 3,
  39176. "ac": 500
  39177. },
  39178. {
  39179. "type": "android",
  39180. "rules": [
  39181. {
  39182. "mdmh": "samsung/*/SM-N920C/*"
  39183. },
  39184. {
  39185. "ua": "SM-N920C"
  39186. }
  39187. ],
  39188. "dpi": [
  39189. 515.1,
  39190. 518.4
  39191. ],
  39192. "bw": 3,
  39193. "ac": 1000
  39194. },
  39195. {
  39196. "type": "android",
  39197. "rules": [
  39198. {
  39199. "mdmh": "samsung/*/SM-N920W8/*"
  39200. },
  39201. {
  39202. "ua": "SM-N920W8"
  39203. }
  39204. ],
  39205. "dpi": [
  39206. 515.1,
  39207. 518.4
  39208. ],
  39209. "bw": 3,
  39210. "ac": 1000
  39211. },
  39212. {
  39213. "type": "android",
  39214. "rules": [
  39215. {
  39216. "mdmh": "samsung/*/GT-I9300I/*"
  39217. },
  39218. {
  39219. "ua": "GT-I9300I"
  39220. }
  39221. ],
  39222. "dpi": [
  39223. 304.8,
  39224. 305.8
  39225. ],
  39226. "bw": 3,
  39227. "ac": 1000
  39228. },
  39229. {
  39230. "type": "android",
  39231. "rules": [
  39232. {
  39233. "mdmh": "samsung/*/GT-I9195/*"
  39234. },
  39235. {
  39236. "ua": "GT-I9195"
  39237. }
  39238. ],
  39239. "dpi": [
  39240. 249.4,
  39241. 256.7
  39242. ],
  39243. "bw": 3,
  39244. "ac": 500
  39245. },
  39246. {
  39247. "type": "android",
  39248. "rules": [
  39249. {
  39250. "mdmh": "samsung/*/SPH-L520/*"
  39251. },
  39252. {
  39253. "ua": "SPH-L520"
  39254. }
  39255. ],
  39256. "dpi": [
  39257. 249.4,
  39258. 255.9
  39259. ],
  39260. "bw": 3,
  39261. "ac": 1000
  39262. },
  39263. {
  39264. "type": "android",
  39265. "rules": [
  39266. {
  39267. "mdmh": "samsung/*/SAMSUNG-SGH-I717/*"
  39268. },
  39269. {
  39270. "ua": "SAMSUNG-SGH-I717"
  39271. }
  39272. ],
  39273. "dpi": 285.8,
  39274. "bw": 3,
  39275. "ac": 1000
  39276. },
  39277. {
  39278. "type": "android",
  39279. "rules": [
  39280. {
  39281. "mdmh": "samsung/*/SPH-D710/*"
  39282. },
  39283. {
  39284. "ua": "SPH-D710"
  39285. }
  39286. ],
  39287. "dpi": [
  39288. 217.7,
  39289. 204.2
  39290. ],
  39291. "bw": 3,
  39292. "ac": 1000
  39293. },
  39294. {
  39295. "type": "android",
  39296. "rules": [
  39297. {
  39298. "mdmh": "samsung/*/GT-N7100/*"
  39299. },
  39300. {
  39301. "ua": "GT-N7100"
  39302. }
  39303. ],
  39304. "dpi": 265.1,
  39305. "bw": 3,
  39306. "ac": 1000
  39307. },
  39308. {
  39309. "type": "android",
  39310. "rules": [
  39311. {
  39312. "mdmh": "samsung/*/SCH-I605/*"
  39313. },
  39314. {
  39315. "ua": "SCH-I605"
  39316. }
  39317. ],
  39318. "dpi": 265.1,
  39319. "bw": 3,
  39320. "ac": 1000
  39321. },
  39322. {
  39323. "type": "android",
  39324. "rules": [
  39325. {
  39326. "mdmh": "samsung/*/Galaxy Nexus/*"
  39327. },
  39328. {
  39329. "ua": "Galaxy Nexus"
  39330. }
  39331. ],
  39332. "dpi": [
  39333. 315.3,
  39334. 314.2
  39335. ],
  39336. "bw": 3,
  39337. "ac": 1000
  39338. },
  39339. {
  39340. "type": "android",
  39341. "rules": [
  39342. {
  39343. "mdmh": "samsung/*/SM-N910H/*"
  39344. },
  39345. {
  39346. "ua": "SM-N910H"
  39347. }
  39348. ],
  39349. "dpi": [
  39350. 515.1,
  39351. 518
  39352. ],
  39353. "bw": 3,
  39354. "ac": 1000
  39355. },
  39356. {
  39357. "type": "android",
  39358. "rules": [
  39359. {
  39360. "mdmh": "samsung/*/SM-N910C/*"
  39361. },
  39362. {
  39363. "ua": "SM-N910C"
  39364. }
  39365. ],
  39366. "dpi": [
  39367. 515.2,
  39368. 520.2
  39369. ],
  39370. "bw": 3,
  39371. "ac": 500
  39372. },
  39373. {
  39374. "type": "android",
  39375. "rules": [
  39376. {
  39377. "mdmh": "samsung/*/SM-G130M/*"
  39378. },
  39379. {
  39380. "ua": "SM-G130M"
  39381. }
  39382. ],
  39383. "dpi": [
  39384. 165.9,
  39385. 164.8
  39386. ],
  39387. "bw": 3,
  39388. "ac": 500
  39389. },
  39390. {
  39391. "type": "android",
  39392. "rules": [
  39393. {
  39394. "mdmh": "samsung/*/SM-G928I/*"
  39395. },
  39396. {
  39397. "ua": "SM-G928I"
  39398. }
  39399. ],
  39400. "dpi": [
  39401. 515.1,
  39402. 518.4
  39403. ],
  39404. "bw": 3,
  39405. "ac": 1000
  39406. },
  39407. {
  39408. "type": "android",
  39409. "rules": [
  39410. {
  39411. "mdmh": "samsung/*/SM-G920F/*"
  39412. },
  39413. {
  39414. "ua": "SM-G920F"
  39415. }
  39416. ],
  39417. "dpi": 580.6,
  39418. "bw": 3,
  39419. "ac": 500
  39420. },
  39421. {
  39422. "type": "android",
  39423. "rules": [
  39424. {
  39425. "mdmh": "samsung/*/SM-G920P/*"
  39426. },
  39427. {
  39428. "ua": "SM-G920P"
  39429. }
  39430. ],
  39431. "dpi": [
  39432. 522.5,
  39433. 577
  39434. ],
  39435. "bw": 3,
  39436. "ac": 1000
  39437. },
  39438. {
  39439. "type": "android",
  39440. "rules": [
  39441. {
  39442. "mdmh": "samsung/*/SM-G925F/*"
  39443. },
  39444. {
  39445. "ua": "SM-G925F"
  39446. }
  39447. ],
  39448. "dpi": 580.6,
  39449. "bw": 3,
  39450. "ac": 500
  39451. },
  39452. {
  39453. "type": "android",
  39454. "rules": [
  39455. {
  39456. "mdmh": "samsung/*/SM-G925V/*"
  39457. },
  39458. {
  39459. "ua": "SM-G925V"
  39460. }
  39461. ],
  39462. "dpi": [
  39463. 522.5,
  39464. 576.6
  39465. ],
  39466. "bw": 3,
  39467. "ac": 1000
  39468. },
  39469. {
  39470. "type": "android",
  39471. "rules": [
  39472. {
  39473. "mdmh": "samsung/*/SM-G930F/*"
  39474. },
  39475. {
  39476. "ua": "SM-G930F"
  39477. }
  39478. ],
  39479. "dpi": 576.6,
  39480. "bw": 3,
  39481. "ac": 1000
  39482. },
  39483. {
  39484. "type": "android",
  39485. "rules": [
  39486. {
  39487. "mdmh": "samsung/*/SM-G935F/*"
  39488. },
  39489. {
  39490. "ua": "SM-G935F"
  39491. }
  39492. ],
  39493. "dpi": 533,
  39494. "bw": 3,
  39495. "ac": 500
  39496. },
  39497. {
  39498. "type": "android",
  39499. "rules": [
  39500. {
  39501. "mdmh": "Sony/*/C6903/*"
  39502. },
  39503. {
  39504. "ua": "C6903"
  39505. }
  39506. ],
  39507. "dpi": [
  39508. 442.5,
  39509. 443.3
  39510. ],
  39511. "bw": 3,
  39512. "ac": 500
  39513. },
  39514. {
  39515. "type": "android",
  39516. "rules": [
  39517. {
  39518. "mdmh": "Sony/*/D6653/*"
  39519. },
  39520. {
  39521. "ua": "D6653"
  39522. }
  39523. ],
  39524. "dpi": [
  39525. 428.6,
  39526. 427.6
  39527. ],
  39528. "bw": 3,
  39529. "ac": 1000
  39530. },
  39531. {
  39532. "type": "android",
  39533. "rules": [
  39534. {
  39535. "mdmh": "Sony/*/E6653/*"
  39536. },
  39537. {
  39538. "ua": "E6653"
  39539. }
  39540. ],
  39541. "dpi": [
  39542. 428.6,
  39543. 425.7
  39544. ],
  39545. "bw": 3,
  39546. "ac": 1000
  39547. },
  39548. {
  39549. "type": "android",
  39550. "rules": [
  39551. {
  39552. "mdmh": "Sony/*/E6853/*"
  39553. },
  39554. {
  39555. "ua": "E6853"
  39556. }
  39557. ],
  39558. "dpi": [
  39559. 403.4,
  39560. 401.9
  39561. ],
  39562. "bw": 3,
  39563. "ac": 1000
  39564. },
  39565. {
  39566. "type": "android",
  39567. "rules": [
  39568. {
  39569. "mdmh": "Sony/*/SGP321/*"
  39570. },
  39571. {
  39572. "ua": "SGP321"
  39573. }
  39574. ],
  39575. "dpi": [
  39576. 224.7,
  39577. 224.1
  39578. ],
  39579. "bw": 3,
  39580. "ac": 500
  39581. },
  39582. {
  39583. "type": "android",
  39584. "rules": [
  39585. {
  39586. "mdmh": "TCT/*/ALCATEL ONE TOUCH Fierce/*"
  39587. },
  39588. {
  39589. "ua": "ALCATEL ONE TOUCH Fierce"
  39590. }
  39591. ],
  39592. "dpi": [
  39593. 240,
  39594. 247.5
  39595. ],
  39596. "bw": 3,
  39597. "ac": 1000
  39598. },
  39599. {
  39600. "type": "android",
  39601. "rules": [
  39602. {
  39603. "mdmh": "THL/*/thl 5000/*"
  39604. },
  39605. {
  39606. "ua": "thl 5000"
  39607. }
  39608. ],
  39609. "dpi": [
  39610. 480,
  39611. 443.3
  39612. ],
  39613. "bw": 3,
  39614. "ac": 1000
  39615. },
  39616. {
  39617. "type": "android",
  39618. "rules": [
  39619. {
  39620. "mdmh": "ZTE/*/ZTE Blade L2/*"
  39621. },
  39622. {
  39623. "ua": "ZTE Blade L2"
  39624. }
  39625. ],
  39626. "dpi": 240,
  39627. "bw": 3,
  39628. "ac": 500
  39629. },
  39630. {
  39631. "type": "ios",
  39632. "rules": [
  39633. {
  39634. "res": [
  39635. 640,
  39636. 960
  39637. ]
  39638. }
  39639. ],
  39640. "dpi": [
  39641. 325.1,
  39642. 328.4
  39643. ],
  39644. "bw": 4,
  39645. "ac": 1000
  39646. },
  39647. {
  39648. "type": "ios",
  39649. "rules": [
  39650. {
  39651. "res": [
  39652. 640,
  39653. 1136
  39654. ]
  39655. }
  39656. ],
  39657. "dpi": [
  39658. 317.1,
  39659. 320.2
  39660. ],
  39661. "bw": 3,
  39662. "ac": 1000
  39663. },
  39664. {
  39665. "type": "ios",
  39666. "rules": [
  39667. {
  39668. "res": [
  39669. 750,
  39670. 1334
  39671. ]
  39672. }
  39673. ],
  39674. "dpi": 326.4,
  39675. "bw": 4,
  39676. "ac": 1000
  39677. },
  39678. {
  39679. "type": "ios",
  39680. "rules": [
  39681. {
  39682. "res": [
  39683. 1242,
  39684. 2208
  39685. ]
  39686. }
  39687. ],
  39688. "dpi": [
  39689. 453.6,
  39690. 458.4
  39691. ],
  39692. "bw": 4,
  39693. "ac": 1000
  39694. },
  39695. {
  39696. "type": "ios",
  39697. "rules": [
  39698. {
  39699. "res": [
  39700. 1125,
  39701. 2001
  39702. ]
  39703. }
  39704. ],
  39705. "dpi": [
  39706. 410.9,
  39707. 415.4
  39708. ],
  39709. "bw": 4,
  39710. "ac": 1000
  39711. }
  39712. ]
  39713. }
  39714. },{}],58:[function(_dereq_,module,exports){
  39715. /*
  39716. * Copyright 2015 Google Inc. All Rights Reserved.
  39717. * Licensed under the Apache License, Version 2.0 (the "License");
  39718. * you may not use this file except in compliance with the License.
  39719. * You may obtain a copy of the License at
  39720. *
  39721. * http://www.apache.org/licenses/LICENSE-2.0
  39722. *
  39723. * Unless required by applicable law or agreed to in writing, software
  39724. * distributed under the License is distributed on an "AS IS" BASIS,
  39725. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  39726. * See the License for the specific language governing permissions and
  39727. * limitations under the License.
  39728. */
  39729. // Offline cache of the DPDB, to be used until we load the online one (and
  39730. // as a fallback in case we can't load the online one).
  39731. var DPDB_CACHE = _dereq_('./dpdb.json');
  39732. var Util = _dereq_('../util.js');
  39733. // Online DPDB URL.
  39734. var ONLINE_DPDB_URL =
  39735. 'https://dpdb.webvr.rocks/dpdb.json';
  39736. /**
  39737. * Calculates device parameters based on the DPDB (Device Parameter Database).
  39738. * Initially, uses the cached DPDB values.
  39739. *
  39740. * If fetchOnline == true, then this object tries to fetch the online version
  39741. * of the DPDB and updates the device info if a better match is found.
  39742. * Calls the onDeviceParamsUpdated callback when there is an update to the
  39743. * device information.
  39744. */
  39745. function Dpdb(fetchOnline, onDeviceParamsUpdated) {
  39746. // Start with the offline DPDB cache while we are loading the real one.
  39747. this.dpdb = DPDB_CACHE;
  39748. // Calculate device params based on the offline version of the DPDB.
  39749. this.recalculateDeviceParams_();
  39750. // XHR to fetch online DPDB file, if requested.
  39751. if (fetchOnline) {
  39752. // Set the callback.
  39753. this.onDeviceParamsUpdated = onDeviceParamsUpdated;
  39754. var xhr = new XMLHttpRequest();
  39755. var obj = this;
  39756. xhr.open('GET', ONLINE_DPDB_URL, true);
  39757. xhr.addEventListener('load', function() {
  39758. obj.loading = false;
  39759. if (xhr.status >= 200 && xhr.status <= 299) {
  39760. // Success.
  39761. obj.dpdb = JSON.parse(xhr.response);
  39762. obj.recalculateDeviceParams_();
  39763. } else {
  39764. // Error loading the DPDB.
  39765. console.error('Error loading online DPDB!');
  39766. }
  39767. });
  39768. xhr.send();
  39769. }
  39770. }
  39771. // Returns the current device parameters.
  39772. Dpdb.prototype.getDeviceParams = function() {
  39773. return this.deviceParams;
  39774. };
  39775. // Recalculates this device's parameters based on the DPDB.
  39776. Dpdb.prototype.recalculateDeviceParams_ = function() {
  39777. var newDeviceParams = this.calcDeviceParams_();
  39778. if (newDeviceParams) {
  39779. this.deviceParams = newDeviceParams;
  39780. // Invoke callback, if it is set.
  39781. if (this.onDeviceParamsUpdated) {
  39782. this.onDeviceParamsUpdated(this.deviceParams);
  39783. }
  39784. } else {
  39785. console.error('Failed to recalculate device parameters.');
  39786. }
  39787. };
  39788. // Returns a DeviceParams object that represents the best guess as to this
  39789. // device's parameters. Can return null if the device does not match any
  39790. // known devices.
  39791. Dpdb.prototype.calcDeviceParams_ = function() {
  39792. var db = this.dpdb; // shorthand
  39793. if (!db) {
  39794. console.error('DPDB not available.');
  39795. return null;
  39796. }
  39797. if (db.format != 1) {
  39798. console.error('DPDB has unexpected format version.');
  39799. return null;
  39800. }
  39801. if (!db.devices || !db.devices.length) {
  39802. console.error('DPDB does not have a devices section.');
  39803. return null;
  39804. }
  39805. // Get the actual user agent and screen dimensions in pixels.
  39806. var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  39807. var width = Util.getScreenWidth();
  39808. var height = Util.getScreenHeight();
  39809. if (!db.devices) {
  39810. console.error('DPDB has no devices section.');
  39811. return null;
  39812. }
  39813. for (var i = 0; i < db.devices.length; i++) {
  39814. var device = db.devices[i];
  39815. if (!device.rules) {
  39816. console.warn('Device[' + i + '] has no rules section.');
  39817. continue;
  39818. }
  39819. if (device.type != 'ios' && device.type != 'android') {
  39820. console.warn('Device[' + i + '] has invalid type.');
  39821. continue;
  39822. }
  39823. // See if this device is of the appropriate type.
  39824. if (Util.isIOS() != (device.type == 'ios')) continue;
  39825. // See if this device matches any of the rules:
  39826. var matched = false;
  39827. for (var j = 0; j < device.rules.length; j++) {
  39828. var rule = device.rules[j];
  39829. if (this.matchRule_(rule, userAgent, width, height)) {
  39830. matched = true;
  39831. break;
  39832. }
  39833. }
  39834. if (!matched) continue;
  39835. // device.dpi might be an array of [ xdpi, ydpi] or just a scalar.
  39836. var xdpi = device.dpi[0] || device.dpi;
  39837. var ydpi = device.dpi[1] || device.dpi;
  39838. return new DeviceParams({ xdpi: xdpi, ydpi: ydpi, bevelMm: device.bw });
  39839. }
  39840. console.warn('No DPDB device match.');
  39841. return null;
  39842. };
  39843. Dpdb.prototype.matchRule_ = function(rule, ua, screenWidth, screenHeight) {
  39844. // We can only match 'ua' and 'res' rules, not other types like 'mdmh'
  39845. // (which are meant for native platforms).
  39846. if (!rule.ua && !rule.res) return false;
  39847. // If our user agent string doesn't contain the indicated user agent string,
  39848. // the match fails.
  39849. if (rule.ua && ua.indexOf(rule.ua) < 0) return false;
  39850. // If the rule specifies screen dimensions that don't correspond to ours,
  39851. // the match fails.
  39852. if (rule.res) {
  39853. if (!rule.res[0] || !rule.res[1]) return false;
  39854. var resX = rule.res[0];
  39855. var resY = rule.res[1];
  39856. // Compare min and max so as to make the order not matter, i.e., it should
  39857. // be true that 640x480 == 480x640.
  39858. if (Math.min(screenWidth, screenHeight) != Math.min(resX, resY) ||
  39859. (Math.max(screenWidth, screenHeight) != Math.max(resX, resY))) {
  39860. return false;
  39861. }
  39862. }
  39863. return true;
  39864. }
  39865. function DeviceParams(params) {
  39866. this.xdpi = params.xdpi;
  39867. this.ydpi = params.ydpi;
  39868. this.bevelMm = params.bevelMm;
  39869. }
  39870. module.exports = Dpdb;
  39871. },{"../util.js":69,"./dpdb.json":57}],59:[function(_dereq_,module,exports){
  39872. /*
  39873. * Copyright 2015 Google Inc. All Rights Reserved.
  39874. * Licensed under the Apache License, Version 2.0 (the "License");
  39875. * you may not use this file except in compliance with the License.
  39876. * You may obtain a copy of the License at
  39877. *
  39878. * http://www.apache.org/licenses/LICENSE-2.0
  39879. *
  39880. * Unless required by applicable law or agreed to in writing, software
  39881. * distributed under the License is distributed on an "AS IS" BASIS,
  39882. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  39883. * See the License for the specific language governing permissions and
  39884. * limitations under the License.
  39885. */
  39886. var Util = _dereq_('./util.js');
  39887. var WebVRPolyfill = _dereq_('./webvr-polyfill.js').WebVRPolyfill;
  39888. // Initialize a WebVRConfig just in case.
  39889. window.WebVRConfig = Util.extend({
  39890. // Forces availability of VR mode, even for non-mobile devices.
  39891. FORCE_ENABLE_VR: false,
  39892. // Complementary filter coefficient. 0 for accelerometer, 1 for gyro.
  39893. K_FILTER: 0.98,
  39894. // How far into the future to predict during fast motion (in seconds).
  39895. PREDICTION_TIME_S: 0.040,
  39896. // Flag to enable touch panner. In case you have your own touch controls.
  39897. TOUCH_PANNER_DISABLED: true,
  39898. // Flag to disabled the UI in VR Mode.
  39899. CARDBOARD_UI_DISABLED: false, // Default: false
  39900. // Flag to disable the instructions to rotate your device.
  39901. ROTATE_INSTRUCTIONS_DISABLED: false, // Default: false.
  39902. // Enable yaw panning only, disabling roll and pitch. This can be useful
  39903. // for panoramas with nothing interesting above or below.
  39904. YAW_ONLY: false,
  39905. // To disable keyboard and mouse controls, if you want to use your own
  39906. // implementation.
  39907. MOUSE_KEYBOARD_CONTROLS_DISABLED: false,
  39908. // Prevent the polyfill from initializing immediately. Requires the app
  39909. // to call InitializeWebVRPolyfill() before it can be used.
  39910. DEFER_INITIALIZATION: false,
  39911. // Enable the deprecated version of the API (navigator.getVRDevices).
  39912. ENABLE_DEPRECATED_API: false,
  39913. // Scales the recommended buffer size reported by WebVR, which can improve
  39914. // performance.
  39915. // UPDATE(2016-05-03): Setting this to 0.5 by default since 1.0 does not
  39916. // perform well on many mobile devices.
  39917. BUFFER_SCALE: 0.5,
  39918. // Allow VRDisplay.submitFrame to change gl bindings, which is more
  39919. // efficient if the application code will re-bind its resources on the
  39920. // next frame anyway. This has been seen to cause rendering glitches with
  39921. // THREE.js.
  39922. // Dirty bindings include: gl.FRAMEBUFFER_BINDING, gl.CURRENT_PROGRAM,
  39923. // gl.ARRAY_BUFFER_BINDING, gl.ELEMENT_ARRAY_BUFFER_BINDING,
  39924. // and gl.TEXTURE_BINDING_2D for texture unit 0.
  39925. DIRTY_SUBMIT_FRAME_BINDINGS: false,
  39926. // When set to true, this will cause a polyfilled VRDisplay to always be
  39927. // appended to the list returned by navigator.getVRDisplays(), even if that
  39928. // list includes a native VRDisplay.
  39929. ALWAYS_APPEND_POLYFILL_DISPLAY: false,
  39930. // There are versions of Chrome (M58-M60?) where the native WebVR API exists,
  39931. // and instead of returning 0 VR displays when none are detected,
  39932. // `navigator.getVRDisplays()`'s promise never resolves. This results
  39933. // in the polyfill hanging and not being able to provide fallback
  39934. // displays, so set a timeout in milliseconds to stop waiting for a response
  39935. // and just use polyfilled displays.
  39936. // https://bugs.chromium.org/p/chromium/issues/detail?id=727969
  39937. GET_VR_DISPLAYS_TIMEOUT: 1000,
  39938. }, window.WebVRConfig);
  39939. if (!window.WebVRConfig.DEFER_INITIALIZATION) {
  39940. new WebVRPolyfill();
  39941. } else {
  39942. window.InitializeWebVRPolyfill = function() {
  39943. new WebVRPolyfill();
  39944. }
  39945. }
  39946. window.WebVRPolyfill = WebVRPolyfill;
  39947. },{"./util.js":69,"./webvr-polyfill.js":72}],60:[function(_dereq_,module,exports){
  39948. /*
  39949. * Copyright 2016 Google Inc. All Rights Reserved.
  39950. * Licensed under the Apache License, Version 2.0 (the "License");
  39951. * you may not use this file except in compliance with the License.
  39952. * You may obtain a copy of the License at
  39953. *
  39954. * http://www.apache.org/licenses/LICENSE-2.0
  39955. *
  39956. * Unless required by applicable law or agreed to in writing, software
  39957. * distributed under the License is distributed on an "AS IS" BASIS,
  39958. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  39959. * See the License for the specific language governing permissions and
  39960. * limitations under the License.
  39961. */
  39962. var MathUtil = window.MathUtil || {};
  39963. MathUtil.degToRad = Math.PI / 180;
  39964. MathUtil.radToDeg = 180 / Math.PI;
  39965. // Some minimal math functionality borrowed from THREE.Math and stripped down
  39966. // for the purposes of this library.
  39967. MathUtil.Vector2 = function ( x, y ) {
  39968. this.x = x || 0;
  39969. this.y = y || 0;
  39970. };
  39971. MathUtil.Vector2.prototype = {
  39972. constructor: MathUtil.Vector2,
  39973. set: function ( x, y ) {
  39974. this.x = x;
  39975. this.y = y;
  39976. return this;
  39977. },
  39978. copy: function ( v ) {
  39979. this.x = v.x;
  39980. this.y = v.y;
  39981. return this;
  39982. },
  39983. subVectors: function ( a, b ) {
  39984. this.x = a.x - b.x;
  39985. this.y = a.y - b.y;
  39986. return this;
  39987. },
  39988. };
  39989. MathUtil.Vector3 = function ( x, y, z ) {
  39990. this.x = x || 0;
  39991. this.y = y || 0;
  39992. this.z = z || 0;
  39993. };
  39994. MathUtil.Vector3.prototype = {
  39995. constructor: MathUtil.Vector3,
  39996. set: function ( x, y, z ) {
  39997. this.x = x;
  39998. this.y = y;
  39999. this.z = z;
  40000. return this;
  40001. },
  40002. copy: function ( v ) {
  40003. this.x = v.x;
  40004. this.y = v.y;
  40005. this.z = v.z;
  40006. return this;
  40007. },
  40008. length: function () {
  40009. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  40010. },
  40011. normalize: function () {
  40012. var scalar = this.length();
  40013. if ( scalar !== 0 ) {
  40014. var invScalar = 1 / scalar;
  40015. this.multiplyScalar(invScalar);
  40016. } else {
  40017. this.x = 0;
  40018. this.y = 0;
  40019. this.z = 0;
  40020. }
  40021. return this;
  40022. },
  40023. multiplyScalar: function ( scalar ) {
  40024. this.x *= scalar;
  40025. this.y *= scalar;
  40026. this.z *= scalar;
  40027. },
  40028. applyQuaternion: function ( q ) {
  40029. var x = this.x;
  40030. var y = this.y;
  40031. var z = this.z;
  40032. var qx = q.x;
  40033. var qy = q.y;
  40034. var qz = q.z;
  40035. var qw = q.w;
  40036. // calculate quat * vector
  40037. var ix = qw * x + qy * z - qz * y;
  40038. var iy = qw * y + qz * x - qx * z;
  40039. var iz = qw * z + qx * y - qy * x;
  40040. var iw = - qx * x - qy * y - qz * z;
  40041. // calculate result * inverse quat
  40042. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  40043. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  40044. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  40045. return this;
  40046. },
  40047. dot: function ( v ) {
  40048. return this.x * v.x + this.y * v.y + this.z * v.z;
  40049. },
  40050. crossVectors: function ( a, b ) {
  40051. var ax = a.x, ay = a.y, az = a.z;
  40052. var bx = b.x, by = b.y, bz = b.z;
  40053. this.x = ay * bz - az * by;
  40054. this.y = az * bx - ax * bz;
  40055. this.z = ax * by - ay * bx;
  40056. return this;
  40057. },
  40058. };
  40059. MathUtil.Quaternion = function ( x, y, z, w ) {
  40060. this.x = x || 0;
  40061. this.y = y || 0;
  40062. this.z = z || 0;
  40063. this.w = ( w !== undefined ) ? w : 1;
  40064. };
  40065. MathUtil.Quaternion.prototype = {
  40066. constructor: MathUtil.Quaternion,
  40067. set: function ( x, y, z, w ) {
  40068. this.x = x;
  40069. this.y = y;
  40070. this.z = z;
  40071. this.w = w;
  40072. return this;
  40073. },
  40074. copy: function ( quaternion ) {
  40075. this.x = quaternion.x;
  40076. this.y = quaternion.y;
  40077. this.z = quaternion.z;
  40078. this.w = quaternion.w;
  40079. return this;
  40080. },
  40081. setFromEulerXYZ: function( x, y, z ) {
  40082. var c1 = Math.cos( x / 2 );
  40083. var c2 = Math.cos( y / 2 );
  40084. var c3 = Math.cos( z / 2 );
  40085. var s1 = Math.sin( x / 2 );
  40086. var s2 = Math.sin( y / 2 );
  40087. var s3 = Math.sin( z / 2 );
  40088. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  40089. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  40090. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  40091. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  40092. return this;
  40093. },
  40094. setFromEulerYXZ: function( x, y, z ) {
  40095. var c1 = Math.cos( x / 2 );
  40096. var c2 = Math.cos( y / 2 );
  40097. var c3 = Math.cos( z / 2 );
  40098. var s1 = Math.sin( x / 2 );
  40099. var s2 = Math.sin( y / 2 );
  40100. var s3 = Math.sin( z / 2 );
  40101. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  40102. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  40103. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  40104. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  40105. return this;
  40106. },
  40107. setFromAxisAngle: function ( axis, angle ) {
  40108. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  40109. // assumes axis is normalized
  40110. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  40111. this.x = axis.x * s;
  40112. this.y = axis.y * s;
  40113. this.z = axis.z * s;
  40114. this.w = Math.cos( halfAngle );
  40115. return this;
  40116. },
  40117. multiply: function ( q ) {
  40118. return this.multiplyQuaternions( this, q );
  40119. },
  40120. multiplyQuaternions: function ( a, b ) {
  40121. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  40122. var qax = a.x, qay = a.y, qaz = a.z, qaw = a.w;
  40123. var qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  40124. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  40125. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  40126. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  40127. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  40128. return this;
  40129. },
  40130. inverse: function () {
  40131. this.x *= -1;
  40132. this.y *= -1;
  40133. this.z *= -1;
  40134. this.normalize();
  40135. return this;
  40136. },
  40137. normalize: function () {
  40138. var l = Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  40139. if ( l === 0 ) {
  40140. this.x = 0;
  40141. this.y = 0;
  40142. this.z = 0;
  40143. this.w = 1;
  40144. } else {
  40145. l = 1 / l;
  40146. this.x = this.x * l;
  40147. this.y = this.y * l;
  40148. this.z = this.z * l;
  40149. this.w = this.w * l;
  40150. }
  40151. return this;
  40152. },
  40153. slerp: function ( qb, t ) {
  40154. if ( t === 0 ) return this;
  40155. if ( t === 1 ) return this.copy( qb );
  40156. var x = this.x, y = this.y, z = this.z, w = this.w;
  40157. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  40158. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  40159. if ( cosHalfTheta < 0 ) {
  40160. this.w = - qb.w;
  40161. this.x = - qb.x;
  40162. this.y = - qb.y;
  40163. this.z = - qb.z;
  40164. cosHalfTheta = - cosHalfTheta;
  40165. } else {
  40166. this.copy( qb );
  40167. }
  40168. if ( cosHalfTheta >= 1.0 ) {
  40169. this.w = w;
  40170. this.x = x;
  40171. this.y = y;
  40172. this.z = z;
  40173. return this;
  40174. }
  40175. var halfTheta = Math.acos( cosHalfTheta );
  40176. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  40177. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  40178. this.w = 0.5 * ( w + this.w );
  40179. this.x = 0.5 * ( x + this.x );
  40180. this.y = 0.5 * ( y + this.y );
  40181. this.z = 0.5 * ( z + this.z );
  40182. return this;
  40183. }
  40184. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  40185. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  40186. this.w = ( w * ratioA + this.w * ratioB );
  40187. this.x = ( x * ratioA + this.x * ratioB );
  40188. this.y = ( y * ratioA + this.y * ratioB );
  40189. this.z = ( z * ratioA + this.z * ratioB );
  40190. return this;
  40191. },
  40192. setFromUnitVectors: function () {
  40193. // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final
  40194. // assumes direction vectors vFrom and vTo are normalized
  40195. var v1, r;
  40196. var EPS = 0.000001;
  40197. return function ( vFrom, vTo ) {
  40198. if ( v1 === undefined ) v1 = new MathUtil.Vector3();
  40199. r = vFrom.dot( vTo ) + 1;
  40200. if ( r < EPS ) {
  40201. r = 0;
  40202. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  40203. v1.set( - vFrom.y, vFrom.x, 0 );
  40204. } else {
  40205. v1.set( 0, - vFrom.z, vFrom.y );
  40206. }
  40207. } else {
  40208. v1.crossVectors( vFrom, vTo );
  40209. }
  40210. this.x = v1.x;
  40211. this.y = v1.y;
  40212. this.z = v1.z;
  40213. this.w = r;
  40214. this.normalize();
  40215. return this;
  40216. }
  40217. }(),
  40218. };
  40219. module.exports = MathUtil;
  40220. },{}],61:[function(_dereq_,module,exports){
  40221. /*
  40222. * Copyright 2016 Google Inc. All Rights Reserved.
  40223. * Licensed under the Apache License, Version 2.0 (the "License");
  40224. * you may not use this file except in compliance with the License.
  40225. * You may obtain a copy of the License at
  40226. *
  40227. * http://www.apache.org/licenses/LICENSE-2.0
  40228. *
  40229. * Unless required by applicable law or agreed to in writing, software
  40230. * distributed under the License is distributed on an "AS IS" BASIS,
  40231. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40232. * See the License for the specific language governing permissions and
  40233. * limitations under the License.
  40234. */
  40235. var VRDisplay = _dereq_('./base.js').VRDisplay;
  40236. var MathUtil = _dereq_('./math-util.js');
  40237. var Util = _dereq_('./util.js');
  40238. // How much to rotate per key stroke.
  40239. var KEY_SPEED = 0.15;
  40240. var KEY_ANIMATION_DURATION = 80;
  40241. // How much to rotate for mouse events.
  40242. var MOUSE_SPEED_X = 0.5;
  40243. var MOUSE_SPEED_Y = 0.3;
  40244. /**
  40245. * VRDisplay based on mouse and keyboard input. Designed for desktops/laptops
  40246. * where orientation events aren't supported. Cannot present.
  40247. */
  40248. function MouseKeyboardVRDisplay() {
  40249. this.displayName = 'Mouse and Keyboard VRDisplay (webvr-polyfill)';
  40250. this.capabilities.hasOrientation = true;
  40251. // Attach to mouse and keyboard events.
  40252. window.addEventListener('keydown', this.onKeyDown_.bind(this));
  40253. window.addEventListener('mousemove', this.onMouseMove_.bind(this));
  40254. window.addEventListener('mousedown', this.onMouseDown_.bind(this));
  40255. window.addEventListener('mouseup', this.onMouseUp_.bind(this));
  40256. // "Private" members.
  40257. this.phi_ = 0;
  40258. this.theta_ = 0;
  40259. // Variables for keyboard-based rotation animation.
  40260. this.targetAngle_ = null;
  40261. this.angleAnimation_ = null;
  40262. // State variables for calculations.
  40263. this.orientation_ = new MathUtil.Quaternion();
  40264. // Variables for mouse-based rotation.
  40265. this.rotateStart_ = new MathUtil.Vector2();
  40266. this.rotateEnd_ = new MathUtil.Vector2();
  40267. this.rotateDelta_ = new MathUtil.Vector2();
  40268. this.isDragging_ = false;
  40269. this.orientationOut_ = new Float32Array(4);
  40270. }
  40271. MouseKeyboardVRDisplay.prototype = new VRDisplay();
  40272. MouseKeyboardVRDisplay.prototype.getImmediatePose = function() {
  40273. this.orientation_.setFromEulerYXZ(this.phi_, this.theta_, 0);
  40274. this.orientationOut_[0] = this.orientation_.x;
  40275. this.orientationOut_[1] = this.orientation_.y;
  40276. this.orientationOut_[2] = this.orientation_.z;
  40277. this.orientationOut_[3] = this.orientation_.w;
  40278. return {
  40279. position: null,
  40280. orientation: this.orientationOut_,
  40281. linearVelocity: null,
  40282. linearAcceleration: null,
  40283. angularVelocity: null,
  40284. angularAcceleration: null
  40285. };
  40286. };
  40287. MouseKeyboardVRDisplay.prototype.onKeyDown_ = function(e) {
  40288. // Track WASD and arrow keys.
  40289. if (e.keyCode == 38) { // Up key.
  40290. this.animatePhi_(this.phi_ + KEY_SPEED);
  40291. } else if (e.keyCode == 39) { // Right key.
  40292. this.animateTheta_(this.theta_ - KEY_SPEED);
  40293. } else if (e.keyCode == 40) { // Down key.
  40294. this.animatePhi_(this.phi_ - KEY_SPEED);
  40295. } else if (e.keyCode == 37) { // Left key.
  40296. this.animateTheta_(this.theta_ + KEY_SPEED);
  40297. }
  40298. };
  40299. MouseKeyboardVRDisplay.prototype.animateTheta_ = function(targetAngle) {
  40300. this.animateKeyTransitions_('theta_', targetAngle);
  40301. };
  40302. MouseKeyboardVRDisplay.prototype.animatePhi_ = function(targetAngle) {
  40303. // Prevent looking too far up or down.
  40304. targetAngle = Util.clamp(targetAngle, -Math.PI/2, Math.PI/2);
  40305. this.animateKeyTransitions_('phi_', targetAngle);
  40306. };
  40307. /**
  40308. * Start an animation to transition an angle from one value to another.
  40309. */
  40310. MouseKeyboardVRDisplay.prototype.animateKeyTransitions_ = function(angleName, targetAngle) {
  40311. // If an animation is currently running, cancel it.
  40312. if (this.angleAnimation_) {
  40313. cancelAnimationFrame(this.angleAnimation_);
  40314. }
  40315. var startAngle = this[angleName];
  40316. var startTime = new Date();
  40317. // Set up an interval timer to perform the animation.
  40318. this.angleAnimation_ = requestAnimationFrame(function animate() {
  40319. // Once we're finished the animation, we're done.
  40320. var elapsed = new Date() - startTime;
  40321. if (elapsed >= KEY_ANIMATION_DURATION) {
  40322. this[angleName] = targetAngle;
  40323. cancelAnimationFrame(this.angleAnimation_);
  40324. return;
  40325. }
  40326. // loop with requestAnimationFrame
  40327. this.angleAnimation_ = requestAnimationFrame(animate.bind(this))
  40328. // Linearly interpolate the angle some amount.
  40329. var percent = elapsed / KEY_ANIMATION_DURATION;
  40330. this[angleName] = startAngle + (targetAngle - startAngle) * percent;
  40331. }.bind(this));
  40332. };
  40333. MouseKeyboardVRDisplay.prototype.onMouseDown_ = function(e) {
  40334. this.rotateStart_.set(e.clientX, e.clientY);
  40335. this.isDragging_ = true;
  40336. };
  40337. // Very similar to https://gist.github.com/mrflix/8351020
  40338. MouseKeyboardVRDisplay.prototype.onMouseMove_ = function(e) {
  40339. if (!this.isDragging_ && !this.isPointerLocked_()) {
  40340. return;
  40341. }
  40342. // Support pointer lock API.
  40343. if (this.isPointerLocked_()) {
  40344. var movementX = e.movementX || e.mozMovementX || 0;
  40345. var movementY = e.movementY || e.mozMovementY || 0;
  40346. this.rotateEnd_.set(this.rotateStart_.x - movementX, this.rotateStart_.y - movementY);
  40347. } else {
  40348. this.rotateEnd_.set(e.clientX, e.clientY);
  40349. }
  40350. // Calculate how much we moved in mouse space.
  40351. this.rotateDelta_.subVectors(this.rotateEnd_, this.rotateStart_);
  40352. this.rotateStart_.copy(this.rotateEnd_);
  40353. // Keep track of the cumulative euler angles.
  40354. this.phi_ += 2 * Math.PI * this.rotateDelta_.y / screen.height * MOUSE_SPEED_Y;
  40355. this.theta_ += 2 * Math.PI * this.rotateDelta_.x / screen.width * MOUSE_SPEED_X;
  40356. // Prevent looking too far up or down.
  40357. this.phi_ = Util.clamp(this.phi_, -Math.PI/2, Math.PI/2);
  40358. };
  40359. MouseKeyboardVRDisplay.prototype.onMouseUp_ = function(e) {
  40360. this.isDragging_ = false;
  40361. };
  40362. MouseKeyboardVRDisplay.prototype.isPointerLocked_ = function() {
  40363. var el = document.pointerLockElement || document.mozPointerLockElement ||
  40364. document.webkitPointerLockElement;
  40365. return el !== undefined;
  40366. };
  40367. MouseKeyboardVRDisplay.prototype.resetPose = function() {
  40368. this.phi_ = 0;
  40369. this.theta_ = 0;
  40370. };
  40371. module.exports = MouseKeyboardVRDisplay;
  40372. },{"./base.js":49,"./math-util.js":60,"./util.js":69}],62:[function(_dereq_,module,exports){
  40373. (function (global){
  40374. // This is the entry point if requiring/importing via node, or
  40375. // a build tool that uses package.json entry (like browserify, webpack).
  40376. // If running in node with a window mock available, globalize its members
  40377. // if needed. Otherwise, just continue to `./main`
  40378. if (typeof global !== 'undefined' && global.window) {
  40379. global.document = global.window.document;
  40380. global.navigator = global.window.navigator;
  40381. }
  40382. _dereq_('./main');
  40383. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  40384. },{"./main":59}],63:[function(_dereq_,module,exports){
  40385. /*
  40386. * Copyright 2015 Google Inc. All Rights Reserved.
  40387. * Licensed under the Apache License, Version 2.0 (the "License");
  40388. * you may not use this file except in compliance with the License.
  40389. * You may obtain a copy of the License at
  40390. *
  40391. * http://www.apache.org/licenses/LICENSE-2.0
  40392. *
  40393. * Unless required by applicable law or agreed to in writing, software
  40394. * distributed under the License is distributed on an "AS IS" BASIS,
  40395. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40396. * See the License for the specific language governing permissions and
  40397. * limitations under the License.
  40398. */
  40399. var Util = _dereq_('./util.js');
  40400. function RotateInstructions() {
  40401. this.loadIcon_();
  40402. var overlay = document.createElement('div');
  40403. var s = overlay.style;
  40404. s.position = 'fixed';
  40405. s.top = 0;
  40406. s.right = 0;
  40407. s.bottom = 0;
  40408. s.left = 0;
  40409. s.backgroundColor = 'gray';
  40410. s.fontFamily = 'sans-serif';
  40411. // Force this to be above the fullscreen canvas, which is at zIndex: 999999.
  40412. s.zIndex = 1000000;
  40413. var img = document.createElement('img');
  40414. img.src = this.icon;
  40415. var s = img.style;
  40416. s.marginLeft = '25%';
  40417. s.marginTop = '25%';
  40418. s.width = '50%';
  40419. overlay.appendChild(img);
  40420. var text = document.createElement('div');
  40421. var s = text.style;
  40422. s.textAlign = 'center';
  40423. s.fontSize = '16px';
  40424. s.lineHeight = '24px';
  40425. s.margin = '24px 25%';
  40426. s.width = '50%';
  40427. text.innerHTML = 'Place your phone into your Cardboard viewer.';
  40428. overlay.appendChild(text);
  40429. var snackbar = document.createElement('div');
  40430. var s = snackbar.style;
  40431. s.backgroundColor = '#CFD8DC';
  40432. s.position = 'fixed';
  40433. s.bottom = 0;
  40434. s.width = '100%';
  40435. s.height = '48px';
  40436. s.padding = '14px 24px';
  40437. s.boxSizing = 'border-box';
  40438. s.color = '#656A6B';
  40439. overlay.appendChild(snackbar);
  40440. var snackbarText = document.createElement('div');
  40441. snackbarText.style.float = 'left';
  40442. snackbarText.innerHTML = 'No Cardboard viewer?';
  40443. var snackbarButton = document.createElement('a');
  40444. snackbarButton.href = 'https://www.google.com/get/cardboard/get-cardboard/';
  40445. snackbarButton.innerHTML = 'get one';
  40446. snackbarButton.target = '_blank';
  40447. var s = snackbarButton.style;
  40448. s.float = 'right';
  40449. s.fontWeight = 600;
  40450. s.textTransform = 'uppercase';
  40451. s.borderLeft = '1px solid gray';
  40452. s.paddingLeft = '24px';
  40453. s.textDecoration = 'none';
  40454. s.color = '#656A6B';
  40455. snackbar.appendChild(snackbarText);
  40456. snackbar.appendChild(snackbarButton);
  40457. this.overlay = overlay;
  40458. this.text = text;
  40459. this.hide();
  40460. }
  40461. RotateInstructions.prototype.show = function(parent) {
  40462. if (!parent && !this.overlay.parentElement) {
  40463. document.body.appendChild(this.overlay);
  40464. } else if (parent) {
  40465. if (this.overlay.parentElement && this.overlay.parentElement != parent)
  40466. this.overlay.parentElement.removeChild(this.overlay);
  40467. parent.appendChild(this.overlay);
  40468. }
  40469. this.overlay.style.display = 'block';
  40470. var img = this.overlay.querySelector('img');
  40471. var s = img.style;
  40472. if (Util.isLandscapeMode()) {
  40473. s.width = '20%';
  40474. s.marginLeft = '40%';
  40475. s.marginTop = '3%';
  40476. } else {
  40477. s.width = '50%';
  40478. s.marginLeft = '25%';
  40479. s.marginTop = '25%';
  40480. }
  40481. };
  40482. RotateInstructions.prototype.hide = function() {
  40483. this.overlay.style.display = 'none';
  40484. };
  40485. RotateInstructions.prototype.showTemporarily = function(ms, parent) {
  40486. this.show(parent);
  40487. this.timer = setTimeout(this.hide.bind(this), ms);
  40488. };
  40489. RotateInstructions.prototype.disableShowTemporarily = function() {
  40490. clearTimeout(this.timer);
  40491. };
  40492. RotateInstructions.prototype.update = function() {
  40493. this.disableShowTemporarily();
  40494. // In portrait VR mode, tell the user to rotate to landscape. Otherwise, hide
  40495. // the instructions.
  40496. if (!Util.isLandscapeMode() && Util.isMobile()) {
  40497. this.show();
  40498. } else {
  40499. this.hide();
  40500. }
  40501. };
  40502. RotateInstructions.prototype.loadIcon_ = function() {
  40503. // Encoded asset_src/rotate-instructions.svg
  40504. 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+');
  40505. };
  40506. module.exports = RotateInstructions;
  40507. },{"./util.js":69}],64:[function(_dereq_,module,exports){
  40508. /*
  40509. * Copyright 2015 Google Inc. All Rights Reserved.
  40510. * Licensed under the Apache License, Version 2.0 (the "License");
  40511. * you may not use this file except in compliance with the License.
  40512. * You may obtain a copy of the License at
  40513. *
  40514. * http://www.apache.org/licenses/LICENSE-2.0
  40515. *
  40516. * Unless required by applicable law or agreed to in writing, software
  40517. * distributed under the License is distributed on an "AS IS" BASIS,
  40518. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40519. * See the License for the specific language governing permissions and
  40520. * limitations under the License.
  40521. */
  40522. var SensorSample = _dereq_('./sensor-sample.js');
  40523. var MathUtil = _dereq_('../math-util.js');
  40524. var Util = _dereq_('../util.js');
  40525. /**
  40526. * An implementation of a simple complementary filter, which fuses gyroscope and
  40527. * accelerometer data from the 'devicemotion' event.
  40528. *
  40529. * Accelerometer data is very noisy, but stable over the long term.
  40530. * Gyroscope data is smooth, but tends to drift over the long term.
  40531. *
  40532. * This fusion is relatively simple:
  40533. * 1. Get orientation estimates from accelerometer by applying a low-pass filter
  40534. * on that data.
  40535. * 2. Get orientation estimates from gyroscope by integrating over time.
  40536. * 3. Combine the two estimates, weighing (1) in the long term, but (2) for the
  40537. * short term.
  40538. */
  40539. function ComplementaryFilter(kFilter) {
  40540. this.kFilter = kFilter;
  40541. // Raw sensor measurements.
  40542. this.currentAccelMeasurement = new SensorSample();
  40543. this.currentGyroMeasurement = new SensorSample();
  40544. this.previousGyroMeasurement = new SensorSample();
  40545. // Set default look direction to be in the correct direction.
  40546. if (Util.isIOS()) {
  40547. this.filterQ = new MathUtil.Quaternion(-1, 0, 0, 1);
  40548. } else {
  40549. this.filterQ = new MathUtil.Quaternion(1, 0, 0, 1);
  40550. }
  40551. this.previousFilterQ = new MathUtil.Quaternion();
  40552. this.previousFilterQ.copy(this.filterQ);
  40553. // Orientation based on the accelerometer.
  40554. this.accelQ = new MathUtil.Quaternion();
  40555. // Whether or not the orientation has been initialized.
  40556. this.isOrientationInitialized = false;
  40557. // Running estimate of gravity based on the current orientation.
  40558. this.estimatedGravity = new MathUtil.Vector3();
  40559. // Measured gravity based on accelerometer.
  40560. this.measuredGravity = new MathUtil.Vector3();
  40561. // Debug only quaternion of gyro-based orientation.
  40562. this.gyroIntegralQ = new MathUtil.Quaternion();
  40563. }
  40564. ComplementaryFilter.prototype.addAccelMeasurement = function(vector, timestampS) {
  40565. this.currentAccelMeasurement.set(vector, timestampS);
  40566. };
  40567. ComplementaryFilter.prototype.addGyroMeasurement = function(vector, timestampS) {
  40568. this.currentGyroMeasurement.set(vector, timestampS);
  40569. var deltaT = timestampS - this.previousGyroMeasurement.timestampS;
  40570. if (Util.isTimestampDeltaValid(deltaT)) {
  40571. this.run_();
  40572. }
  40573. this.previousGyroMeasurement.copy(this.currentGyroMeasurement);
  40574. };
  40575. ComplementaryFilter.prototype.run_ = function() {
  40576. if (!this.isOrientationInitialized) {
  40577. this.accelQ = this.accelToQuaternion_(this.currentAccelMeasurement.sample);
  40578. this.previousFilterQ.copy(this.accelQ);
  40579. this.isOrientationInitialized = true;
  40580. return;
  40581. }
  40582. var deltaT = this.currentGyroMeasurement.timestampS -
  40583. this.previousGyroMeasurement.timestampS;
  40584. // Convert gyro rotation vector to a quaternion delta.
  40585. var gyroDeltaQ = this.gyroToQuaternionDelta_(this.currentGyroMeasurement.sample, deltaT);
  40586. this.gyroIntegralQ.multiply(gyroDeltaQ);
  40587. // filter_1 = K * (filter_0 + gyro * dT) + (1 - K) * accel.
  40588. this.filterQ.copy(this.previousFilterQ);
  40589. this.filterQ.multiply(gyroDeltaQ);
  40590. // Calculate the delta between the current estimated gravity and the real
  40591. // gravity vector from accelerometer.
  40592. var invFilterQ = new MathUtil.Quaternion();
  40593. invFilterQ.copy(this.filterQ);
  40594. invFilterQ.inverse();
  40595. this.estimatedGravity.set(0, 0, -1);
  40596. this.estimatedGravity.applyQuaternion(invFilterQ);
  40597. this.estimatedGravity.normalize();
  40598. this.measuredGravity.copy(this.currentAccelMeasurement.sample);
  40599. this.measuredGravity.normalize();
  40600. // Compare estimated gravity with measured gravity, get the delta quaternion
  40601. // between the two.
  40602. var deltaQ = new MathUtil.Quaternion();
  40603. deltaQ.setFromUnitVectors(this.estimatedGravity, this.measuredGravity);
  40604. deltaQ.inverse();
  40605. if (Util.isDebug()) {
  40606. console.log('Delta: %d deg, G_est: (%s, %s, %s), G_meas: (%s, %s, %s)',
  40607. MathUtil.radToDeg * Util.getQuaternionAngle(deltaQ),
  40608. (this.estimatedGravity.x).toFixed(1),
  40609. (this.estimatedGravity.y).toFixed(1),
  40610. (this.estimatedGravity.z).toFixed(1),
  40611. (this.measuredGravity.x).toFixed(1),
  40612. (this.measuredGravity.y).toFixed(1),
  40613. (this.measuredGravity.z).toFixed(1));
  40614. }
  40615. // Calculate the SLERP target: current orientation plus the measured-estimated
  40616. // quaternion delta.
  40617. var targetQ = new MathUtil.Quaternion();
  40618. targetQ.copy(this.filterQ);
  40619. targetQ.multiply(deltaQ);
  40620. // SLERP factor: 0 is pure gyro, 1 is pure accel.
  40621. this.filterQ.slerp(targetQ, 1 - this.kFilter);
  40622. this.previousFilterQ.copy(this.filterQ);
  40623. };
  40624. ComplementaryFilter.prototype.getOrientation = function() {
  40625. return this.filterQ;
  40626. };
  40627. ComplementaryFilter.prototype.accelToQuaternion_ = function(accel) {
  40628. var normAccel = new MathUtil.Vector3();
  40629. normAccel.copy(accel);
  40630. normAccel.normalize();
  40631. var quat = new MathUtil.Quaternion();
  40632. quat.setFromUnitVectors(new MathUtil.Vector3(0, 0, -1), normAccel);
  40633. quat.inverse();
  40634. return quat;
  40635. };
  40636. ComplementaryFilter.prototype.gyroToQuaternionDelta_ = function(gyro, dt) {
  40637. // Extract axis and angle from the gyroscope data.
  40638. var quat = new MathUtil.Quaternion();
  40639. var axis = new MathUtil.Vector3();
  40640. axis.copy(gyro);
  40641. axis.normalize();
  40642. quat.setFromAxisAngle(axis, gyro.length() * dt);
  40643. return quat;
  40644. };
  40645. module.exports = ComplementaryFilter;
  40646. },{"../math-util.js":60,"../util.js":69,"./sensor-sample.js":67}],65:[function(_dereq_,module,exports){
  40647. /*
  40648. * Copyright 2015 Google Inc. All Rights Reserved.
  40649. * Licensed under the Apache License, Version 2.0 (the "License");
  40650. * you may not use this file except in compliance with the License.
  40651. * You may obtain a copy of the License at
  40652. *
  40653. * http://www.apache.org/licenses/LICENSE-2.0
  40654. *
  40655. * Unless required by applicable law or agreed to in writing, software
  40656. * distributed under the License is distributed on an "AS IS" BASIS,
  40657. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40658. * See the License for the specific language governing permissions and
  40659. * limitations under the License.
  40660. */
  40661. var ComplementaryFilter = _dereq_('./complementary-filter.js');
  40662. var PosePredictor = _dereq_('./pose-predictor.js');
  40663. var TouchPanner = _dereq_('../touch-panner.js');
  40664. var MathUtil = _dereq_('../math-util.js');
  40665. var Util = _dereq_('../util.js');
  40666. /**
  40667. * The pose sensor, implemented using DeviceMotion APIs.
  40668. */
  40669. function FusionPoseSensor() {
  40670. this.deviceId = 'webvr-polyfill:fused';
  40671. this.deviceName = 'VR Position Device (webvr-polyfill:fused)';
  40672. this.accelerometer = new MathUtil.Vector3();
  40673. this.gyroscope = new MathUtil.Vector3();
  40674. this.start();
  40675. this.filter = new ComplementaryFilter(window.WebVRConfig.K_FILTER);
  40676. this.posePredictor = new PosePredictor(window.WebVRConfig.PREDICTION_TIME_S);
  40677. this.touchPanner = new TouchPanner();
  40678. this.filterToWorldQ = new MathUtil.Quaternion();
  40679. // Set the filter to world transform, depending on OS.
  40680. if (Util.isIOS()) {
  40681. this.filterToWorldQ.setFromAxisAngle(new MathUtil.Vector3(1, 0, 0), Math.PI / 2);
  40682. } else {
  40683. this.filterToWorldQ.setFromAxisAngle(new MathUtil.Vector3(1, 0, 0), -Math.PI / 2);
  40684. }
  40685. this.inverseWorldToScreenQ = new MathUtil.Quaternion();
  40686. this.worldToScreenQ = new MathUtil.Quaternion();
  40687. this.originalPoseAdjustQ = new MathUtil.Quaternion();
  40688. this.originalPoseAdjustQ.setFromAxisAngle(new MathUtil.Vector3(0, 0, 1),
  40689. -window.orientation * Math.PI / 180);
  40690. this.setScreenTransform_();
  40691. // Adjust this filter for being in landscape mode.
  40692. if (Util.isLandscapeMode()) {
  40693. this.filterToWorldQ.multiply(this.inverseWorldToScreenQ);
  40694. }
  40695. // Keep track of a reset transform for resetSensor.
  40696. this.resetQ = new MathUtil.Quaternion();
  40697. this.isFirefoxAndroid = Util.isFirefoxAndroid();
  40698. this.isIOS = Util.isIOS();
  40699. this.orientationOut_ = new Float32Array(4);
  40700. }
  40701. FusionPoseSensor.prototype.getPosition = function() {
  40702. // This PoseSensor doesn't support position
  40703. return null;
  40704. };
  40705. FusionPoseSensor.prototype.getOrientation = function() {
  40706. // Convert from filter space to the the same system used by the
  40707. // deviceorientation event.
  40708. var orientation = this.filter.getOrientation();
  40709. // Predict orientation.
  40710. this.predictedQ = this.posePredictor.getPrediction(orientation, this.gyroscope, this.previousTimestampS);
  40711. // Convert to THREE coordinate system: -Z forward, Y up, X right.
  40712. var out = new MathUtil.Quaternion();
  40713. out.copy(this.filterToWorldQ);
  40714. out.multiply(this.resetQ);
  40715. if (!window.WebVRConfig.TOUCH_PANNER_DISABLED) {
  40716. out.multiply(this.touchPanner.getOrientation());
  40717. }
  40718. out.multiply(this.predictedQ);
  40719. out.multiply(this.worldToScreenQ);
  40720. // Handle the yaw-only case.
  40721. if (window.WebVRConfig.YAW_ONLY) {
  40722. // Make a quaternion that only turns around the Y-axis.
  40723. out.x = 0;
  40724. out.z = 0;
  40725. out.normalize();
  40726. }
  40727. this.orientationOut_[0] = out.x;
  40728. this.orientationOut_[1] = out.y;
  40729. this.orientationOut_[2] = out.z;
  40730. this.orientationOut_[3] = out.w;
  40731. return this.orientationOut_;
  40732. };
  40733. FusionPoseSensor.prototype.resetPose = function() {
  40734. // Reduce to inverted yaw-only.
  40735. this.resetQ.copy(this.filter.getOrientation());
  40736. this.resetQ.x = 0;
  40737. this.resetQ.y = 0;
  40738. this.resetQ.z *= -1;
  40739. this.resetQ.normalize();
  40740. // Take into account extra transformations in landscape mode.
  40741. if (Util.isLandscapeMode()) {
  40742. this.resetQ.multiply(this.inverseWorldToScreenQ);
  40743. }
  40744. // Take into account original pose.
  40745. this.resetQ.multiply(this.originalPoseAdjustQ);
  40746. if (!window.WebVRConfig.TOUCH_PANNER_DISABLED) {
  40747. this.touchPanner.resetSensor();
  40748. }
  40749. };
  40750. FusionPoseSensor.prototype.onDeviceMotion_ = function(deviceMotion) {
  40751. this.updateDeviceMotion_(deviceMotion);
  40752. };
  40753. FusionPoseSensor.prototype.updateDeviceMotion_ = function(deviceMotion) {
  40754. var accGravity = deviceMotion.accelerationIncludingGravity;
  40755. var rotRate = deviceMotion.rotationRate;
  40756. var timestampS = deviceMotion.timeStamp / 1000;
  40757. var deltaS = timestampS - this.previousTimestampS;
  40758. if (deltaS <= Util.MIN_TIMESTEP || deltaS > Util.MAX_TIMESTEP) {
  40759. console.warn('Invalid timestamps detected. Time step between successive ' +
  40760. 'gyroscope sensor samples is very small or not monotonic');
  40761. this.previousTimestampS = timestampS;
  40762. return;
  40763. }
  40764. this.accelerometer.set(-accGravity.x, -accGravity.y, -accGravity.z);
  40765. this.gyroscope.set(rotRate.alpha, rotRate.beta, rotRate.gamma);
  40766. // With iOS and Firefox Android, rotationRate is reported in degrees,
  40767. // so we first convert to radians.
  40768. if (this.isIOS || this.isFirefoxAndroid) {
  40769. this.gyroscope.multiplyScalar(Math.PI / 180);
  40770. }
  40771. this.filter.addAccelMeasurement(this.accelerometer, timestampS);
  40772. this.filter.addGyroMeasurement(this.gyroscope, timestampS);
  40773. this.previousTimestampS = timestampS;
  40774. };
  40775. FusionPoseSensor.prototype.onOrientationChange_ = function(screenOrientation) {
  40776. this.setScreenTransform_();
  40777. };
  40778. /**
  40779. * This is only needed if we are in an cross origin iframe on iOS to work around
  40780. * this issue: https://bugs.webkit.org/show_bug.cgi?id=152299.
  40781. */
  40782. FusionPoseSensor.prototype.onMessage_ = function(event) {
  40783. var message = event.data;
  40784. // If there's no message type, ignore it.
  40785. if (!message || !message.type) {
  40786. return;
  40787. }
  40788. // Ignore all messages that aren't devicemotion.
  40789. var type = message.type.toLowerCase();
  40790. if (type !== 'devicemotion') {
  40791. return;
  40792. }
  40793. // Update device motion.
  40794. this.updateDeviceMotion_(message.deviceMotionEvent);
  40795. };
  40796. FusionPoseSensor.prototype.setScreenTransform_ = function() {
  40797. this.worldToScreenQ.set(0, 0, 0, 1);
  40798. switch (window.orientation) {
  40799. case 0:
  40800. break;
  40801. case 90:
  40802. this.worldToScreenQ.setFromAxisAngle(new MathUtil.Vector3(0, 0, 1), -Math.PI / 2);
  40803. break;
  40804. case -90:
  40805. this.worldToScreenQ.setFromAxisAngle(new MathUtil.Vector3(0, 0, 1), Math.PI / 2);
  40806. break;
  40807. case 180:
  40808. // TODO.
  40809. break;
  40810. }
  40811. this.inverseWorldToScreenQ.copy(this.worldToScreenQ);
  40812. this.inverseWorldToScreenQ.inverse();
  40813. };
  40814. FusionPoseSensor.prototype.start = function() {
  40815. this.onDeviceMotionCallback_ = this.onDeviceMotion_.bind(this);
  40816. this.onOrientationChangeCallback_ = this.onOrientationChange_.bind(this);
  40817. this.onMessageCallback_ = this.onMessage_.bind(this);
  40818. // Only listen for postMessages if we're in an iOS and embedded inside a cross
  40819. // domain IFrame. In this case, the polyfill can still work if the containing
  40820. // page sends synthetic devicemotion events. For an example of this, see
  40821. // iframe-message-sender.js in VR View: https://goo.gl/XDtvFZ
  40822. if (Util.isIOS() && Util.isInsideCrossDomainIFrame()) {
  40823. window.addEventListener('message', this.onMessageCallback_);
  40824. }
  40825. window.addEventListener('orientationchange', this.onOrientationChangeCallback_);
  40826. window.addEventListener('devicemotion', this.onDeviceMotionCallback_);
  40827. };
  40828. FusionPoseSensor.prototype.stop = function() {
  40829. window.removeEventListener('devicemotion', this.onDeviceMotionCallback_);
  40830. window.removeEventListener('orientationchange', this.onOrientationChangeCallback_);
  40831. window.removeEventListener('message', this.onMessageCallback_);
  40832. };
  40833. module.exports = FusionPoseSensor;
  40834. },{"../math-util.js":60,"../touch-panner.js":68,"../util.js":69,"./complementary-filter.js":64,"./pose-predictor.js":66}],66:[function(_dereq_,module,exports){
  40835. /*
  40836. * Copyright 2015 Google Inc. All Rights Reserved.
  40837. * Licensed under the Apache License, Version 2.0 (the "License");
  40838. * you may not use this file except in compliance with the License.
  40839. * You may obtain a copy of the License at
  40840. *
  40841. * http://www.apache.org/licenses/LICENSE-2.0
  40842. *
  40843. * Unless required by applicable law or agreed to in writing, software
  40844. * distributed under the License is distributed on an "AS IS" BASIS,
  40845. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40846. * See the License for the specific language governing permissions and
  40847. * limitations under the License.
  40848. */
  40849. var MathUtil = _dereq_('../math-util');
  40850. var Util = _dereq_('../util');
  40851. /**
  40852. * Given an orientation and the gyroscope data, predicts the future orientation
  40853. * of the head. This makes rendering appear faster.
  40854. *
  40855. * Also see: http://msl.cs.uiuc.edu/~lavalle/papers/LavYerKatAnt14.pdf
  40856. *
  40857. * @param {Number} predictionTimeS time from head movement to the appearance of
  40858. * the corresponding image.
  40859. */
  40860. function PosePredictor(predictionTimeS) {
  40861. this.predictionTimeS = predictionTimeS;
  40862. // The quaternion corresponding to the previous state.
  40863. this.previousQ = new MathUtil.Quaternion();
  40864. // Previous time a prediction occurred.
  40865. this.previousTimestampS = null;
  40866. // The delta quaternion that adjusts the current pose.
  40867. this.deltaQ = new MathUtil.Quaternion();
  40868. // The output quaternion.
  40869. this.outQ = new MathUtil.Quaternion();
  40870. }
  40871. PosePredictor.prototype.getPrediction = function(currentQ, gyro, timestampS) {
  40872. if (!this.previousTimestampS) {
  40873. this.previousQ.copy(currentQ);
  40874. this.previousTimestampS = timestampS;
  40875. return currentQ;
  40876. }
  40877. // Calculate axis and angle based on gyroscope rotation rate data.
  40878. var axis = new MathUtil.Vector3();
  40879. axis.copy(gyro);
  40880. axis.normalize();
  40881. var angularSpeed = gyro.length();
  40882. // If we're rotating slowly, don't do prediction.
  40883. if (angularSpeed < MathUtil.degToRad * 20) {
  40884. if (Util.isDebug()) {
  40885. console.log('Moving slowly, at %s deg/s: no prediction',
  40886. (MathUtil.radToDeg * angularSpeed).toFixed(1));
  40887. }
  40888. this.outQ.copy(currentQ);
  40889. this.previousQ.copy(currentQ);
  40890. return this.outQ;
  40891. }
  40892. // Get the predicted angle based on the time delta and latency.
  40893. var deltaT = timestampS - this.previousTimestampS;
  40894. var predictAngle = angularSpeed * this.predictionTimeS;
  40895. this.deltaQ.setFromAxisAngle(axis, predictAngle);
  40896. this.outQ.copy(this.previousQ);
  40897. this.outQ.multiply(this.deltaQ);
  40898. this.previousQ.copy(currentQ);
  40899. this.previousTimestampS = timestampS;
  40900. return this.outQ;
  40901. };
  40902. module.exports = PosePredictor;
  40903. },{"../math-util":60,"../util":69}],67:[function(_dereq_,module,exports){
  40904. function SensorSample(sample, timestampS) {
  40905. this.set(sample, timestampS);
  40906. };
  40907. SensorSample.prototype.set = function(sample, timestampS) {
  40908. this.sample = sample;
  40909. this.timestampS = timestampS;
  40910. };
  40911. SensorSample.prototype.copy = function(sensorSample) {
  40912. this.set(sensorSample.sample, sensorSample.timestampS);
  40913. };
  40914. module.exports = SensorSample;
  40915. },{}],68:[function(_dereq_,module,exports){
  40916. /*
  40917. * Copyright 2015 Google Inc. All Rights Reserved.
  40918. * Licensed under the Apache License, Version 2.0 (the "License");
  40919. * you may not use this file except in compliance with the License.
  40920. * You may obtain a copy of the License at
  40921. *
  40922. * http://www.apache.org/licenses/LICENSE-2.0
  40923. *
  40924. * Unless required by applicable law or agreed to in writing, software
  40925. * distributed under the License is distributed on an "AS IS" BASIS,
  40926. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40927. * See the License for the specific language governing permissions and
  40928. * limitations under the License.
  40929. */
  40930. var MathUtil = _dereq_('./math-util.js');
  40931. var Util = _dereq_('./util.js');
  40932. var ROTATE_SPEED = 0.5;
  40933. /**
  40934. * Provides a quaternion responsible for pre-panning the scene before further
  40935. * transformations due to device sensors.
  40936. */
  40937. function TouchPanner() {
  40938. window.addEventListener('touchstart', this.onTouchStart_.bind(this));
  40939. window.addEventListener('touchmove', this.onTouchMove_.bind(this));
  40940. window.addEventListener('touchend', this.onTouchEnd_.bind(this));
  40941. this.isTouching = false;
  40942. this.rotateStart = new MathUtil.Vector2();
  40943. this.rotateEnd = new MathUtil.Vector2();
  40944. this.rotateDelta = new MathUtil.Vector2();
  40945. this.theta = 0;
  40946. this.orientation = new MathUtil.Quaternion();
  40947. }
  40948. TouchPanner.prototype.getOrientation = function() {
  40949. this.orientation.setFromEulerXYZ(0, 0, this.theta);
  40950. return this.orientation;
  40951. };
  40952. TouchPanner.prototype.resetSensor = function() {
  40953. this.theta = 0;
  40954. };
  40955. TouchPanner.prototype.onTouchStart_ = function(e) {
  40956. // Only respond if there is exactly one touch.
  40957. // Note that the Daydream controller passes in a `touchstart` event with
  40958. // no `touches` property, so we must check for that case too.
  40959. if (!e.touches || e.touches.length != 1) {
  40960. return;
  40961. }
  40962. this.rotateStart.set(e.touches[0].pageX, e.touches[0].pageY);
  40963. this.isTouching = true;
  40964. };
  40965. TouchPanner.prototype.onTouchMove_ = function(e) {
  40966. if (!this.isTouching) {
  40967. return;
  40968. }
  40969. this.rotateEnd.set(e.touches[0].pageX, e.touches[0].pageY);
  40970. this.rotateDelta.subVectors(this.rotateEnd, this.rotateStart);
  40971. this.rotateStart.copy(this.rotateEnd);
  40972. // On iOS, direction is inverted.
  40973. if (Util.isIOS()) {
  40974. this.rotateDelta.x *= -1;
  40975. }
  40976. var element = document.body;
  40977. this.theta += 2 * Math.PI * this.rotateDelta.x / element.clientWidth * ROTATE_SPEED;
  40978. };
  40979. TouchPanner.prototype.onTouchEnd_ = function(e) {
  40980. this.isTouching = false;
  40981. };
  40982. module.exports = TouchPanner;
  40983. },{"./math-util.js":60,"./util.js":69}],69:[function(_dereq_,module,exports){
  40984. /*
  40985. * Copyright 2015 Google Inc. All Rights Reserved.
  40986. * Licensed under the Apache License, Version 2.0 (the "License");
  40987. * you may not use this file except in compliance with the License.
  40988. * You may obtain a copy of the License at
  40989. *
  40990. * http://www.apache.org/licenses/LICENSE-2.0
  40991. *
  40992. * Unless required by applicable law or agreed to in writing, software
  40993. * distributed under the License is distributed on an "AS IS" BASIS,
  40994. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40995. * See the License for the specific language governing permissions and
  40996. * limitations under the License.
  40997. */
  40998. var Util = window.Util || {};
  40999. Util.MIN_TIMESTEP = 0.001;
  41000. Util.MAX_TIMESTEP = 1;
  41001. Util.base64 = function(mimeType, base64) {
  41002. return 'data:' + mimeType + ';base64,' + base64;
  41003. };
  41004. Util.clamp = function(value, min, max) {
  41005. return Math.min(Math.max(min, value), max);
  41006. };
  41007. Util.lerp = function(a, b, t) {
  41008. return a + ((b - a) * t);
  41009. };
  41010. /**
  41011. * Light polyfill for `Promise.race`. Returns
  41012. * a promise that resolves when the first promise
  41013. * provided resolves.
  41014. *
  41015. * @param {Array<Promise>} promises
  41016. */
  41017. Util.race = function(promises) {
  41018. if (Promise.race) {
  41019. return Promise.race(promises);
  41020. }
  41021. return new Promise(function (resolve, reject) {
  41022. for (var i = 0; i < promises.length; i++) {
  41023. promises[i].then(resolve, reject);
  41024. }
  41025. });
  41026. };
  41027. Util.isIOS = (function() {
  41028. var isIOS = /iPad|iPhone|iPod/.test(navigator.platform);
  41029. return function() {
  41030. return isIOS;
  41031. };
  41032. })();
  41033. Util.isWebViewAndroid = (function() {
  41034. var isWebViewAndroid = navigator.userAgent.indexOf('Version') !== -1 &&
  41035. navigator.userAgent.indexOf('Android') !== -1 &&
  41036. navigator.userAgent.indexOf('Chrome') !== -1;
  41037. return function() {
  41038. return isWebViewAndroid;
  41039. };
  41040. })();
  41041. Util.isSafari = (function() {
  41042. var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  41043. return function() {
  41044. return isSafari;
  41045. };
  41046. })();
  41047. Util.isFirefoxAndroid = (function() {
  41048. var isFirefoxAndroid = navigator.userAgent.indexOf('Firefox') !== -1 &&
  41049. navigator.userAgent.indexOf('Android') !== -1;
  41050. return function() {
  41051. return isFirefoxAndroid;
  41052. };
  41053. })();
  41054. Util.isLandscapeMode = function() {
  41055. return (window.orientation == 90 || window.orientation == -90);
  41056. };
  41057. // Helper method to validate the time steps of sensor timestamps.
  41058. Util.isTimestampDeltaValid = function(timestampDeltaS) {
  41059. if (isNaN(timestampDeltaS)) {
  41060. return false;
  41061. }
  41062. if (timestampDeltaS <= Util.MIN_TIMESTEP) {
  41063. return false;
  41064. }
  41065. if (timestampDeltaS > Util.MAX_TIMESTEP) {
  41066. return false;
  41067. }
  41068. return true;
  41069. };
  41070. Util.getScreenWidth = function() {
  41071. return Math.max(window.screen.width, window.screen.height) *
  41072. window.devicePixelRatio;
  41073. };
  41074. Util.getScreenHeight = function() {
  41075. return Math.min(window.screen.width, window.screen.height) *
  41076. window.devicePixelRatio;
  41077. };
  41078. Util.requestFullscreen = function(element) {
  41079. if (Util.isWebViewAndroid()) {
  41080. return false;
  41081. }
  41082. if (element.requestFullscreen) {
  41083. element.requestFullscreen();
  41084. } else if (element.webkitRequestFullscreen) {
  41085. element.webkitRequestFullscreen();
  41086. } else if (element.mozRequestFullScreen) {
  41087. element.mozRequestFullScreen();
  41088. } else if (element.msRequestFullscreen) {
  41089. element.msRequestFullscreen();
  41090. } else {
  41091. return false;
  41092. }
  41093. return true;
  41094. };
  41095. Util.exitFullscreen = function() {
  41096. if (document.exitFullscreen) {
  41097. document.exitFullscreen();
  41098. } else if (document.webkitExitFullscreen) {
  41099. document.webkitExitFullscreen();
  41100. } else if (document.mozCancelFullScreen) {
  41101. document.mozCancelFullScreen();
  41102. } else if (document.msExitFullscreen) {
  41103. document.msExitFullscreen();
  41104. } else {
  41105. return false;
  41106. }
  41107. return true;
  41108. };
  41109. Util.getFullscreenElement = function() {
  41110. return document.fullscreenElement ||
  41111. document.webkitFullscreenElement ||
  41112. document.mozFullScreenElement ||
  41113. document.msFullscreenElement;
  41114. };
  41115. Util.linkProgram = function(gl, vertexSource, fragmentSource, attribLocationMap) {
  41116. // No error checking for brevity.
  41117. var vertexShader = gl.createShader(gl.VERTEX_SHADER);
  41118. gl.shaderSource(vertexShader, vertexSource);
  41119. gl.compileShader(vertexShader);
  41120. var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
  41121. gl.shaderSource(fragmentShader, fragmentSource);
  41122. gl.compileShader(fragmentShader);
  41123. var program = gl.createProgram();
  41124. gl.attachShader(program, vertexShader);
  41125. gl.attachShader(program, fragmentShader);
  41126. for (var attribName in attribLocationMap)
  41127. gl.bindAttribLocation(program, attribLocationMap[attribName], attribName);
  41128. gl.linkProgram(program);
  41129. gl.deleteShader(vertexShader);
  41130. gl.deleteShader(fragmentShader);
  41131. return program;
  41132. };
  41133. Util.getProgramUniforms = function(gl, program) {
  41134. var uniforms = {};
  41135. var uniformCount = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  41136. var uniformName = '';
  41137. for (var i = 0; i < uniformCount; i++) {
  41138. var uniformInfo = gl.getActiveUniform(program, i);
  41139. uniformName = uniformInfo.name.replace('[0]', '');
  41140. uniforms[uniformName] = gl.getUniformLocation(program, uniformName);
  41141. }
  41142. return uniforms;
  41143. };
  41144. Util.orthoMatrix = function (out, left, right, bottom, top, near, far) {
  41145. var lr = 1 / (left - right),
  41146. bt = 1 / (bottom - top),
  41147. nf = 1 / (near - far);
  41148. out[0] = -2 * lr;
  41149. out[1] = 0;
  41150. out[2] = 0;
  41151. out[3] = 0;
  41152. out[4] = 0;
  41153. out[5] = -2 * bt;
  41154. out[6] = 0;
  41155. out[7] = 0;
  41156. out[8] = 0;
  41157. out[9] = 0;
  41158. out[10] = 2 * nf;
  41159. out[11] = 0;
  41160. out[12] = (left + right) * lr;
  41161. out[13] = (top + bottom) * bt;
  41162. out[14] = (far + near) * nf;
  41163. out[15] = 1;
  41164. return out;
  41165. };
  41166. Util.copyArray = function (source, dest) {
  41167. for (var i = 0, n = source.length; i < n; i++) {
  41168. dest[i] = source[i];
  41169. }
  41170. };
  41171. Util.isMobile = function() {
  41172. var check = false;
  41173. (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);
  41174. return check;
  41175. };
  41176. Util.extend = function(dest, src) {
  41177. for (var key in src) {
  41178. if (src.hasOwnProperty(key)) {
  41179. dest[key] = src[key];
  41180. }
  41181. }
  41182. return dest;
  41183. }
  41184. Util.safariCssSizeWorkaround = function(canvas) {
  41185. // TODO(smus): Remove this workaround when Safari for iOS is fixed.
  41186. // iOS only workaround (for https://bugs.webkit.org/show_bug.cgi?id=152556).
  41187. //
  41188. // "To the last I grapple with thee;
  41189. // from hell's heart I stab at thee;
  41190. // for hate's sake I spit my last breath at thee."
  41191. // -- Moby Dick, by Herman Melville
  41192. if (Util.isIOS()) {
  41193. var width = canvas.style.width;
  41194. var height = canvas.style.height;
  41195. canvas.style.width = (parseInt(width) + 1) + 'px';
  41196. canvas.style.height = (parseInt(height)) + 'px';
  41197. setTimeout(function() {
  41198. canvas.style.width = width;
  41199. canvas.style.height = height;
  41200. }, 100);
  41201. }
  41202. // Debug only.
  41203. window.Util = Util;
  41204. window.canvas = canvas;
  41205. };
  41206. Util.isDebug = function() {
  41207. return Util.getQueryParameter('debug');
  41208. };
  41209. Util.getQueryParameter = function(name) {
  41210. var name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  41211. var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
  41212. results = regex.exec(location.search);
  41213. return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  41214. };
  41215. Util.frameDataFromPose = (function() {
  41216. var piOver180 = Math.PI / 180.0;
  41217. var rad45 = Math.PI * 0.25;
  41218. // Borrowed from glMatrix.
  41219. function mat4_perspectiveFromFieldOfView(out, fov, near, far) {
  41220. var upTan = Math.tan(fov ? (fov.upDegrees * piOver180) : rad45),
  41221. downTan = Math.tan(fov ? (fov.downDegrees * piOver180) : rad45),
  41222. leftTan = Math.tan(fov ? (fov.leftDegrees * piOver180) : rad45),
  41223. rightTan = Math.tan(fov ? (fov.rightDegrees * piOver180) : rad45),
  41224. xScale = 2.0 / (leftTan + rightTan),
  41225. yScale = 2.0 / (upTan + downTan);
  41226. out[0] = xScale;
  41227. out[1] = 0.0;
  41228. out[2] = 0.0;
  41229. out[3] = 0.0;
  41230. out[4] = 0.0;
  41231. out[5] = yScale;
  41232. out[6] = 0.0;
  41233. out[7] = 0.0;
  41234. out[8] = -((leftTan - rightTan) * xScale * 0.5);
  41235. out[9] = ((upTan - downTan) * yScale * 0.5);
  41236. out[10] = far / (near - far);
  41237. out[11] = -1.0;
  41238. out[12] = 0.0;
  41239. out[13] = 0.0;
  41240. out[14] = (far * near) / (near - far);
  41241. out[15] = 0.0;
  41242. return out;
  41243. }
  41244. function mat4_fromRotationTranslation(out, q, v) {
  41245. // Quaternion math
  41246. var x = q[0], y = q[1], z = q[2], w = q[3],
  41247. x2 = x + x,
  41248. y2 = y + y,
  41249. z2 = z + z,
  41250. xx = x * x2,
  41251. xy = x * y2,
  41252. xz = x * z2,
  41253. yy = y * y2,
  41254. yz = y * z2,
  41255. zz = z * z2,
  41256. wx = w * x2,
  41257. wy = w * y2,
  41258. wz = w * z2;
  41259. out[0] = 1 - (yy + zz);
  41260. out[1] = xy + wz;
  41261. out[2] = xz - wy;
  41262. out[3] = 0;
  41263. out[4] = xy - wz;
  41264. out[5] = 1 - (xx + zz);
  41265. out[6] = yz + wx;
  41266. out[7] = 0;
  41267. out[8] = xz + wy;
  41268. out[9] = yz - wx;
  41269. out[10] = 1 - (xx + yy);
  41270. out[11] = 0;
  41271. out[12] = v[0];
  41272. out[13] = v[1];
  41273. out[14] = v[2];
  41274. out[15] = 1;
  41275. return out;
  41276. };
  41277. function mat4_translate(out, a, v) {
  41278. var x = v[0], y = v[1], z = v[2],
  41279. a00, a01, a02, a03,
  41280. a10, a11, a12, a13,
  41281. a20, a21, a22, a23;
  41282. if (a === out) {
  41283. out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
  41284. out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
  41285. out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
  41286. out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
  41287. } else {
  41288. a00 = a[0]; a01 = a[1]; a02 = a[2]; a03 = a[3];
  41289. a10 = a[4]; a11 = a[5]; a12 = a[6]; a13 = a[7];
  41290. a20 = a[8]; a21 = a[9]; a22 = a[10]; a23 = a[11];
  41291. out[0] = a00; out[1] = a01; out[2] = a02; out[3] = a03;
  41292. out[4] = a10; out[5] = a11; out[6] = a12; out[7] = a13;
  41293. out[8] = a20; out[9] = a21; out[10] = a22; out[11] = a23;
  41294. out[12] = a00 * x + a10 * y + a20 * z + a[12];
  41295. out[13] = a01 * x + a11 * y + a21 * z + a[13];
  41296. out[14] = a02 * x + a12 * y + a22 * z + a[14];
  41297. out[15] = a03 * x + a13 * y + a23 * z + a[15];
  41298. }
  41299. return out;
  41300. };
  41301. function mat4_invert(out, a) {
  41302. var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3],
  41303. a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7],
  41304. a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11],
  41305. a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15],
  41306. b00 = a00 * a11 - a01 * a10,
  41307. b01 = a00 * a12 - a02 * a10,
  41308. b02 = a00 * a13 - a03 * a10,
  41309. b03 = a01 * a12 - a02 * a11,
  41310. b04 = a01 * a13 - a03 * a11,
  41311. b05 = a02 * a13 - a03 * a12,
  41312. b06 = a20 * a31 - a21 * a30,
  41313. b07 = a20 * a32 - a22 * a30,
  41314. b08 = a20 * a33 - a23 * a30,
  41315. b09 = a21 * a32 - a22 * a31,
  41316. b10 = a21 * a33 - a23 * a31,
  41317. b11 = a22 * a33 - a23 * a32,
  41318. // Calculate the determinant
  41319. det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  41320. if (!det) {
  41321. return null;
  41322. }
  41323. det = 1.0 / det;
  41324. out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
  41325. out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
  41326. out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
  41327. out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
  41328. out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
  41329. out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
  41330. out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
  41331. out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
  41332. out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
  41333. out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
  41334. out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
  41335. out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
  41336. out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
  41337. out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
  41338. out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
  41339. out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
  41340. return out;
  41341. };
  41342. var defaultOrientation = new Float32Array([0, 0, 0, 1]);
  41343. var defaultPosition = new Float32Array([0, 0, 0]);
  41344. function updateEyeMatrices(projection, view, pose, parameters, vrDisplay) {
  41345. mat4_perspectiveFromFieldOfView(projection, parameters ? parameters.fieldOfView : null, vrDisplay.depthNear, vrDisplay.depthFar);
  41346. var orientation = pose.orientation || defaultOrientation;
  41347. var position = pose.position || defaultPosition;
  41348. mat4_fromRotationTranslation(view, orientation, position);
  41349. if (parameters)
  41350. mat4_translate(view, view, parameters.offset);
  41351. mat4_invert(view, view);
  41352. }
  41353. return function(frameData, pose, vrDisplay) {
  41354. if (!frameData || !pose)
  41355. return false;
  41356. frameData.pose = pose;
  41357. frameData.timestamp = pose.timestamp;
  41358. updateEyeMatrices(
  41359. frameData.leftProjectionMatrix, frameData.leftViewMatrix,
  41360. pose, vrDisplay.getEyeParameters("left"), vrDisplay);
  41361. updateEyeMatrices(
  41362. frameData.rightProjectionMatrix, frameData.rightViewMatrix,
  41363. pose, vrDisplay.getEyeParameters("right"), vrDisplay);
  41364. return true;
  41365. };
  41366. })();
  41367. Util.isInsideCrossDomainIFrame = function() {
  41368. var isFramed = (window.self !== window.top);
  41369. var refDomain = Util.getDomainFromUrl(document.referrer);
  41370. var thisDomain = Util.getDomainFromUrl(window.location.href);
  41371. return isFramed && (refDomain !== thisDomain);
  41372. };
  41373. // From http://stackoverflow.com/a/23945027.
  41374. Util.getDomainFromUrl = function(url) {
  41375. var domain;
  41376. // Find & remove protocol (http, ftp, etc.) and get domain.
  41377. if (url.indexOf("://") > -1) {
  41378. domain = url.split('/')[2];
  41379. }
  41380. else {
  41381. domain = url.split('/')[0];
  41382. }
  41383. //find & remove port number
  41384. domain = domain.split(':')[0];
  41385. return domain;
  41386. }
  41387. module.exports = Util;
  41388. },{}],70:[function(_dereq_,module,exports){
  41389. /*
  41390. * Copyright 2015 Google Inc. All Rights Reserved.
  41391. * Licensed under the Apache License, Version 2.0 (the "License");
  41392. * you may not use this file except in compliance with the License.
  41393. * You may obtain a copy of the License at
  41394. *
  41395. * http://www.apache.org/licenses/LICENSE-2.0
  41396. *
  41397. * Unless required by applicable law or agreed to in writing, software
  41398. * distributed under the License is distributed on an "AS IS" BASIS,
  41399. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41400. * See the License for the specific language governing permissions and
  41401. * limitations under the License.
  41402. */
  41403. var DeviceInfo = _dereq_('./device-info.js');
  41404. var Util = _dereq_('./util.js');
  41405. var DEFAULT_VIEWER = 'CardboardV1';
  41406. var VIEWER_KEY = 'WEBVR_CARDBOARD_VIEWER';
  41407. var CLASS_NAME = 'webvr-polyfill-viewer-selector';
  41408. /**
  41409. * Creates a viewer selector with the options specified. Supports being shown
  41410. * and hidden. Generates events when viewer parameters change. Also supports
  41411. * saving the currently selected index in localStorage.
  41412. */
  41413. function ViewerSelector() {
  41414. // Try to load the selected key from local storage.
  41415. try {
  41416. this.selectedKey = localStorage.getItem(VIEWER_KEY);
  41417. } catch (error) {
  41418. console.error('Failed to load viewer profile: %s', error);
  41419. }
  41420. //If none exists, or if localstorage is unavailable, use the default key.
  41421. if (!this.selectedKey) {
  41422. this.selectedKey = DEFAULT_VIEWER;
  41423. }
  41424. this.dialog = this.createDialog_(DeviceInfo.Viewers);
  41425. this.root = null;
  41426. this.onChangeCallbacks_ = [];
  41427. }
  41428. ViewerSelector.prototype.show = function(root) {
  41429. this.root = root;
  41430. root.appendChild(this.dialog);
  41431. // Ensure the currently selected item is checked.
  41432. var selected = this.dialog.querySelector('#' + this.selectedKey);
  41433. selected.checked = true;
  41434. // Show the UI.
  41435. this.dialog.style.display = 'block';
  41436. };
  41437. ViewerSelector.prototype.hide = function() {
  41438. if (this.root && this.root.contains(this.dialog)) {
  41439. this.root.removeChild(this.dialog);
  41440. }
  41441. this.dialog.style.display = 'none';
  41442. };
  41443. ViewerSelector.prototype.getCurrentViewer = function() {
  41444. return DeviceInfo.Viewers[this.selectedKey];
  41445. };
  41446. ViewerSelector.prototype.getSelectedKey_ = function() {
  41447. var input = this.dialog.querySelector('input[name=field]:checked');
  41448. if (input) {
  41449. return input.id;
  41450. }
  41451. return null;
  41452. };
  41453. ViewerSelector.prototype.onChange = function(cb) {
  41454. this.onChangeCallbacks_.push(cb);
  41455. };
  41456. ViewerSelector.prototype.fireOnChange_ = function(viewer) {
  41457. for (var i = 0; i < this.onChangeCallbacks_.length; i++) {
  41458. this.onChangeCallbacks_[i](viewer);
  41459. }
  41460. };
  41461. ViewerSelector.prototype.onSave_ = function() {
  41462. this.selectedKey = this.getSelectedKey_();
  41463. if (!this.selectedKey || !DeviceInfo.Viewers[this.selectedKey]) {
  41464. console.error('ViewerSelector.onSave_: this should never happen!');
  41465. return;
  41466. }
  41467. this.fireOnChange_(DeviceInfo.Viewers[this.selectedKey]);
  41468. // Attempt to save the viewer profile, but fails in private mode.
  41469. try {
  41470. localStorage.setItem(VIEWER_KEY, this.selectedKey);
  41471. } catch(error) {
  41472. console.error('Failed to save viewer profile: %s', error);
  41473. }
  41474. this.hide();
  41475. };
  41476. /**
  41477. * Creates the dialog.
  41478. */
  41479. ViewerSelector.prototype.createDialog_ = function(options) {
  41480. var container = document.createElement('div');
  41481. container.classList.add(CLASS_NAME);
  41482. container.style.display = 'none';
  41483. // Create an overlay that dims the background, and which goes away when you
  41484. // tap it.
  41485. var overlay = document.createElement('div');
  41486. var s = overlay.style;
  41487. s.position = 'fixed';
  41488. s.left = 0;
  41489. s.top = 0;
  41490. s.width = '100%';
  41491. s.height = '100%';
  41492. s.background = 'rgba(0, 0, 0, 0.3)';
  41493. overlay.addEventListener('click', this.hide.bind(this));
  41494. var width = 280;
  41495. var dialog = document.createElement('div');
  41496. var s = dialog.style;
  41497. s.boxSizing = 'border-box';
  41498. s.position = 'fixed';
  41499. s.top = '24px';
  41500. s.left = '50%';
  41501. s.marginLeft = (-width/2) + 'px';
  41502. s.width = width + 'px';
  41503. s.padding = '24px';
  41504. s.overflow = 'hidden';
  41505. s.background = '#fafafa';
  41506. s.fontFamily = "'Roboto', sans-serif";
  41507. s.boxShadow = '0px 5px 20px #666';
  41508. dialog.appendChild(this.createH1_('Select your viewer'));
  41509. for (var id in options) {
  41510. dialog.appendChild(this.createChoice_(id, options[id].label));
  41511. }
  41512. dialog.appendChild(this.createButton_('Save', this.onSave_.bind(this)));
  41513. container.appendChild(overlay);
  41514. container.appendChild(dialog);
  41515. return container;
  41516. };
  41517. ViewerSelector.prototype.createH1_ = function(name) {
  41518. var h1 = document.createElement('h1');
  41519. var s = h1.style;
  41520. s.color = 'black';
  41521. s.fontSize = '20px';
  41522. s.fontWeight = 'bold';
  41523. s.marginTop = 0;
  41524. s.marginBottom = '24px';
  41525. h1.innerHTML = name;
  41526. return h1;
  41527. };
  41528. ViewerSelector.prototype.createChoice_ = function(id, name) {
  41529. /*
  41530. <div class="choice">
  41531. <input id="v1" type="radio" name="field" value="v1">
  41532. <label for="v1">Cardboard V1</label>
  41533. </div>
  41534. */
  41535. var div = document.createElement('div');
  41536. div.style.marginTop = '8px';
  41537. div.style.color = 'black';
  41538. var input = document.createElement('input');
  41539. input.style.fontSize = '30px';
  41540. input.setAttribute('id', id);
  41541. input.setAttribute('type', 'radio');
  41542. input.setAttribute('value', id);
  41543. input.setAttribute('name', 'field');
  41544. var label = document.createElement('label');
  41545. label.style.marginLeft = '4px';
  41546. label.setAttribute('for', id);
  41547. label.innerHTML = name;
  41548. div.appendChild(input);
  41549. div.appendChild(label);
  41550. return div;
  41551. };
  41552. ViewerSelector.prototype.createButton_ = function(label, onclick) {
  41553. var button = document.createElement('button');
  41554. button.innerHTML = label;
  41555. var s = button.style;
  41556. s.float = 'right';
  41557. s.textTransform = 'uppercase';
  41558. s.color = '#1094f7';
  41559. s.fontSize = '14px';
  41560. s.letterSpacing = 0;
  41561. s.border = 0;
  41562. s.background = 'none';
  41563. s.marginTop = '16px';
  41564. button.addEventListener('click', onclick);
  41565. return button;
  41566. };
  41567. module.exports = ViewerSelector;
  41568. },{"./device-info.js":54,"./util.js":69}],71:[function(_dereq_,module,exports){
  41569. /*
  41570. * Copyright 2015 Google Inc. All Rights Reserved.
  41571. * Licensed under the Apache License, Version 2.0 (the "License");
  41572. * you may not use this file except in compliance with the License.
  41573. * You may obtain a copy of the License at
  41574. *
  41575. * http://www.apache.org/licenses/LICENSE-2.0
  41576. *
  41577. * Unless required by applicable law or agreed to in writing, software
  41578. * distributed under the License is distributed on an "AS IS" BASIS,
  41579. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41580. * See the License for the specific language governing permissions and
  41581. * limitations under the License.
  41582. */
  41583. var Util = _dereq_('./util.js');
  41584. /**
  41585. * Android and iOS compatible wakelock implementation.
  41586. *
  41587. * Refactored thanks to dkovalev@.
  41588. */
  41589. function AndroidWakeLock() {
  41590. var video = document.createElement('video');
  41591. video.setAttribute('loop', '');
  41592. function addSourceToVideo(element, type, dataURI) {
  41593. var source = document.createElement('source');
  41594. source.src = dataURI;
  41595. source.type = 'video/' + type;
  41596. element.appendChild(source);
  41597. }
  41598. addSourceToVideo(video,'webm', Util.base64('video/webm', 'GkXfo0AgQoaBAUL3gQFC8oEEQvOBCEKCQAR3ZWJtQoeBAkKFgQIYU4BnQI0VSalmQCgq17FAAw9CQE2AQAZ3aGFtbXlXQUAGd2hhbW15RIlACECPQAAAAAAAFlSua0AxrkAu14EBY8WBAZyBACK1nEADdW5khkAFVl9WUDglhohAA1ZQOIOBAeBABrCBCLqBCB9DtnVAIueBAKNAHIEAAIAwAQCdASoIAAgAAUAmJaQAA3AA/vz0AAA='));
  41599. addSourceToVideo(video, 'mp4', Util.base64('video/mp4', 'AAAAHGZ0eXBpc29tAAACAGlzb21pc28ybXA0MQAAAAhmcmVlAAAAG21kYXQAAAGzABAHAAABthADAowdbb9/AAAC6W1vb3YAAABsbXZoZAAAAAB8JbCAfCWwgAAAA+gAAAAAAAEAAAEAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAIVdHJhawAAAFx0a2hkAAAAD3wlsIB8JbCAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAIAAAACAAAAAABsW1kaWEAAAAgbWRoZAAAAAB8JbCAfCWwgAAAA+gAAAAAVcQAAAAAAC1oZGxyAAAAAAAAAAB2aWRlAAAAAAAAAAAAAAAAVmlkZW9IYW5kbGVyAAAAAVxtaW5mAAAAFHZtaGQAAAABAAAAAAAAAAAAAAAkZGluZgAAABxkcmVmAAAAAAAAAAEAAAAMdXJsIAAAAAEAAAEcc3RibAAAALhzdHNkAAAAAAAAAAEAAACobXA0dgAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAIAAgASAAAAEgAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABj//wAAAFJlc2RzAAAAAANEAAEABDwgEQAAAAADDUAAAAAABS0AAAGwAQAAAbWJEwAAAQAAAAEgAMSNiB9FAEQBFGMAAAGyTGF2YzUyLjg3LjQGAQIAAAAYc3R0cwAAAAAAAAABAAAAAQAAAAAAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAEAAAABAAAAFHN0c3oAAAAAAAAAEwAAAAEAAAAUc3RjbwAAAAAAAAABAAAALAAAAGB1ZHRhAAAAWG1ldGEAAAAAAAAAIWhkbHIAAAAAAAAAAG1kaXJhcHBsAAAAAAAAAAAAAAAAK2lsc3QAAAAjqXRvbwAAABtkYXRhAAAAAQAAAABMYXZmNTIuNzguMw=='));
  41600. this.request = function() {
  41601. if (video.paused) {
  41602. video.play();
  41603. }
  41604. };
  41605. this.release = function() {
  41606. video.pause();
  41607. };
  41608. }
  41609. function iOSWakeLock() {
  41610. var timer = null;
  41611. this.request = function() {
  41612. if (!timer) {
  41613. timer = setInterval(function() {
  41614. window.location = window.location;
  41615. setTimeout(window.stop, 0);
  41616. }, 30000);
  41617. }
  41618. }
  41619. this.release = function() {
  41620. if (timer) {
  41621. clearInterval(timer);
  41622. timer = null;
  41623. }
  41624. }
  41625. }
  41626. function getWakeLock() {
  41627. var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  41628. if (userAgent.match(/iPhone/i) || userAgent.match(/iPod/i)) {
  41629. return iOSWakeLock;
  41630. } else {
  41631. return AndroidWakeLock;
  41632. }
  41633. }
  41634. module.exports = getWakeLock();
  41635. },{"./util.js":69}],72:[function(_dereq_,module,exports){
  41636. /*
  41637. * Copyright 2015 Google Inc. All Rights Reserved.
  41638. * Licensed under the Apache License, Version 2.0 (the "License");
  41639. * you may not use this file except in compliance with the License.
  41640. * You may obtain a copy of the License at
  41641. *
  41642. * http://www.apache.org/licenses/LICENSE-2.0
  41643. *
  41644. * Unless required by applicable law or agreed to in writing, software
  41645. * distributed under the License is distributed on an "AS IS" BASIS,
  41646. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41647. * See the License for the specific language governing permissions and
  41648. * limitations under the License.
  41649. */
  41650. var Util = _dereq_('./util.js');
  41651. var CardboardVRDisplay = _dereq_('./cardboard-vr-display.js');
  41652. var MouseKeyboardVRDisplay = _dereq_('./mouse-keyboard-vr-display.js');
  41653. // Uncomment to add positional tracking via webcam.
  41654. //var WebcamPositionSensorVRDevice = require('./webcam-position-sensor-vr-device.js');
  41655. var VRDisplay = _dereq_('./base.js').VRDisplay;
  41656. var VRFrameData = _dereq_('./base.js').VRFrameData;
  41657. var HMDVRDevice = _dereq_('./base.js').HMDVRDevice;
  41658. var PositionSensorVRDevice = _dereq_('./base.js').PositionSensorVRDevice;
  41659. var VRDisplayHMDDevice = _dereq_('./display-wrappers.js').VRDisplayHMDDevice;
  41660. var VRDisplayPositionSensorDevice = _dereq_('./display-wrappers.js').VRDisplayPositionSensorDevice;
  41661. var version = _dereq_('../package.json').version;
  41662. function WebVRPolyfill() {
  41663. this.displays = [];
  41664. this.devices = []; // For deprecated objects
  41665. this.devicesPopulated = false;
  41666. this.nativeWebVRAvailable = this.isWebVRAvailable();
  41667. this.nativeLegacyWebVRAvailable = this.isDeprecatedWebVRAvailable();
  41668. this.nativeGetVRDisplaysFunc = this.nativeWebVRAvailable ?
  41669. navigator.getVRDisplays :
  41670. null;
  41671. if (!this.nativeLegacyWebVRAvailable) {
  41672. this.enablePolyfill();
  41673. if (window.WebVRConfig.ENABLE_DEPRECATED_API) {
  41674. this.enableDeprecatedPolyfill();
  41675. }
  41676. }
  41677. // Put a shim in place to update the API to 1.1 if needed.
  41678. InstallWebVRSpecShim();
  41679. }
  41680. WebVRPolyfill.prototype.isWebVRAvailable = function() {
  41681. return ('getVRDisplays' in navigator);
  41682. };
  41683. WebVRPolyfill.prototype.isDeprecatedWebVRAvailable = function() {
  41684. return ('getVRDevices' in navigator) || ('mozGetVRDevices' in navigator);
  41685. };
  41686. WebVRPolyfill.prototype.connectDisplay = function(vrDisplay) {
  41687. vrDisplay.fireVRDisplayConnect_();
  41688. this.displays.push(vrDisplay);
  41689. };
  41690. WebVRPolyfill.prototype.populateDevices = function() {
  41691. if (this.devicesPopulated) {
  41692. return;
  41693. }
  41694. // Initialize our virtual VR devices.
  41695. var vrDisplay = null;
  41696. // Add a Cardboard VRDisplay on compatible mobile devices
  41697. if (this.isCardboardCompatible()) {
  41698. vrDisplay = new CardboardVRDisplay();
  41699. this.connectDisplay(vrDisplay);
  41700. // For backwards compatibility
  41701. if (window.WebVRConfig.ENABLE_DEPRECATED_API) {
  41702. this.devices.push(new VRDisplayHMDDevice(vrDisplay));
  41703. this.devices.push(new VRDisplayPositionSensorDevice(vrDisplay));
  41704. }
  41705. }
  41706. // Add a Mouse and Keyboard driven VRDisplay for desktops/laptops
  41707. if (!this.isMobile() && !window.WebVRConfig.MOUSE_KEYBOARD_CONTROLS_DISABLED) {
  41708. vrDisplay = new MouseKeyboardVRDisplay();
  41709. this.connectDisplay(vrDisplay);
  41710. // For backwards compatibility
  41711. if (window.WebVRConfig.ENABLE_DEPRECATED_API) {
  41712. this.devices.push(new VRDisplayHMDDevice(vrDisplay));
  41713. this.devices.push(new VRDisplayPositionSensorDevice(vrDisplay));
  41714. }
  41715. }
  41716. // Uncomment to add positional tracking via webcam.
  41717. //if (!this.isMobile() && window.WebVRConfig.ENABLE_DEPRECATED_API) {
  41718. // positionDevice = new WebcamPositionSensorVRDevice();
  41719. // this.devices.push(positionDevice);
  41720. //}
  41721. this.devicesPopulated = true;
  41722. };
  41723. WebVRPolyfill.prototype.enablePolyfill = function() {
  41724. // Provide navigator.getVRDisplays.
  41725. navigator.getVRDisplays = this.getVRDisplays.bind(this);
  41726. // Polyfill native VRDisplay.getFrameData
  41727. if (this.nativeWebVRAvailable && window.VRFrameData) {
  41728. var NativeVRFrameData = window.VRFrameData;
  41729. var nativeFrameData = new window.VRFrameData();
  41730. var nativeGetFrameData = window.VRDisplay.prototype.getFrameData;
  41731. window.VRFrameData = VRFrameData;
  41732. window.VRDisplay.prototype.getFrameData = function(frameData) {
  41733. if (frameData instanceof NativeVRFrameData) {
  41734. nativeGetFrameData.call(this, frameData);
  41735. return;
  41736. }
  41737. /*
  41738. Copy frame data from the native object into the polyfilled object.
  41739. */
  41740. nativeGetFrameData.call(this, nativeFrameData);
  41741. frameData.pose = nativeFrameData.pose;
  41742. Util.copyArray(nativeFrameData.leftProjectionMatrix, frameData.leftProjectionMatrix);
  41743. Util.copyArray(nativeFrameData.rightProjectionMatrix, frameData.rightProjectionMatrix);
  41744. Util.copyArray(nativeFrameData.leftViewMatrix, frameData.leftViewMatrix);
  41745. Util.copyArray(nativeFrameData.rightViewMatrix, frameData.rightViewMatrix);
  41746. //todo: copy
  41747. };
  41748. }
  41749. // Provide the `VRDisplay` object.
  41750. window.VRDisplay = VRDisplay;
  41751. // Provide the `navigator.vrEnabled` property.
  41752. if (navigator && !navigator.vrEnabled) {
  41753. var self = this;
  41754. Object.defineProperty(navigator, 'vrEnabled', {
  41755. get: function () {
  41756. return self.isCardboardCompatible() &&
  41757. (self.isFullScreenAvailable() || Util.isIOS());
  41758. }
  41759. });
  41760. }
  41761. if (!('VRFrameData' in window)) {
  41762. // Provide the VRFrameData object.
  41763. window.VRFrameData = VRFrameData;
  41764. }
  41765. };
  41766. WebVRPolyfill.prototype.enableDeprecatedPolyfill = function() {
  41767. // Provide navigator.getVRDevices.
  41768. navigator.getVRDevices = this.getVRDevices.bind(this);
  41769. // Provide the CardboardHMDVRDevice and PositionSensorVRDevice objects.
  41770. window.HMDVRDevice = HMDVRDevice;
  41771. window.PositionSensorVRDevice = PositionSensorVRDevice;
  41772. };
  41773. WebVRPolyfill.prototype.getVRDisplays = function() {
  41774. this.populateDevices();
  41775. var polyfillDisplays = this.displays;
  41776. if (!this.nativeWebVRAvailable) {
  41777. return Promise.resolve(polyfillDisplays);
  41778. }
  41779. // Set up a race condition if this browser has a bug where
  41780. // `navigator.getVRDisplays()` never resolves.
  41781. var timeoutId;
  41782. var vrDisplaysNative = this.nativeGetVRDisplaysFunc.call(navigator);
  41783. var timeoutPromise = new Promise(function(resolve) {
  41784. timeoutId = setTimeout(function() {
  41785. console.warn('Native WebVR implementation detected, but `getVRDisplays()` failed to resolve. Falling back to polyfill.');
  41786. resolve([]);
  41787. }, window.WebVRConfig.GET_VR_DISPLAYS_TIMEOUT);
  41788. });
  41789. return Util.race([
  41790. vrDisplaysNative,
  41791. timeoutPromise
  41792. ]).then(function(nativeDisplays) {
  41793. clearTimeout(timeoutId);
  41794. if (window.WebVRConfig.ALWAYS_APPEND_POLYFILL_DISPLAY) {
  41795. return nativeDisplays.concat(polyfillDisplays);
  41796. } else {
  41797. return nativeDisplays.length > 0 ? nativeDisplays : polyfillDisplays;
  41798. }
  41799. });
  41800. };
  41801. WebVRPolyfill.prototype.getVRDevices = function() {
  41802. console.warn('getVRDevices is deprecated. Please update your code to use getVRDisplays instead.');
  41803. var self = this;
  41804. return new Promise(function(resolve, reject) {
  41805. try {
  41806. if (!self.devicesPopulated) {
  41807. if (self.nativeWebVRAvailable) {
  41808. return navigator.getVRDisplays(function(displays) {
  41809. for (var i = 0; i < displays.length; ++i) {
  41810. self.devices.push(new VRDisplayHMDDevice(displays[i]));
  41811. self.devices.push(new VRDisplayPositionSensorDevice(displays[i]));
  41812. }
  41813. self.devicesPopulated = true;
  41814. resolve(self.devices);
  41815. }, reject);
  41816. }
  41817. if (self.nativeLegacyWebVRAvailable) {
  41818. return (navigator.getVRDDevices || navigator.mozGetVRDevices)(function(devices) {
  41819. for (var i = 0; i < devices.length; ++i) {
  41820. if (devices[i] instanceof HMDVRDevice) {
  41821. self.devices.push(devices[i]);
  41822. }
  41823. if (devices[i] instanceof PositionSensorVRDevice) {
  41824. self.devices.push(devices[i]);
  41825. }
  41826. }
  41827. self.devicesPopulated = true;
  41828. resolve(self.devices);
  41829. }, reject);
  41830. }
  41831. }
  41832. self.populateDevices();
  41833. resolve(self.devices);
  41834. } catch (e) {
  41835. reject(e);
  41836. }
  41837. });
  41838. };
  41839. WebVRPolyfill.prototype.NativeVRFrameData = window.VRFrameData;
  41840. /**
  41841. * Determine if a device is mobile.
  41842. */
  41843. WebVRPolyfill.prototype.isMobile = function() {
  41844. return /Android/i.test(navigator.userAgent) ||
  41845. /iPhone|iPad|iPod/i.test(navigator.userAgent);
  41846. };
  41847. WebVRPolyfill.prototype.isCardboardCompatible = function() {
  41848. // For now, support all iOS and Android devices.
  41849. // Also enable the WebVRConfig.FORCE_VR flag for debugging.
  41850. return this.isMobile() || window.WebVRConfig.FORCE_ENABLE_VR;
  41851. };
  41852. WebVRPolyfill.prototype.isFullScreenAvailable = function() {
  41853. return (document.fullscreenEnabled ||
  41854. document.mozFullScreenEnabled ||
  41855. document.webkitFullscreenEnabled ||
  41856. false);
  41857. };
  41858. // Installs a shim that updates a WebVR 1.0 spec implementation to WebVR 1.1
  41859. function InstallWebVRSpecShim() {
  41860. if ('VRDisplay' in window && !('VRFrameData' in window)) {
  41861. // Provide the VRFrameData object.
  41862. window.VRFrameData = VRFrameData;
  41863. // A lot of Chrome builds don't have depthNear and depthFar, even
  41864. // though they're in the WebVR 1.0 spec. Patch them in if they're not present.
  41865. if(!('depthNear' in window.VRDisplay.prototype)) {
  41866. window.VRDisplay.prototype.depthNear = 0.01;
  41867. }
  41868. if(!('depthFar' in window.VRDisplay.prototype)) {
  41869. window.VRDisplay.prototype.depthFar = 10000.0;
  41870. }
  41871. window.VRDisplay.prototype.getFrameData = function(frameData) {
  41872. return Util.frameDataFromPose(frameData, this.getPose(), this);
  41873. }
  41874. }
  41875. };
  41876. WebVRPolyfill.InstallWebVRSpecShim = InstallWebVRSpecShim;
  41877. WebVRPolyfill.version = version;
  41878. module.exports.WebVRPolyfill = WebVRPolyfill;
  41879. },{"../package.json":48,"./base.js":49,"./cardboard-vr-display.js":52,"./display-wrappers.js":55,"./mouse-keyboard-vr-display.js":61,"./util.js":69}],73:[function(_dereq_,module,exports){
  41880. var newline = /\n/
  41881. var newlineChar = '\n'
  41882. var whitespace = /\s/
  41883. module.exports = function(text, opt) {
  41884. var lines = module.exports.lines(text, opt)
  41885. return lines.map(function(line) {
  41886. return text.substring(line.start, line.end)
  41887. }).join('\n')
  41888. }
  41889. module.exports.lines = function wordwrap(text, opt) {
  41890. opt = opt||{}
  41891. //zero width results in nothing visible
  41892. if (opt.width === 0 && opt.mode !== 'nowrap')
  41893. return []
  41894. text = text||''
  41895. var width = typeof opt.width === 'number' ? opt.width : Number.MAX_VALUE
  41896. var start = Math.max(0, opt.start||0)
  41897. var end = typeof opt.end === 'number' ? opt.end : text.length
  41898. var mode = opt.mode
  41899. var measure = opt.measure || monospace
  41900. if (mode === 'pre')
  41901. return pre(measure, text, start, end, width)
  41902. else
  41903. return greedy(measure, text, start, end, width, mode)
  41904. }
  41905. function idxOf(text, chr, start, end) {
  41906. var idx = text.indexOf(chr, start)
  41907. if (idx === -1 || idx > end)
  41908. return end
  41909. return idx
  41910. }
  41911. function isWhitespace(chr) {
  41912. return whitespace.test(chr)
  41913. }
  41914. function pre(measure, text, start, end, width) {
  41915. var lines = []
  41916. var lineStart = start
  41917. for (var i=start; i<end && i<text.length; i++) {
  41918. var chr = text.charAt(i)
  41919. var isNewline = newline.test(chr)
  41920. //If we've reached a newline, then step down a line
  41921. //Or if we've reached the EOF
  41922. if (isNewline || i===end-1) {
  41923. var lineEnd = isNewline ? i : i+1
  41924. var measured = measure(text, lineStart, lineEnd, width)
  41925. lines.push(measured)
  41926. lineStart = i+1
  41927. }
  41928. }
  41929. return lines
  41930. }
  41931. function greedy(measure, text, start, end, width, mode) {
  41932. //A greedy word wrapper based on LibGDX algorithm
  41933. //https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/BitmapFontCache.java
  41934. var lines = []
  41935. var testWidth = width
  41936. //if 'nowrap' is specified, we only wrap on newline chars
  41937. if (mode === 'nowrap')
  41938. testWidth = Number.MAX_VALUE
  41939. while (start < end && start < text.length) {
  41940. //get next newline position
  41941. var newLine = idxOf(text, newlineChar, start, end)
  41942. //eat whitespace at start of line
  41943. while (start < newLine) {
  41944. if (!isWhitespace( text.charAt(start) ))
  41945. break
  41946. start++
  41947. }
  41948. //determine visible # of glyphs for the available width
  41949. var measured = measure(text, start, newLine, testWidth)
  41950. var lineEnd = start + (measured.end-measured.start)
  41951. var nextStart = lineEnd + newlineChar.length
  41952. //if we had to cut the line before the next newline...
  41953. if (lineEnd < newLine) {
  41954. //find char to break on
  41955. while (lineEnd > start) {
  41956. if (isWhitespace(text.charAt(lineEnd)))
  41957. break
  41958. lineEnd--
  41959. }
  41960. if (lineEnd === start) {
  41961. if (nextStart > start + newlineChar.length) nextStart--
  41962. lineEnd = nextStart // If no characters to break, show all.
  41963. } else {
  41964. nextStart = lineEnd
  41965. //eat whitespace at end of line
  41966. while (lineEnd > start) {
  41967. if (!isWhitespace(text.charAt(lineEnd - newlineChar.length)))
  41968. break
  41969. lineEnd--
  41970. }
  41971. }
  41972. }
  41973. if (lineEnd >= start) {
  41974. var result = measure(text, start, lineEnd, testWidth)
  41975. lines.push(result)
  41976. }
  41977. start = nextStart
  41978. }
  41979. return lines
  41980. }
  41981. //determines the visible number of glyphs within a given width
  41982. function monospace(text, start, end, width) {
  41983. var glyphs = Math.min(width, end-start)
  41984. return {
  41985. start: start,
  41986. end: start+glyphs
  41987. }
  41988. }
  41989. },{}],74:[function(_dereq_,module,exports){
  41990. "use strict";
  41991. var window = _dereq_("global/window")
  41992. var isFunction = _dereq_("is-function")
  41993. var parseHeaders = _dereq_("parse-headers")
  41994. var xtend = _dereq_("xtend")
  41995. module.exports = createXHR
  41996. createXHR.XMLHttpRequest = window.XMLHttpRequest || noop
  41997. createXHR.XDomainRequest = "withCredentials" in (new createXHR.XMLHttpRequest()) ? createXHR.XMLHttpRequest : window.XDomainRequest
  41998. forEachArray(["get", "put", "post", "patch", "head", "delete"], function(method) {
  41999. createXHR[method === "delete" ? "del" : method] = function(uri, options, callback) {
  42000. options = initParams(uri, options, callback)
  42001. options.method = method.toUpperCase()
  42002. return _createXHR(options)
  42003. }
  42004. })
  42005. function forEachArray(array, iterator) {
  42006. for (var i = 0; i < array.length; i++) {
  42007. iterator(array[i])
  42008. }
  42009. }
  42010. function isEmpty(obj){
  42011. for(var i in obj){
  42012. if(obj.hasOwnProperty(i)) return false
  42013. }
  42014. return true
  42015. }
  42016. function initParams(uri, options, callback) {
  42017. var params = uri
  42018. if (isFunction(options)) {
  42019. callback = options
  42020. if (typeof uri === "string") {
  42021. params = {uri:uri}
  42022. }
  42023. } else {
  42024. params = xtend(options, {uri: uri})
  42025. }
  42026. params.callback = callback
  42027. return params
  42028. }
  42029. function createXHR(uri, options, callback) {
  42030. options = initParams(uri, options, callback)
  42031. return _createXHR(options)
  42032. }
  42033. function _createXHR(options) {
  42034. if(typeof options.callback === "undefined"){
  42035. throw new Error("callback argument missing")
  42036. }
  42037. var called = false
  42038. var callback = function cbOnce(err, response, body){
  42039. if(!called){
  42040. called = true
  42041. options.callback(err, response, body)
  42042. }
  42043. }
  42044. function readystatechange() {
  42045. if (xhr.readyState === 4) {
  42046. loadFunc()
  42047. }
  42048. }
  42049. function getBody() {
  42050. // Chrome with requestType=blob throws errors arround when even testing access to responseText
  42051. var body = undefined
  42052. if (xhr.response) {
  42053. body = xhr.response
  42054. } else {
  42055. body = xhr.responseText || getXml(xhr)
  42056. }
  42057. if (isJson) {
  42058. try {
  42059. body = JSON.parse(body)
  42060. } catch (e) {}
  42061. }
  42062. return body
  42063. }
  42064. function errorFunc(evt) {
  42065. clearTimeout(timeoutTimer)
  42066. if(!(evt instanceof Error)){
  42067. evt = new Error("" + (evt || "Unknown XMLHttpRequest Error") )
  42068. }
  42069. evt.statusCode = 0
  42070. return callback(evt, failureResponse)
  42071. }
  42072. // will load the data & process the response in a special response object
  42073. function loadFunc() {
  42074. if (aborted) return
  42075. var status
  42076. clearTimeout(timeoutTimer)
  42077. if(options.useXDR && xhr.status===undefined) {
  42078. //IE8 CORS GET successful response doesn't have a status field, but body is fine
  42079. status = 200
  42080. } else {
  42081. status = (xhr.status === 1223 ? 204 : xhr.status)
  42082. }
  42083. var response = failureResponse
  42084. var err = null
  42085. if (status !== 0){
  42086. response = {
  42087. body: getBody(),
  42088. statusCode: status,
  42089. method: method,
  42090. headers: {},
  42091. url: uri,
  42092. rawRequest: xhr
  42093. }
  42094. if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE
  42095. response.headers = parseHeaders(xhr.getAllResponseHeaders())
  42096. }
  42097. } else {
  42098. err = new Error("Internal XMLHttpRequest Error")
  42099. }
  42100. return callback(err, response, response.body)
  42101. }
  42102. var xhr = options.xhr || null
  42103. if (!xhr) {
  42104. if (options.cors || options.useXDR) {
  42105. xhr = new createXHR.XDomainRequest()
  42106. }else{
  42107. xhr = new createXHR.XMLHttpRequest()
  42108. }
  42109. }
  42110. var key
  42111. var aborted
  42112. var uri = xhr.url = options.uri || options.url
  42113. var method = xhr.method = options.method || "GET"
  42114. var body = options.body || options.data
  42115. var headers = xhr.headers = options.headers || {}
  42116. var sync = !!options.sync
  42117. var isJson = false
  42118. var timeoutTimer
  42119. var failureResponse = {
  42120. body: undefined,
  42121. headers: {},
  42122. statusCode: 0,
  42123. method: method,
  42124. url: uri,
  42125. rawRequest: xhr
  42126. }
  42127. if ("json" in options && options.json !== false) {
  42128. isJson = true
  42129. headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json") //Don't override existing accept header declared by user
  42130. if (method !== "GET" && method !== "HEAD") {
  42131. headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json") //Don't override existing accept header declared by user
  42132. body = JSON.stringify(options.json === true ? body : options.json)
  42133. }
  42134. }
  42135. xhr.onreadystatechange = readystatechange
  42136. xhr.onload = loadFunc
  42137. xhr.onerror = errorFunc
  42138. // IE9 must have onprogress be set to a unique function.
  42139. xhr.onprogress = function () {
  42140. // IE must die
  42141. }
  42142. xhr.onabort = function(){
  42143. aborted = true;
  42144. }
  42145. xhr.ontimeout = errorFunc
  42146. xhr.open(method, uri, !sync, options.username, options.password)
  42147. //has to be after open
  42148. if(!sync) {
  42149. xhr.withCredentials = !!options.withCredentials
  42150. }
  42151. // Cannot set timeout with sync request
  42152. // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly
  42153. // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent
  42154. if (!sync && options.timeout > 0 ) {
  42155. timeoutTimer = setTimeout(function(){
  42156. if (aborted) return
  42157. aborted = true//IE9 may still call readystatechange
  42158. xhr.abort("timeout")
  42159. var e = new Error("XMLHttpRequest timeout")
  42160. e.code = "ETIMEDOUT"
  42161. errorFunc(e)
  42162. }, options.timeout )
  42163. }
  42164. if (xhr.setRequestHeader) {
  42165. for(key in headers){
  42166. if(headers.hasOwnProperty(key)){
  42167. xhr.setRequestHeader(key, headers[key])
  42168. }
  42169. }
  42170. } else if (options.headers && !isEmpty(options.headers)) {
  42171. throw new Error("Headers cannot be set on an XDomainRequest object")
  42172. }
  42173. if ("responseType" in options) {
  42174. xhr.responseType = options.responseType
  42175. }
  42176. if ("beforeSend" in options &&
  42177. typeof options.beforeSend === "function"
  42178. ) {
  42179. options.beforeSend(xhr)
  42180. }
  42181. // Microsoft Edge browser sends "undefined" when send is called with undefined value.
  42182. // XMLHttpRequest spec says to pass null as body to indicate no body
  42183. // See https://github.com/naugtur/xhr/issues/100.
  42184. xhr.send(body || null)
  42185. return xhr
  42186. }
  42187. function getXml(xhr) {
  42188. if (xhr.responseType === "document") {
  42189. return xhr.responseXML
  42190. }
  42191. var firefoxBugTakenEffect = xhr.status === 204 && xhr.responseXML && xhr.responseXML.documentElement.nodeName === "parsererror"
  42192. if (xhr.responseType === "" && !firefoxBugTakenEffect) {
  42193. return xhr.responseXML
  42194. }
  42195. return null
  42196. }
  42197. function noop() {}
  42198. },{"global/window":15,"is-function":20,"parse-headers":31,"xtend":76}],75:[function(_dereq_,module,exports){
  42199. module.exports = (function xmlparser() {
  42200. //common browsers
  42201. if (typeof window.DOMParser !== 'undefined') {
  42202. return function(str) {
  42203. var parser = new window.DOMParser()
  42204. return parser.parseFromString(str, 'application/xml')
  42205. }
  42206. }
  42207. //IE8 fallback
  42208. if (typeof window.ActiveXObject !== 'undefined'
  42209. && new window.ActiveXObject('Microsoft.XMLDOM')) {
  42210. return function(str) {
  42211. var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM")
  42212. xmlDoc.async = "false"
  42213. xmlDoc.loadXML(str)
  42214. return xmlDoc
  42215. }
  42216. }
  42217. //last resort fallback
  42218. return function(str) {
  42219. var div = document.createElement('div')
  42220. div.innerHTML = str
  42221. return div
  42222. }
  42223. })()
  42224. },{}],76:[function(_dereq_,module,exports){
  42225. module.exports = extend
  42226. var hasOwnProperty = Object.prototype.hasOwnProperty;
  42227. function extend() {
  42228. var target = {}
  42229. for (var i = 0; i < arguments.length; i++) {
  42230. var source = arguments[i]
  42231. for (var key in source) {
  42232. if (hasOwnProperty.call(source, key)) {
  42233. target[key] = source[key]
  42234. }
  42235. }
  42236. }
  42237. return target
  42238. }
  42239. },{}],77:[function(_dereq_,module,exports){
  42240. module.exports={
  42241. "name": "aframe",
  42242. "version": "0.6.1",
  42243. "description": "A web framework for building virtual reality experiences.",
  42244. "homepage": "https://aframe.io/",
  42245. "main": "dist/aframe-master.js",
  42246. "scripts": {
  42247. "browserify": "browserify src/index.js -s 'AFRAME' -p browserify-derequire",
  42248. "build": "shx mkdir -p build/ && npm run browserify -- --debug -t [envify --INSPECTOR_VERSION dev] -o build/aframe.js",
  42249. "codecov": "codecov",
  42250. "dev": "npm run build && cross-env INSPECTOR_VERSION=dev node ./scripts/budo -t envify",
  42251. "dist": "node scripts/updateVersionLog.js && npm run dist:min && npm run dist:max",
  42252. "dist:max": "npm run browserify -s -- --debug | exorcist dist/aframe-master.js.map > dist/aframe-master.js",
  42253. "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",
  42254. "docs": "markserv --dir docs --port 9001",
  42255. "preghpages": "node ./scripts/preghpages.js",
  42256. "ghpages": "ghpages -p gh-pages/",
  42257. "lint": "semistandard -v | snazzy",
  42258. "lint:fix": "semistandard --fix",
  42259. "precommit": "npm run lint",
  42260. "prerelease": "node scripts/release.js 0.6.0 0.6.1",
  42261. "start": "npm run dev",
  42262. "test": "karma start ./tests/karma.conf.js",
  42263. "test:docs": "node scripts/docsLint.js",
  42264. "test:firefox": "npm test -- --browsers Firefox",
  42265. "test:chrome": "npm test -- --browsers Chrome",
  42266. "test:node": "mocha --ui tdd tests/node"
  42267. },
  42268. "repository": "aframevr/aframe",
  42269. "license": "MIT",
  42270. "dependencies": {
  42271. "@tweenjs/tween.js": "^16.8.0",
  42272. "browserify-css": "^0.8.2",
  42273. "debug": "ngokevin/debug#noTimestamp",
  42274. "deep-assign": "^2.0.0",
  42275. "document-register-element": "dmarcos/document-register-element#8ccc532b7",
  42276. "envify": "^3.4.1",
  42277. "load-bmfont": "^1.2.3",
  42278. "object-assign": "^4.0.1",
  42279. "present": "0.0.6",
  42280. "promise-polyfill": "^3.1.0",
  42281. "style-attr": "^1.0.2",
  42282. "three": "^0.84.0",
  42283. "three-bmfont-text": "^2.1.0",
  42284. "webvr-polyfill": "^0.9.36"
  42285. },
  42286. "devDependencies": {
  42287. "browserify": "^13.1.0",
  42288. "browserify-derequire": "^0.9.4",
  42289. "browserify-istanbul": "^2.0.0",
  42290. "budo": "^9.2.0",
  42291. "chai": "^3.5.0",
  42292. "chai-shallow-deep-equal": "^1.4.0",
  42293. "chalk": "^1.1.3",
  42294. "codecov": "^1.0.1",
  42295. "cross-env": "^5.0.1",
  42296. "exorcist": "^0.4.0",
  42297. "ghpages": "0.0.8",
  42298. "git-rev": "^0.2.1",
  42299. "glob": "^7.1.1",
  42300. "husky": "^0.11.7",
  42301. "istanbul": "^0.4.5",
  42302. "jsdom": "^9.11.0",
  42303. "karma": "1.4.1",
  42304. "karma-browserify": "^5.1.0",
  42305. "karma-chai-shallow-deep-equal": "0.0.4",
  42306. "karma-chrome-launcher": "^2.0.0",
  42307. "karma-coverage": "^1.1.1",
  42308. "karma-env-preprocessor": "^0.1.1",
  42309. "karma-firefox-launcher": "^1.0.0",
  42310. "karma-mocha": "^1.1.1",
  42311. "karma-mocha-reporter": "^2.1.0",
  42312. "karma-sinon-chai": "1.2.4",
  42313. "lolex": "^1.5.1",
  42314. "markserv": "0.0.20",
  42315. "minifyify": "^7.3.3",
  42316. "mocha": "^3.0.2",
  42317. "mozilla-download": "^1.1.1",
  42318. "replace-in-file": "^2.5.3",
  42319. "semistandard": "^9.0.0",
  42320. "shelljs": "^0.7.7",
  42321. "shx": "^0.2.2",
  42322. "sinon": "^1.17.5",
  42323. "sinon-chai": "2.8.0",
  42324. "snazzy": "^5.0.0",
  42325. "too-wordy": "ngokevin/too-wordy",
  42326. "uglifyjs": "^2.4.10",
  42327. "write-good": "^0.9.1"
  42328. },
  42329. "link": true,
  42330. "browserify": {
  42331. "transform": [
  42332. "browserify-css",
  42333. "envify"
  42334. ]
  42335. },
  42336. "semistandard": {
  42337. "ignore": [
  42338. "build/**",
  42339. "dist/**",
  42340. "examples/**/shaders/*.js",
  42341. "**/vendor/**"
  42342. ]
  42343. },
  42344. "keywords": [
  42345. "3d",
  42346. "aframe",
  42347. "cardboard",
  42348. "components",
  42349. "oculus",
  42350. "three",
  42351. "three.js",
  42352. "rift",
  42353. "vive",
  42354. "vr",
  42355. "web-components",
  42356. "webvr"
  42357. ],
  42358. "browserify-css": {
  42359. "minify": true
  42360. },
  42361. "engines": {
  42362. "node": ">= 4.6.0",
  42363. "npm": "^2.15.9"
  42364. }
  42365. }
  42366. },{}],78:[function(_dereq_,module,exports){
  42367. var registerComponent = _dereq_('../core/component').registerComponent;
  42368. var THREE = _dereq_('../lib/three');
  42369. var utils = _dereq_('../utils/');
  42370. var bind = utils.bind;
  42371. var checkHasPositionalTracking = utils.device.checkHasPositionalTracking;
  42372. /**
  42373. * Camera component.
  42374. * Pairs along with camera system to handle tracking the active camera.
  42375. */
  42376. module.exports.Component = registerComponent('camera', {
  42377. schema: {
  42378. active: {default: true},
  42379. far: {default: 10000},
  42380. fov: {default: 80, min: 0},
  42381. near: {default: 0.005, min: 0},
  42382. userHeight: {default: 0, min: 0},
  42383. zoom: {default: 1, min: 0}
  42384. },
  42385. /**
  42386. * Initialize three.js camera and add it to the entity.
  42387. * Add reference from scene to this entity as the camera.
  42388. */
  42389. init: function () {
  42390. var camera;
  42391. var el = this.el;
  42392. var sceneEl = el.sceneEl;
  42393. this.savedPose = null;
  42394. // Create camera.
  42395. camera = this.camera = new THREE.PerspectiveCamera();
  42396. el.setObject3D('camera', camera);
  42397. // Add listeners to save and restore camera pose if headset is present.
  42398. this.onEnterVR = bind(this.onEnterVR, this);
  42399. this.onExitVR = bind(this.onExitVR, this);
  42400. sceneEl.addEventListener('enter-vr', this.onEnterVR);
  42401. sceneEl.addEventListener('exit-vr', this.onExitVR);
  42402. },
  42403. /**
  42404. * Update three.js camera.
  42405. */
  42406. update: function (oldData) {
  42407. var el = this.el;
  42408. var data = this.data;
  42409. var camera = this.camera;
  42410. var system = this.system;
  42411. // Update height offset.
  42412. this.addHeightOffset(oldData.userHeight);
  42413. // Update properties.
  42414. camera.aspect = data.aspect || (window.innerWidth / window.innerHeight);
  42415. camera.far = data.far;
  42416. camera.fov = data.fov;
  42417. camera.near = data.near;
  42418. camera.zoom = data.zoom;
  42419. camera.updateProjectionMatrix();
  42420. // Active property did not change.
  42421. if (oldData && oldData.active === data.active) { return; }
  42422. // If `active` property changes, or first update, handle active camera with system.
  42423. if (data.active && system.activeCameraEl !== el) {
  42424. // Camera enabled. Set camera to this camera.
  42425. system.setActiveCamera(el);
  42426. } else if (!data.active && system.activeCameraEl === el) {
  42427. // Camera disabled. Set camera to another camera.
  42428. system.disableActiveCamera();
  42429. }
  42430. },
  42431. /**
  42432. * Remove camera on remove (callback).
  42433. */
  42434. remove: function () {
  42435. var sceneEl = this.el.sceneEl;
  42436. this.el.removeObject3D('camera');
  42437. sceneEl.removeEventListener('enter-vr', this.onEnterVR);
  42438. sceneEl.removeEventListener('exit-vr', this.onExitVR);
  42439. },
  42440. /**
  42441. * Save pose and remove the offset.
  42442. */
  42443. onEnterVR: function () {
  42444. this.saveCameraPose();
  42445. this.removeHeightOffset();
  42446. },
  42447. /**
  42448. * Restore the pose. Do not need to re-add the offset because it was saved on entering VR.
  42449. */
  42450. onExitVR: function () {
  42451. this.restoreCameraPose();
  42452. },
  42453. /**
  42454. * Offsets the position of the camera to set a human scale perspective
  42455. * This offset is not necessary when using a headset because the SDK
  42456. * will return the real user's head height and position.
  42457. */
  42458. addHeightOffset: function (oldOffset) {
  42459. var el = this.el;
  42460. var currentPosition;
  42461. var userHeightOffset = this.data.userHeight;
  42462. oldOffset = oldOffset || 0;
  42463. currentPosition = el.getAttribute('position') || {x: 0, y: 0, z: 0};
  42464. el.setAttribute('position', {
  42465. x: currentPosition.x,
  42466. y: currentPosition.y - oldOffset + userHeightOffset,
  42467. z: currentPosition.z
  42468. });
  42469. },
  42470. /**
  42471. * Remove the height offset (called when entering VR) since WebVR API gives absolute
  42472. * position.
  42473. */
  42474. removeHeightOffset: function () {
  42475. var currentPosition;
  42476. var el = this.el;
  42477. var hasPositionalTracking;
  42478. var userHeightOffset = this.data.userHeight;
  42479. // Remove the offset if there is positional tracking when entering VR.
  42480. // Necessary for fullscreen mode with no headset.
  42481. // Checking this.hasPositionalTracking to make the value injectable for unit tests.
  42482. hasPositionalTracking = this.hasPositionalTracking !== undefined ? this.hasPositionalTracking : checkHasPositionalTracking();
  42483. if (!userHeightOffset || !hasPositionalTracking) { return; }
  42484. currentPosition = el.getAttribute('position') || {x: 0, y: 0, z: 0};
  42485. el.setAttribute('position', {
  42486. x: currentPosition.x,
  42487. y: currentPosition.y - userHeightOffset,
  42488. z: currentPosition.z
  42489. });
  42490. },
  42491. /**
  42492. * Save camera pose before entering VR to restore later if exiting.
  42493. */
  42494. saveCameraPose: function () {
  42495. var el = this.el;
  42496. var hasPositionalTracking = this.hasPositionalTracking !== undefined ? this.hasPositionalTracking : checkHasPositionalTracking();
  42497. if (this.savedPose || !hasPositionalTracking) { return; }
  42498. this.savedPose = {
  42499. position: el.getAttribute('position'),
  42500. rotation: el.getAttribute('rotation')
  42501. };
  42502. },
  42503. /**
  42504. * Reset camera pose to before entering VR.
  42505. */
  42506. restoreCameraPose: function () {
  42507. var el = this.el;
  42508. var savedPose = this.savedPose;
  42509. var hasPositionalTracking = this.hasPositionalTracking !== undefined ? this.hasPositionalTracking : checkHasPositionalTracking();
  42510. if (!savedPose || !hasPositionalTracking) { return; }
  42511. // Reset camera orientation.
  42512. el.setAttribute('position', savedPose.position);
  42513. el.setAttribute('rotation', savedPose.rotation);
  42514. this.savedPose = null;
  42515. }
  42516. });
  42517. },{"../core/component":126,"../lib/three":174,"../utils/":197}],79:[function(_dereq_,module,exports){
  42518. var registerComponent = _dereq_('../core/component').registerComponent;
  42519. var THREE = _dereq_('../lib/three');
  42520. module.exports.Component = registerComponent('collada-model', {
  42521. schema: {type: 'asset'},
  42522. init: function () {
  42523. this.model = null;
  42524. this.loader = new THREE.ColladaLoader();
  42525. this.loader.options.convertUpAxis = true;
  42526. },
  42527. update: function () {
  42528. var self = this;
  42529. var el = this.el;
  42530. var src = this.data;
  42531. if (!src) { return; }
  42532. this.remove();
  42533. this.loader.load(src, function (colladaModel) {
  42534. self.model = colladaModel.scene;
  42535. el.setObject3D('mesh', self.model);
  42536. el.emit('model-loaded', {format: 'collada', model: self.model});
  42537. });
  42538. },
  42539. remove: function () {
  42540. if (!this.model) { return; }
  42541. this.el.removeObject3D('mesh');
  42542. }
  42543. });
  42544. },{"../core/component":126,"../lib/three":174}],80:[function(_dereq_,module,exports){
  42545. /* global THREE */
  42546. var registerComponent = _dereq_('../core/component').registerComponent;
  42547. var utils = _dereq_('../utils/');
  42548. var bind = utils.bind;
  42549. var EVENTS = {
  42550. CLICK: 'click',
  42551. FUSING: 'fusing',
  42552. MOUSEENTER: 'mouseenter',
  42553. MOUSEDOWN: 'mousedown',
  42554. MOUSELEAVE: 'mouseleave',
  42555. MOUSEUP: 'mouseup'
  42556. };
  42557. var STATES = {
  42558. FUSING: 'cursor-fusing',
  42559. HOVERING: 'cursor-hovering',
  42560. HOVERED: 'cursor-hovered'
  42561. };
  42562. /**
  42563. * Cursor component. Applies the raycaster component specifically for starting the raycaster
  42564. * from the camera and pointing from camera's facing direction, and then only returning the
  42565. * closest intersection. Cursor can be fine-tuned by setting raycaster properties.
  42566. *
  42567. * @member {object} fuseTimeout - Timeout to trigger fuse-click.
  42568. * @member {Element} cursorDownEl - Entity that was last mousedowned during current click.
  42569. * @member {object} intersection - Attributes of the current intersection event, including
  42570. * 3D- and 2D-space coordinates. See: http://threejs.org/docs/api/core/Raycaster.html
  42571. * @member {Element} intersectedEl - Currently-intersected entity. Used to keep track to
  42572. * emit events when unintersecting.
  42573. */
  42574. module.exports.Component = registerComponent('cursor', {
  42575. dependencies: ['raycaster'],
  42576. schema: {
  42577. downEvents: {default: []},
  42578. fuse: {default: utils.device.isMobile()},
  42579. fuseTimeout: {default: 1500, min: 0},
  42580. upEvents: {default: []},
  42581. rayOrigin: {default: 'entity', oneOf: ['mouse', 'entity']}
  42582. },
  42583. init: function () {
  42584. this.fuseTimeout = undefined;
  42585. this.cursorDownEl = null;
  42586. this.intersection = null;
  42587. this.intersectedEl = null;
  42588. // Bind methods.
  42589. this.onCursorDown = bind(this.onCursorDown, this);
  42590. this.onCursorUp = bind(this.onCursorUp, this);
  42591. this.onIntersection = bind(this.onIntersection, this);
  42592. this.onIntersectionCleared = bind(this.onIntersectionCleared, this);
  42593. this.onMouseMove = bind(this.onMouseMove, this);
  42594. },
  42595. update: function (oldData) {
  42596. if (this.data.rayOrigin === oldData.rayOrigin) { return; }
  42597. this.updateMouseEventListeners();
  42598. },
  42599. play: function () {
  42600. this.addEventListeners();
  42601. },
  42602. pause: function () {
  42603. this.removeEventListeners();
  42604. },
  42605. remove: function () {
  42606. var el = this.el;
  42607. el.removeState(STATES.HOVERING);
  42608. el.removeState(STATES.FUSING);
  42609. clearTimeout(this.fuseTimeout);
  42610. if (this.intersectedEl) { this.intersectedEl.removeState(STATES.HOVERED); }
  42611. this.removeEventListeners();
  42612. },
  42613. addEventListeners: function () {
  42614. var canvas;
  42615. var data = this.data;
  42616. var el = this.el;
  42617. var self = this;
  42618. canvas = el.sceneEl.canvas;
  42619. if (canvas) {
  42620. canvas.addEventListener('mousedown', this.onCursorDown);
  42621. canvas.addEventListener('mouseup', this.onCursorUp);
  42622. } else {
  42623. el.sceneEl.addEventListener('render-target-loaded', function () {
  42624. canvas = el.sceneEl.canvas;
  42625. canvas.addEventListener('mousedown', self.onCursorDown);
  42626. canvas.addEventListener('mouseup', self.onCursorUp);
  42627. });
  42628. }
  42629. data.downEvents.forEach(function (downEvent) {
  42630. el.addEventListener(downEvent, self.onCursorDown);
  42631. });
  42632. data.upEvents.forEach(function (upEvent) {
  42633. el.addEventListener(upEvent, self.onCursorUp);
  42634. });
  42635. el.addEventListener('raycaster-intersection', this.onIntersection);
  42636. el.addEventListener('raycaster-intersection-cleared', this.onIntersectionCleared);
  42637. },
  42638. removeEventListeners: function () {
  42639. var canvas;
  42640. var data = this.data;
  42641. var el = this.el;
  42642. var self = this;
  42643. canvas = el.sceneEl.canvas;
  42644. if (canvas) {
  42645. canvas.removeEventListener('mousedown', this.onCursorDown);
  42646. canvas.removeEventListener('mouseup', this.onCursorUp);
  42647. }
  42648. data.downEvents.forEach(function (downEvent) {
  42649. el.removeEventListener(downEvent, self.onCursorDown);
  42650. });
  42651. data.upEvents.forEach(function (upEvent) {
  42652. el.removeEventListener(upEvent, self.onCursorUp);
  42653. });
  42654. el.removeEventListener('raycaster-intersection', this.onIntersection);
  42655. el.removeEventListener('raycaster-intersection-cleared', this.onIntersectionCleared);
  42656. window.removeEventListener('mousemove', this.onMouseMove);
  42657. },
  42658. updateMouseEventListeners: function () {
  42659. var el = this.el;
  42660. window.removeEventListener('mousemove', this.onMouseMove);
  42661. el.setAttribute('raycaster', 'useWorldCoordinates', false);
  42662. if (this.data.rayOrigin !== 'mouse') { return; }
  42663. window.addEventListener('mousemove', this.onMouseMove, false);
  42664. el.setAttribute('raycaster', 'useWorldCoordinates', true);
  42665. },
  42666. onMouseMove: (function () {
  42667. var mouse = new THREE.Vector2();
  42668. var origin = new THREE.Vector3();
  42669. var direction = new THREE.Vector3();
  42670. var rayCasterConfig = {
  42671. origin: origin,
  42672. direction: direction
  42673. };
  42674. return function (evt) {
  42675. var camera = this.el.sceneEl.camera;
  42676. camera.parent.updateMatrixWorld();
  42677. camera.updateMatrixWorld();
  42678. mouse.x = (evt.clientX / window.innerWidth) * 2 - 1;
  42679. mouse.y = -(evt.clientY / window.innerHeight) * 2 + 1;
  42680. origin.setFromMatrixPosition(camera.matrixWorld);
  42681. direction.set(mouse.x, mouse.y, 0.5).unproject(camera).sub(origin).normalize();
  42682. this.el.setAttribute('raycaster', rayCasterConfig);
  42683. };
  42684. })(),
  42685. /**
  42686. * Trigger mousedown and keep track of the mousedowned entity.
  42687. */
  42688. onCursorDown: function (evt) {
  42689. this.twoWayEmit(EVENTS.MOUSEDOWN);
  42690. this.cursorDownEl = this.intersectedEl;
  42691. },
  42692. /**
  42693. * Trigger mouseup if:
  42694. * - Not fusing (mobile has no mouse).
  42695. * - Currently intersecting an entity.
  42696. * - Currently-intersected entity is the same as the one when mousedown was triggered,
  42697. * in case user mousedowned one entity, dragged to another, and mouseupped.
  42698. */
  42699. onCursorUp: function (evt) {
  42700. this.twoWayEmit(EVENTS.MOUSEUP);
  42701. // If intersected entity has changed since the cursorDown, still emit mouseUp on the
  42702. // previously cursorUp entity.
  42703. if (this.cursorDownEl && this.cursorDownEl !== this.intersectedEl) {
  42704. this.cursorDownEl.emit(EVENTS.MOUSEUP, {cursorEl: this.el, intersection: null});
  42705. }
  42706. if (!this.data.fuse && this.intersectedEl && this.cursorDownEl === this.intersectedEl) {
  42707. this.twoWayEmit(EVENTS.CLICK);
  42708. }
  42709. this.cursorDownEl = null;
  42710. },
  42711. /**
  42712. * Handle intersection.
  42713. */
  42714. onIntersection: function (evt) {
  42715. var self = this;
  42716. var cursorEl = this.el;
  42717. var data = this.data;
  42718. var index;
  42719. var intersectedEl;
  42720. var intersection;
  42721. // Select closest object, excluding the cursor.
  42722. index = evt.detail.els[0] === cursorEl ? 1 : 0;
  42723. intersection = evt.detail.intersections[index];
  42724. intersectedEl = evt.detail.els[index];
  42725. // If cursor is the only intersected object, ignore the event.
  42726. if (!intersectedEl) { return; }
  42727. // Already intersecting this entity.
  42728. if (this.intersectedEl === intersectedEl) {
  42729. this.intersection = intersection;
  42730. return;
  42731. }
  42732. // Unset current intersection.
  42733. if (this.intersectedEl) { this.clearCurrentIntersection(); }
  42734. // Set new intersection.
  42735. this.intersection = intersection;
  42736. this.intersectedEl = intersectedEl;
  42737. // Hovering.
  42738. cursorEl.addState(STATES.HOVERING);
  42739. intersectedEl.addState(STATES.HOVERED);
  42740. self.twoWayEmit(EVENTS.MOUSEENTER);
  42741. // Begin fuse if necessary.
  42742. if (data.fuseTimeout === 0 || !data.fuse) { return; }
  42743. cursorEl.addState(STATES.FUSING);
  42744. this.twoWayEmit(EVENTS.FUSING);
  42745. this.fuseTimeout = setTimeout(function fuse () {
  42746. cursorEl.removeState(STATES.FUSING);
  42747. self.twoWayEmit(EVENTS.CLICK);
  42748. }, data.fuseTimeout);
  42749. },
  42750. /**
  42751. * Handle intersection cleared.
  42752. */
  42753. onIntersectionCleared: function (evt) {
  42754. var cursorEl = this.el;
  42755. var intersectedEl = evt.detail.el;
  42756. // Ignore the cursor.
  42757. if (cursorEl === intersectedEl) { return; }
  42758. // Ignore if the event didn't occur on the current intersection.
  42759. if (intersectedEl !== this.intersectedEl) { return; }
  42760. this.clearCurrentIntersection();
  42761. },
  42762. clearCurrentIntersection: function () {
  42763. var cursorEl = this.el;
  42764. // No longer hovering (or fusing).
  42765. this.intersectedEl.removeState(STATES.HOVERED);
  42766. cursorEl.removeState(STATES.HOVERING);
  42767. cursorEl.removeState(STATES.FUSING);
  42768. this.twoWayEmit(EVENTS.MOUSELEAVE);
  42769. // Unset intersected entity (after emitting the event).
  42770. this.intersection = null;
  42771. this.intersectedEl = null;
  42772. // Clear fuseTimeout.
  42773. clearTimeout(this.fuseTimeout);
  42774. },
  42775. /**
  42776. * Helper to emit on both the cursor and the intersected entity (if exists).
  42777. */
  42778. twoWayEmit: function (evtName) {
  42779. var el = this.el;
  42780. var intersectedEl = this.intersectedEl;
  42781. var intersection = this.intersection;
  42782. el.emit(evtName, {intersectedEl: intersectedEl, intersection: intersection});
  42783. if (!intersectedEl) { return; }
  42784. intersectedEl.emit(evtName, {cursorEl: el, intersection: intersection});
  42785. }
  42786. });
  42787. },{"../core/component":126,"../utils/":197}],81:[function(_dereq_,module,exports){
  42788. var registerComponent = _dereq_('../core/component').registerComponent;
  42789. var bind = _dereq_('../utils/bind');
  42790. var checkControllerPresentAndSetup = _dereq_('../utils/tracked-controls').checkControllerPresentAndSetup;
  42791. var emitIfAxesChanged = _dereq_('../utils/tracked-controls').emitIfAxesChanged;
  42792. var DAYDREAM_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/google/';
  42793. var DAYDREAM_CONTROLLER_MODEL_OBJ_URL = DAYDREAM_CONTROLLER_MODEL_BASE_URL + 'vr_controller_daydream.obj';
  42794. var DAYDREAM_CONTROLLER_MODEL_OBJ_MTL = DAYDREAM_CONTROLLER_MODEL_BASE_URL + 'vr_controller_daydream.mtl';
  42795. var GAMEPAD_ID_PREFIX = 'Daydream Controller';
  42796. /**
  42797. * Daydream controls.
  42798. */
  42799. module.exports.Component = registerComponent('daydream-controls', {
  42800. schema: {
  42801. hand: {default: ''}, // Informs the degenerate arm model.
  42802. buttonColor: {type: 'color', default: '#000000'},
  42803. buttonTouchedColor: {type: 'color', default: '#777777'},
  42804. buttonHighlightColor: {type: 'color', default: '#FFFFFF'},
  42805. model: {default: true},
  42806. // Use -999 as sentinel value to auto-determine based on hand.
  42807. rotationOffset: {default: 0},
  42808. armModel: {default: true}
  42809. },
  42810. // buttonId
  42811. // 0 - trackpad
  42812. // 1 - menu (never dispatched on this layer)
  42813. // 2 - system (never dispatched on this layer)
  42814. mapping: {
  42815. axes: {'trackpad': [0, 1]},
  42816. buttons: ['trackpad', 'menu', 'system']
  42817. },
  42818. // Use these labels for detail on axis events such as thumbstickmoved.
  42819. // e.g. for thumbstickmoved detail, the first axis returned is labeled x, and the second is labeled y.
  42820. axisLabels: ['x', 'y', 'z', 'w'],
  42821. bindMethods: function () {
  42822. this.onModelLoaded = bind(this.onModelLoaded, this);
  42823. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  42824. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  42825. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  42826. this.onAxisMoved = bind(this.onAxisMoved, this);
  42827. this.onGamepadConnectionEvent = bind(this.onGamepadConnectionEvent, this);
  42828. },
  42829. init: function () {
  42830. var self = this;
  42831. this.animationActive = 'pointing';
  42832. this.onButtonChanged = bind(this.onButtonChanged, this);
  42833. this.onButtonDown = function (evt) { self.onButtonEvent(evt.detail.id, 'down'); };
  42834. this.onButtonUp = function (evt) { self.onButtonEvent(evt.detail.id, 'up'); };
  42835. this.onButtonTouchStart = function (evt) { self.onButtonEvent(evt.detail.id, 'touchstart'); };
  42836. this.onButtonTouchEnd = function (evt) { self.onButtonEvent(evt.detail.id, 'touchend'); };
  42837. this.onAxisMoved = bind(this.onAxisMoved, this);
  42838. this.controllerPresent = false;
  42839. this.everGotGamepadEvent = false;
  42840. this.lastControllerCheck = 0;
  42841. this.bindMethods();
  42842. this.checkControllerPresentAndSetup = checkControllerPresentAndSetup; // to allow mock
  42843. this.emitIfAxesChanged = emitIfAxesChanged; // to allow mock
  42844. },
  42845. addEventListeners: function () {
  42846. var el = this.el;
  42847. el.addEventListener('buttonchanged', this.onButtonChanged);
  42848. el.addEventListener('buttondown', this.onButtonDown);
  42849. el.addEventListener('buttonup', this.onButtonUp);
  42850. el.addEventListener('touchstart', this.onButtonTouchStart);
  42851. el.addEventListener('touchend', this.onButtonTouchEnd);
  42852. el.addEventListener('model-loaded', this.onModelLoaded);
  42853. el.addEventListener('axismove', this.onAxisMoved);
  42854. this.controllerEventsActive = true;
  42855. },
  42856. removeEventListeners: function () {
  42857. var el = this.el;
  42858. el.removeEventListener('buttonchanged', this.onButtonChanged);
  42859. el.removeEventListener('buttondown', this.onButtonDown);
  42860. el.removeEventListener('buttonup', this.onButtonUp);
  42861. el.removeEventListener('touchstart', this.onButtonTouchStart);
  42862. el.removeEventListener('touchend', this.onButtonTouchEnd);
  42863. el.removeEventListener('model-loaded', this.onModelLoaded);
  42864. el.removeEventListener('axismove', this.onAxisMoved);
  42865. this.controllerEventsActive = false;
  42866. },
  42867. checkIfControllerPresent: function () {
  42868. this.checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {hand: this.data.hand});
  42869. },
  42870. onGamepadConnectionEvent: function (evt) {
  42871. this.everGotGamepadEvent = true;
  42872. // Due to an apparent bug in FF Nightly
  42873. // where only one gamepadconnected / disconnected event is fired,
  42874. // which makes it difficult to handle in individual controller entities,
  42875. // we no longer remove the controllersupdate listener as a result.
  42876. this.checkIfControllerPresent();
  42877. },
  42878. play: function () {
  42879. this.checkIfControllerPresent();
  42880. this.addControllersUpdateListener();
  42881. window.addEventListener('gamepadconnected', this.onGamepadConnectionEvent, false);
  42882. window.addEventListener('gamepaddisconnected', this.onGamepadConnectionEvent, false);
  42883. },
  42884. pause: function () {
  42885. this.removeEventListeners();
  42886. this.removeControllersUpdateListener();
  42887. window.removeEventListener('gamepadconnected', this.onGamepadConnectionEvent, false);
  42888. window.removeEventListener('gamepaddisconnected', this.onGamepadConnectionEvent, false);
  42889. },
  42890. injectTrackedControls: function () {
  42891. var el = this.el;
  42892. var data = this.data;
  42893. el.setAttribute('tracked-controls', {idPrefix: GAMEPAD_ID_PREFIX, hand: data.hand, rotationOffset: data.rotationOffset, armModel: data.armModel});
  42894. if (!this.data.model) { return; }
  42895. this.el.setAttribute('obj-model', {
  42896. obj: DAYDREAM_CONTROLLER_MODEL_OBJ_URL,
  42897. mtl: DAYDREAM_CONTROLLER_MODEL_OBJ_MTL
  42898. });
  42899. },
  42900. addControllersUpdateListener: function () {
  42901. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  42902. },
  42903. removeControllersUpdateListener: function () {
  42904. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  42905. },
  42906. onControllersUpdate: function () {
  42907. if (!this.everGotGamepadEvent) { this.checkIfControllerPresent(); }
  42908. },
  42909. // No need for onButtonChanged, since Daydream controller has no analog buttons.
  42910. onModelLoaded: function (evt) {
  42911. var controllerObject3D = evt.detail.model;
  42912. var buttonMeshes;
  42913. if (!this.data.model) { return; }
  42914. buttonMeshes = this.buttonMeshes = {};
  42915. buttonMeshes.menu = controllerObject3D.getObjectByName('AppButton_AppButton_Cylinder.004');
  42916. buttonMeshes.system = controllerObject3D.getObjectByName('HomeButton_HomeButton_Cylinder.005');
  42917. buttonMeshes.trackpad = controllerObject3D.getObjectByName('TouchPad_TouchPad_Cylinder.003');
  42918. // Offset pivot point
  42919. controllerObject3D.position.set(0, 0, -0.04);
  42920. },
  42921. onAxisMoved: function (evt) { this.emitIfAxesChanged(this, this.mapping.axes, evt); },
  42922. onButtonChanged: function (evt) {
  42923. var button = this.mapping.buttons[evt.detail.id];
  42924. if (!button) return;
  42925. // Pass along changed event with button state, using button mapping for convenience.
  42926. this.el.emit(button + 'changed', evt.detail.state);
  42927. },
  42928. onButtonEvent: function (id, evtName) {
  42929. var buttonName = this.mapping.buttons[id];
  42930. var i;
  42931. if (Array.isArray(buttonName)) {
  42932. for (i = 0; i < buttonName.length; i++) {
  42933. this.el.emit(buttonName[i] + evtName);
  42934. }
  42935. } else {
  42936. this.el.emit(buttonName + evtName);
  42937. }
  42938. this.updateModel(buttonName, evtName);
  42939. },
  42940. updateModel: function (buttonName, evtName) {
  42941. var i;
  42942. if (!this.data.model) { return; }
  42943. if (Array.isArray(buttonName)) {
  42944. for (i = 0; i < buttonName.length; i++) {
  42945. this.updateButtonModel(buttonName[i], evtName);
  42946. }
  42947. } else {
  42948. this.updateButtonModel(buttonName, evtName);
  42949. }
  42950. },
  42951. updateButtonModel: function (buttonName, state) {
  42952. var buttonMeshes = this.buttonMeshes;
  42953. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  42954. var color;
  42955. switch (state) {
  42956. case 'down':
  42957. color = this.data.buttonHighlightColor;
  42958. break;
  42959. case 'touchstart':
  42960. color = this.data.buttonTouchedColor;
  42961. break;
  42962. default:
  42963. color = this.data.buttonColor;
  42964. }
  42965. buttonMeshes[buttonName].material.color.set(color);
  42966. }
  42967. });
  42968. },{"../core/component":126,"../utils/bind":191,"../utils/tracked-controls":201}],82:[function(_dereq_,module,exports){
  42969. var registerComponent = _dereq_('../core/component').registerComponent;
  42970. var bind = _dereq_('../utils/bind');
  42971. var checkControllerPresentAndSetup = _dereq_('../utils/tracked-controls').checkControllerPresentAndSetup;
  42972. var emitIfAxesChanged = _dereq_('../utils/tracked-controls').emitIfAxesChanged;
  42973. var GEARVR_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/samsung/';
  42974. var GEARVR_CONTROLLER_MODEL_OBJ_URL = GEARVR_CONTROLLER_MODEL_BASE_URL + 'gear_vr_controller.obj';
  42975. var GEARVR_CONTROLLER_MODEL_OBJ_MTL = GEARVR_CONTROLLER_MODEL_BASE_URL + 'gear_vr_controller.mtl';
  42976. var GAMEPAD_ID_PREFIX = 'Gear VR';
  42977. /**
  42978. * Vive Controls Component
  42979. * Interfaces with vive controllers and maps Gamepad events to
  42980. * common controller buttons: trackpad, trigger, grip, menu and system
  42981. * It loads a controller model and highlights the pressed buttons
  42982. */
  42983. module.exports.Component = registerComponent('gearvr-controls', {
  42984. schema: {
  42985. hand: {default: ''}, // This informs the degenerate arm model.
  42986. buttonColor: {type: 'color', default: '#000000'},
  42987. buttonTouchedColor: {type: 'color', default: '#777777'},
  42988. buttonHighlightColor: {type: 'color', default: '#FFFFFF'},
  42989. model: {default: true},
  42990. rotationOffset: {default: 0}, // use -999 as sentinel value to auto-determine based on hand
  42991. armModel: {default: true}
  42992. },
  42993. // buttonId
  42994. // 0 - trackpad
  42995. // 1 - triggeri
  42996. mapping: {
  42997. axes: {'trackpad': [0, 1]},
  42998. buttons: ['trackpad', 'trigger']
  42999. },
  43000. // Use these labels for detail on axis events such as thumbstickmoved.
  43001. // e.g. for thumbstickmoved detail, the first axis returned is labeled x, and the second is labeled y.
  43002. axisLabels: ['x', 'y', 'z', 'w'],
  43003. bindMethods: function () {
  43004. this.onModelLoaded = bind(this.onModelLoaded, this);
  43005. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  43006. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  43007. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  43008. this.onAxisMoved = bind(this.onAxisMoved, this);
  43009. this.onGamepadConnectionEvent = bind(this.onGamepadConnectionEvent, this);
  43010. },
  43011. init: function () {
  43012. var self = this;
  43013. this.animationActive = 'pointing';
  43014. this.onButtonChanged = bind(this.onButtonChanged, this);
  43015. this.onButtonDown = function (evt) { self.onButtonEvent(evt.detail.id, 'down'); };
  43016. this.onButtonUp = function (evt) { self.onButtonEvent(evt.detail.id, 'up'); };
  43017. this.onButtonTouchStart = function (evt) { self.onButtonEvent(evt.detail.id, 'touchstart'); };
  43018. this.onButtonTouchEnd = function (evt) { self.onButtonEvent(evt.detail.id, 'touchend'); };
  43019. this.onAxisMoved = bind(this.onAxisMoved, this);
  43020. this.controllerPresent = false;
  43021. this.everGotGamepadEvent = false;
  43022. this.lastControllerCheck = 0;
  43023. this.bindMethods();
  43024. this.checkControllerPresentAndSetup = checkControllerPresentAndSetup; // to allow mock
  43025. this.emitIfAxesChanged = emitIfAxesChanged; // to allow mock
  43026. },
  43027. addEventListeners: function () {
  43028. var el = this.el;
  43029. el.addEventListener('buttonchanged', this.onButtonChanged);
  43030. el.addEventListener('buttondown', this.onButtonDown);
  43031. el.addEventListener('buttonup', this.onButtonUp);
  43032. el.addEventListener('touchstart', this.onButtonTouchStart);
  43033. el.addEventListener('touchend', this.onButtonTouchEnd);
  43034. el.addEventListener('model-loaded', this.onModelLoaded);
  43035. el.addEventListener('axismove', this.onAxisMoved);
  43036. this.controllerEventsActive = true;
  43037. this.addControllersUpdateListener();
  43038. },
  43039. removeEventListeners: function () {
  43040. var el = this.el;
  43041. el.removeEventListener('buttonchanged', this.onButtonChanged);
  43042. el.removeEventListener('buttondown', this.onButtonDown);
  43043. el.removeEventListener('buttonup', this.onButtonUp);
  43044. el.removeEventListener('touchstart', this.onButtonTouchStart);
  43045. el.removeEventListener('touchend', this.onButtonTouchEnd);
  43046. el.removeEventListener('model-loaded', this.onModelLoaded);
  43047. el.removeEventListener('axismove', this.onAxisMoved);
  43048. this.controllerEventsActive = false;
  43049. this.removeControllersUpdateListener();
  43050. },
  43051. checkIfControllerPresent: function () {
  43052. this.checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, this.data.hand ? {hand: this.data.hand} : {});
  43053. },
  43054. onGamepadConnectionEvent: function (evt) {
  43055. this.checkIfControllerPresent();
  43056. },
  43057. play: function () {
  43058. this.checkIfControllerPresent();
  43059. // Note that due to gamepadconnected event propagation issues, we don't rely on events.
  43060. window.addEventListener('gamepaddisconnected', this.checkIfControllerPresent, false);
  43061. this.addControllersUpdateListener();
  43062. },
  43063. pause: function () {
  43064. this.removeEventListeners();
  43065. this.removeControllersUpdateListener();
  43066. // Note that due to gamepadconnected event propagation issues, we don't rely on events.
  43067. window.removeEventListener('gamepaddisconnected', this.checkIfControllerPresent, false);
  43068. },
  43069. injectTrackedControls: function () {
  43070. var el = this.el;
  43071. var data = this.data;
  43072. el.setAttribute('tracked-controls', {idPrefix: GAMEPAD_ID_PREFIX, rotationOffset: data.rotationOffset, armModel: data.armModel});
  43073. if (!this.data.model) { return; }
  43074. this.el.setAttribute('obj-model', {
  43075. obj: GEARVR_CONTROLLER_MODEL_OBJ_URL,
  43076. mtl: GEARVR_CONTROLLER_MODEL_OBJ_MTL
  43077. });
  43078. },
  43079. addControllersUpdateListener: function () {
  43080. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  43081. },
  43082. removeControllersUpdateListener: function () {
  43083. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  43084. },
  43085. onControllersUpdate: function () {
  43086. // Note that due to gamepadconnected event propagation issues, we don't rely on events.
  43087. this.checkIfControllerPresent();
  43088. },
  43089. // No need for onButtonChanged, since Gear VR controller has no analog buttons.
  43090. onModelLoaded: function (evt) {
  43091. var controllerObject3D = evt.detail.model;
  43092. var buttonMeshes;
  43093. if (!this.data.model) { return; }
  43094. buttonMeshes = this.buttonMeshes = {};
  43095. buttonMeshes.trigger = controllerObject3D.getObjectByName('Trigger');
  43096. buttonMeshes.trackpad = controllerObject3D.getObjectByName('Touchpad');
  43097. },
  43098. onButtonChanged: function (evt) {
  43099. var button = this.mapping.buttons[evt.detail.id];
  43100. if (!button) return;
  43101. // Pass along changed event with button state, using button mapping for convenience.
  43102. this.el.emit(button + 'changed', evt.detail.state);
  43103. },
  43104. onButtonEvent: function (id, evtName) {
  43105. var buttonName = this.mapping.buttons[id];
  43106. var i;
  43107. if (Array.isArray(buttonName)) {
  43108. for (i = 0; i < buttonName.length; i++) {
  43109. this.el.emit(buttonName[i] + evtName);
  43110. }
  43111. } else {
  43112. this.el.emit(buttonName + evtName);
  43113. }
  43114. this.updateModel(buttonName, evtName);
  43115. },
  43116. onAxisMoved: function (evt) { this.emitIfAxesChanged(this, this.mapping.axes, evt); },
  43117. updateModel: function (buttonName, evtName) {
  43118. var i;
  43119. if (!this.data.model) { return; }
  43120. if (Array.isArray(buttonName)) {
  43121. for (i = 0; i < buttonName.length; i++) {
  43122. this.updateButtonModel(buttonName[i], evtName);
  43123. }
  43124. } else {
  43125. this.updateButtonModel(buttonName, evtName);
  43126. }
  43127. },
  43128. updateButtonModel: function (buttonName, state) {
  43129. var buttonMeshes = this.buttonMeshes;
  43130. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  43131. var color;
  43132. switch (state) {
  43133. case 'down':
  43134. color = this.data.buttonHighlightColor;
  43135. break;
  43136. case 'touchstart':
  43137. color = this.data.buttonTouchedColor;
  43138. break;
  43139. default:
  43140. color = this.data.buttonColor;
  43141. }
  43142. buttonMeshes[buttonName].material.color.set(color);
  43143. }
  43144. });
  43145. },{"../core/component":126,"../utils/bind":191,"../utils/tracked-controls":201}],83:[function(_dereq_,module,exports){
  43146. var debug = _dereq_('../utils/debug');
  43147. var geometries = _dereq_('../core/geometry').geometries;
  43148. var geometryNames = _dereq_('../core/geometry').geometryNames;
  43149. var registerComponent = _dereq_('../core/component').registerComponent;
  43150. var THREE = _dereq_('../lib/three');
  43151. var dummyGeometry = new THREE.Geometry();
  43152. var warn = debug('components:geometry:warn');
  43153. /**
  43154. * Geometry component. Combined with material component to make a mesh in 3D object.
  43155. * Extended with registered geometries.
  43156. */
  43157. module.exports.Component = registerComponent('geometry', {
  43158. schema: {
  43159. buffer: {default: true},
  43160. mergeTo: {type: 'selector'},
  43161. primitive: {default: 'box', oneOf: geometryNames},
  43162. skipCache: {default: false}
  43163. },
  43164. init: function () {
  43165. this.geometry = null;
  43166. },
  43167. /**
  43168. * Talk to geometry system to get or create geometry.
  43169. */
  43170. update: function (previousData) {
  43171. var data = this.data;
  43172. var mesh = this.el.getOrCreateObject3D('mesh', THREE.Mesh);
  43173. var system = this.system;
  43174. // Dispose old geometry if we created one.
  43175. if (this.geometry) {
  43176. system.unuseGeometry(previousData);
  43177. this.geometry = null;
  43178. }
  43179. // Create new geometry.
  43180. this.geometry = mesh.geometry = system.getOrCreateGeometry(data);
  43181. if (data.mergeTo) {
  43182. this.mergeTo(data.mergeTo);
  43183. }
  43184. },
  43185. /**
  43186. * Merge geometry to another entity's geometry.
  43187. * Remove the entity from the scene. Not a reversible operation.
  43188. *
  43189. * @param {Element} toEl - Entity where the geometry will be merged to.
  43190. */
  43191. mergeTo: function (toEl) {
  43192. var el = this.el;
  43193. var mesh = el.getObject3D('mesh');
  43194. var toMesh;
  43195. if (!toEl || !toEl.isEntity) {
  43196. warn('There is not a valid entity to merge the geometry to');
  43197. return;
  43198. }
  43199. if (toEl === el) {
  43200. warn('Source and target geometries cannot be the same for merge');
  43201. return;
  43202. }
  43203. // Create mesh if entity does not have one.
  43204. toMesh = toEl.getObject3D('mesh');
  43205. if (!toMesh) {
  43206. toMesh = toEl.getOrCreateObject3D('mesh', THREE.Mesh);
  43207. toEl.setAttribute('material', el.getAttribute('material'));
  43208. return;
  43209. }
  43210. if (toMesh.geometry instanceof THREE.Geometry === false ||
  43211. mesh.geometry instanceof THREE.Geometry === false) {
  43212. warn('Geometry merge is only available for `THREE.Geometry` types. ' +
  43213. 'Check that both of the merging geometry and the target geometry have `buffer` ' +
  43214. 'set to false');
  43215. return;
  43216. }
  43217. if (this.data.skipCache === false) {
  43218. warn('Cached geometries are not allowed to merge. Set `skipCache` to true');
  43219. return;
  43220. }
  43221. mesh.parent.updateMatrixWorld();
  43222. toMesh.geometry.merge(mesh.geometry, mesh.matrixWorld);
  43223. el.emit('geometry-merged', {mergeTarget: toEl});
  43224. el.parentNode.removeChild(el);
  43225. },
  43226. /**
  43227. * Tell geometry system that entity is no longer using the geometry.
  43228. * Unset the geometry on the mesh
  43229. */
  43230. remove: function () {
  43231. this.system.unuseGeometry(this.data);
  43232. this.el.getObject3D('mesh').geometry = dummyGeometry;
  43233. this.geometry = null;
  43234. },
  43235. /**
  43236. * Update geometry component schema based on geometry type.
  43237. *
  43238. * @param {object} data - New data passed by Component.
  43239. */
  43240. updateSchema: function (data) {
  43241. var newGeometryType = data.primitive;
  43242. var currentGeometryType = this.data && this.data.primitive;
  43243. var schema = geometries[newGeometryType] && geometries[newGeometryType].schema;
  43244. // Geometry has no schema.
  43245. if (!schema) { throw new Error('Unknown geometry schema `' + newGeometryType + '`'); }
  43246. // Nothing has changed.
  43247. if (currentGeometryType && currentGeometryType === newGeometryType) { return; }
  43248. this.extendSchema(schema);
  43249. }
  43250. });
  43251. },{"../core/component":126,"../core/geometry":127,"../lib/three":174,"../utils/debug":193}],84:[function(_dereq_,module,exports){
  43252. var registerComponent = _dereq_('../core/component').registerComponent;
  43253. var THREE = _dereq_('../lib/three');
  43254. /**
  43255. * glTF model loader.
  43256. */
  43257. module.exports.Component = registerComponent('gltf-model', {
  43258. schema: {type: 'model'},
  43259. init: function () {
  43260. this.model = null;
  43261. this.loader = new THREE.GLTFLoader();
  43262. },
  43263. update: function () {
  43264. var self = this;
  43265. var el = this.el;
  43266. var src = this.data;
  43267. if (!src) { return; }
  43268. this.remove();
  43269. this.loader.load(src, function gltfLoaded (gltfModel) {
  43270. self.model = gltfModel.scene || gltfModel.scenes[0];
  43271. self.model.animations = gltfModel.animations;
  43272. self.system.registerModel(self.model);
  43273. el.setObject3D('mesh', self.model);
  43274. el.emit('model-loaded', {format: 'gltf', model: self.model});
  43275. });
  43276. },
  43277. remove: function () {
  43278. if (!this.model) { return; }
  43279. this.el.removeObject3D('mesh');
  43280. this.system.unregisterModel(this.model);
  43281. }
  43282. });
  43283. },{"../core/component":126,"../lib/three":174}],85:[function(_dereq_,module,exports){
  43284. /* global THREE */
  43285. var registerComponent = _dereq_('../core/component').registerComponent;
  43286. // Found at https://github.com/aframevr/assets.
  43287. var MODEL_URLS = {
  43288. left: 'https://cdn.aframe.io/controllers/oculus-hands/v2/leftHand.json',
  43289. right: 'https://cdn.aframe.io/controllers/oculus-hands/v2/rightHand.json'
  43290. };
  43291. // Poses.
  43292. var ANIMATIONS = {
  43293. open: 'Open',
  43294. // point: grip active, trackpad surface active, trigger inactive.
  43295. point: 'Point',
  43296. // pointThumb: grip active, trigger inactive, trackpad surface inactive.
  43297. pointThumb: 'Point + Thumb',
  43298. // fist: grip active, trigger active, trackpad surface active.
  43299. fist: 'Fist',
  43300. // hold: trigger active, grip inactive.
  43301. hold: 'Hold',
  43302. // thumbUp: grip active, trigger active, trackpad surface inactive.
  43303. thumbUp: 'Thumb Up'
  43304. };
  43305. // Map animation to public events for the API.
  43306. var EVENTS = {};
  43307. EVENTS[ANIMATIONS.fist] = 'grip';
  43308. EVENTS[ANIMATIONS.thumbUp] = 'pistol';
  43309. EVENTS[ANIMATIONS.point] = 'pointing';
  43310. EVENTS[ANIMATIONS.thumb] = 'thumb';
  43311. /**
  43312. * Hand controls component that abstracts 6DoF controls: oculus-touch-controls, vive-controls.
  43313. * Originally meant to be a sample implementation of applications-specific controls that
  43314. * abstracts multiple types of controllers.
  43315. *
  43316. * Auto-detect appropriate controller.
  43317. * Handle common events coming from the detected vendor-specific controls.
  43318. * Translate button events to semantic hand-related event names:
  43319. * (gripclose, gripopen, thumbup, thumbdown, pointup, pointdown)
  43320. * Load hand model with gestures that are applied based on the button pressed.
  43321. *
  43322. * @property {string} Hand mapping (`left`, `right`).
  43323. */
  43324. module.exports.Component = registerComponent('hand-controls', {
  43325. schema: {default: 'left'},
  43326. init: function () {
  43327. var self = this;
  43328. // Current pose.
  43329. this.gesture = ANIMATIONS.open;
  43330. // Active buttons populated by events provided by oculus-touch-controls and vive-controls.
  43331. this.pressedButtons = {};
  43332. this.touchedButtons = {};
  43333. this.loader = new THREE.ObjectLoader();
  43334. this.loader.setCrossOrigin('anonymous');
  43335. this.onGripDown = function () { self.handleButton('grip', 'down'); };
  43336. this.onGripUp = function () { self.handleButton('grip', 'up'); };
  43337. this.onTrackpadDown = function () { self.handleButton('trackpad', 'down'); };
  43338. this.onTrackpadUp = function () { self.handleButton('trackpad', 'up'); };
  43339. this.onTrackpadTouchStart = function () { self.handleButton('trackpad', 'touchstart'); };
  43340. this.onTrackpadTouchEnd = function () { self.handleButton('trackpad', 'touchend'); };
  43341. this.onTriggerDown = function () { self.handleButton('trigger', 'down'); };
  43342. this.onTriggerUp = function () { self.handleButton('trigger', 'up'); };
  43343. this.onTriggerTouchStart = function () { self.handleButton('trigger', 'touchstart'); };
  43344. this.onTriggerTouchEnd = function () { self.handleButton('trigger', 'touchend'); };
  43345. this.onGripTouchStart = function () { self.handleButton('grip', 'touchstart'); };
  43346. this.onGripTouchEnd = function () { self.handleButton('grip', 'touchend'); };
  43347. this.onThumbstickDown = function () { self.handleButton('thumbstick', 'down'); };
  43348. this.onThumbstickUp = function () { self.handleButton('thumbstick', 'up'); };
  43349. this.onAorXTouchStart = function () { self.handleButton('AorX', 'touchstart'); };
  43350. this.onAorXTouchEnd = function () { self.handleButton('AorX', 'touchend'); };
  43351. this.onBorYTouchStart = function () { self.handleButton('BorY', 'touchstart'); };
  43352. this.onBorYTouchEnd = function () { self.handleButton('BorY', 'touchend'); };
  43353. this.onSurfaceTouchStart = function () { self.handleButton('surface', 'touchstart'); };
  43354. this.onSurfaceTouchEnd = function () { self.handleButton('surface', 'touchend'); };
  43355. },
  43356. play: function () {
  43357. this.addEventListeners();
  43358. },
  43359. pause: function () {
  43360. this.removeEventListeners();
  43361. },
  43362. tick: function (time, delta) {
  43363. var mesh = this.el.getObject3D('mesh');
  43364. if (!mesh) { return; }
  43365. mesh.mixer.update(delta / 1000);
  43366. },
  43367. addEventListeners: function () {
  43368. var el = this.el;
  43369. el.addEventListener('gripdown', this.onGripDown);
  43370. el.addEventListener('gripup', this.onGripUp);
  43371. el.addEventListener('trackpaddown', this.onTrackpadDown);
  43372. el.addEventListener('trackpadup', this.onTrackpadUp);
  43373. el.addEventListener('trackpadtouchstart', this.onTrackpadTouchStart);
  43374. el.addEventListener('trackpadtouchend', this.onTrackpadTouchEnd);
  43375. el.addEventListener('triggerdown', this.onTriggerDown);
  43376. el.addEventListener('triggerup', this.onTriggerUp);
  43377. el.addEventListener('triggertouchstart', this.onTriggerTouchStart);
  43378. el.addEventListener('triggertouchend', this.onTriggerTouchEnd);
  43379. el.addEventListener('griptouchstart', this.onGripTouchStart);
  43380. el.addEventListener('griptouchend', this.onGripTouchEnd);
  43381. el.addEventListener('thumbstickdown', this.onThumbstickDown);
  43382. el.addEventListener('thumbstickup', this.onThumbstickUp);
  43383. el.addEventListener('abuttontouchstart', this.onAorXTouchStart);
  43384. el.addEventListener('abuttontouchend', this.onAorXTouchEnd);
  43385. el.addEventListener('bbuttontouchstart', this.onBorYTouchStart);
  43386. el.addEventListener('bbuttontouchend', this.onBorYTouchEnd);
  43387. el.addEventListener('xbuttontouchstart', this.onAorXTouchStart);
  43388. el.addEventListener('xbuttontouchend', this.onAorXTouchEnd);
  43389. el.addEventListener('ybuttontouchstart', this.onBorYTouchStart);
  43390. el.addEventListener('ybuttontouchend', this.onBorYTouchEnd);
  43391. el.addEventListener('surfacetouchstart', this.onSurfaceTouchStart);
  43392. el.addEventListener('surfacetouchend', this.onSurfaceTouchEnd);
  43393. },
  43394. removeEventListeners: function () {
  43395. var el = this.el;
  43396. el.removeEventListener('gripdown', this.onGripDown);
  43397. el.removeEventListener('gripup', this.onGripUp);
  43398. el.removeEventListener('trackpaddown', this.onTrackpadDown);
  43399. el.removeEventListener('trackpadup', this.onTrackpadUp);
  43400. el.removeEventListener('trackpadtouchstart', this.onTrackpadTouchStart);
  43401. el.removeEventListener('trackpadtouchend', this.onTrackpadTouchEnd);
  43402. el.removeEventListener('triggerdown', this.onTriggerDown);
  43403. el.removeEventListener('triggerup', this.onTriggerUp);
  43404. el.removeEventListener('triggertouchstart', this.onTriggerTouchStart);
  43405. el.removeEventListener('triggertouchend', this.onTriggerTouchEnd);
  43406. el.removeEventListener('griptouchstart', this.onGripTouchStart);
  43407. el.removeEventListener('griptouchend', this.onGripTouchEnd);
  43408. el.removeEventListener('thumbstickdown', this.onThumbstickDown);
  43409. el.removeEventListener('thumbstickup', this.onThumbstickUp);
  43410. el.removeEventListener('abuttontouchstart', this.onAorXTouchStart);
  43411. el.removeEventListener('abuttontouchend', this.onAorXTouchEnd);
  43412. el.removeEventListener('bbuttontouchstart', this.onBorYTouchStart);
  43413. el.removeEventListener('bbuttontouchend', this.onBorYTouchEnd);
  43414. el.removeEventListener('xbuttontouchstart', this.onAorXTouchStart);
  43415. el.removeEventListener('xbuttontouchend', this.onAorXTouchEnd);
  43416. el.removeEventListener('ybuttontouchstart', this.onBorYTouchStart);
  43417. el.removeEventListener('ybuttontouchend', this.onBorYTouchEnd);
  43418. el.removeEventListener('surfacetouchstart', this.onSurfaceTouchStart);
  43419. el.removeEventListener('surfacetouchend', this.onSurfaceTouchEnd);
  43420. },
  43421. /**
  43422. * Update handler. More like the `init` handler since the only property is the hand, and
  43423. * that won't be changing much.
  43424. */
  43425. update: function (previousHand) {
  43426. var controlConfiguration;
  43427. var el = this.el;
  43428. var hand = this.data;
  43429. // Get common configuration to abstract Vive and Oculus.
  43430. controlConfiguration = {
  43431. hand: hand,
  43432. model: false,
  43433. rotationOffset: hand === 'left' ? 90 : -90
  43434. };
  43435. el.setAttribute('vive-controls', controlConfiguration);
  43436. el.setAttribute('oculus-touch-controls', controlConfiguration);
  43437. // Set model.
  43438. if (hand !== previousHand) {
  43439. this.loader.load(MODEL_URLS[hand], function (scene) {
  43440. var mesh = scene.getObjectByName('Hand');
  43441. mesh.material.skinning = true;
  43442. mesh.mixer = new THREE.AnimationMixer(mesh);
  43443. el.setObject3D('mesh', mesh);
  43444. });
  43445. }
  43446. },
  43447. remove: function () {
  43448. this.el.removeObject3D('mesh');
  43449. },
  43450. /**
  43451. * Play model animation, based on which button was pressed and which kind of event.
  43452. *
  43453. * 1. Process buttons.
  43454. * 2. Determine gesture (this.determineGesture()).
  43455. * 3. Animation gesture (this.animationGesture()).
  43456. * 4. Emit gesture events (this.emitGestureEvents()).
  43457. *
  43458. * @param {string} button - Name of the button.
  43459. * @param {string} evt - Type of event for the button (i.e., down/up/touchstart/touchend).
  43460. */
  43461. handleButton: function (button, evt) {
  43462. var lastGesture;
  43463. var isPressed = evt === 'down';
  43464. var isTouched = evt === 'touchstart';
  43465. // Update objects.
  43466. if (evt.indexOf('touch') === 0) {
  43467. // Update touch object.
  43468. if (isTouched === this.touchedButtons[button]) { return; }
  43469. this.touchedButtons[button] = isTouched;
  43470. } else {
  43471. // Update button object.
  43472. if (isPressed === this.pressedButtons[button]) { return; }
  43473. this.pressedButtons[button] = isPressed;
  43474. }
  43475. // Determine the gesture.
  43476. lastGesture = this.gesture;
  43477. this.gesture = this.determineGesture();
  43478. // Same gesture.
  43479. if (this.gesture === lastGesture) { return; }
  43480. // Animate gesture.
  43481. this.animateGesture(this.gesture, lastGesture);
  43482. // Emit events.
  43483. this.emitGestureEvents(this.gesture, lastGesture);
  43484. },
  43485. /**
  43486. * Determine which pose hand should be in considering active and touched buttons.
  43487. */
  43488. determineGesture: function () {
  43489. var gesture;
  43490. var isGripActive = this.pressedButtons['grip'];
  43491. var isSurfaceActive = this.pressedButtons['surface'] || this.touchedButtons['surface'];
  43492. var isTrackpadActive = this.pressedButtons['trackpad'] || this.touchedButtons['trackpad'];
  43493. var isTriggerActive = this.pressedButtons['trigger'] || this.touchedButtons['trigger'];
  43494. var isABXYActive = this.touchedButtons['AorX'] || this.touchedButtons['BorY'];
  43495. var isOculusTouch = isOculusTouchController(this.el.components['tracked-controls']);
  43496. // Works well with Oculus Touch but Vive needs tweaks.
  43497. if (isGripActive) {
  43498. if (!isOculusTouch) {
  43499. gesture = ANIMATIONS.fist;
  43500. } else
  43501. if (isSurfaceActive || isABXYActive || isTrackpadActive) {
  43502. gesture = isTriggerActive ? ANIMATIONS.fist : ANIMATIONS.point;
  43503. } else {
  43504. gesture = isTriggerActive ? ANIMATIONS.thumbUp : ANIMATIONS.pointThumb;
  43505. }
  43506. } else {
  43507. if (isTriggerActive) {
  43508. gesture = isOculusTouch ? ANIMATIONS.hold : ANIMATIONS.fist;
  43509. } else if (!isOculusTouch && isTrackpadActive) {
  43510. gesture = ANIMATIONS.point;
  43511. }
  43512. }
  43513. return gesture;
  43514. },
  43515. /**
  43516. * Play gesture animation.
  43517. *
  43518. * @param {string} gesture - Which pose to animate to. If absent, then animate to open.
  43519. * @param {string} lastGesture - Previous gesture, to reverse back to open if needed.
  43520. */
  43521. animateGesture: function (gesture, lastGesture) {
  43522. if (gesture) {
  43523. this.playAnimation(gesture || ANIMATIONS.open, lastGesture, false);
  43524. return;
  43525. }
  43526. // If no gesture, then reverse the current gesture back to open pose.
  43527. this.playAnimation(lastGesture, lastGesture, true);
  43528. },
  43529. /**
  43530. * Emit `hand-controls`-specific events.
  43531. */
  43532. emitGestureEvents: function (gesture, lastGesture) {
  43533. var el = this.el;
  43534. var eventName;
  43535. if (lastGesture === gesture) { return; }
  43536. // Emit event for lastGesture not inactive.
  43537. eventName = getGestureEventName(lastGesture, false);
  43538. if (eventName) { el.emit(eventName); }
  43539. // Emit event for current gesture now active.
  43540. eventName = getGestureEventName(gesture, true);
  43541. if (eventName) { el.emit(eventName); }
  43542. },
  43543. /**
  43544. * Play hand animation based on button state.
  43545. *
  43546. * @param {string} gesture - Name of the animation as specified by the model.
  43547. * @param {string} lastGesture - Previous pose.
  43548. * @param {boolean} reverse - Whether animation should play in reverse.
  43549. */
  43550. playAnimation: function (gesture, lastGesture, reverse) {
  43551. var fromAction;
  43552. var mesh = this.el.getObject3D('mesh');
  43553. var toAction;
  43554. if (!mesh) { return; }
  43555. // Grab clip action.
  43556. toAction = mesh.mixer.clipAction(gesture);
  43557. toAction.clampWhenFinished = true;
  43558. toAction.loop = THREE.PingPong;
  43559. toAction.repetitions = 0;
  43560. toAction.timeScale = reverse ? -1 : 1;
  43561. toAction.weight = 1;
  43562. // No gesture to gesture or gesture to no gesture.
  43563. if (!lastGesture || gesture === lastGesture) {
  43564. // Stop all current animations.
  43565. mesh.mixer.stopAllAction();
  43566. // Play animation.
  43567. toAction.play();
  43568. return;
  43569. }
  43570. // Animate or crossfade from gesture to gesture.
  43571. fromAction = mesh.mixer.clipAction(lastGesture);
  43572. mesh.mixer.stopAllAction();
  43573. fromAction.weight = 0.15;
  43574. fromAction.play();
  43575. toAction.play();
  43576. fromAction.crossFadeTo(toAction, 0.15, true);
  43577. }
  43578. });
  43579. /**
  43580. * Suffix gestures based on toggle state (e.g., open/close, up/down, start/end).
  43581. *
  43582. * @param {string} gesture
  43583. * @param {boolean} active
  43584. */
  43585. function getGestureEventName (gesture, active) {
  43586. var eventName;
  43587. if (!gesture) { return; }
  43588. eventName = EVENTS[gesture];
  43589. if (eventName === 'grip') {
  43590. return eventName + (active ? 'close' : 'open');
  43591. }
  43592. if (eventName === 'point' || eventName === 'thumb') {
  43593. return eventName + (active ? 'up' : 'down');
  43594. }
  43595. if (eventName === 'pointing' || eventName === 'pistol') {
  43596. return eventName + (active ? 'start' : 'end');
  43597. }
  43598. return;
  43599. }
  43600. function isOculusTouchController (trackedControls) {
  43601. var controllerId = trackedControls && trackedControls.controller &&
  43602. trackedControls.controller.id;
  43603. return controllerId && controllerId.indexOf('Oculus Touch') === 0;
  43604. }
  43605. },{"../core/component":126}],86:[function(_dereq_,module,exports){
  43606. _dereq_('./camera');
  43607. _dereq_('./collada-model');
  43608. _dereq_('./cursor');
  43609. _dereq_('./daydream-controls');
  43610. _dereq_('./gearvr-controls');
  43611. _dereq_('./geometry');
  43612. _dereq_('./gltf-model');
  43613. _dereq_('./hand-controls');
  43614. _dereq_('./laser-controls');
  43615. _dereq_('./light');
  43616. _dereq_('./line');
  43617. _dereq_('./link');
  43618. _dereq_('./look-controls');
  43619. _dereq_('./material');
  43620. _dereq_('./obj-model');
  43621. _dereq_('./oculus-touch-controls');
  43622. _dereq_('./position');
  43623. _dereq_('./raycaster');
  43624. _dereq_('./rotation');
  43625. _dereq_('./scale');
  43626. _dereq_('./shadow');
  43627. _dereq_('./sound');
  43628. _dereq_('./text');
  43629. _dereq_('./tracked-controls');
  43630. _dereq_('./visible');
  43631. _dereq_('./vive-controls');
  43632. _dereq_('./wasd-controls');
  43633. _dereq_('./scene/canvas');
  43634. _dereq_('./scene/debug');
  43635. _dereq_('./scene/embedded');
  43636. _dereq_('./scene/inspector');
  43637. _dereq_('./scene/fog');
  43638. _dereq_('./scene/keyboard-shortcuts');
  43639. _dereq_('./scene/pool');
  43640. _dereq_('./scene/screenshot');
  43641. _dereq_('./scene/stats');
  43642. _dereq_('./scene/vr-mode-ui');
  43643. },{"./camera":78,"./collada-model":79,"./cursor":80,"./daydream-controls":81,"./gearvr-controls":82,"./geometry":83,"./gltf-model":84,"./hand-controls":85,"./laser-controls":87,"./light":88,"./line":89,"./link":90,"./look-controls":91,"./material":92,"./obj-model":93,"./oculus-touch-controls":94,"./position":95,"./raycaster":96,"./rotation":97,"./scale":98,"./scene/canvas":99,"./scene/debug":100,"./scene/embedded":101,"./scene/fog":102,"./scene/inspector":103,"./scene/keyboard-shortcuts":104,"./scene/pool":105,"./scene/screenshot":106,"./scene/stats":107,"./scene/vr-mode-ui":108,"./shadow":109,"./sound":110,"./text":111,"./tracked-controls":112,"./visible":113,"./vive-controls":114,"./wasd-controls":115}],87:[function(_dereq_,module,exports){
  43644. var registerComponent = _dereq_('../core/component').registerComponent;
  43645. var utils = _dereq_('../utils/');
  43646. registerComponent('laser-controls', {
  43647. schema: {
  43648. hand: {default: 'right'}
  43649. },
  43650. init: function () {
  43651. var config = this.config;
  43652. var data = this.data;
  43653. var el = this.el;
  43654. // Set all controller models.
  43655. el.setAttribute('daydream-controls', {hand: data.hand});
  43656. el.setAttribute('gearvr-controls', {hand: data.hand});
  43657. el.setAttribute('oculus-touch-controls', {hand: data.hand});
  43658. el.setAttribute('vive-controls', {hand: data.hand});
  43659. // Wait for controller to connect before
  43660. el.addEventListener('controllerconnected', function (evt) {
  43661. var controllerConfig = config[evt.detail.name];
  43662. if (!controllerConfig) { return; }
  43663. el.setAttribute('raycaster', utils.extend({
  43664. showLine: true
  43665. }, controllerConfig.raycaster || {}));
  43666. el.setAttribute('cursor', utils.extend({
  43667. fuse: false
  43668. }, controllerConfig.cursor));
  43669. });
  43670. },
  43671. config: {
  43672. 'daydream-controls': {
  43673. cursor: {downEvents: ['trackpaddown'], upEvents: ['trackpadup']}
  43674. },
  43675. 'gearvr-controls': {
  43676. cursor: {downEvents: ['trackpaddown'], upEvents: ['trackpadup']},
  43677. raycaster: {origin: {x: 0, y: 0.0005, z: 0}}
  43678. },
  43679. 'oculus-touch-controls': {
  43680. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  43681. raycaster: {origin: {x: 0.001, y: 0, z: 0.065}, direction: {x: 0, y: -0.8, z: -1}}
  43682. },
  43683. 'vive-controls': {
  43684. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']}
  43685. }
  43686. }
  43687. });
  43688. },{"../core/component":126,"../utils/":197}],88:[function(_dereq_,module,exports){
  43689. var bind = _dereq_('../utils/bind');
  43690. var diff = _dereq_('../utils').diff;
  43691. var debug = _dereq_('../utils/debug');
  43692. var registerComponent = _dereq_('../core/component').registerComponent;
  43693. var THREE = _dereq_('../lib/three');
  43694. var degToRad = THREE.Math.degToRad;
  43695. var warn = debug('components:light:warn');
  43696. /**
  43697. * Light component.
  43698. */
  43699. module.exports.Component = registerComponent('light', {
  43700. schema: {
  43701. angle: {default: 60, if: {type: ['spot']}},
  43702. color: {type: 'color'},
  43703. groundColor: {type: 'color', if: {type: ['hemisphere']}},
  43704. decay: {default: 1, if: {type: ['point', 'spot']}},
  43705. distance: {default: 0.0, min: 0, if: {type: ['point', 'spot']}},
  43706. intensity: {default: 1.0, min: 0, if: {type: ['ambient', 'directional', 'hemisphere', 'point', 'spot']}},
  43707. penumbra: {default: 0, min: 0, max: 1, if: {type: ['spot']}},
  43708. type: {default: 'directional', oneOf: ['ambient', 'directional', 'hemisphere', 'point', 'spot']},
  43709. target: {type: 'selector', if: {type: ['spot', 'directional']}},
  43710. // Shadows.
  43711. castShadow: {default: false, if: {type: ['point', 'spot', 'directional']}},
  43712. shadowBias: {default: 0, if: {castShadow: true}},
  43713. shadowCameraFar: {default: 500, if: {castShadow: true}},
  43714. shadowCameraFov: {default: 90, if: {castShadow: true}},
  43715. shadowCameraNear: {default: 0.5, if: {castShadow: true}},
  43716. shadowCameraTop: {default: 5, if: {castShadow: true}},
  43717. shadowCameraRight: {default: 5, if: {castShadow: true}},
  43718. shadowCameraBottom: {default: -5, if: {castShadow: true}},
  43719. shadowCameraLeft: {default: -5, if: {castShadow: true}},
  43720. shadowCameraVisible: {default: false, if: {castShadow: true}},
  43721. shadowMapHeight: {default: 512, if: {castShadow: true}},
  43722. shadowMapWidth: {default: 512, if: {castShadow: true}}
  43723. },
  43724. /**
  43725. * Notifies scene a light has been added to remove default lighting.
  43726. */
  43727. init: function () {
  43728. var el = this.el;
  43729. this.light = null;
  43730. this.defaultTarget = null;
  43731. this.system.registerLight(el);
  43732. },
  43733. /**
  43734. * (Re)create or update light.
  43735. */
  43736. update: function (oldData) {
  43737. var data = this.data;
  43738. var diffData = diff(data, oldData);
  43739. var light = this.light;
  43740. var self = this;
  43741. // Existing light.
  43742. if (light && !('type' in diffData)) {
  43743. var shadowsLoaded = false;
  43744. // Light type has not changed. Update light.
  43745. Object.keys(diffData).forEach(function (key) {
  43746. var value = data[key];
  43747. switch (key) {
  43748. case 'color': {
  43749. light.color.set(value);
  43750. break;
  43751. }
  43752. case 'groundColor': {
  43753. light.groundColor.set(value);
  43754. break;
  43755. }
  43756. case 'angle': {
  43757. light.angle = degToRad(value);
  43758. break;
  43759. }
  43760. case 'target': {
  43761. // Reset target if selector is null.
  43762. if (value === null) {
  43763. if (data.type === 'spot' || data.type === 'directional') {
  43764. light.target = self.defaultTarget;
  43765. }
  43766. } else {
  43767. // Target specified, set target to entity's `object3D` when it is loaded.
  43768. if (value.hasLoaded) {
  43769. self.onSetTarget(value, light);
  43770. } else {
  43771. value.addEventListener('loaded', bind(self.onSetTarget, self, value, light));
  43772. }
  43773. }
  43774. break;
  43775. }
  43776. case 'castShadow':
  43777. case 'shadowBias':
  43778. case 'shadowCameraFar':
  43779. case 'shadowCameraFov':
  43780. case 'shadowCameraNear':
  43781. case 'shadowCameraTop':
  43782. case 'shadowCameraRight':
  43783. case 'shadowCameraBottom':
  43784. case 'shadowCameraLeft':
  43785. case 'shadowCameraVisible':
  43786. case 'shadowMapHeight':
  43787. case 'shadowMapWidth':
  43788. if (!shadowsLoaded) {
  43789. self.updateShadow();
  43790. shadowsLoaded = true;
  43791. }
  43792. break;
  43793. default: {
  43794. light[key] = value;
  43795. }
  43796. }
  43797. });
  43798. return;
  43799. }
  43800. // No light yet or light type has changed. Create and add light.
  43801. this.setLight(this.data);
  43802. this.updateShadow();
  43803. },
  43804. setLight: function (data) {
  43805. var el = this.el;
  43806. var newLight = this.getLight(data);
  43807. if (newLight) {
  43808. if (this.light) {
  43809. el.removeObject3D('light');
  43810. }
  43811. this.light = newLight;
  43812. this.light.el = el;
  43813. el.setObject3D('light', this.light);
  43814. // HACK solution for issue #1624
  43815. if (data.type === 'spot' || data.type === 'directional' || data.type === 'hemisphere') {
  43816. el.getObject3D('light').translateY(-1);
  43817. }
  43818. // set and position default lighttarget as a child to enable spotlight orientation
  43819. if (data.type === 'spot') {
  43820. el.setObject3D('light-target', this.defaultTarget);
  43821. el.getObject3D('light-target').position.set(0, 0, -1);
  43822. }
  43823. }
  43824. },
  43825. /**
  43826. * Updates shadow-related properties on the current light.
  43827. */
  43828. updateShadow: function () {
  43829. var el = this.el;
  43830. var data = this.data;
  43831. var light = this.light;
  43832. light.castShadow = data.castShadow;
  43833. // Shadow camera helper.
  43834. var cameraHelper = el.getObject3D('cameraHelper');
  43835. if (data.shadowCameraVisible && !cameraHelper) {
  43836. el.setObject3D('cameraHelper', new THREE.CameraHelper(light.shadow.camera));
  43837. } else if (!data.shadowCameraVisible && cameraHelper) {
  43838. el.removeObject3D('cameraHelper');
  43839. }
  43840. if (!data.castShadow) { return light; }
  43841. // Shadow appearance.
  43842. light.shadow.bias = data.shadowBias;
  43843. light.shadow.mapSize.height = data.shadowMapHeight;
  43844. light.shadow.mapSize.width = data.shadowMapWidth;
  43845. // Shadow camera.
  43846. light.shadow.camera.near = data.shadowCameraNear;
  43847. light.shadow.camera.far = data.shadowCameraFar;
  43848. if (light.shadow.camera instanceof THREE.OrthographicCamera) {
  43849. light.shadow.camera.top = data.shadowCameraTop;
  43850. light.shadow.camera.right = data.shadowCameraRight;
  43851. light.shadow.camera.bottom = data.shadowCameraBottom;
  43852. light.shadow.camera.left = data.shadowCameraLeft;
  43853. } else {
  43854. light.shadow.camera.fov = data.shadowCameraFov;
  43855. }
  43856. light.shadow.camera.updateProjectionMatrix();
  43857. if (cameraHelper) { cameraHelper.update(); }
  43858. },
  43859. /**
  43860. * Creates a new three.js light object given data object defining the light.
  43861. *
  43862. * @param {object} data
  43863. */
  43864. getLight: function (data) {
  43865. var angle = data.angle;
  43866. var color = new THREE.Color(data.color).getHex();
  43867. var decay = data.decay;
  43868. var distance = data.distance;
  43869. var groundColor = new THREE.Color(data.groundColor).getHex();
  43870. var intensity = data.intensity;
  43871. var type = data.type;
  43872. var target = data.target;
  43873. var light = null;
  43874. switch (type.toLowerCase()) {
  43875. case 'ambient': {
  43876. return new THREE.AmbientLight(color, intensity);
  43877. }
  43878. case 'directional': {
  43879. light = new THREE.DirectionalLight(color, intensity);
  43880. this.defaultTarget = light.target;
  43881. if (target) {
  43882. if (target.hasLoaded) {
  43883. this.onSetTarget(target, light);
  43884. } else {
  43885. target.addEventListener('loaded', bind(this.onSetTarget, this, target, light));
  43886. }
  43887. }
  43888. return light;
  43889. }
  43890. case 'hemisphere': {
  43891. return new THREE.HemisphereLight(color, groundColor, intensity);
  43892. }
  43893. case 'point': {
  43894. return new THREE.PointLight(color, intensity, distance, decay);
  43895. }
  43896. case 'spot': {
  43897. light = new THREE.SpotLight(color, intensity, distance, degToRad(angle), data.penumbra, decay);
  43898. this.defaultTarget = light.target;
  43899. if (target) {
  43900. if (target.hasLoaded) {
  43901. this.onSetTarget(target, light);
  43902. } else {
  43903. target.addEventListener('loaded', bind(this.onSetTarget, this, target, light));
  43904. }
  43905. }
  43906. return light;
  43907. }
  43908. default: {
  43909. warn('%s is not a valid light type. ' +
  43910. 'Choose from ambient, directional, hemisphere, point, spot.', type);
  43911. }
  43912. }
  43913. },
  43914. onSetTarget: function (targetEl, light) {
  43915. light.target = targetEl.object3D;
  43916. },
  43917. /**
  43918. * Remove light on remove (callback).
  43919. */
  43920. remove: function () {
  43921. var el = this.el;
  43922. el.removeObject3D('light');
  43923. if (el.getObject3D('cameraHelper')) {
  43924. el.removeObject3D('cameraHelper');
  43925. }
  43926. }
  43927. });
  43928. },{"../core/component":126,"../lib/three":174,"../utils":197,"../utils/bind":191,"../utils/debug":193}],89:[function(_dereq_,module,exports){
  43929. /* global THREE */
  43930. var registerComponent = _dereq_('../core/component').registerComponent;
  43931. module.exports.Component = registerComponent('line', {
  43932. schema: {
  43933. start: {type: 'vec3', default: {x: 0, y: 0, z: 0}},
  43934. end: {type: 'vec3', default: {x: 0, y: 0, z: 0}},
  43935. color: {type: 'color', default: '#74BEC1'},
  43936. opacity: {type: 'number', default: 1},
  43937. visible: {default: true}
  43938. },
  43939. multiple: true,
  43940. init: function () {
  43941. var data = this.data;
  43942. var geometry;
  43943. var material;
  43944. material = this.material = new THREE.LineBasicMaterial({
  43945. color: data.color,
  43946. opacity: data.opacity,
  43947. transparent: data.opacity < 1,
  43948. visible: data.visible
  43949. });
  43950. geometry = this.geometry = new THREE.BufferGeometry();
  43951. geometry.addAttribute('position', new THREE.BufferAttribute(new Float32Array(2 * 3), 3));
  43952. this.line = new THREE.Line(geometry, material);
  43953. this.el.setObject3D(this.attrName, this.line);
  43954. },
  43955. update: function (oldData) {
  43956. var data = this.data;
  43957. var geometry = this.geometry;
  43958. var geoNeedsUpdate = false;
  43959. var material = this.material;
  43960. var positionArray = geometry.attributes.position.array;
  43961. // Update geometry.
  43962. if (!isEqualVec3(data.start, oldData.start)) {
  43963. positionArray[0] = data.start.x;
  43964. positionArray[1] = data.start.y;
  43965. positionArray[2] = data.start.z;
  43966. geoNeedsUpdate = true;
  43967. }
  43968. if (!isEqualVec3(data.end, oldData.end)) {
  43969. positionArray[3] = data.end.x;
  43970. positionArray[4] = data.end.y;
  43971. positionArray[5] = data.end.z;
  43972. geoNeedsUpdate = true;
  43973. }
  43974. if (geoNeedsUpdate) {
  43975. geometry.attributes.position.needsUpdate = true;
  43976. geometry.computeBoundingSphere();
  43977. }
  43978. material.color.setStyle(data.color);
  43979. material.opacity = data.opacity;
  43980. material.transparent = data.opacity < 1;
  43981. material.visible = data.visible;
  43982. },
  43983. remove: function () {
  43984. this.el.removeObject3D('line', this.line);
  43985. }
  43986. });
  43987. function isEqualVec3 (a, b) {
  43988. if (!a || !b) { return false; }
  43989. return (a.x === b.x && a.y === b.y && a.z === b.z);
  43990. }
  43991. },{"../core/component":126}],90:[function(_dereq_,module,exports){
  43992. var registerComponent = _dereq_('../core/component').registerComponent;
  43993. var registerShader = _dereq_('../core/shader').registerShader;
  43994. var THREE = _dereq_('../lib/three');
  43995. /**
  43996. * Link component. Connect experiences and traverse between them in VR
  43997. *
  43998. * @member {object} hiddenEls - Stores the hidden elements during peek mode.
  43999. */
  44000. module.exports.Component = registerComponent('link', {
  44001. schema: {
  44002. color: {default: 'white', type: 'color'},
  44003. highlighted: {default: false},
  44004. highlightedColor: {default: '#24CAFF', type: 'color'},
  44005. href: {default: ''},
  44006. image: {type: 'asset'},
  44007. on: {default: 'click'},
  44008. peekMode: {default: false},
  44009. title: {default: ''},
  44010. visualAspectEnabled: {default: true}
  44011. },
  44012. init: function () {
  44013. this.navigate = this.navigate.bind(this);
  44014. this.previousQuaternion = undefined;
  44015. // Store hidden elements during peek mode so we can show them again later.
  44016. this.hiddenEls = [];
  44017. this.initVisualAspect();
  44018. },
  44019. update: function (oldData) {
  44020. var data = this.data;
  44021. var el = this.el;
  44022. var strokeColor = data.highlighted ? data.highlightedColor : data.color;
  44023. el.setAttribute('material', 'strokeColor', strokeColor);
  44024. if (data.on !== oldData.on) { this.updateEventListener(); }
  44025. if (data.visualAspectEnabled && oldData.peekMode !== undefined && data.peekMode !== oldData.peekMode) {
  44026. this.updatePeekMode();
  44027. }
  44028. if (!data.image || oldData.image === data.image) { return; }
  44029. el.setAttribute('material', 'pano',
  44030. typeof data.image === 'string' ? data.image : data.image.src);
  44031. },
  44032. /*
  44033. * Hide / Show all elements and Hide / Show the full 360 preview
  44034. * of the linked page.
  44035. */
  44036. updatePeekMode: function () {
  44037. var el = this.el;
  44038. var sphereEl = this.sphereEl;
  44039. if (this.data.peekMode) {
  44040. this.hideAll();
  44041. el.getObject3D('mesh').visible = false;
  44042. sphereEl.setAttribute('visible', true);
  44043. } else {
  44044. this.showAll();
  44045. el.getObject3D('mesh').visible = true;
  44046. sphereEl.setAttribute('visible', false);
  44047. }
  44048. },
  44049. play: function () {
  44050. this.updateEventListener();
  44051. },
  44052. pause: function () {
  44053. this.removeEventListener();
  44054. },
  44055. updateEventListener: function () {
  44056. var el = this.el;
  44057. if (!el.isPlaying) { return; }
  44058. this.removeEventListener();
  44059. el.addEventListener(this.data.on, this.navigate);
  44060. },
  44061. removeEventListener: function () {
  44062. var on = this.data.on;
  44063. if (!on) { return; }
  44064. this.el.removeEventListener(on, this.navigate);
  44065. },
  44066. initVisualAspect: function () {
  44067. var el = this.el;
  44068. var textEl;
  44069. var sphereEl;
  44070. var semiSphereEl;
  44071. if (!this.data.visualAspectEnabled) { return; }
  44072. textEl = this.textEl = this.textEl || document.createElement('a-entity');
  44073. sphereEl = this.sphereEl = this.sphereEl || document.createElement('a-entity');
  44074. semiSphereEl = this.semiSphereEl = this.semiSphereEl || document.createElement('a-entity');
  44075. // Set Portal
  44076. el.setAttribute('geometry', {primitive: 'circle', radius: 1.0, segments: 64});
  44077. el.setAttribute('material', {
  44078. shader: 'portal',
  44079. pano: this.data.image,
  44080. side: 'double'
  44081. });
  44082. // Set text that displays the link title / url
  44083. textEl.setAttribute('text', {
  44084. color: 'white',
  44085. align: 'center',
  44086. font: 'kelsonsans',
  44087. value: this.data.title || this.data.href,
  44088. width: 4
  44089. });
  44090. textEl.setAttribute('position', '0 1.5 0');
  44091. el.appendChild(textEl);
  44092. // Set the sphere that is rendered when the camera is close
  44093. // to the portal to allow the user peek inside
  44094. semiSphereEl.setAttribute('geometry', {
  44095. primitive: 'sphere',
  44096. radius: 1.0,
  44097. phiStart: 0,
  44098. segmentsWidth: 64,
  44099. segmentsHeight: 64,
  44100. phiLength: 180,
  44101. thetaStart: 0,
  44102. thetaLength: 360
  44103. });
  44104. semiSphereEl.setAttribute('material', {
  44105. shader: 'portal',
  44106. borderEnabled: 0.0,
  44107. pano: this.data.image,
  44108. side: 'back'
  44109. });
  44110. semiSphereEl.setAttribute('rotation', '0 180 0');
  44111. semiSphereEl.setAttribute('position', '0 0 0');
  44112. semiSphereEl.setAttribute('visible', false);
  44113. el.appendChild(semiSphereEl);
  44114. // Set the sphere that is rendered when the camera is close
  44115. // to the portal to allow the user peek inside
  44116. sphereEl.setAttribute('geometry', {
  44117. primitive: 'sphere',
  44118. radius: 10,
  44119. segmentsWidth: 64,
  44120. segmentsHeight: 64
  44121. });
  44122. sphereEl.setAttribute('material', {
  44123. shader: 'portal',
  44124. borderEnabled: 0.0,
  44125. pano: this.data.image,
  44126. side: 'back'
  44127. });
  44128. sphereEl.setAttribute('visible', false);
  44129. el.appendChild(sphereEl);
  44130. },
  44131. navigate: function () {
  44132. window.location = this.data.href;
  44133. },
  44134. /**
  44135. * The tick handles:
  44136. * 1. Swap the plane the represents the portal with a sphere with a hole when the camera is close
  44137. * so the user can peek inside the portal. The sphere is rendered on the oposite side of the portal
  44138. * from where the user enters.
  44139. * 2. It places the url / title above or inside the portal depending on the distance to the camera.
  44140. * 3. The portal faces the camera when it's far away from the user.
  44141. *
  44142. */
  44143. tick: (function () {
  44144. var elWorldPosition = new THREE.Vector3();
  44145. var cameraWorldPosition = new THREE.Vector3();
  44146. var scale = new THREE.Vector3();
  44147. var quaternion = new THREE.Quaternion();
  44148. return function () {
  44149. if (!this.data.visualAspectEnabled) { return; }
  44150. var el = this.el;
  44151. var object3D = el.object3D;
  44152. var camera = el.sceneEl.camera;
  44153. var cameraPortalOrientation;
  44154. var distance;
  44155. var textEl = this.textEl;
  44156. // Update matrices
  44157. object3D.updateMatrixWorld();
  44158. camera.parent.updateMatrixWorld();
  44159. camera.updateMatrixWorld();
  44160. object3D.matrix.decompose(elWorldPosition, quaternion, scale);
  44161. elWorldPosition.setFromMatrixPosition(object3D.matrixWorld);
  44162. cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld);
  44163. distance = elWorldPosition.distanceTo(cameraWorldPosition);
  44164. // Store original orientation to be restored when the portal
  44165. // stops facing the camera
  44166. this.previousQuaternion = this.previousQuaternion || quaternion.clone();
  44167. // If the portal is far away from the user the portal faces the camera
  44168. if (distance > 20) {
  44169. object3D.lookAt(cameraWorldPosition);
  44170. } else { // When the portal is close to the user (camera)
  44171. cameraPortalOrientation = this.calculateCameraPortalOrientation();
  44172. // If the user gets very close to the portal it is replaced
  44173. // by a holed sphere where she can peek inside
  44174. if (distance < 0.5) {
  44175. // Configure text size and sphere orientation depending
  44176. // the side the user approaches the portal
  44177. if (this.semiSphereEl.getAttribute('visible') === true) { return; }
  44178. textEl.setAttribute('text', 'width', 1.5);
  44179. if (cameraPortalOrientation <= 0.0) {
  44180. textEl.setAttribute('position', '0 0 0.75');
  44181. textEl.setAttribute('rotation', '0 180 0');
  44182. this.semiSphereEl.setAttribute('rotation', '0 0 0');
  44183. } else {
  44184. textEl.setAttribute('position', '0 0 -0.75');
  44185. textEl.setAttribute('rotation', '0 0 0');
  44186. this.semiSphereEl.setAttribute('rotation', '0 180 0');
  44187. }
  44188. el.getObject3D('mesh').visible = false;
  44189. this.semiSphereEl.setAttribute('visible', true);
  44190. this.peekCameraPortalOrientation = cameraPortalOrientation;
  44191. } else {
  44192. // Calculate wich side the camera is approaching the camera (back / front)
  44193. // Adjust text orientation based on camera position.
  44194. if (cameraPortalOrientation <= 0.0) {
  44195. textEl.setAttribute('rotation', '0 180 0');
  44196. } else {
  44197. textEl.setAttribute('rotation', '0 0 0');
  44198. }
  44199. textEl.setAttribute('text', 'width', 5);
  44200. textEl.setAttribute('position', '0 1.5 0');
  44201. el.getObject3D('mesh').visible = true;
  44202. this.semiSphereEl.setAttribute('visible', false);
  44203. this.peekCameraPortalOrientation = undefined;
  44204. }
  44205. if (this.previousQuaternion) {
  44206. object3D.quaternion.copy(this.previousQuaternion);
  44207. this.previousQuaternion = undefined;
  44208. }
  44209. }
  44210. };
  44211. })(),
  44212. hideAll: function () {
  44213. var el = this.el;
  44214. var hiddenEls = this.hiddenEls;
  44215. var self = this;
  44216. if (hiddenEls.length > 0) { return; }
  44217. el.sceneEl.object3D.traverse(function (object) {
  44218. if (object && object.el && object.el.hasAttribute('link-controls')) { return; }
  44219. if (!object.el || object === el.sceneEl.object3D || object.el === el || object.el === self.sphereEl ||
  44220. object.el === el.sceneEl.cameraEl || object.el.getAttribute('visible') === false || object.el === self.textEl || object.el === self.semiSphereEl) { return; }
  44221. object.el.setAttribute('visible', false);
  44222. hiddenEls.push(object.el);
  44223. });
  44224. },
  44225. showAll: function () {
  44226. this.hiddenEls.forEach(function (el) { el.setAttribute('visible', true); });
  44227. this.hiddenEls = [];
  44228. },
  44229. /**
  44230. * Calculate if the camera / user faces the front or back face of the portal
  44231. * @returns {number} > 0 if the camera faces the front of the portal < 0 if it faces the back.
  44232. */
  44233. calculateCameraPortalOrientation: (function () {
  44234. var mat4 = new THREE.Matrix4();
  44235. var cameraPosition = new THREE.Vector3();
  44236. var portalNormal = new THREE.Vector3(0, 0, 1);
  44237. var portalPosition = new THREE.Vector3(0, 0, 0);
  44238. return function () {
  44239. var el = this.el;
  44240. var camera = el.sceneEl.camera;
  44241. // Reset tmp variables
  44242. cameraPosition.set(0, 0, 0);
  44243. portalNormal.set(0, 0, 1);
  44244. portalPosition.set(0, 0, 0);
  44245. // Apply portal orientation to the normal
  44246. el.object3D.matrixWorld.extractRotation(mat4);
  44247. portalNormal.applyMatrix4(mat4);
  44248. // Calculate portal world position
  44249. el.object3D.updateMatrixWorld();
  44250. el.object3D.localToWorld(portalPosition);
  44251. // Calculate camera world position
  44252. camera.parent.parent.updateMatrixWorld();
  44253. camera.parent.updateMatrixWorld();
  44254. camera.updateMatrixWorld();
  44255. camera.localToWorld(cameraPosition);
  44256. // Calculate vector from portal to camera
  44257. // (portal) -------> (camera)
  44258. cameraPosition.sub(portalPosition).normalize();
  44259. portalNormal.normalize();
  44260. // The side where the camera (user) approaches the portal
  44261. // is given by the sign of the dot product of the portal normal
  44262. // and the portal to camera vectors.
  44263. return Math.sign(portalNormal.dot(cameraPosition));
  44264. };
  44265. })(),
  44266. remove: function () {
  44267. this.removeEventListener();
  44268. }
  44269. });
  44270. /* eslint-disable */
  44271. registerShader('portal', {
  44272. schema: {
  44273. pano: {type: 'map', is: 'uniform'},
  44274. borderEnabled: {default: 1.0, type: 'int', is: 'uniform'},
  44275. strokeColor: {default: 'white', type: 'color', is: 'uniform'}
  44276. },
  44277. vertexShader: [
  44278. 'vec3 portalPosition;',
  44279. 'varying vec3 vWorldPosition;',
  44280. 'varying float vDistanceToCenter;',
  44281. 'varying float vDistance;',
  44282. 'void main() {',
  44283. 'vDistanceToCenter = clamp(length(position - vec3(0.0, 0.0, 0.0)), 0.0, 1.0);',
  44284. 'portalPosition = (modelMatrix * vec4(0.0, 0.0, 0.0, 1.0)).xyz;',
  44285. 'vDistance = length(portalPosition - cameraPosition);',
  44286. 'vWorldPosition = (modelMatrix * vec4(position, 1.0)).xyz;',
  44287. 'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  44288. '}'
  44289. ].join('\n'),
  44290. fragmentShader: [
  44291. '#define RECIPROCAL_PI2 0.15915494',
  44292. 'uniform sampler2D pano;',
  44293. 'uniform vec3 strokeColor;',
  44294. 'uniform float borderEnabled;',
  44295. 'varying float vDistanceToCenter;',
  44296. 'varying float vDistance;',
  44297. 'varying vec3 vWorldPosition;',
  44298. 'void main() {',
  44299. 'vec3 direction = normalize(vWorldPosition - cameraPosition);',
  44300. 'vec2 sampleUV;',
  44301. 'float borderThickness = clamp(exp(-vDistance / 50.0), 0.6, 0.95);',
  44302. 'sampleUV.y = saturate(direction.y * 0.5 + 0.5);',
  44303. 'sampleUV.x = atan(direction.z, direction.x) * -RECIPROCAL_PI2 + 0.5;',
  44304. 'if (vDistanceToCenter > borderThickness && borderEnabled == 1.0) {',
  44305. 'gl_FragColor = vec4(strokeColor, 1.0);',
  44306. '} else {',
  44307. 'gl_FragColor = mix(texture2D(pano, sampleUV), vec4(0.93, 0.17, 0.36, 1.0), clamp(pow((vDistance / 15.0), 2.0), 0.0, 1.0));',
  44308. '}',
  44309. '}'
  44310. ].join('\n')
  44311. });
  44312. /* eslint-enable */
  44313. },{"../core/component":126,"../core/shader":135,"../lib/three":174}],91:[function(_dereq_,module,exports){
  44314. var registerComponent = _dereq_('../core/component').registerComponent;
  44315. var THREE = _dereq_('../lib/three');
  44316. var bind = _dereq_('../utils/bind');
  44317. // To avoid recalculation at every mouse movement tick
  44318. var GRABBING_CLASS = 'a-grabbing';
  44319. var PI_2 = Math.PI / 2;
  44320. var radToDeg = THREE.Math.radToDeg;
  44321. /**
  44322. * look-controls. Update entity pose, factoring mouse, touch, and WebVR API data.
  44323. */
  44324. module.exports.Component = registerComponent('look-controls', {
  44325. dependencies: ['position', 'rotation'],
  44326. schema: {
  44327. enabled: {default: true},
  44328. hmdEnabled: {default: true},
  44329. reverseMouseDrag: {default: false},
  44330. standing: {default: true}
  44331. },
  44332. init: function () {
  44333. var sceneEl = this.el.sceneEl;
  44334. this.previousHMDPosition = new THREE.Vector3();
  44335. this.hmdQuaternion = new THREE.Quaternion();
  44336. this.hmdEuler = new THREE.Euler();
  44337. this.setupMouseControls();
  44338. this.setupHMDControls();
  44339. this.bindMethods();
  44340. // Reset previous HMD position when we exit VR.
  44341. sceneEl.addEventListener('exit-vr', this.onExitVR);
  44342. },
  44343. update: function (oldData) {
  44344. var data = this.data;
  44345. // Disable grab cursor classes if no longer enabled.
  44346. if (data.enabled !== oldData.enabled) {
  44347. this.updateGrabCursor(data.enabled);
  44348. }
  44349. // Reset pitch and yaw if disabling HMD.
  44350. if (oldData && !data.hmdEnabled && !oldData.hmdEnabled) {
  44351. this.pitchObject.rotation.set(0, 0, 0);
  44352. this.yawObject.rotation.set(0, 0, 0);
  44353. }
  44354. },
  44355. tick: function (t) {
  44356. var data = this.data;
  44357. if (!data.enabled) { return; }
  44358. this.controls.standing = data.standing;
  44359. this.controls.update();
  44360. this.updateOrientation();
  44361. this.updatePosition();
  44362. },
  44363. play: function () {
  44364. this.addEventListeners();
  44365. },
  44366. pause: function () {
  44367. this.removeEventListeners();
  44368. },
  44369. remove: function () {
  44370. this.removeEventListeners();
  44371. },
  44372. bindMethods: function () {
  44373. this.onMouseDown = bind(this.onMouseDown, this);
  44374. this.onMouseMove = bind(this.onMouseMove, this);
  44375. this.onMouseUp = bind(this.onMouseUp, this);
  44376. this.onTouchStart = bind(this.onTouchStart, this);
  44377. this.onTouchMove = bind(this.onTouchMove, this);
  44378. this.onTouchEnd = bind(this.onTouchEnd, this);
  44379. this.onExitVR = bind(this.onExitVR, this);
  44380. },
  44381. /**
  44382. * Set up states and Object3Ds needed to store rotation data.
  44383. */
  44384. setupMouseControls: function () {
  44385. this.mouseDown = false;
  44386. this.pitchObject = new THREE.Object3D();
  44387. this.yawObject = new THREE.Object3D();
  44388. this.yawObject.position.y = 10;
  44389. this.yawObject.add(this.pitchObject);
  44390. },
  44391. /**
  44392. * Set up VR controls that will copy data to the dolly.
  44393. */
  44394. setupHMDControls: function () {
  44395. this.dolly = new THREE.Object3D();
  44396. this.euler = new THREE.Euler();
  44397. this.controls = new THREE.VRControls(this.dolly);
  44398. this.controls.userHeight = 0.0;
  44399. },
  44400. /**
  44401. * Add mouse and touch event listeners to canvas.
  44402. */
  44403. addEventListeners: function () {
  44404. var sceneEl = this.el.sceneEl;
  44405. var canvasEl = sceneEl.canvas;
  44406. // Wait for canvas to load.
  44407. if (!canvasEl) {
  44408. sceneEl.addEventListener('render-target-loaded', bind(this.addEventListeners, this));
  44409. return;
  44410. }
  44411. // Mouse events.
  44412. canvasEl.addEventListener('mousedown', this.onMouseDown, false);
  44413. window.addEventListener('mousemove', this.onMouseMove, false);
  44414. window.addEventListener('mouseup', this.onMouseUp, false);
  44415. // Touch events.
  44416. canvasEl.addEventListener('touchstart', this.onTouchStart);
  44417. window.addEventListener('touchmove', this.onTouchMove);
  44418. window.addEventListener('touchend', this.onTouchEnd);
  44419. },
  44420. /**
  44421. * Remove mouse and touch event listeners from canvas.
  44422. */
  44423. removeEventListeners: function () {
  44424. var sceneEl = this.el.sceneEl;
  44425. var canvasEl = sceneEl && sceneEl.canvas;
  44426. if (!canvasEl) { return; }
  44427. // Mouse events.
  44428. canvasEl.removeEventListener('mousedown', this.onMouseDown);
  44429. canvasEl.removeEventListener('mousemove', this.onMouseMove);
  44430. canvasEl.removeEventListener('mouseup', this.onMouseUp);
  44431. canvasEl.removeEventListener('mouseout', this.onMouseUp);
  44432. // Touch events.
  44433. canvasEl.removeEventListener('touchstart', this.onTouchStart);
  44434. canvasEl.removeEventListener('touchmove', this.onTouchMove);
  44435. canvasEl.removeEventListener('touchend', this.onTouchEnd);
  44436. },
  44437. /**
  44438. * Update orientation for mobile, mouse drag, and headset.
  44439. * Mouse-drag only enabled if HMD is not active.
  44440. */
  44441. updateOrientation: function () {
  44442. var currentRotation;
  44443. var deltaRotation;
  44444. var hmdEuler = this.hmdEuler;
  44445. var hmdQuaternion = this.hmdQuaternion;
  44446. var pitchObject = this.pitchObject;
  44447. var yawObject = this.yawObject;
  44448. var sceneEl = this.el.sceneEl;
  44449. var rotation;
  44450. // Calculate HMD quaternion.
  44451. hmdQuaternion = hmdQuaternion.copy(this.dolly.quaternion);
  44452. hmdEuler.setFromQuaternion(hmdQuaternion, 'YXZ');
  44453. if (sceneEl.isMobile) {
  44454. // On mobile, do camera rotation with touch events and sensors.
  44455. rotation = {
  44456. x: radToDeg(hmdEuler.x) + radToDeg(pitchObject.rotation.x),
  44457. y: radToDeg(hmdEuler.y) + radToDeg(yawObject.rotation.y),
  44458. z: radToDeg(hmdEuler.z)
  44459. };
  44460. } else if (!sceneEl.is('vr-mode') || isNullVector(hmdEuler) || !this.data.hmdEnabled) {
  44461. // Mouse drag if WebVR not active (not connected, no incoming sensor data).
  44462. currentRotation = this.el.getAttribute('rotation');
  44463. deltaRotation = this.calculateDeltaRotation();
  44464. if (this.data.reverseMouseDrag) {
  44465. rotation = {
  44466. x: currentRotation.x - deltaRotation.x,
  44467. y: currentRotation.y - deltaRotation.y,
  44468. z: currentRotation.z
  44469. };
  44470. } else {
  44471. rotation = {
  44472. x: currentRotation.x + deltaRotation.x,
  44473. y: currentRotation.y + deltaRotation.y,
  44474. z: currentRotation.z
  44475. };
  44476. }
  44477. } else {
  44478. // Mouse rotation ignored with an active headset. Use headset rotation.
  44479. rotation = {
  44480. x: radToDeg(hmdEuler.x),
  44481. y: radToDeg(hmdEuler.y),
  44482. z: radToDeg(hmdEuler.z)
  44483. };
  44484. }
  44485. this.el.setAttribute('rotation', rotation);
  44486. },
  44487. /**
  44488. * Calculate delta rotation for mouse-drag and touch-drag.
  44489. */
  44490. calculateDeltaRotation: function () {
  44491. var currentRotationX = radToDeg(this.pitchObject.rotation.x);
  44492. var currentRotationY = radToDeg(this.yawObject.rotation.y);
  44493. var deltaRotation;
  44494. deltaRotation = {
  44495. x: currentRotationX - (this.previousRotationX || 0),
  44496. y: currentRotationY - (this.previousRotationY || 0)
  44497. };
  44498. // Store current rotation for next tick.
  44499. this.previousRotationX = currentRotationX;
  44500. this.previousRotationY = currentRotationY;
  44501. return deltaRotation;
  44502. },
  44503. /**
  44504. * Handle positional tracking.
  44505. */
  44506. updatePosition: (function () {
  44507. var deltaHMDPosition = new THREE.Vector3();
  44508. return function () {
  44509. var el = this.el;
  44510. var currentPosition = el.getAttribute('position');
  44511. var currentHMDPosition;
  44512. var previousHMDPosition = this.previousHMDPosition;
  44513. var sceneEl = this.el.sceneEl;
  44514. if (!sceneEl.is('vr-mode')) { return; }
  44515. // Calculate change in position.
  44516. currentHMDPosition = this.calculateHMDPosition();
  44517. deltaHMDPosition.copy(currentHMDPosition).sub(previousHMDPosition);
  44518. if (isNullVector(deltaHMDPosition)) { return; }
  44519. previousHMDPosition.copy(currentHMDPosition);
  44520. el.setAttribute('position', {
  44521. x: currentPosition.x + deltaHMDPosition.x,
  44522. y: currentPosition.y + deltaHMDPosition.y,
  44523. z: currentPosition.z + deltaHMDPosition.z
  44524. });
  44525. };
  44526. })(),
  44527. /**
  44528. * Get headset position from VRControls.
  44529. */
  44530. calculateHMDPosition: (function () {
  44531. var position = new THREE.Vector3();
  44532. return function () {
  44533. this.dolly.updateMatrix();
  44534. position.setFromMatrixPosition(this.dolly.matrix);
  44535. return position;
  44536. };
  44537. })(),
  44538. /**
  44539. * Translate mouse drag into rotation.
  44540. *
  44541. * Dragging up and down rotates the camera around the X-axis (yaw).
  44542. * Dragging left and right rotates the camera around the Y-axis (pitch).
  44543. */
  44544. onMouseMove: function (event) {
  44545. var pitchObject = this.pitchObject;
  44546. var yawObject = this.yawObject;
  44547. var previousMouseEvent = this.previousMouseEvent;
  44548. var movementX;
  44549. var movementY;
  44550. // Not dragging or not enabled.
  44551. if (!this.mouseDown || !this.data.enabled) { return; }
  44552. // Calculate delta.
  44553. movementX = event.movementX || event.mozMovementX;
  44554. movementY = event.movementY || event.mozMovementY;
  44555. if (movementX === undefined || movementY === undefined) {
  44556. movementX = event.screenX - previousMouseEvent.screenX;
  44557. movementY = event.screenY - previousMouseEvent.screenY;
  44558. }
  44559. this.previousMouseEvent = event;
  44560. // Calculate rotation.
  44561. yawObject.rotation.y -= movementX * 0.002;
  44562. pitchObject.rotation.x -= movementY * 0.002;
  44563. pitchObject.rotation.x = Math.max(-PI_2, Math.min(PI_2, pitchObject.rotation.x));
  44564. },
  44565. /**
  44566. * Register mouse down to detect mouse drag.
  44567. */
  44568. onMouseDown: function (evt) {
  44569. if (!this.data.enabled) { return; }
  44570. // Handle only primary button.
  44571. if (evt.button !== 0) { return; }
  44572. this.mouseDown = true;
  44573. this.previousMouseEvent = evt;
  44574. document.body.classList.add(GRABBING_CLASS);
  44575. },
  44576. /**
  44577. * Register mouse up to detect release of mouse drag.
  44578. */
  44579. onMouseUp: function () {
  44580. this.mouseDown = false;
  44581. document.body.classList.remove(GRABBING_CLASS);
  44582. },
  44583. /**
  44584. * Register touch down to detect touch drag.
  44585. */
  44586. onTouchStart: function (evt) {
  44587. if (evt.touches.length !== 1) { return; }
  44588. this.touchStart = {
  44589. x: evt.touches[0].pageX,
  44590. y: evt.touches[0].pageY
  44591. };
  44592. this.touchStarted = true;
  44593. },
  44594. /**
  44595. * Translate touch move to Y-axis rotation.
  44596. */
  44597. onTouchMove: function (evt) {
  44598. var canvas = this.el.sceneEl.canvas;
  44599. var deltaY;
  44600. var yawObject = this.yawObject;
  44601. if (!this.touchStarted) { return; }
  44602. deltaY = 2 * Math.PI * (evt.touches[0].pageX - this.touchStart.x) / canvas.clientWidth;
  44603. // Limit touch orientaion to to yaw (y axis).
  44604. yawObject.rotation.y -= deltaY * 0.5;
  44605. this.touchStart = {
  44606. x: evt.touches[0].pageX,
  44607. y: evt.touches[0].pageY
  44608. };
  44609. },
  44610. /**
  44611. * Register touch end to detect release of touch drag.
  44612. */
  44613. onTouchEnd: function () {
  44614. this.touchStarted = false;
  44615. },
  44616. onExitVR: function () {
  44617. this.previousHMDPosition.set(0, 0, 0);
  44618. },
  44619. /**
  44620. * Toggle the feature of showing/hiding the grab cursor.
  44621. */
  44622. updateGrabCursor: function (enabled) {
  44623. var sceneEl = this.el.sceneEl;
  44624. function enableGrabCursor () { sceneEl.canvas.classList.add('a-grab-cursor'); }
  44625. function disableGrabCursor () { sceneEl.canvas.classList.remove('a-grab-cursor'); }
  44626. if (!sceneEl.canvas) {
  44627. if (enabled) {
  44628. sceneEl.addEventListener('render-target-loaded', enableGrabCursor);
  44629. } else {
  44630. sceneEl.addEventListener('render-target-loaded', disableGrabCursor);
  44631. }
  44632. return;
  44633. }
  44634. if (enabled) {
  44635. enableGrabCursor();
  44636. return;
  44637. }
  44638. disableGrabCursor();
  44639. }
  44640. });
  44641. function isNullVector (vector) {
  44642. return vector.x === 0 && vector.y === 0 && vector.z === 0;
  44643. }
  44644. },{"../core/component":126,"../lib/three":174,"../utils/bind":191}],92:[function(_dereq_,module,exports){
  44645. /* global Promise */
  44646. var utils = _dereq_('../utils/');
  44647. var component = _dereq_('../core/component');
  44648. var THREE = _dereq_('../lib/three');
  44649. var shader = _dereq_('../core/shader');
  44650. var error = utils.debug('components:material:error');
  44651. var registerComponent = component.registerComponent;
  44652. var shaders = shader.shaders;
  44653. var shaderNames = shader.shaderNames;
  44654. /**
  44655. * Material component.
  44656. *
  44657. * @member {object} shader - Determines how material is shaded. Defaults to `standard`,
  44658. * three.js's implementation of PBR. Another standard shading model is `flat` which
  44659. * uses MeshBasicMaterial.
  44660. */
  44661. module.exports.Component = registerComponent('material', {
  44662. schema: {
  44663. alphaTest: {default: 0.0, min: 0.0, max: 1.0},
  44664. depthTest: {default: true},
  44665. depthWrite: {default: true},
  44666. flatShading: {default: false},
  44667. npot: {default: false},
  44668. offset: {type: 'vec2', default: {x: 0, y: 0}},
  44669. opacity: {default: 1.0, min: 0.0, max: 1.0},
  44670. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  44671. shader: {default: 'standard', oneOf: shaderNames},
  44672. side: {default: 'front', oneOf: ['front', 'back', 'double']},
  44673. transparent: {default: false},
  44674. vertexColors: {type: 'string', default: 'none', oneOf: ['face', 'vertex']},
  44675. visible: {default: true}
  44676. },
  44677. init: function () {
  44678. this.material = null;
  44679. },
  44680. /**
  44681. * Update or create material.
  44682. *
  44683. * @param {object|null} oldData
  44684. */
  44685. update: function (oldData) {
  44686. var data = this.data;
  44687. if (!this.shader || data.shader !== oldData.shader) {
  44688. this.updateShader(data.shader);
  44689. }
  44690. this.shader.update(this.data);
  44691. this.updateMaterial(oldData);
  44692. },
  44693. updateSchema: function (data) {
  44694. var newShader = data.shader;
  44695. var currentShader = this.data && this.data.shader;
  44696. var shader = newShader || currentShader;
  44697. var schema = shaders[shader] && shaders[shader].schema;
  44698. if (!schema) { error('Unknown shader schema ' + shader); }
  44699. if (currentShader && newShader === currentShader) { return; }
  44700. this.extendSchema(schema);
  44701. this.updateBehavior();
  44702. },
  44703. updateBehavior: function () {
  44704. var schema = this.schema;
  44705. var self = this;
  44706. var sceneEl = this.el.sceneEl;
  44707. var tickProperties = {};
  44708. var tick = function (time, delta) {
  44709. Object.keys(tickProperties).forEach(function update (key) {
  44710. tickProperties[key] = time;
  44711. });
  44712. self.shader.update(tickProperties);
  44713. };
  44714. this.tick = undefined;
  44715. Object.keys(schema).forEach(function (key) {
  44716. if (schema[key].type === 'time') {
  44717. self.tick = tick;
  44718. tickProperties[key] = true;
  44719. }
  44720. });
  44721. if (!sceneEl) { return; }
  44722. if (!this.tick) {
  44723. sceneEl.removeBehavior(this);
  44724. } else {
  44725. sceneEl.addBehavior(this);
  44726. }
  44727. },
  44728. updateShader: function (shaderName) {
  44729. var data = this.data;
  44730. var Shader = shaders[shaderName] && shaders[shaderName].Shader;
  44731. var shaderInstance;
  44732. if (!Shader) { throw new Error('Unknown shader ' + shaderName); }
  44733. // Get material from A-Frame shader.
  44734. shaderInstance = this.shader = new Shader();
  44735. shaderInstance.el = this.el;
  44736. shaderInstance.init(data);
  44737. this.setMaterial(shaderInstance.material);
  44738. this.updateSchema(data);
  44739. },
  44740. /**
  44741. * Set and update base material properties.
  44742. * Set `needsUpdate` when needed.
  44743. */
  44744. updateMaterial: function (oldData) {
  44745. var data = this.data;
  44746. var material = this.material;
  44747. // Base material properties.
  44748. material.alphaTest = data.alphaTest;
  44749. material.depthTest = data.depthTest !== false;
  44750. material.depthWrite = data.depthWrite !== false;
  44751. material.opacity = data.opacity;
  44752. material.shading = data.flatShading ? THREE.FlatShading : THREE.SmoothShading;
  44753. material.side = parseSide(data.side);
  44754. material.transparent = data.transparent !== false || data.opacity < 1.0;
  44755. material.vertexColors = parseVertexColors(data.vertexColors);
  44756. material.visible = data.visible;
  44757. // Check if material needs update.
  44758. if (Object.keys(oldData).length &&
  44759. (oldData.alphaTest !== data.alphaTest ||
  44760. oldData.side !== data.side ||
  44761. oldData.vertexColors !== data.vertexColors)) {
  44762. material.needsUpdate = true;
  44763. }
  44764. },
  44765. /**
  44766. * Remove material on remove (callback).
  44767. * Dispose of it from memory and unsubscribe from scene updates.
  44768. */
  44769. remove: function () {
  44770. var defaultMaterial = new THREE.MeshBasicMaterial();
  44771. var material = this.material;
  44772. var object3D = this.el.getObject3D('mesh');
  44773. if (object3D) { object3D.material = defaultMaterial; }
  44774. disposeMaterial(material, this.system);
  44775. },
  44776. /**
  44777. * (Re)create new material. Has side-effects of setting `this.material` and updating
  44778. * material registration in scene.
  44779. *
  44780. * @param {object} data - Material component data.
  44781. * @param {object} type - Material type to create.
  44782. * @returns {object} Material.
  44783. */
  44784. setMaterial: function (material) {
  44785. var mesh = this.el.getOrCreateObject3D('mesh', THREE.Mesh);
  44786. var system = this.system;
  44787. if (this.material) { disposeMaterial(this.material, system); }
  44788. this.material = mesh.material = material;
  44789. system.registerMaterial(material);
  44790. }
  44791. });
  44792. /**
  44793. * Return a three.js constant determining which material face sides to render
  44794. * based on the side parameter (passed as a component property).
  44795. *
  44796. * @param {string} [side=front] - `front`, `back`, or `double`.
  44797. * @returns {number} THREE.FrontSide, THREE.BackSide, or THREE.DoubleSide.
  44798. */
  44799. function parseSide (side) {
  44800. switch (side) {
  44801. case 'back': {
  44802. return THREE.BackSide;
  44803. }
  44804. case 'double': {
  44805. return THREE.DoubleSide;
  44806. }
  44807. default: {
  44808. // Including case `front`.
  44809. return THREE.FrontSide;
  44810. }
  44811. }
  44812. }
  44813. /**
  44814. * Return a three.js constant determining vertex coloring.
  44815. */
  44816. function parseVertexColors (coloring) {
  44817. switch (coloring) {
  44818. case 'face': {
  44819. return THREE.FaceColors;
  44820. }
  44821. case 'vertex': {
  44822. return THREE.VertexColors;
  44823. }
  44824. default: {
  44825. return THREE.NoColors;
  44826. }
  44827. }
  44828. }
  44829. /**
  44830. * Dispose of material from memory and unsubscribe material from scene updates like fog.
  44831. */
  44832. function disposeMaterial (material, system) {
  44833. material.dispose();
  44834. system.unregisterMaterial(material);
  44835. }
  44836. },{"../core/component":126,"../core/shader":135,"../lib/three":174,"../utils/":197}],93:[function(_dereq_,module,exports){
  44837. var debug = _dereq_('../utils/debug');
  44838. var registerComponent = _dereq_('../core/component').registerComponent;
  44839. var THREE = _dereq_('../lib/three');
  44840. var warn = debug('components:obj-model:warn');
  44841. module.exports.Component = registerComponent('obj-model', {
  44842. schema: {
  44843. mtl: {type: 'model'},
  44844. obj: {type: 'model'}
  44845. },
  44846. init: function () {
  44847. this.model = null;
  44848. this.objLoader = new THREE.OBJLoader();
  44849. this.mtlLoader = new THREE.MTLLoader(this.objLoader.manager);
  44850. // Allow cross-origin images to be loaded.
  44851. this.mtlLoader.crossOrigin = '';
  44852. },
  44853. update: function () {
  44854. var data = this.data;
  44855. if (!data.obj) { return; }
  44856. this.remove();
  44857. this.loadObj(data.obj, data.mtl);
  44858. },
  44859. remove: function () {
  44860. if (!this.model) { return; }
  44861. this.el.removeObject3D('mesh');
  44862. },
  44863. loadObj: function (objUrl, mtlUrl) {
  44864. var self = this;
  44865. var el = this.el;
  44866. var mtlLoader = this.mtlLoader;
  44867. var objLoader = this.objLoader;
  44868. if (mtlUrl) {
  44869. // .OBJ with an .MTL.
  44870. if (el.hasAttribute('material')) {
  44871. warn('Material component properties are ignored when a .MTL is provided');
  44872. }
  44873. mtlLoader.setTexturePath(mtlUrl.substr(0, mtlUrl.lastIndexOf('/') + 1));
  44874. mtlLoader.load(mtlUrl, function (materials) {
  44875. materials.preload();
  44876. objLoader.setMaterials(materials);
  44877. objLoader.load(objUrl, function (objModel) {
  44878. self.model = objModel;
  44879. el.setObject3D('mesh', objModel);
  44880. el.emit('model-loaded', {format: 'obj', model: objModel});
  44881. });
  44882. });
  44883. return;
  44884. }
  44885. // .OBJ only.
  44886. objLoader.load(objUrl, function loadObjOnly (objModel) {
  44887. // Apply material.
  44888. var material = el.components.material;
  44889. if (material) {
  44890. objModel.traverse(function (child) {
  44891. if (child instanceof THREE.Mesh) {
  44892. child.material = material.material;
  44893. }
  44894. });
  44895. }
  44896. self.model = objModel;
  44897. el.setObject3D('mesh', objModel);
  44898. el.emit('model-loaded', {format: 'obj', model: objModel});
  44899. });
  44900. }
  44901. });
  44902. },{"../core/component":126,"../lib/three":174,"../utils/debug":193}],94:[function(_dereq_,module,exports){
  44903. var bind = _dereq_('../utils/bind');
  44904. var registerComponent = _dereq_('../core/component').registerComponent;
  44905. var controllerUtils = _dereq_('../utils/tracked-controls');
  44906. var TOUCH_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/oculus/oculus-touch-controller-';
  44907. var TOUCH_CONTROLLER_MODEL_OBJ_URL_L = TOUCH_CONTROLLER_MODEL_BASE_URL + 'left.obj';
  44908. var TOUCH_CONTROLLER_MODEL_OBJ_MTL_L = TOUCH_CONTROLLER_MODEL_BASE_URL + 'left.mtl';
  44909. var TOUCH_CONTROLLER_MODEL_OBJ_URL_R = TOUCH_CONTROLLER_MODEL_BASE_URL + 'right.obj';
  44910. var TOUCH_CONTROLLER_MODEL_OBJ_MTL_R = TOUCH_CONTROLLER_MODEL_BASE_URL + 'right.mtl';
  44911. var GAMEPAD_ID_PREFIX = 'Oculus Touch';
  44912. var PIVOT_OFFSET = {x: 0, y: -0.015, z: 0.04};
  44913. /**
  44914. * Oculus Touch Controls Component
  44915. * Interfaces with Oculus Touch controllers and maps Gamepad events to
  44916. * common controller buttons: trackpad, trigger, grip, menu and system
  44917. * It loads a controller model and highlights the pressed buttons
  44918. */
  44919. module.exports.Component = registerComponent('oculus-touch-controls', {
  44920. schema: {
  44921. hand: {default: 'left'},
  44922. buttonColor: {type: 'color', default: '#999'}, // Off-white.
  44923. buttonTouchColor: {type: 'color', default: '#8AB'},
  44924. buttonHighlightColor: {type: 'color', default: '#2DF'}, // Light blue.
  44925. model: {default: true},
  44926. rotationOffset: {default: 0} // no default offset; -999 is sentinel value to auto-determine based on hand
  44927. },
  44928. // buttonId
  44929. // 0 - thumbstick (which has separate axismove / thumbstickmoved events)
  44930. // 1 - trigger (with analog value, which goes up to 1)
  44931. // 2 - grip (with analog value, which goes up to 1)
  44932. // 3 - X (left) or A (right)
  44933. // 4 - Y (left) or B (right)
  44934. // 5 - surface (touch only)
  44935. mapping: {
  44936. left: {
  44937. axes: {'thumbstick': [0, 1]},
  44938. buttons: ['thumbstick', 'trigger', 'grip', 'xbutton', 'ybutton', 'surface']
  44939. },
  44940. right: {
  44941. axes: {'thumbstick': [0, 1]},
  44942. buttons: ['thumbstick', 'trigger', 'grip', 'abutton', 'bbutton', 'surface']
  44943. }
  44944. },
  44945. // Use these labels for detail on axis events such as thumbstickmoved.
  44946. // e.g. for thumbstickmoved detail, the first axis returned is labeled x, and the second is labeled y.
  44947. axisLabels: ['x', 'y', 'z', 'w'],
  44948. bindMethods: function () {
  44949. this.onModelLoaded = bind(this.onModelLoaded, this);
  44950. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  44951. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  44952. this.onAxisMoved = bind(this.onAxisMoved, this);
  44953. },
  44954. init: function () {
  44955. var self = this;
  44956. this.onButtonChanged = bind(this.onButtonChanged, this);
  44957. this.onButtonDown = function (evt) { self.onButtonEvent(evt.detail.id, 'down'); };
  44958. this.onButtonUp = function (evt) { self.onButtonEvent(evt.detail.id, 'up'); };
  44959. this.onButtonTouchStart = function (evt) { self.onButtonEvent(evt.detail.id, 'touchstart'); };
  44960. this.onButtonTouchEnd = function (evt) { self.onButtonEvent(evt.detail.id, 'touchend'); };
  44961. this.controllerPresent = false;
  44962. this.lastControllerCheck = 0;
  44963. this.previousButtonValues = {};
  44964. this.bindMethods();
  44965. this.emitIfAxesChanged = controllerUtils.emitIfAxesChanged; // Allow mock.
  44966. this.checkControllerPresentAndSetup = controllerUtils.checkControllerPresentAndSetup; // Allow mock.
  44967. },
  44968. addEventListeners: function () {
  44969. var el = this.el;
  44970. el.addEventListener('buttonchanged', this.onButtonChanged);
  44971. el.addEventListener('buttondown', this.onButtonDown);
  44972. el.addEventListener('buttonup', this.onButtonUp);
  44973. el.addEventListener('touchstart', this.onButtonTouchStart);
  44974. el.addEventListener('touchend', this.onButtonTouchEnd);
  44975. el.addEventListener('axismove', this.onAxisMoved);
  44976. el.addEventListener('model-loaded', this.onModelLoaded);
  44977. this.controllerEventsActive = true;
  44978. },
  44979. removeEventListeners: function () {
  44980. var el = this.el;
  44981. el.removeEventListener('buttonchanged', this.onButtonChanged);
  44982. el.removeEventListener('buttondown', this.onButtonDown);
  44983. el.removeEventListener('buttonup', this.onButtonUp);
  44984. el.removeEventListener('touchstart', this.onButtonTouchStart);
  44985. el.removeEventListener('touchend', this.onButtonTouchEnd);
  44986. el.removeEventListener('axismove', this.onAxisMoved);
  44987. el.removeEventListener('model-loaded', this.onModelLoaded);
  44988. this.controllerEventsActive = false;
  44989. },
  44990. checkIfControllerPresent: function () {
  44991. this.checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {
  44992. hand: this.data.hand
  44993. });
  44994. },
  44995. play: function () {
  44996. this.checkIfControllerPresent();
  44997. this.addControllersUpdateListener();
  44998. // Note that due to gamepadconnected event propagation issues, we don't rely on events.
  44999. window.addEventListener('gamepaddisconnected', this.checkIfControllerPresent, false);
  45000. },
  45001. pause: function () {
  45002. this.removeEventListeners();
  45003. this.removeControllersUpdateListener();
  45004. // Note that due to gamepadconnected event propagation issues, we don't rely on events.
  45005. window.removeEventListener('gamepaddisconnected', this.checkIfControllerPresent, false);
  45006. },
  45007. updateControllerModel: function () {
  45008. var objUrl, mtlUrl;
  45009. if (!this.data.model) { return; }
  45010. if (this.data.hand === 'right') {
  45011. objUrl = 'url(' + TOUCH_CONTROLLER_MODEL_OBJ_URL_R + ')';
  45012. mtlUrl = 'url(' + TOUCH_CONTROLLER_MODEL_OBJ_MTL_R + ')';
  45013. } else {
  45014. objUrl = 'url(' + TOUCH_CONTROLLER_MODEL_OBJ_URL_L + ')';
  45015. mtlUrl = 'url(' + TOUCH_CONTROLLER_MODEL_OBJ_MTL_L + ')';
  45016. }
  45017. this.el.setAttribute('obj-model', {obj: objUrl, mtl: mtlUrl});
  45018. },
  45019. injectTrackedControls: function () {
  45020. var data = this.data;
  45021. var offset = data.hand === 'right' ? -90 : 90;
  45022. this.el.setAttribute('tracked-controls', {
  45023. id: data.hand === 'right' ? 'Oculus Touch (Right)' : 'Oculus Touch (Left)',
  45024. controller: 0,
  45025. rotationOffset: data.rotationOffset !== -999 ? data.rotationOffset : offset
  45026. });
  45027. this.updateControllerModel();
  45028. },
  45029. addControllersUpdateListener: function () {
  45030. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  45031. },
  45032. removeControllersUpdateListener: function () {
  45033. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  45034. },
  45035. onControllersUpdate: function () {
  45036. // Note that due to gamepadconnected event propagation issues, we don't rely on events.
  45037. this.checkIfControllerPresent();
  45038. },
  45039. onButtonChanged: function (evt) {
  45040. var button = this.mapping[this.data.hand].buttons[evt.detail.id];
  45041. var buttonMeshes = this.buttonMeshes;
  45042. var analogValue;
  45043. if (!button) { return; }
  45044. if (button === 'trigger' || button === 'grip') { analogValue = evt.detail.state.value; }
  45045. // Update trigger and/or grip meshes, if any.
  45046. if (buttonMeshes) {
  45047. if (button === 'trigger' && buttonMeshes.trigger) {
  45048. buttonMeshes.trigger.rotation.x = -analogValue * (Math.PI / 24);
  45049. }
  45050. if (button === 'grip' && buttonMeshes.grip) {
  45051. buttonMeshes.grip.rotation.y = (this.data.hand === 'left' ? -1 : 1) * analogValue * (Math.PI / 60);
  45052. }
  45053. }
  45054. // Pass along changed event with button state, using the buttom mapping for convenience.
  45055. this.el.emit(button + 'changed', evt.detail.state);
  45056. },
  45057. onModelLoaded: function (evt) {
  45058. var controllerObject3D = evt.detail.model;
  45059. var buttonMeshes;
  45060. if (!this.data.model) { return; }
  45061. var leftHand = this.data.hand === 'left';
  45062. buttonMeshes = this.buttonMeshes = {};
  45063. buttonMeshes.grip = controllerObject3D.getObjectByName(leftHand ? 'buttonHand_oculus-touch-controller-left.004' : 'buttonHand_oculus-touch-controller-right.005');
  45064. buttonMeshes.thumbstick = controllerObject3D.getObjectByName(leftHand ? 'stick_oculus-touch-controller-left.007' : 'stick_oculus-touch-controller-right.004');
  45065. buttonMeshes.trigger = controllerObject3D.getObjectByName(leftHand ? 'buttonTrigger_oculus-touch-controller-left.005' : 'buttonTrigger_oculus-touch-controller-right.006');
  45066. buttonMeshes.xbutton = controllerObject3D.getObjectByName('buttonX_oculus-touch-controller-left.002');
  45067. buttonMeshes.abutton = controllerObject3D.getObjectByName('buttonA_oculus-touch-controller-right.002');
  45068. buttonMeshes.ybutton = controllerObject3D.getObjectByName('buttonY_oculus-touch-controller-left.001');
  45069. buttonMeshes.bbutton = controllerObject3D.getObjectByName('buttonB_oculus-touch-controller-right.003');
  45070. // Offset pivot point
  45071. controllerObject3D.position = PIVOT_OFFSET;
  45072. },
  45073. onButtonEvent: function (id, evtName) {
  45074. var buttonName = this.mapping[this.data.hand].buttons[id];
  45075. var i;
  45076. if (Array.isArray(buttonName)) {
  45077. for (i = 0; i < buttonName.length; i++) {
  45078. this.el.emit(buttonName[i] + evtName);
  45079. }
  45080. } else {
  45081. this.el.emit(buttonName + evtName);
  45082. }
  45083. this.updateModel(buttonName, evtName);
  45084. },
  45085. onAxisMoved: function (evt) {
  45086. this.emitIfAxesChanged(this, this.mapping[this.data.hand].axes, evt);
  45087. },
  45088. updateModel: function (buttonName, evtName) {
  45089. var i;
  45090. if (Array.isArray(buttonName)) {
  45091. for (i = 0; i < buttonName.length; i++) {
  45092. this.updateButtonModel(buttonName[i], evtName);
  45093. }
  45094. } else {
  45095. this.updateButtonModel(buttonName, evtName);
  45096. }
  45097. },
  45098. updateButtonModel: function (buttonName, state) {
  45099. var color = (state === 'up' || state === 'touchend') ? this.data.buttonColor : state === 'touchstart' ? this.data.buttonTouchColor : this.data.buttonHighlightColor;
  45100. var buttonMeshes = this.buttonMeshes;
  45101. if (!this.data.model) { return; }
  45102. if (buttonMeshes && buttonMeshes[buttonName]) {
  45103. buttonMeshes[buttonName].material.color.set(color);
  45104. }
  45105. }
  45106. });
  45107. },{"../core/component":126,"../utils/bind":191,"../utils/tracked-controls":201}],95:[function(_dereq_,module,exports){
  45108. var registerComponent = _dereq_('../core/component').registerComponent;
  45109. module.exports.Component = registerComponent('position', {
  45110. schema: {type: 'vec3'},
  45111. update: function () {
  45112. var object3D = this.el.object3D;
  45113. var data = this.data;
  45114. object3D.position.set(data.x, data.y, data.z);
  45115. }
  45116. });
  45117. },{"../core/component":126}],96:[function(_dereq_,module,exports){
  45118. var registerComponent = _dereq_('../core/component').registerComponent;
  45119. var THREE = _dereq_('../lib/three');
  45120. var utils = _dereq_('../utils/');
  45121. var bind = utils.bind;
  45122. var dummyVec = new THREE.Vector3();
  45123. /**
  45124. * Raycaster component.
  45125. *
  45126. * Pass options to three.js Raycaster including which objects to test.
  45127. * Poll for intersections.
  45128. * Emit event on origin entity and on target entity on intersect.
  45129. *
  45130. * @member {array} intersectedEls - List of currently intersected entities.
  45131. * @member {array} objects - Cached list of meshes to intersect.
  45132. * @member {number} prevCheckTime - Previous time intersection was checked. To help interval.
  45133. * @member {object} raycaster - three.js Raycaster.
  45134. */
  45135. module.exports.Component = registerComponent('raycaster', {
  45136. schema: {
  45137. direction: {type: 'vec3', default: {x: 0, y: 0, z: -1}},
  45138. far: {default: 1000},
  45139. interval: {default: 100},
  45140. near: {default: 0},
  45141. objects: {default: ''},
  45142. origin: {type: 'vec3'},
  45143. recursive: {default: true},
  45144. showLine: {default: false},
  45145. useWorldCoordinates: {default: false}
  45146. },
  45147. init: function () {
  45148. // Calculate unit vector for line direction. Can be multiplied via scalar to performantly
  45149. // adjust line length.
  45150. this.lineData = {};
  45151. this.lineEndVec3 = new THREE.Vector3();
  45152. this.unitLineEndVec3 = new THREE.Vector3();
  45153. this.intersectedEls = [];
  45154. this.objects = null;
  45155. this.prevCheckTime = undefined;
  45156. this.prevIntersectedEls = [];
  45157. this.raycaster = new THREE.Raycaster();
  45158. this.updateOriginDirection();
  45159. this.refreshObjects = bind(this.refreshObjects, this);
  45160. this.refreshOnceChildLoaded = bind(this.refreshOnceChildLoaded, this);
  45161. },
  45162. /**
  45163. * Create or update raycaster object.
  45164. */
  45165. update: function (oldData) {
  45166. var data = this.data;
  45167. var el = this.el;
  45168. var raycaster = this.raycaster;
  45169. // Set raycaster properties.
  45170. raycaster.far = data.far;
  45171. raycaster.near = data.near;
  45172. // Draw line.
  45173. if (data.showLine &&
  45174. (data.far !== oldData.far || data.origin !== oldData.origin ||
  45175. data.direction !== oldData.direction)) {
  45176. this.unitLineEndVec3.copy(data.origin).add(data.direction).normalize();
  45177. this.drawLine();
  45178. }
  45179. if (!data.showLine && oldData.showLine) {
  45180. el.removeAttribute('line');
  45181. }
  45182. this.refreshObjects();
  45183. },
  45184. play: function () {
  45185. this.el.sceneEl.addEventListener('loaded', this.refreshObjects);
  45186. this.el.sceneEl.addEventListener('child-attached', this.refreshOnceChildLoaded);
  45187. this.el.sceneEl.addEventListener('child-detached', this.refreshObjects);
  45188. },
  45189. pause: function () {
  45190. this.el.sceneEl.removeEventListener('loaded', this.refreshObjects);
  45191. this.el.sceneEl.removeEventListener('child-attached', this.refreshOnceChildLoaded);
  45192. this.el.sceneEl.removeEventListener('child-detached', this.refreshObjects);
  45193. },
  45194. remove: function () {
  45195. if (this.data.showLine) {
  45196. this.el.removeAttribute('line');
  45197. }
  45198. },
  45199. /**
  45200. * Update list of objects to test for intersection once child is loaded.
  45201. */
  45202. refreshOnceChildLoaded: function (evt) {
  45203. var self = this;
  45204. var childEl = evt.detail.el;
  45205. if (!childEl) { return; }
  45206. if (childEl.hasLoaded) {
  45207. this.refreshObjects();
  45208. } else {
  45209. childEl.addEventListener('loaded', function nowRefresh (evt) {
  45210. childEl.removeEventListener('loaded', nowRefresh);
  45211. self.refreshObjects();
  45212. });
  45213. }
  45214. },
  45215. /**
  45216. * Update list of objects to test for intersection.
  45217. */
  45218. refreshObjects: function () {
  45219. var children;
  45220. var data = this.data;
  45221. var i;
  45222. var objects;
  45223. // Target entities.
  45224. var targetEls = data.objects ? this.el.sceneEl.querySelectorAll(data.objects) : null;
  45225. // Push meshes onto list of objects to intersect.
  45226. if (targetEls) {
  45227. objects = [];
  45228. for (i = 0; i < targetEls.length; i++) {
  45229. objects.push(targetEls[i].object3D);
  45230. }
  45231. } else {
  45232. // If objects not defined, intersect with everything.
  45233. objects = this.el.sceneEl.object3D.children;
  45234. }
  45235. this.objects = [];
  45236. for (i = 0; i < objects.length; i++) {
  45237. // A-Frame wraps everything in THREE.Group. Grab the children.
  45238. children = objects[i].children;
  45239. // Add the object3D children for non-recursive raycasting.
  45240. // If no children, refresh after entity loaded.
  45241. if (children) { this.objects.push.apply(this.objects, children); }
  45242. }
  45243. },
  45244. /**
  45245. * Check for intersections and cleared intersections on an interval.
  45246. */
  45247. tick: (function () {
  45248. var intersections = [];
  45249. return function (time) {
  45250. var el = this.el;
  45251. var data = this.data;
  45252. var i;
  45253. var intersectedEls = this.intersectedEls;
  45254. var intersection;
  45255. var lineLength;
  45256. var prevCheckTime = this.prevCheckTime;
  45257. var prevIntersectedEls = this.prevIntersectedEls;
  45258. var rawIntersections;
  45259. // Only check for intersection if interval time has passed.
  45260. if (prevCheckTime && (time - prevCheckTime < data.interval)) { return; }
  45261. // Update check time.
  45262. this.prevCheckTime = time;
  45263. // Store old previously intersected entities.
  45264. copyArray(this.prevIntersectedEls, this.intersectedEls);
  45265. // Raycast.
  45266. this.updateOriginDirection();
  45267. rawIntersections = this.raycaster.intersectObjects(this.objects, data.recursive);
  45268. // Only keep intersections against objects that have a reference to an entity.
  45269. intersections.length = 0;
  45270. for (i = 0; i < rawIntersections.length; i++) {
  45271. intersection = rawIntersections[i];
  45272. // Don't intersect with own line.
  45273. if (data.showLine && intersection.object === el.getObject3D('line')) {
  45274. continue;
  45275. }
  45276. if (intersection.object.el) {
  45277. intersections.push(intersection);
  45278. }
  45279. }
  45280. // Update intersectedEls.
  45281. intersectedEls.length = intersections.length;
  45282. for (i = 0; i < intersections.length; i++) {
  45283. intersectedEls[i] = intersections[i].object.el;
  45284. }
  45285. // Emit intersected on intersected entity per intersected entity.
  45286. for (i = 0; i < intersections.length; i++) {
  45287. intersections[i].object.el.emit('raycaster-intersected', {
  45288. el: el,
  45289. intersection: intersections[i]
  45290. });
  45291. }
  45292. // Emit all intersections at once on raycasting entity.
  45293. if (intersections.length) {
  45294. el.emit('raycaster-intersection', {
  45295. els: intersectedEls,
  45296. intersections: intersections
  45297. });
  45298. }
  45299. // Emit intersection cleared on both entities per formerly intersected entity.
  45300. for (i = 0; i < prevIntersectedEls.length; i++) {
  45301. if (intersectedEls.indexOf(prevIntersectedEls[i]) !== -1) { return; }
  45302. el.emit('raycaster-intersection-cleared', {el: prevIntersectedEls[i]});
  45303. prevIntersectedEls[i].emit('raycaster-intersected-cleared', {el: el});
  45304. }
  45305. // Update line length.
  45306. if (data.showLine) {
  45307. if (intersections.length) {
  45308. if (intersections[0].object.el === el && intersections[1]) {
  45309. lineLength = intersections[1].distance;
  45310. } else {
  45311. lineLength = intersections[0].distance;
  45312. }
  45313. }
  45314. this.drawLine(lineLength);
  45315. }
  45316. };
  45317. })(),
  45318. /**
  45319. * Update origin and direction of raycaster using entity transforms and supplied origin or
  45320. * direction offsets.
  45321. */
  45322. updateOriginDirection: (function () {
  45323. var direction = new THREE.Vector3();
  45324. var quaternion = new THREE.Quaternion();
  45325. var originVec3 = new THREE.Vector3();
  45326. // Closure to make quaternion/vector3 objects private.
  45327. return function updateOriginDirection () {
  45328. var el = this.el;
  45329. var data = this.data;
  45330. if (data.useWorldCoordinates) {
  45331. this.raycaster.set(data.origin, data.direction);
  45332. return;
  45333. }
  45334. // Grab the position and rotation.
  45335. el.object3D.updateMatrixWorld();
  45336. el.object3D.matrixWorld.decompose(originVec3, quaternion, dummyVec);
  45337. // If non-zero origin, translate the origin into world space.
  45338. if (data.origin.x !== 0 || data.origin.y !== 0 || data.origin.z !== 0) {
  45339. originVec3 = el.object3D.localToWorld(originVec3.copy(data.origin));
  45340. }
  45341. // three.js raycaster direction is relative to 0, 0, 0 NOT the origin / offset we
  45342. // provide. Apply the offset to the direction, then rotation from the object,
  45343. // and normalize.
  45344. direction.copy(data.direction).add(data.origin).applyQuaternion(quaternion).normalize();
  45345. // Apply offset and direction, in world coordinates.
  45346. this.raycaster.set(originVec3, direction);
  45347. };
  45348. })(),
  45349. /**
  45350. * Create or update line to give raycaster visual representation.
  45351. * Customize the line through through line component.
  45352. * We draw the line in the raycaster component to customize the line to the
  45353. * raycaster's origin, direction, and far.
  45354. *
  45355. * Unlike the raycaster, we create the line as a child of the object. The line will
  45356. * be affected by the transforms of the objects, so we don't have to calculate transforms
  45357. * like we do with the raycaster.
  45358. *
  45359. * @param {number} length - Length of line. Pass in to shorten the line to the intersection
  45360. * point. If not provided, length will default to the max length, `raycaster.far`.
  45361. */
  45362. drawLine: (function (length) {
  45363. var lineEndVec3 = new THREE.Vector3();
  45364. var lineData = {};
  45365. return function (length) {
  45366. var data = this.data;
  45367. var el = this.el;
  45368. // Treat Infinity as 1000m for the line.
  45369. if (length === undefined) {
  45370. length = data.far === Infinity ? 1000 : data.far;
  45371. }
  45372. // Update the length of the line if given. `unitLineEndVec3` is the direction
  45373. // given by data.direction, then we apply a scalar to give it a length.
  45374. lineData.start = data.origin;
  45375. lineData.end = lineEndVec3.copy(this.unitLineEndVec3).multiplyScalar(length);
  45376. el.setAttribute('line', lineData);
  45377. };
  45378. })()
  45379. });
  45380. /**
  45381. * Copy contents of one array to another without allocating new array.
  45382. */
  45383. function copyArray (a, b) {
  45384. var i;
  45385. a.length = b.length;
  45386. for (i = 0; i < b.length; i++) {
  45387. a[i] = b[i];
  45388. }
  45389. }
  45390. },{"../core/component":126,"../lib/three":174,"../utils/":197}],97:[function(_dereq_,module,exports){
  45391. var degToRad = _dereq_('../lib/three').Math.degToRad;
  45392. var registerComponent = _dereq_('../core/component').registerComponent;
  45393. module.exports.Component = registerComponent('rotation', {
  45394. schema: {type: 'vec3'},
  45395. /**
  45396. * Updates object3D rotation.
  45397. */
  45398. update: function () {
  45399. var data = this.data;
  45400. var object3D = this.el.object3D;
  45401. object3D.rotation.set(degToRad(data.x), degToRad(data.y), degToRad(data.z));
  45402. object3D.rotation.order = 'YXZ';
  45403. }
  45404. });
  45405. },{"../core/component":126,"../lib/three":174}],98:[function(_dereq_,module,exports){
  45406. var registerComponent = _dereq_('../core/component').registerComponent;
  45407. // Avoids triggering a zero-determinant which makes object3D matrix non-invertible.
  45408. var zeroScale = 0.00001;
  45409. module.exports.Component = registerComponent('scale', {
  45410. schema: {
  45411. type: 'vec3',
  45412. default: {x: 1, y: 1, z: 1}
  45413. },
  45414. update: function () {
  45415. var data = this.data;
  45416. var object3D = this.el.object3D;
  45417. var x = data.x === 0 ? zeroScale : data.x;
  45418. var y = data.y === 0 ? zeroScale : data.y;
  45419. var z = data.z === 0 ? zeroScale : data.z;
  45420. object3D.scale.set(x, y, z);
  45421. }
  45422. });
  45423. },{"../core/component":126}],99:[function(_dereq_,module,exports){
  45424. var bind = _dereq_('../../utils/bind');
  45425. var registerComponent = _dereq_('../../core/component').registerComponent;
  45426. module.exports.Component = registerComponent('canvas', {
  45427. init: function () {
  45428. var canvasEl;
  45429. var sceneEl = this.el;
  45430. canvasEl = document.createElement('canvas');
  45431. canvasEl.classList.add('a-canvas');
  45432. // Mark canvas as provided/injected by A-Frame.
  45433. canvasEl.dataset.aframeCanvas = true;
  45434. sceneEl.appendChild(canvasEl);
  45435. document.addEventListener('fullscreenchange', onFullScreenChange);
  45436. document.addEventListener('mozfullscreenchange', onFullScreenChange);
  45437. document.addEventListener('webkitfullscreenchange', onFullScreenChange);
  45438. // Prevent overscroll on mobile.
  45439. canvasEl.addEventListener('touchmove', function (event) {
  45440. event.preventDefault();
  45441. });
  45442. // Set canvas on scene.
  45443. sceneEl.canvas = canvasEl;
  45444. sceneEl.emit('render-target-loaded', {target: canvasEl});
  45445. // For unknown reasons a syncrhonous resize does not work on desktop when
  45446. // entering/exiting fullscreen.
  45447. setTimeout(bind(sceneEl.resize, sceneEl), 0);
  45448. function onFullScreenChange () {
  45449. var fullscreenEl =
  45450. document.fullscreenElement ||
  45451. document.mozFullScreenElement ||
  45452. document.webkitFullscreenElement;
  45453. // No fullscren element === exit fullscreen
  45454. if (!fullscreenEl) { sceneEl.exitVR(); }
  45455. document.activeElement.blur();
  45456. document.body.focus();
  45457. }
  45458. }
  45459. });
  45460. },{"../../core/component":126,"../../utils/bind":191}],100:[function(_dereq_,module,exports){
  45461. var register = _dereq_('../../core/component').registerComponent;
  45462. module.exports.Component = register('debug', {
  45463. schema: {default: true}
  45464. });
  45465. },{"../../core/component":126}],101:[function(_dereq_,module,exports){
  45466. var registerComponent = _dereq_('../../core/component').registerComponent;
  45467. /**
  45468. * Component to embed an a-frame scene within the layout of a 2D page.
  45469. */
  45470. module.exports.Component = registerComponent('embedded', {
  45471. dependencies: ['vr-mode-ui'],
  45472. schema: {default: true},
  45473. update: function () {
  45474. var sceneEl = this.el;
  45475. var enterVREl = sceneEl.querySelector('.a-enter-vr');
  45476. if (this.data === true) {
  45477. if (enterVREl) { enterVREl.classList.add('embedded'); }
  45478. sceneEl.removeFullScreenStyles();
  45479. } else {
  45480. if (enterVREl) { enterVREl.classList.remove('embedded'); }
  45481. sceneEl.addFullScreenStyles();
  45482. }
  45483. }
  45484. });
  45485. },{"../../core/component":126}],102:[function(_dereq_,module,exports){
  45486. var register = _dereq_('../../core/component').registerComponent;
  45487. var THREE = _dereq_('../../lib/three');
  45488. var debug = _dereq_('../../utils/debug');
  45489. var warn = debug('components:fog:warn');
  45490. /**
  45491. * Fog component.
  45492. * Applies only to the scene entity.
  45493. */
  45494. module.exports.Component = register('fog', {
  45495. schema: {
  45496. color: {type: 'color', default: '#000'},
  45497. density: {default: 0.00025},
  45498. far: {default: 1000, min: 0},
  45499. near: {default: 1, min: 0},
  45500. type: {default: 'linear', oneOf: ['linear', 'exponential']}
  45501. },
  45502. update: function () {
  45503. var data = this.data;
  45504. var el = this.el;
  45505. var fog = this.el.object3D.fog;
  45506. if (!el.isScene) {
  45507. warn('Fog component can only be applied to <a-scene>');
  45508. return;
  45509. }
  45510. // (Re)create fog if fog doesn't exist or fog type changed.
  45511. if (!fog || data.type !== fog.name) {
  45512. el.object3D.fog = getFog(data);
  45513. el.systems.material.updateMaterials();
  45514. return;
  45515. }
  45516. // Fog data changed. Update fog.
  45517. Object.keys(this.schema).forEach(function (key) {
  45518. var value = data[key];
  45519. if (key === 'color') { value = new THREE.Color(value); }
  45520. fog[key] = value;
  45521. });
  45522. },
  45523. /**
  45524. * Remove fog on remove (callback).
  45525. */
  45526. remove: function () {
  45527. var fog = this.el.object3D.fog;
  45528. if (!fog) { return; }
  45529. fog.far = 0;
  45530. fog.near = 0.1;
  45531. }
  45532. });
  45533. /**
  45534. * Creates a fog object. Sets fog.name to be able to detect fog type changes.
  45535. *
  45536. * @param {object} data - Fog data.
  45537. * @returns {object} fog
  45538. */
  45539. function getFog (data) {
  45540. var fog;
  45541. if (data.type === 'exponential') {
  45542. fog = new THREE.FogExp2(data.color, data.density);
  45543. } else {
  45544. fog = new THREE.Fog(data.color, data.near, data.far);
  45545. }
  45546. fog.name = data.type;
  45547. return fog;
  45548. }
  45549. },{"../../core/component":126,"../../lib/three":174,"../../utils/debug":193}],103:[function(_dereq_,module,exports){
  45550. (function (process){
  45551. /* global AFRAME */
  45552. var AFRAME_INJECTED = _dereq_('../../constants').AFRAME_INJECTED;
  45553. var bind = _dereq_('../../utils/bind');
  45554. var pkg = _dereq_('../../../package');
  45555. var registerComponent = _dereq_('../../core/component').registerComponent;
  45556. /**
  45557. * 0.4.2 to 0.4.x
  45558. * Will need to update this when A-Frame goes to 1.x.x.
  45559. */
  45560. function getFuzzyPatchVersion (version) {
  45561. var split = version.split('.');
  45562. split[2] = 'x';
  45563. return split.join('.');
  45564. }
  45565. var INSPECTOR_DEV_URL = 'https://aframe.io/aframe-inspector/dist/aframe-inspector.js';
  45566. var INSPECTOR_RELEASE_URL = 'https://unpkg.com/aframe-inspector@' + getFuzzyPatchVersion(pkg.version) + '/dist/aframe-inspector.min.js';
  45567. var INSPECTOR_URL = process.env.INSPECTOR_VERSION === 'dev' ? INSPECTOR_DEV_URL : INSPECTOR_RELEASE_URL;
  45568. var LOADING_MESSAGE = 'Loading Inspector';
  45569. var LOADING_ERROR_MESSAGE = 'Error loading Inspector';
  45570. module.exports.Component = registerComponent('inspector', {
  45571. schema: {
  45572. url: {default: INSPECTOR_URL}
  45573. },
  45574. init: function () {
  45575. this.onKeydown = bind(this.onKeydown, this);
  45576. this.onMessage = bind(this.onMessage, this);
  45577. this.initOverlay();
  45578. window.addEventListener('keydown', this.onKeydown);
  45579. window.addEventListener('message', this.onMessage);
  45580. },
  45581. initOverlay: function () {
  45582. var dotsHTML = '<span class="dots"><span>.</span><span>.</span><span>.</span></span>';
  45583. this.loadingMessageEl = document.createElement('div');
  45584. this.loadingMessageEl.classList.add('a-inspector-loader');
  45585. this.loadingMessageEl.innerHTML = LOADING_MESSAGE + dotsHTML;
  45586. },
  45587. remove: function () {
  45588. this.removeEventListeners();
  45589. },
  45590. /**
  45591. * <ctrl> + <alt> + i keyboard shortcut.
  45592. */
  45593. onKeydown: function (evt) {
  45594. var shortcutPressed = evt.keyCode === 73 && evt.ctrlKey && evt.altKey;
  45595. if (!this.data || !shortcutPressed) { return; }
  45596. this.injectInspector();
  45597. },
  45598. showLoader: function () {
  45599. document.body.appendChild(this.loadingMessageEl);
  45600. },
  45601. hideLoader: function () {
  45602. document.body.removeChild(this.loadingMessageEl);
  45603. },
  45604. /**
  45605. * postMessage. aframe.io uses this to create a button on examples to open Inspector.
  45606. */
  45607. onMessage: function (evt) {
  45608. if (evt.data === 'INJECT_AFRAME_INSPECTOR') { this.injectInspector(); }
  45609. },
  45610. injectInspector: function () {
  45611. var self = this;
  45612. var script;
  45613. if (AFRAME.INSPECTOR || AFRAME.inspectorInjected) { return; }
  45614. this.showLoader();
  45615. // Inject.
  45616. script = document.createElement('script');
  45617. script.src = this.data.url;
  45618. script.setAttribute('data-name', 'aframe-inspector');
  45619. script.setAttribute(AFRAME_INJECTED, '');
  45620. script.onload = function () {
  45621. AFRAME.INSPECTOR.open();
  45622. self.hideLoader();
  45623. self.removeEventListeners();
  45624. };
  45625. script.onerror = function () {
  45626. self.loadingMessageEl.innerHTML = LOADING_ERROR_MESSAGE;
  45627. };
  45628. document.head.appendChild(script);
  45629. AFRAME.inspectorInjected = true;
  45630. },
  45631. removeEventListeners: function () {
  45632. window.removeEventListener('keydown', this.onKeydown);
  45633. window.removeEventListener('message', this.onMessage);
  45634. }
  45635. });
  45636. }).call(this,_dereq_('_process'))
  45637. },{"../../../package":77,"../../constants":117,"../../core/component":126,"../../utils/bind":191,"_process":34}],104:[function(_dereq_,module,exports){
  45638. var registerComponent = _dereq_('../../core/component').registerComponent;
  45639. var shouldCaptureKeyEvent = _dereq_('../../utils/').shouldCaptureKeyEvent;
  45640. module.exports.Component = registerComponent('keyboard-shortcuts', {
  45641. schema: {
  45642. enterVR: {default: true},
  45643. exitVR: {default: true}
  45644. },
  45645. init: function () {
  45646. var self = this;
  45647. var scene = this.el;
  45648. this.listener = window.addEventListener('keyup', function (event) {
  45649. if (!shouldCaptureKeyEvent(event)) { return; }
  45650. if (self.enterVREnabled && event.keyCode === 70) { // f.
  45651. scene.enterVR();
  45652. }
  45653. if (self.enterVREnabled && event.keyCode === 27) { // escape.
  45654. scene.exitVR();
  45655. }
  45656. }, false);
  45657. },
  45658. update: function (oldData) {
  45659. var data = this.data;
  45660. this.enterVREnabled = data.enterVR;
  45661. },
  45662. remove: function () {
  45663. window.removeEventListener('keyup', this.listener);
  45664. }
  45665. });
  45666. },{"../../core/component":126,"../../utils/":197}],105:[function(_dereq_,module,exports){
  45667. var debug = _dereq_('../../utils/debug');
  45668. var registerComponent = _dereq_('../../core/component').registerComponent;
  45669. var warn = debug('components:pool:warn');
  45670. /**
  45671. * Pool component.
  45672. * A pool of entities that will be reused.
  45673. * It avoids creating and destroying the same kind of entities
  45674. * in dynamic scenes. It will help reduce GC pauses. Useful for example
  45675. * in a game where you want to reuse enemies entities.
  45676. *
  45677. * @member {array} availableEls - Available entities in the pool.
  45678. * @member {array} usedEls - Entities of the pool in use.
  45679. *
  45680. */
  45681. module.exports.Component = registerComponent('pool', {
  45682. schema: {
  45683. mixin: {default: ''},
  45684. size: {default: 0},
  45685. dynamic: {default: false}
  45686. },
  45687. multiple: true,
  45688. initPool: function () {
  45689. var i;
  45690. var mixin = this.data.mixin;
  45691. if (!mixin) { return; }
  45692. this.availableEls = [];
  45693. this.usedEls = [];
  45694. for (i = 0; i < this.data.size; ++i) {
  45695. this.createEntity();
  45696. }
  45697. },
  45698. update: function (oldData) {
  45699. var data = this.data;
  45700. if (oldData.mixin !== data.mixin || oldData.size !== data.size) {
  45701. this.initPool();
  45702. }
  45703. },
  45704. /**
  45705. * Add a new entity to the list of available entities.
  45706. */
  45707. createEntity: function () {
  45708. var el = document.createElement('a-entity');
  45709. el.play = this.wrapPlay(el.play);
  45710. el.setAttribute('mixin', this.data.mixin);
  45711. el.setAttribute('visible', false);
  45712. this.el.appendChild(el);
  45713. this.availableEls.push(el);
  45714. },
  45715. /**
  45716. * Play wrapper for pooled entities. When pausing and playing
  45717. * a scene we don't want to play the entities that are not in use
  45718. */
  45719. wrapPlay: function (playMethod) {
  45720. var usedEls = this.usedEls;
  45721. return function () {
  45722. if (usedEls.indexOf(this) === -1) { return; }
  45723. playMethod.call(this);
  45724. };
  45725. },
  45726. /**
  45727. * Used to request one of the available entities of the pool
  45728. */
  45729. requestEntity: function () {
  45730. var el;
  45731. if (this.availableEls.length === 0) {
  45732. if (this.data.dynamic === false) {
  45733. warn('Requested entity from empty pool ' + this.name);
  45734. return;
  45735. } else {
  45736. warn('Requested entity from empty pool. This pool is dynamic' +
  45737. 'and will resize automatically. You might want to increase its initial size' + this.name);
  45738. }
  45739. this.createEntity();
  45740. }
  45741. el = this.availableEls.shift();
  45742. this.usedEls.push(el);
  45743. el.setAttribute('visible', true);
  45744. return el;
  45745. },
  45746. /**
  45747. * Used to return a used entity to the pool
  45748. */
  45749. returnEntity: function (el) {
  45750. var index = this.usedEls.indexOf(el);
  45751. if (index === -1) {
  45752. warn('The returned entity was not previously pooled from ' + this.name);
  45753. return;
  45754. }
  45755. this.usedEls.splice(index, 1);
  45756. this.availableEls.push(el);
  45757. el.setAttribute('visible', false);
  45758. el.pause();
  45759. }
  45760. });
  45761. },{"../../core/component":126,"../../utils/debug":193}],106:[function(_dereq_,module,exports){
  45762. /* global ImageData, URL */
  45763. var registerComponent = _dereq_('../../core/component').registerComponent;
  45764. var THREE = _dereq_('../../lib/three');
  45765. var VERTEX_SHADER = [
  45766. 'attribute vec3 position;',
  45767. 'attribute vec2 uv;',
  45768. 'uniform mat4 projectionMatrix;',
  45769. 'uniform mat4 modelViewMatrix;',
  45770. 'varying vec2 vUv;',
  45771. 'void main() {',
  45772. ' vUv = vec2( 1.- uv.x, uv.y );',
  45773. ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );',
  45774. '}'
  45775. ].join('\n');
  45776. var FRAGMENT_SHADER = [
  45777. 'precision mediump float;',
  45778. 'uniform samplerCube map;',
  45779. 'varying vec2 vUv;',
  45780. '#define M_PI 3.141592653589793238462643383279',
  45781. 'void main() {',
  45782. ' vec2 uv = vUv;',
  45783. ' float longitude = uv.x * 2. * M_PI - M_PI + M_PI / 2.;',
  45784. ' float latitude = uv.y * M_PI;',
  45785. ' vec3 dir = vec3(',
  45786. ' - sin( longitude ) * sin( latitude ),',
  45787. ' cos( latitude ),',
  45788. ' - cos( longitude ) * sin( latitude )',
  45789. ' );',
  45790. ' normalize( dir );',
  45791. ' gl_FragColor = vec4( textureCube( map, dir ).rgb, 1.0 );',
  45792. '}'
  45793. ].join('\n');
  45794. /**
  45795. * Component to take screenshots of the scene using a keboard shortcut (alt+s).
  45796. * It can be configured to either take 360&deg; captures (`equirectangular`)
  45797. * or regular screenshots (`projection`)
  45798. *
  45799. * This is based on https://github.com/spite/THREE.CubemapToEquirectangular
  45800. * To capture an equirectangular projection of the scene a THREE.CubeCamera is used
  45801. * The cube map produced by the CubeCamera is projected on a quad and then rendered to
  45802. * WebGLRenderTarget with an ortographic camera.
  45803. */
  45804. module.exports.Component = registerComponent('screenshot', {
  45805. schema: {
  45806. width: {default: 4096},
  45807. height: {default: 2048}
  45808. },
  45809. init: function () {
  45810. var el = this.el;
  45811. var self = this;
  45812. if (el.renderer) {
  45813. setup();
  45814. } else {
  45815. el.addEventListener('render-target-loaded', setup);
  45816. }
  45817. function setup () {
  45818. var gl = el.renderer.getContext();
  45819. self.cubeMapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  45820. self.material = new THREE.RawShaderMaterial({
  45821. uniforms: {map: {type: 't', value: null}},
  45822. vertexShader: VERTEX_SHADER,
  45823. fragmentShader: FRAGMENT_SHADER,
  45824. side: THREE.DoubleSide
  45825. });
  45826. self.quad = new THREE.Mesh(
  45827. new THREE.PlaneBufferGeometry(1, 1),
  45828. self.material
  45829. );
  45830. self.quad.visible = false;
  45831. self.camera = new THREE.OrthographicCamera(-1 / 2, 1 / 2, 1 / 2, -1 / 2, -10000, 10000);
  45832. self.canvas = document.createElement('canvas');
  45833. self.ctx = self.canvas.getContext('2d');
  45834. if (el.camera) { el.camera.add(self.quad); }
  45835. self.onKeyDown = self.onKeyDown.bind(self);
  45836. self.onCameraActive = self.onCameraActive.bind(self);
  45837. el.addEventListener('camera-set-active', self.onCameraActive);
  45838. }
  45839. },
  45840. getRenderTarget: function (width, height) {
  45841. return new THREE.WebGLRenderTarget(width, height, {
  45842. minFilter: THREE.LinearFilter,
  45843. magFilter: THREE.LinearFilter,
  45844. wrapS: THREE.ClampToEdgeWrapping,
  45845. wrapT: THREE.ClampToEdgeWrapping,
  45846. format: THREE.RGBAFormat,
  45847. type: THREE.UnsignedByteType
  45848. });
  45849. },
  45850. resize: function (width, height) {
  45851. // Resize quad.
  45852. this.quad.scale.set(width, height, 1);
  45853. // Resize camera.
  45854. this.camera.left = -1 * width / 2;
  45855. this.camera.right = width / 2;
  45856. this.camera.top = height / 2;
  45857. this.camera.bottom = -1 * height / 2;
  45858. this.camera.updateProjectionMatrix();
  45859. // Resize canvas.
  45860. this.canvas.width = width;
  45861. this.canvas.height = height;
  45862. },
  45863. play: function () {
  45864. window.addEventListener('keydown', this.onKeyDown);
  45865. },
  45866. onCameraActive: function (evt) {
  45867. var cameraParent = this.quad.parent;
  45868. if (cameraParent) { cameraParent.remove(this.quad); }
  45869. evt.detail.cameraEl.getObject3D('camera').add(this.quad);
  45870. },
  45871. /**
  45872. * <ctrl> + <alt> + s = Regular screenshot.
  45873. * <ctrl> + <alt> + <shift> + s = Equirectangular screenshot.
  45874. */
  45875. onKeyDown: function (evt) {
  45876. var shortcutPressed = evt.keyCode === 83 && evt.ctrlKey && evt.altKey;
  45877. if (!this.data || !shortcutPressed) { return; }
  45878. var projection = evt.shiftKey ? 'equirectangular' : 'perspective';
  45879. this.capture(projection);
  45880. },
  45881. /**
  45882. * Capture a screenshot of the scene.
  45883. *
  45884. * @param {string} projection - Screenshot projection (equirectangular or perspective).
  45885. */
  45886. setCapture: function (projection) {
  45887. var el = this.el;
  45888. var size;
  45889. var camera;
  45890. var cubeCamera;
  45891. // Configure camera.
  45892. if (projection === 'perspective') {
  45893. // Quad is only used in equirectangular mode. Hide it in this case.
  45894. this.quad.visible = false;
  45895. // Use scene camera.
  45896. camera = el.camera;
  45897. size = {width: this.data.width, height: this.data.height};
  45898. } else {
  45899. // Use ortho camera.
  45900. camera = this.camera;
  45901. // Copy position and rotation of scene camera into the ortho one.
  45902. camera.position.copy(el.camera.getWorldPosition());
  45903. camera.rotation.copy(el.camera.getWorldRotation());
  45904. // Create cube camera and copy position from scene camera.
  45905. cubeCamera = new THREE.CubeCamera(el.camera.near, el.camera.far,
  45906. Math.min(this.cubeMapSize, 2048));
  45907. cubeCamera.position.copy(el.camera.getWorldPosition());
  45908. cubeCamera.rotation.copy(el.camera.getWorldRotation());
  45909. // Render scene with cube camera.
  45910. cubeCamera.updateCubeMap(el.renderer, el.object3D);
  45911. this.quad.material.uniforms.map.value = cubeCamera.renderTarget.texture;
  45912. size = {width: this.data.width, height: this.data.height};
  45913. // Use quad to project image taken by the cube camera.
  45914. this.quad.visible = true;
  45915. }
  45916. return {
  45917. camera: camera,
  45918. size: size,
  45919. projection: projection
  45920. };
  45921. },
  45922. /**
  45923. * Maintained for backwards compatibility.
  45924. */
  45925. capture: function (projection) {
  45926. var params = this.setCapture(projection);
  45927. this.renderCapture(params.camera, params.size, params.projection);
  45928. // Trigger file download.
  45929. this.saveCapture();
  45930. },
  45931. /**
  45932. * Return canvas instead of triggering download (e.g., for uploading blob to server).
  45933. */
  45934. getCanvas: function (projection) {
  45935. var params = this.setCapture(projection);
  45936. this.renderCapture(params.camera, params.size, params.projection);
  45937. return this.canvas;
  45938. },
  45939. renderCapture: function (camera, size, projection) {
  45940. var autoClear = this.el.renderer.autoClear;
  45941. var el = this.el;
  45942. var imageData;
  45943. var output;
  45944. var pixels;
  45945. var renderer = this.el.renderer;
  45946. // Create rendering target and buffer to store the read pixels.
  45947. output = this.getRenderTarget(size.width, size.height);
  45948. pixels = new Uint8Array(4 * size.width * size.height);
  45949. // Resize quad, camera, and canvas.
  45950. this.resize(size.width, size.height);
  45951. // Render scene to render target.
  45952. renderer.autoClear = true;
  45953. renderer.render(el.object3D, camera, output, true);
  45954. renderer.autoClear = autoClear;
  45955. // Read image pizels back.
  45956. renderer.readRenderTargetPixels(output, 0, 0, size.width, size.height, pixels);
  45957. if (projection === 'perspective') {
  45958. pixels = this.flipPixelsVertically(pixels, size.width, size.height);
  45959. }
  45960. imageData = new ImageData(new Uint8ClampedArray(pixels), size.width, size.height);
  45961. // Hide quad after projecting the image.
  45962. this.quad.visible = false;
  45963. // Copy pixels into canvas.
  45964. this.ctx.putImageData(imageData, 0, 0);
  45965. },
  45966. flipPixelsVertically: function (pixels, width, height) {
  45967. var flippedPixels = pixels.slice(0);
  45968. for (var x = 0; x < width; ++x) {
  45969. for (var y = 0; y < height; ++y) {
  45970. flippedPixels[x * 4 + y * width * 4] = pixels[x * 4 + (height - y) * width * 4];
  45971. flippedPixels[x * 4 + 1 + y * width * 4] = pixels[x * 4 + 1 + (height - y) * width * 4];
  45972. flippedPixels[x * 4 + 2 + y * width * 4] = pixels[x * 4 + 2 + (height - y) * width * 4];
  45973. flippedPixels[x * 4 + 3 + y * width * 4] = pixels[x * 4 + 3 + (height - y) * width * 4];
  45974. }
  45975. }
  45976. return flippedPixels;
  45977. },
  45978. /**
  45979. * Download capture to file.
  45980. */
  45981. saveCapture: function () {
  45982. this.canvas.toBlob(function (blob) {
  45983. var fileName = 'screenshot-' + document.title.toLowerCase() + '-' + Date.now() + '.png';
  45984. var linkEl = document.createElement('a');
  45985. var url = URL.createObjectURL(blob);
  45986. linkEl.href = url;
  45987. linkEl.setAttribute('download', fileName);
  45988. linkEl.innerHTML = 'downloading...';
  45989. linkEl.style.display = 'none';
  45990. document.body.appendChild(linkEl);
  45991. setTimeout(function () {
  45992. linkEl.click();
  45993. document.body.removeChild(linkEl);
  45994. }, 1);
  45995. }, 'image/png');
  45996. }
  45997. });
  45998. },{"../../core/component":126,"../../lib/three":174}],107:[function(_dereq_,module,exports){
  45999. var registerComponent = _dereq_('../../core/component').registerComponent;
  46000. var RStats = _dereq_('../../../vendor/rStats');
  46001. var utils = _dereq_('../../utils');
  46002. _dereq_('../../../vendor/rStats.extras');
  46003. _dereq_('../../lib/rStatsAframe');
  46004. var AFrameStats = window.aframeStats;
  46005. var bind = utils.bind;
  46006. var HIDDEN_CLASS = 'a-hidden';
  46007. var ThreeStats = window.threeStats;
  46008. /**
  46009. * Stats appended to document.body by RStats.
  46010. */
  46011. module.exports.Component = registerComponent('stats', {
  46012. schema: {default: true},
  46013. init: function () {
  46014. var scene = this.el;
  46015. if (utils.getUrlParameter('stats') === 'false') { return; }
  46016. this.stats = createStats(scene);
  46017. this.statsEl = document.querySelector('.rs-base');
  46018. this.hideBound = bind(this.hide, this);
  46019. this.showBound = bind(this.show, this);
  46020. scene.addEventListener('enter-vr', this.hideBound);
  46021. scene.addEventListener('exit-vr', this.showBound);
  46022. },
  46023. update: function () {
  46024. if (!this.stats) { return; }
  46025. return (!this.data) ? this.hide() : this.show();
  46026. },
  46027. remove: function () {
  46028. this.el.removeEventListener('enter-vr', this.hideBound);
  46029. this.el.removeEventListener('exit-vr', this.showBound);
  46030. if (!this.statsEl) { return; } // Scene detached.
  46031. this.statsEl.parentNode.removeChild(this.statsEl);
  46032. },
  46033. tick: function () {
  46034. var stats = this.stats;
  46035. if (!stats) { return; }
  46036. stats('rAF').tick();
  46037. stats('FPS').frame();
  46038. stats().update();
  46039. },
  46040. hide: function () {
  46041. this.statsEl.classList.add(HIDDEN_CLASS);
  46042. },
  46043. show: function () {
  46044. this.statsEl.classList.remove(HIDDEN_CLASS);
  46045. }
  46046. });
  46047. function createStats (scene) {
  46048. var threeStats = new ThreeStats(scene.renderer);
  46049. var aframeStats = new AFrameStats(scene);
  46050. var plugins = scene.isMobile ? [] : [threeStats, aframeStats];
  46051. return new RStats({
  46052. css: [], // Our stylesheet is injected from `src/index.js`.
  46053. values: {
  46054. fps: {caption: 'fps', below: 30}
  46055. },
  46056. groups: [
  46057. {caption: 'Framerate', values: ['fps', 'raf']}
  46058. ],
  46059. plugins: plugins
  46060. });
  46061. }
  46062. },{"../../../vendor/rStats":205,"../../../vendor/rStats.extras":204,"../../core/component":126,"../../lib/rStatsAframe":173,"../../utils":197}],108:[function(_dereq_,module,exports){
  46063. var registerComponent = _dereq_('../../core/component').registerComponent;
  46064. var constants = _dereq_('../../constants/');
  46065. var utils = _dereq_('../../utils/');
  46066. var bind = utils.bind;
  46067. var ENTER_VR_CLASS = 'a-enter-vr';
  46068. var ENTER_VR_BTN_CLASS = 'a-enter-vr-button';
  46069. var HIDDEN_CLASS = 'a-hidden';
  46070. var ORIENTATION_MODAL_CLASS = 'a-orientation-modal';
  46071. /**
  46072. * UI for entering VR mode.
  46073. */
  46074. module.exports.Component = registerComponent('vr-mode-ui', {
  46075. dependencies: ['canvas'],
  46076. schema: {
  46077. enabled: {default: true}
  46078. },
  46079. init: function () {
  46080. var self = this;
  46081. var sceneEl = this.el;
  46082. if (utils.getUrlParameter('ui') === 'false') { return; }
  46083. this.enterVR = bind(sceneEl.enterVR, sceneEl);
  46084. this.exitVR = bind(sceneEl.exitVR, sceneEl);
  46085. this.insideLoader = false;
  46086. this.enterVREl = null;
  46087. this.orientationModalEl = null;
  46088. // Hide/show VR UI when entering/exiting VR mode.
  46089. sceneEl.addEventListener('enter-vr', bind(this.updateEnterVRInterface, this));
  46090. sceneEl.addEventListener('exit-vr', bind(this.updateEnterVRInterface, this));
  46091. window.addEventListener('message', function (event) {
  46092. if (event.data.type === 'loaderReady') {
  46093. self.insideLoader = true;
  46094. self.remove();
  46095. }
  46096. });
  46097. // Modal that tells the user to change orientation if in portrait.
  46098. window.addEventListener('orientationchange',
  46099. bind(this.toggleOrientationModalIfNeeded, this));
  46100. },
  46101. update: function () {
  46102. var sceneEl = this.el;
  46103. if (!this.data.enabled || this.insideLoader || utils.getUrlParameter('ui') === 'false') {
  46104. return this.remove();
  46105. }
  46106. if (this.enterVREl || this.orientationModalEl) { return; }
  46107. // Add UI if enabled and not already present.
  46108. this.enterVREl = createEnterVRButton(this.enterVR);
  46109. sceneEl.appendChild(this.enterVREl);
  46110. this.orientationModalEl = createOrientationModal(this.exitVR);
  46111. sceneEl.appendChild(this.orientationModalEl);
  46112. this.updateEnterVRInterface();
  46113. },
  46114. remove: function () {
  46115. [this.enterVREl, this.orientationModalEl].forEach(function (uiElement) {
  46116. if (uiElement) {
  46117. uiElement.parentNode.removeChild(uiElement);
  46118. }
  46119. });
  46120. },
  46121. updateEnterVRInterface: function () {
  46122. this.toggleEnterVRButtonIfNeeded();
  46123. this.toggleOrientationModalIfNeeded();
  46124. },
  46125. toggleEnterVRButtonIfNeeded: function () {
  46126. var sceneEl = this.el;
  46127. if (!this.enterVREl) { return; }
  46128. if (sceneEl.is('vr-mode')) {
  46129. this.enterVREl.classList.add(HIDDEN_CLASS);
  46130. } else {
  46131. this.enterVREl.classList.remove(HIDDEN_CLASS);
  46132. }
  46133. },
  46134. toggleOrientationModalIfNeeded: function () {
  46135. var sceneEl = this.el;
  46136. var orientationModalEl = this.orientationModalEl;
  46137. if (!orientationModalEl || !sceneEl.isMobile) { return; }
  46138. if (!utils.device.isLandscape() && sceneEl.is('vr-mode')) {
  46139. // Show if in VR mode on portrait.
  46140. orientationModalEl.classList.remove(HIDDEN_CLASS);
  46141. } else {
  46142. orientationModalEl.classList.add(HIDDEN_CLASS);
  46143. }
  46144. }
  46145. });
  46146. /**
  46147. * Creates a button that when clicked will enter into stereo-rendering mode for VR.
  46148. *
  46149. * Structure: <div><button></div>
  46150. *
  46151. * @param {function} enterVRHandler
  46152. * @returns {Element} Wrapper <div>.
  46153. */
  46154. function createEnterVRButton (enterVRHandler) {
  46155. var vrButton;
  46156. var wrapper;
  46157. // Create elements.
  46158. wrapper = document.createElement('div');
  46159. wrapper.classList.add(ENTER_VR_CLASS);
  46160. wrapper.setAttribute(constants.AFRAME_INJECTED, '');
  46161. vrButton = document.createElement('button');
  46162. vrButton.className = ENTER_VR_BTN_CLASS;
  46163. vrButton.setAttribute('title', 'Enter VR mode with a headset or fullscreen mode on a desktop. Visit https://webvr.rocks or https://webvr.info for more information.');
  46164. vrButton.setAttribute(constants.AFRAME_INJECTED, '');
  46165. // Insert elements.
  46166. wrapper.appendChild(vrButton);
  46167. vrButton.addEventListener('click', function (evt) {
  46168. enterVRHandler();
  46169. });
  46170. return wrapper;
  46171. }
  46172. /**
  46173. * Create a modal that tells mobile users to orient the phone to landscape.
  46174. * Add a close button that if clicked, exits VR and closes the modal.
  46175. */
  46176. function createOrientationModal (exitVRHandler) {
  46177. var modal = document.createElement('div');
  46178. modal.className = ORIENTATION_MODAL_CLASS;
  46179. modal.classList.add(HIDDEN_CLASS);
  46180. modal.setAttribute(constants.AFRAME_INJECTED, '');
  46181. var exit = document.createElement('button');
  46182. exit.setAttribute(constants.AFRAME_INJECTED, '');
  46183. exit.innerHTML = 'Exit VR';
  46184. // Exit VR on close.
  46185. exit.addEventListener('click', exitVRHandler);
  46186. modal.appendChild(exit);
  46187. return modal;
  46188. }
  46189. },{"../../constants/":117,"../../core/component":126,"../../utils/":197}],109:[function(_dereq_,module,exports){
  46190. var component = _dereq_('../core/component');
  46191. var THREE = _dereq_('../lib/three');
  46192. var bind = _dereq_('../utils/bind');
  46193. var registerComponent = component.registerComponent;
  46194. /**
  46195. * Shadow component.
  46196. *
  46197. * When applied to an entity, that entity's geometry and any descendants will cast or receive
  46198. * shadows as specified by the `cast` and `receive` properties.
  46199. */
  46200. module.exports.Component = registerComponent('shadow', {
  46201. schema: {
  46202. cast: {default: true},
  46203. receive: {default: true}
  46204. },
  46205. init: function () {
  46206. this.onMeshChanged = bind(this.update, this);
  46207. this.el.addEventListener('object3dset', this.onMeshChanged);
  46208. this.system.setShadowMapEnabled(true);
  46209. },
  46210. update: function () {
  46211. var data = this.data;
  46212. this.updateDescendants(data.cast, data.receive);
  46213. },
  46214. remove: function () {
  46215. var el = this.el;
  46216. el.removeEventListener('object3dset', this.onMeshChanged);
  46217. this.updateDescendants(false, false);
  46218. },
  46219. updateDescendants: function (cast, receive) {
  46220. var sceneEl = this.el.sceneEl;
  46221. this.el.object3D.traverse(function (node) {
  46222. if (!(node instanceof THREE.Mesh)) { return; }
  46223. node.castShadow = cast;
  46224. node.receiveShadow = receive;
  46225. // If scene has already rendered, materials must be updated.
  46226. if (sceneEl.hasLoaded && node.material) {
  46227. var materials = node.material.materials || [node.material];
  46228. for (var i = 0; i < materials.length; i++) {
  46229. materials[i].needsUpdate = true;
  46230. }
  46231. }
  46232. });
  46233. }
  46234. });
  46235. },{"../core/component":126,"../lib/three":174,"../utils/bind":191}],110:[function(_dereq_,module,exports){
  46236. var registerComponent = _dereq_('../core/component').registerComponent;
  46237. var debug = _dereq_('../utils/debug');
  46238. var bind = _dereq_('../utils/bind');
  46239. var THREE = _dereq_('../lib/three');
  46240. var warn = debug('components:sound:warn');
  46241. /**
  46242. * Sound component.
  46243. */
  46244. module.exports.Component = registerComponent('sound', {
  46245. schema: {
  46246. autoplay: {default: false},
  46247. distanceModel: {default: 'inverse',
  46248. oneOf: ['linear', 'inverse', 'exponential']},
  46249. loop: {default: false},
  46250. maxDistance: {default: 10000},
  46251. on: {default: ''},
  46252. poolSize: {default: 1},
  46253. positional: {default: true},
  46254. refDistance: {default: 1},
  46255. rolloffFactor: {default: 1},
  46256. src: {type: 'audio'},
  46257. volume: {default: 1}
  46258. },
  46259. multiple: true,
  46260. init: function () {
  46261. this.listener = null;
  46262. this.audioLoader = new THREE.AudioLoader();
  46263. this.pool = new THREE.Group();
  46264. this.loaded = false;
  46265. this.mustPlay = false;
  46266. this.playSound = bind(this.playSound, this);
  46267. },
  46268. update: function (oldData) {
  46269. var data = this.data;
  46270. var srcChanged = data.src !== oldData.src;
  46271. // Create new sound if not yet created or changing `src`.
  46272. if (srcChanged) {
  46273. if (!data.src) {
  46274. warn('Audio source was not specified with `src`');
  46275. return;
  46276. }
  46277. this.setupSound();
  46278. }
  46279. this.pool.children.forEach(function (sound) {
  46280. if (data.positional) {
  46281. sound.setDistanceModel(data.distanceModel);
  46282. sound.setMaxDistance(data.maxDistance);
  46283. sound.setRefDistance(data.refDistance);
  46284. sound.setRolloffFactor(data.rolloffFactor);
  46285. }
  46286. sound.setLoop(data.loop);
  46287. sound.setVolume(data.volume);
  46288. sound.isPaused = false;
  46289. });
  46290. if (data.on !== oldData.on) {
  46291. this.updateEventListener(oldData.on);
  46292. }
  46293. // All sound values set. Load in `src`.
  46294. if (srcChanged) {
  46295. var self = this;
  46296. this.loaded = false;
  46297. this.audioLoader.load(data.src, function (buffer) {
  46298. self.pool.children.forEach(function (sound) {
  46299. sound.setBuffer(buffer);
  46300. });
  46301. self.loaded = true;
  46302. // Remove this key from cache, otherwise we can't play it again
  46303. THREE.Cache.remove(data.src);
  46304. if (self.data.autoplay || self.mustPlay) { self.playSound(); }
  46305. self.el.emit('sound-loaded');
  46306. });
  46307. }
  46308. },
  46309. pause: function () {
  46310. this.stopSound();
  46311. this.removeEventListener();
  46312. },
  46313. play: function () {
  46314. if (this.data.autoplay) { this.playSound(); }
  46315. this.updateEventListener();
  46316. },
  46317. remove: function () {
  46318. this.removeEventListener();
  46319. this.el.removeObject3D(this.attrName);
  46320. try {
  46321. this.pool.children.forEach(function (sound) {
  46322. sound.disconnect();
  46323. });
  46324. } catch (e) {
  46325. // disconnect() will throw if it was never connected initially.
  46326. warn('Audio source not properly disconnected');
  46327. }
  46328. },
  46329. /**
  46330. * Update listener attached to the user defined on event.
  46331. */
  46332. updateEventListener: function (oldEvt) {
  46333. var el = this.el;
  46334. if (oldEvt) { el.removeEventListener(oldEvt, this.playSound); }
  46335. el.addEventListener(this.data.on, this.playSound);
  46336. },
  46337. removeEventListener: function () {
  46338. this.el.removeEventListener(this.data.on, this.playSound);
  46339. },
  46340. /**
  46341. * Removes current sound object, creates new sound object, adds to entity.
  46342. *
  46343. * @returns {object} sound
  46344. */
  46345. setupSound: function () {
  46346. var el = this.el;
  46347. var sceneEl = el.sceneEl;
  46348. if (this.pool.children.length > 0) {
  46349. this.stopSound();
  46350. el.removeObject3D('sound');
  46351. }
  46352. // Only want one AudioListener. Cache it on the scene.
  46353. var listener = this.listener = sceneEl.audioListener || new THREE.AudioListener();
  46354. sceneEl.audioListener = listener;
  46355. if (sceneEl.camera) {
  46356. sceneEl.camera.add(listener);
  46357. }
  46358. // Wait for camera if necessary.
  46359. sceneEl.addEventListener('camera-set-active', function (evt) {
  46360. evt.detail.cameraEl.getObject3D('camera').add(listener);
  46361. });
  46362. // Create [poolSize] audio instances and attach them to pool
  46363. this.pool = new THREE.Group();
  46364. for (var i = 0; i < this.data.poolSize; i++) {
  46365. var sound = this.data.positional ? new THREE.PositionalAudio(listener) : new THREE.Audio(listener);
  46366. this.pool.add(sound);
  46367. }
  46368. el.setObject3D(this.attrName, this.pool);
  46369. this.pool.children.forEach(function (sound) {
  46370. sound.onEnded = function () {
  46371. sound.isPlaying = false;
  46372. el.emit('sound-ended', {index: i});
  46373. };
  46374. });
  46375. },
  46376. /**
  46377. * Pause all the sounds in the pool.
  46378. */
  46379. pauseSound: function () {
  46380. this.isPlaying = false;
  46381. this.pool.children.forEach(function (sound) {
  46382. if (!sound.source || !sound.source.buffer || !sound.isPlaying || sound.isPaused) { return; }
  46383. sound.isPaused = true;
  46384. sound.pause();
  46385. });
  46386. },
  46387. /**
  46388. * Look for an unused sound in the pool and play it if found.
  46389. */
  46390. playSound: function () {
  46391. if (!this.loaded) {
  46392. warn('Sound not loaded yet. It will be played once it finished loading');
  46393. this.mustPlay = true;
  46394. return;
  46395. }
  46396. var found = false;
  46397. this.isPlaying = true;
  46398. this.pool.children.forEach(function (sound) {
  46399. if (!sound.isPlaying && sound.buffer && !found) {
  46400. sound.play();
  46401. sound.isPaused = false;
  46402. found = true;
  46403. return;
  46404. }
  46405. });
  46406. if (!found) {
  46407. warn('All the sounds are playing. If you need to play more sounds simultaneously ' +
  46408. 'consider increasing the size of pool with the `poolSize` attribute.', this.el);
  46409. return;
  46410. }
  46411. this.mustPlay = false;
  46412. },
  46413. /**
  46414. * Stop all the sounds in the pool.
  46415. */
  46416. stopSound: function () {
  46417. this.isPlaying = false;
  46418. this.pool.children.forEach(function (sound) {
  46419. if (!sound.source || !sound.source.buffer) { return; }
  46420. sound.stop();
  46421. });
  46422. }
  46423. });
  46424. },{"../core/component":126,"../lib/three":174,"../utils/bind":191,"../utils/debug":193}],111:[function(_dereq_,module,exports){
  46425. var createTextGeometry = _dereq_('three-bmfont-text');
  46426. var loadBMFont = _dereq_('load-bmfont');
  46427. var path = _dereq_('path');
  46428. var registerComponent = _dereq_('../core/component').registerComponent;
  46429. var coreShader = _dereq_('../core/shader');
  46430. var THREE = _dereq_('../lib/three');
  46431. var utils = _dereq_('../utils/');
  46432. var error = utils.debug('components:text:error');
  46433. var shaders = coreShader.shaders;
  46434. var warn = utils.debug('components:text:warn');
  46435. // 1 to match other A-Frame default widths.
  46436. var DEFAULT_WIDTH = 1;
  46437. // @bryik set anisotropy to 16. Improves look of large amounts of text when viewed from angle.
  46438. var MAX_ANISOTROPY = 16;
  46439. var FONT_BASE_URL = 'https://cdn.aframe.io/fonts/';
  46440. var FONTS = {
  46441. aileronsemibold: FONT_BASE_URL + 'Aileron-Semibold.fnt',
  46442. dejavu: FONT_BASE_URL + 'DejaVu-sdf.fnt',
  46443. exo2bold: FONT_BASE_URL + 'Exo2Bold.fnt',
  46444. exo2semibold: FONT_BASE_URL + 'Exo2SemiBold.fnt',
  46445. kelsonsans: FONT_BASE_URL + 'KelsonSans.fnt',
  46446. monoid: FONT_BASE_URL + 'Monoid.fnt',
  46447. mozillavr: FONT_BASE_URL + 'mozillavr.fnt',
  46448. roboto: FONT_BASE_URL + 'Roboto-msdf.json',
  46449. sourcecodepro: FONT_BASE_URL + 'SourceCodePro.fnt'
  46450. };
  46451. var MSDF_FONTS = ['roboto'];
  46452. var DEFAULT_FONT = 'roboto';
  46453. module.exports.FONTS = FONTS;
  46454. var cache = new PromiseCache();
  46455. var fontWidthFactors = {};
  46456. /**
  46457. * SDF-based text component.
  46458. * Based on https://github.com/Jam3/three-bmfont-text.
  46459. *
  46460. * All the stock fonts are for the `sdf` registered shader, an improved version of jam3's
  46461. * original `sdf` shader.
  46462. */
  46463. module.exports.Component = registerComponent('text', {
  46464. multiple: true,
  46465. schema: {
  46466. align: {type: 'string', default: 'left', oneOf: ['left', 'right', 'center']},
  46467. alphaTest: {default: 0.5},
  46468. // `anchor` defaults to center to match geometries.
  46469. anchor: {default: 'center', oneOf: ['left', 'right', 'center', 'align']},
  46470. baseline: {default: 'center', oneOf: ['top', 'center', 'bottom']},
  46471. color: {type: 'color', default: '#FFF'},
  46472. font: {type: 'string', default: DEFAULT_FONT},
  46473. // `fontImage` defaults to the font name as a .png (e.g., mozillavr.fnt -> mozillavr.png).
  46474. fontImage: {type: 'string'},
  46475. // `height` has no default, will be populated at layout.
  46476. height: {type: 'number'},
  46477. letterSpacing: {type: 'number', default: 0},
  46478. // `lineHeight` defaults to font's `lineHeight` value.
  46479. lineHeight: {type: 'number'},
  46480. opacity: {type: 'number', default: 1.0},
  46481. shader: {default: 'sdf', oneOf: shaders},
  46482. side: {default: 'front', oneOf: ['front', 'back', 'double']},
  46483. tabSize: {default: 4},
  46484. transparent: {default: true},
  46485. value: {type: 'string'},
  46486. whiteSpace: {default: 'normal', oneOf: ['normal', 'pre', 'nowrap']},
  46487. // `width` defaults to geometry width if present, else `DEFAULT_WIDTH`.
  46488. width: {type: 'number'},
  46489. // `wrapCount` units are about one default font character. Wrap roughly at this number.
  46490. wrapCount: {type: 'number', default: 40},
  46491. // `wrapPixels` will wrap using bmfont pixel units (e.g., dejavu's is 32 pixels).
  46492. wrapPixels: {type: 'number'},
  46493. // `yOffset` to adjust generated fonts from tools that may have incorrect metrics.
  46494. yOffset: {type: 'number', default: 0},
  46495. // `zOffset` will provide a small z offset to avoid z-fighting.
  46496. zOffset: {type: 'number', default: 0.001}
  46497. },
  46498. init: function () {
  46499. this.texture = new THREE.Texture();
  46500. this.texture.anisotropy = MAX_ANISOTROPY;
  46501. this.geometry = createTextGeometry();
  46502. this.createOrUpdateMaterial();
  46503. this.mesh = new THREE.Mesh(this.geometry, this.material);
  46504. this.el.setObject3D(this.attrName, this.mesh);
  46505. },
  46506. update: function (oldData) {
  46507. var data = coerceData(this.data);
  46508. var font = this.currentFont;
  46509. // Update material.
  46510. this.createOrUpdateMaterial();
  46511. // New font. `updateFont` will later change data and layout.
  46512. if (oldData.font !== data.font) {
  46513. this.updateFont();
  46514. return;
  46515. }
  46516. // Update geometry and layout.
  46517. if (font) {
  46518. this.updateGeometry(this.geometry, data, font);
  46519. this.updateLayout(data);
  46520. }
  46521. },
  46522. /**
  46523. * Clean up geometry, material, texture, mesh, objects.
  46524. */
  46525. remove: function () {
  46526. this.geometry.dispose();
  46527. this.geometry = null;
  46528. this.el.removeObject3D(this.attrName);
  46529. this.material.dispose();
  46530. this.material = null;
  46531. this.texture.dispose();
  46532. this.texture = null;
  46533. if (this.shaderObject) {
  46534. delete this.shaderObject;
  46535. }
  46536. },
  46537. /**
  46538. * Update the shader of the material.
  46539. */
  46540. createOrUpdateMaterial: function () {
  46541. var data = this.data;
  46542. var hasChangedShader;
  46543. var material = this.material;
  46544. var NewShader;
  46545. var shaderData;
  46546. var shaderName;
  46547. // Infer shader if using a stock font (or from `-msdf` filename convention).
  46548. shaderName = data.shader;
  46549. if (MSDF_FONTS.indexOf(data.font) !== -1 || data.font.indexOf('-msdf.') >= 0) {
  46550. shaderName = 'msdf';
  46551. } else if (data.font in FONTS && MSDF_FONTS.indexOf(data.font) === -1) {
  46552. shaderName = 'sdf';
  46553. }
  46554. hasChangedShader = (this.shaderObject && this.shaderObject.name) !== shaderName;
  46555. shaderData = {
  46556. alphaTest: data.alphaTest,
  46557. color: data.color,
  46558. map: this.texture,
  46559. opacity: data.opacity,
  46560. side: parseSide(data.side),
  46561. transparent: data.transparent
  46562. };
  46563. // Shader has not changed, do an update.
  46564. if (!hasChangedShader) {
  46565. // Update shader material.
  46566. this.shaderObject.update(shaderData);
  46567. // Apparently, was not set on `init` nor `update`.
  46568. material.transparent = shaderData.transparent;
  46569. updateBaseMaterial(material, shaderData);
  46570. return;
  46571. }
  46572. // Shader has changed. Create a shader material.
  46573. NewShader = createShader(this.el, shaderName, shaderData);
  46574. this.material = NewShader.material;
  46575. this.shaderObject = NewShader.shader;
  46576. // Set new shader material.
  46577. updateBaseMaterial(this.material, shaderData);
  46578. if (this.mesh) { this.mesh.material = this.material; }
  46579. },
  46580. /**
  46581. * Load font for geometry, load font image for material, and apply.
  46582. */
  46583. updateFont: function () {
  46584. var data = this.data;
  46585. var el = this.el;
  46586. var fontSrc;
  46587. var geometry = this.geometry;
  46588. var self = this;
  46589. if (!data.font) { warn('No font specified. Using the default font.'); }
  46590. // Make invisible during font swap.
  46591. this.mesh.visible = false;
  46592. // Look up font URL to use, and perform cached load.
  46593. fontSrc = this.lookupFont(data.font || DEFAULT_FONT) || data.font;
  46594. cache.get(fontSrc, function doLoadFont () {
  46595. return loadFont(fontSrc, data.yOffset);
  46596. }).then(function setFont (font) {
  46597. var coercedData;
  46598. var fontImgSrc;
  46599. if (font.pages.length !== 1) {
  46600. throw new Error('Currently only single-page bitmap fonts are supported.');
  46601. }
  46602. if (!fontWidthFactors[fontSrc]) {
  46603. font.widthFactor = fontWidthFactors[font] = computeFontWidthFactor(font);
  46604. }
  46605. // Update geometry given font metrics.
  46606. coercedData = coerceData(data);
  46607. self.updateGeometry(geometry, self.data, font);
  46608. // Set font and update layout.
  46609. self.currentFont = font;
  46610. self.updateLayout(coercedData);
  46611. // Look up font image URL to use, and perform cached load.
  46612. fontImgSrc = data.fontImage || fontSrc.replace(/(\.fnt)|(\.json)/, '.png') ||
  46613. path.dirname(data.font) + '/' + font.pages[0];
  46614. cache.get(fontImgSrc, function () {
  46615. return loadTexture(fontImgSrc);
  46616. }).then(function (image) {
  46617. // Make mesh visible and apply font image as texture.
  46618. self.mesh.visible = true;
  46619. self.texture.image = image;
  46620. self.texture.needsUpdate = true;
  46621. el.emit('textfontset', {font: data.font, fontObj: font});
  46622. }).catch(function (err) {
  46623. error(err);
  46624. throw err;
  46625. });
  46626. }).catch(function (err) {
  46627. error(err);
  46628. throw err;
  46629. });
  46630. },
  46631. /**
  46632. * Update layout with anchor, alignment, baseline, and considering any meshes.
  46633. */
  46634. updateLayout: function (data) {
  46635. var anchor;
  46636. var baseline;
  46637. var el = this.el;
  46638. var geometry = this.geometry;
  46639. var geometryComponent = el.getAttribute('geometry');
  46640. var height;
  46641. var layout = geometry.layout;
  46642. var mesh = this.mesh;
  46643. var textRenderWidth;
  46644. var textScale;
  46645. var width;
  46646. var x;
  46647. var y;
  46648. // Determine width to use (defined width, geometry's width, or default width).
  46649. geometryComponent = el.getAttribute('geometry');
  46650. width = data.width || (geometryComponent && geometryComponent.width) || DEFAULT_WIDTH;
  46651. // Determine wrap pixel count. Either specified or by experimental fudge factor.
  46652. // Note that experimental factor will never be correct for variable width fonts.
  46653. textRenderWidth = computeWidth(data.wrapPixels, data.wrapCount,
  46654. this.currentFont.widthFactor);
  46655. textScale = width / textRenderWidth;
  46656. // Determine height to use.
  46657. height = textScale * (layout.height + layout.descender);
  46658. // Update geometry dimensions to match text layout if width and height are set to 0.
  46659. // For example, scales a plane to fit text.
  46660. if (geometryComponent) {
  46661. if (!geometryComponent.width) { el.setAttribute('geometry', 'width', width); }
  46662. if (!geometryComponent.height) { el.setAttribute('geometry', 'height', height); }
  46663. }
  46664. // Calculate X position to anchor text left, center, or right.
  46665. anchor = data.anchor === 'align' ? data.align : data.anchor;
  46666. if (anchor === 'left') {
  46667. x = 0;
  46668. } else if (anchor === 'right') {
  46669. x = -1 * layout.width;
  46670. } else if (anchor === 'center') {
  46671. x = -1 * layout.width / 2;
  46672. } else {
  46673. throw new TypeError('Invalid text.anchor property value', anchor);
  46674. }
  46675. // Calculate Y position to anchor text top, center, or bottom.
  46676. baseline = data.baseline;
  46677. if (baseline === 'bottom') {
  46678. y = 0;
  46679. } else if (baseline === 'top') {
  46680. y = -1 * layout.height + layout.ascender;
  46681. } else if (baseline === 'center') {
  46682. y = -1 * layout.height / 2;
  46683. } else {
  46684. throw new TypeError('Invalid text.baseline property value', baseline);
  46685. }
  46686. // Position and scale mesh to apply layout.
  46687. mesh.position.x = x * textScale;
  46688. mesh.position.y = y * textScale;
  46689. // Place text slightly in front to avoid Z-fighting.
  46690. mesh.position.z = data.zOffset;
  46691. mesh.scale.set(textScale, -1 * textScale, textScale);
  46692. this.geometry.computeBoundingSphere();
  46693. },
  46694. /**
  46695. * Grab font from the constant.
  46696. * Set as a method for test stubbing purposes.
  46697. */
  46698. lookupFont: function (key) {
  46699. return FONTS[key];
  46700. },
  46701. /**
  46702. * Update the text geometry using `three-bmfont-text.update`.
  46703. */
  46704. updateGeometry: function (geometry, data, font) {
  46705. geometry.update(utils.extend({}, data, {
  46706. font: font,
  46707. width: computeWidth(data.wrapPixels, data.wrapCount, font.widthFactor),
  46708. text: data.value.replace(/\\n/g, '\n').replace(/\\t/g, '\t'),
  46709. lineHeight: data.lineHeight || font.common.lineHeight
  46710. }));
  46711. }
  46712. });
  46713. function parseSide (side) {
  46714. switch (side) {
  46715. case 'back': {
  46716. return THREE.BackSide;
  46717. }
  46718. case 'double': {
  46719. return THREE.DoubleSide;
  46720. }
  46721. default: {
  46722. return THREE.FrontSide;
  46723. }
  46724. }
  46725. }
  46726. /**
  46727. * Coerce some data to numbers.
  46728. * as they will be passed directly into text creation and update
  46729. */
  46730. function coerceData (data) {
  46731. data = utils.clone(data);
  46732. if (data.lineHeight !== undefined) {
  46733. data.lineHeight = parseFloat(data.lineHeight);
  46734. if (!isFinite(data.lineHeight)) { data.lineHeight = undefined; }
  46735. }
  46736. if (data.width !== undefined) {
  46737. data.width = parseFloat(data.width);
  46738. if (!isFinite(data.width)) { data.width = undefined; }
  46739. }
  46740. return data;
  46741. }
  46742. /**
  46743. * @returns {Promise}
  46744. */
  46745. function loadFont (src, yOffset) {
  46746. return new Promise(function (resolve, reject) {
  46747. loadBMFont(src, function (err, font) {
  46748. if (err) {
  46749. error('Error loading font', src);
  46750. reject(err);
  46751. return;
  46752. }
  46753. // Fix negative Y offsets for Roboto MSDF font from tool. Experimentally determined.
  46754. if (src.indexOf('/Roboto-msdf.json') >= 0) { yOffset = 30; }
  46755. if (yOffset) { font.chars.map(function doOffset (ch) { ch.yoffset += yOffset; }); }
  46756. resolve(font);
  46757. });
  46758. });
  46759. }
  46760. /**
  46761. * @returns {Promise}
  46762. */
  46763. function loadTexture (src) {
  46764. return new Promise(function (resolve, reject) {
  46765. new THREE.ImageLoader().load(src, function (image) {
  46766. resolve(image);
  46767. }, undefined, function () {
  46768. error('Error loading font image', src);
  46769. reject(null);
  46770. });
  46771. });
  46772. }
  46773. function createShader (el, shaderName, data) {
  46774. var shader;
  46775. var shaderObject;
  46776. // Set up Shader.
  46777. shaderObject = new shaders[shaderName].Shader();
  46778. shaderObject.el = el;
  46779. shaderObject.init(data);
  46780. shaderObject.update(data);
  46781. // Get material.
  46782. shader = shaderObject.material;
  46783. // Apparently, was not set on `init` nor `update`.
  46784. shader.transparent = data.transparent;
  46785. return {
  46786. material: shader,
  46787. shader: shaderObject
  46788. };
  46789. }
  46790. /**
  46791. * @todo Add more supported material properties (e.g., `visible`).
  46792. */
  46793. function updateBaseMaterial (material, data) {
  46794. material.side = data.side;
  46795. }
  46796. /**
  46797. * Determine wrap pixel count. Either specified or by experimental fudge factor.
  46798. * Note that experimental factor will never be correct for variable width fonts.
  46799. */
  46800. function computeWidth (wrapPixels, wrapCount, widthFactor) {
  46801. return wrapPixels || ((0.5 + wrapCount) * widthFactor);
  46802. }
  46803. /**
  46804. * Compute default font width factor to use.
  46805. */
  46806. function computeFontWidthFactor (font) {
  46807. var sum = 0;
  46808. var digitsum = 0;
  46809. var digits = 0;
  46810. font.chars.map(function (ch) {
  46811. sum += ch.xadvance;
  46812. if (ch.id >= 48 && ch.id <= 57) {
  46813. digits++;
  46814. digitsum += ch.xadvance;
  46815. }
  46816. });
  46817. return digits ? digitsum / digits : sum / font.chars.length;
  46818. }
  46819. /**
  46820. * Get or create a promise given a key and promise generator.
  46821. * @todo Move to a utility and use in other parts of A-Frame.
  46822. */
  46823. function PromiseCache () {
  46824. var cache = this.cache = {};
  46825. this.get = function (key, promiseGenerator) {
  46826. if (key in cache) {
  46827. return cache[key];
  46828. }
  46829. cache[key] = promiseGenerator();
  46830. return cache[key];
  46831. };
  46832. }
  46833. },{"../core/component":126,"../core/shader":135,"../lib/three":174,"../utils/":197,"load-bmfont":24,"path":32,"three-bmfont-text":38}],112:[function(_dereq_,module,exports){
  46834. var registerComponent = _dereq_('../core/component').registerComponent;
  46835. var THREE = _dereq_('../lib/three');
  46836. var DEFAULT_CAMERA_HEIGHT = _dereq_('../constants').DEFAULT_CAMERA_HEIGHT;
  46837. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  46838. // Vector from eyes to elbow (divided by user height).
  46839. var EYES_TO_ELBOW = {x: 0.175, y: -0.3, z: -0.03};
  46840. // Vector from eyes to elbow (divided by user height).
  46841. var FOREARM = {x: 0, y: 0, z: -0.175};
  46842. /**
  46843. * Tracked controls component.
  46844. * Wrap the gamepad API for pose and button states.
  46845. * Select the appropriate controller and apply pose to the entity.
  46846. * Observe button states and emit appropriate events.
  46847. *
  46848. * @property {number} controller - Index of controller in array returned by Gamepad API.
  46849. * @property {string} id - Selected controller among those returned by Gamepad API.
  46850. */
  46851. module.exports.Component = registerComponent('tracked-controls', {
  46852. schema: {
  46853. controller: {default: 0},
  46854. id: {type: 'string', default: ''},
  46855. idPrefix: {type: 'string', default: ''},
  46856. rotationOffset: {default: 0},
  46857. // Arm model parameters, to use when not 6DOF. (pose hasPosition false, no position)
  46858. armModel: {default: true},
  46859. headElement: {type: 'selector'}
  46860. },
  46861. init: function () {
  46862. this.axis = [0, 0, 0];
  46863. this.buttonStates = {};
  46864. this.dolly = new THREE.Object3D();
  46865. this.controllerEuler = new THREE.Euler();
  46866. this.controllerEuler.order = 'YXZ';
  46867. this.controllerPosition = new THREE.Vector3();
  46868. this.controllerQuaternion = new THREE.Quaternion();
  46869. this.deltaControllerPosition = new THREE.Vector3();
  46870. this.standingMatrix = new THREE.Matrix4();
  46871. this.previousControllerPosition = new THREE.Vector3();
  46872. this.updateGamepad();
  46873. },
  46874. tick: function (time, delta) {
  46875. var mesh = this.el.getObject3D('mesh');
  46876. // Update mesh animations.
  46877. if (mesh && mesh.update) { mesh.update(delta / 1000); }
  46878. this.updateGamepad();
  46879. this.updatePose();
  46880. this.updateButtons();
  46881. },
  46882. /**
  46883. * Return default user height to use for non-6DOF arm model.
  46884. */
  46885. defaultUserHeight: function () { return DEFAULT_CAMERA_HEIGHT; }, // default camera height (for cameras with zero)
  46886. /**
  46887. * Return head element to use for non-6DOF arm model.
  46888. */
  46889. getHeadElement: function () { return this.data.headElement || this.el.sceneEl.camera.el; },
  46890. /**
  46891. * Handle update to `id` or `idPrefix.
  46892. */
  46893. updateGamepad: function () {
  46894. var controllers = this.system.controllers;
  46895. var data = this.data;
  46896. var i;
  46897. var matchCount = 0;
  46898. // Hand IDs: 0 is right, 1 is left.
  46899. for (i = 0; i < controllers.length; i++) {
  46900. if ((data.idPrefix && controllers[i].id.indexOf(data.idPrefix) === 0) ||
  46901. (!data.idPrefix && controllers[i].id === data.id)) {
  46902. matchCount++;
  46903. if (matchCount - 1 === data.controller) {
  46904. this.controller = controllers[i];
  46905. return;
  46906. }
  46907. }
  46908. }
  46909. },
  46910. applyArmModel: function (controllerPosition) {
  46911. // Use controllerPosition and deltaControllerPosition to avoid creating yet more variables...
  46912. var controller = this.controller;
  46913. var pose = controller.pose;
  46914. var controllerQuaternion = this.controllerQuaternion;
  46915. var controllerEuler = this.controllerEuler;
  46916. var deltaControllerPosition = this.deltaControllerPosition;
  46917. var hand = (controller ? controller.hand : undefined) || DEFAULT_HANDEDNESS;
  46918. var headEl = this.getHeadElement();
  46919. var headObject3D = headEl.object3D;
  46920. var headCamera = headEl.components.camera;
  46921. var userHeight = (headCamera ? headCamera.data.userHeight : 0) || this.defaultUserHeight();
  46922. // Use camera position as head position.
  46923. controllerPosition.copy(headObject3D.position);
  46924. // Set offset for degenerate "arm model" to elbow.
  46925. deltaControllerPosition.set(
  46926. EYES_TO_ELBOW.x * (hand === 'left' ? -1 : hand === 'right' ? 1 : 0),
  46927. EYES_TO_ELBOW.y, // lower than your eyes
  46928. EYES_TO_ELBOW.z); // slightly out in front
  46929. // Scale offset by user height.
  46930. deltaControllerPosition.multiplyScalar(userHeight);
  46931. // Apply camera Y rotation (not X or Z, so you can look down at your hand).
  46932. deltaControllerPosition.applyAxisAngle(headObject3D.up, headObject3D.rotation.y);
  46933. // Apply rotated offset to position.
  46934. controllerPosition.add(deltaControllerPosition);
  46935. // Set offset for degenerate "arm model" forearm.
  46936. deltaControllerPosition.set(FOREARM.x, FOREARM.y, FOREARM.z); // forearm sticking out from elbow
  46937. // Scale offset by user height.
  46938. deltaControllerPosition.multiplyScalar(userHeight);
  46939. // Apply controller X and Y rotation (tilting up/down/left/right is usually moving the arm)
  46940. if (pose.orientation) {
  46941. controllerQuaternion.fromArray(pose.orientation);
  46942. } else {
  46943. controllerQuaternion.copy(headObject3D.quaternion);
  46944. }
  46945. controllerEuler.setFromQuaternion(controllerQuaternion);
  46946. controllerEuler.set(controllerEuler.x, controllerEuler.y, 0);
  46947. deltaControllerPosition.applyEuler(controllerEuler);
  46948. // Apply rotated offset to position.
  46949. controllerPosition.add(deltaControllerPosition);
  46950. },
  46951. /**
  46952. * Read pose from controller (from Gamepad API), apply transforms, apply to entity.
  46953. */
  46954. updatePose: function () {
  46955. var controller = this.controller;
  46956. var controllerEuler = this.controllerEuler;
  46957. var controllerPosition = this.controllerPosition;
  46958. var currentPosition;
  46959. var deltaControllerPosition = this.deltaControllerPosition;
  46960. var dolly = this.dolly;
  46961. var el = this.el;
  46962. var pose;
  46963. var standingMatrix = this.standingMatrix;
  46964. var vrDisplay = this.system.vrDisplay;
  46965. var headEl = this.getHeadElement();
  46966. var headObject3D = headEl.object3D;
  46967. var headCamera = headEl.components.camera;
  46968. var userHeight = (headCamera ? headCamera.data.userHeight : 0) || this.defaultUserHeight();
  46969. if (!controller) { return; }
  46970. // Compose pose from Gamepad.
  46971. pose = controller.pose;
  46972. // If no orientation, use camera.
  46973. if (pose.orientation) {
  46974. dolly.quaternion.fromArray(pose.orientation);
  46975. } else {
  46976. dolly.quaternion.copy(headObject3D.quaternion);
  46977. }
  46978. if (pose.position) {
  46979. dolly.position.fromArray(pose.position);
  46980. } else {
  46981. if (this.data.armModel) {
  46982. // The controller is not 6DOF, so apply arm model.
  46983. this.applyArmModel(controllerPosition);
  46984. }
  46985. dolly.position.copy(controllerPosition);
  46986. }
  46987. dolly.updateMatrix();
  46988. // Apply transforms, if 6DOF and in VR.
  46989. if (pose.position && vrDisplay) {
  46990. if (vrDisplay.stageParameters) {
  46991. standingMatrix.fromArray(vrDisplay.stageParameters.sittingToStandingTransform);
  46992. dolly.applyMatrix(standingMatrix);
  46993. } else {
  46994. // Apply default camera height
  46995. dolly.position.y += userHeight;
  46996. dolly.updateMatrix();
  46997. }
  46998. }
  46999. // Decompose.
  47000. controllerEuler.setFromRotationMatrix(dolly.matrix);
  47001. controllerPosition.setFromMatrixPosition(dolly.matrix);
  47002. // Apply rotation (as absolute, with rotation offset).
  47003. el.setAttribute('rotation', {
  47004. x: THREE.Math.radToDeg(controllerEuler.x),
  47005. y: THREE.Math.radToDeg(controllerEuler.y),
  47006. z: THREE.Math.radToDeg(controllerEuler.z) + this.data.rotationOffset
  47007. });
  47008. // Apply position (as delta from previous Gamepad position).
  47009. deltaControllerPosition.copy(controllerPosition).sub(this.previousControllerPosition);
  47010. this.previousControllerPosition.copy(controllerPosition);
  47011. currentPosition = el.getAttribute('position');
  47012. el.setAttribute('position', {
  47013. x: currentPosition.x + deltaControllerPosition.x,
  47014. y: currentPosition.y + deltaControllerPosition.y,
  47015. z: currentPosition.z + deltaControllerPosition.z
  47016. });
  47017. },
  47018. /**
  47019. * Handle button changes including axes, presses, touches, values.
  47020. */
  47021. updateButtons: function () {
  47022. var buttonState;
  47023. var controller = this.controller;
  47024. var id;
  47025. if (!controller) { return; }
  47026. // Check every button.
  47027. for (id = 0; id < controller.buttons.length; ++id) {
  47028. // Initialize button state.
  47029. if (!this.buttonStates[id]) {
  47030. this.buttonStates[id] = {pressed: false, touched: false, value: 0};
  47031. }
  47032. buttonState = controller.buttons[id];
  47033. this.handleButton(id, buttonState);
  47034. }
  47035. // Check axes.
  47036. this.handleAxes();
  47037. },
  47038. /**
  47039. * Handle presses and touches for a single button.
  47040. *
  47041. * @param {number} id - Index of button in Gamepad button array.
  47042. * @param {number} buttonState - Value of button state from 0 to 1.
  47043. * @returns {boolean} Whether button has changed in any way.
  47044. */
  47045. handleButton: function (id, buttonState) {
  47046. var changed = this.handlePress(id, buttonState) ||
  47047. this.handleTouch(id, buttonState) ||
  47048. this.handleValue(id, buttonState);
  47049. if (!changed) { return false; }
  47050. this.el.emit('buttonchanged', {id: id, state: buttonState});
  47051. return true;
  47052. },
  47053. /**
  47054. * An axis is an array of values from -1 (up, left) to 1 (down, right).
  47055. * Compare each component of the axis to the previous value to determine change.
  47056. *
  47057. * @returns {boolean} Whether axes changed.
  47058. */
  47059. handleAxes: function () {
  47060. var changed = false;
  47061. var controllerAxes = this.controller.axes;
  47062. var i;
  47063. var previousAxis = this.axis;
  47064. var changedAxes = [];
  47065. // Check if axis changed.
  47066. for (i = 0; i < controllerAxes.length; ++i) {
  47067. changedAxes.push(previousAxis[i] !== controllerAxes[i]);
  47068. if (changedAxes[i]) { changed = true; }
  47069. }
  47070. if (!changed) { return false; }
  47071. this.axis = controllerAxes.slice();
  47072. this.el.emit('axismove', {axis: this.axis, changed: changedAxes});
  47073. return true;
  47074. },
  47075. /**
  47076. * Determine whether a button press has occured and emit events as appropriate.
  47077. *
  47078. * @param {string} id - ID of the button to check.
  47079. * @param {object} buttonState - State of the button to check.
  47080. * @returns {boolean} Whether button press state changed.
  47081. */
  47082. handlePress: function (id, buttonState) {
  47083. var evtName;
  47084. var previousButtonState = this.buttonStates[id];
  47085. // Not changed.
  47086. if (buttonState.pressed === previousButtonState.pressed) { return false; }
  47087. evtName = buttonState.pressed ? 'down' : 'up';
  47088. this.el.emit('button' + evtName, {id: id, state: buttonState});
  47089. previousButtonState.pressed = buttonState.pressed;
  47090. return true;
  47091. },
  47092. /**
  47093. * Determine whether a button touch has occured and emit events as appropriate.
  47094. *
  47095. * @param {string} id - ID of the button to check.
  47096. * @param {object} buttonState - State of the button to check.
  47097. * @returns {boolean} Whether button touch state changed.
  47098. */
  47099. handleTouch: function (id, buttonState) {
  47100. var evtName;
  47101. var previousButtonState = this.buttonStates[id];
  47102. // Not changed.
  47103. if (buttonState.touched === previousButtonState.touched) { return false; }
  47104. evtName = buttonState.touched ? 'start' : 'end';
  47105. // Due to unfortunate name collision, add empty touches array to avoid Daydream error.
  47106. this.el.emit('touch' + evtName, {id: id, state: buttonState}, true, {touches: []});
  47107. previousButtonState.touched = buttonState.touched;
  47108. return true;
  47109. },
  47110. /**
  47111. * Determine whether a button value has changed.
  47112. *
  47113. * @param {string} id - Id of the button to check.
  47114. * @param {object} buttonState - State of the button to check.
  47115. * @returns {boolean} Whether button value changed.
  47116. */
  47117. handleValue: function (id, buttonState) {
  47118. var previousButtonState = this.buttonStates[id];
  47119. // Not changed.
  47120. if (buttonState.value === previousButtonState.value) { return false; }
  47121. previousButtonState.value = buttonState.value;
  47122. return true;
  47123. }
  47124. });
  47125. },{"../constants":117,"../core/component":126,"../lib/three":174}],113:[function(_dereq_,module,exports){
  47126. var registerComponent = _dereq_('../core/component').registerComponent;
  47127. /**
  47128. * Visibility component.
  47129. */
  47130. module.exports.Component = registerComponent('visible', {
  47131. schema: {default: true},
  47132. update: function () {
  47133. this.el.object3D.visible = this.data;
  47134. }
  47135. });
  47136. },{"../core/component":126}],114:[function(_dereq_,module,exports){
  47137. var registerComponent = _dereq_('../core/component').registerComponent;
  47138. var utils = _dereq_('../utils/');
  47139. var bind = utils.bind;
  47140. var checkControllerPresentAndSetup = utils.trackedControls.checkControllerPresentAndSetup;
  47141. var emitIfAxesChanged = utils.trackedControls.emitIfAxesChanged;
  47142. var VIVE_CONTROLLER_MODEL_OBJ_URL = 'https://cdn.aframe.io/controllers/vive/vr_controller_vive.obj';
  47143. var VIVE_CONTROLLER_MODEL_OBJ_MTL = 'https://cdn.aframe.io/controllers/vive/vr_controller_vive.mtl';
  47144. var GAMEPAD_ID_PREFIX = 'OpenVR ';
  47145. /**
  47146. * Vive controls.
  47147. * Interface with Vive controllers and map Gamepad events to controller buttons:
  47148. * trackpad, trigger, grip, menu, system
  47149. * Load a controller model and highlight the pressed buttons.
  47150. */
  47151. module.exports.Component = registerComponent('vive-controls', {
  47152. schema: {
  47153. hand: {default: 'left'},
  47154. buttonColor: {type: 'color', default: '#FAFAFA'}, // Off-white.
  47155. buttonHighlightColor: {type: 'color', default: '#22D1EE'}, // Light blue.
  47156. model: {default: true},
  47157. rotationOffset: {default: 0}
  47158. },
  47159. /**
  47160. * Button IDs:
  47161. * 0 - trackpad
  47162. * 1 - trigger (intensity value from 0.5 to 1)
  47163. * 2 - grip
  47164. * 3 - menu (dispatch but better for menu options)
  47165. * 4 - system (never dispatched on this layer)
  47166. */
  47167. mapping: {
  47168. axes: {'trackpad': [0, 1]},
  47169. buttons: ['trackpad', 'trigger', 'grip', 'menu', 'system']
  47170. },
  47171. /**
  47172. * Labels for detail on axis events such as `thumbstickmoved`.
  47173. * For example, on `thumbstickmoved` detail, the first axis returned is labeled x, and the
  47174. * second is labeled y.
  47175. */
  47176. axisLabels: ['x', 'y', 'z', 'w'],
  47177. init: function () {
  47178. var self = this;
  47179. this.animationActive = 'pointing';
  47180. this.checkControllerPresentAndSetup = checkControllerPresentAndSetup; // To allow mock.
  47181. this.controllerPresent = false;
  47182. this.emitIfAxesChanged = emitIfAxesChanged; // To allow mock.
  47183. this.lastControllerCheck = 0;
  47184. this.onButtonChanged = bind(this.onButtonChanged, this);
  47185. this.onButtonDown = function (evt) { self.onButtonEvent(evt.detail.id, 'down'); };
  47186. this.onButtonUp = function (evt) { self.onButtonEvent(evt.detail.id, 'up'); };
  47187. this.onButtonTouchEnd = function (evt) { self.onButtonEvent(evt.detail.id, 'touchend'); };
  47188. this.onButtonTouchStart = function (evt) { self.onButtonEvent(evt.detail.id, 'touchstart'); };
  47189. this.onAxisMoved = bind(this.onAxisMoved, this);
  47190. this.previousButtonValues = {};
  47191. this.bindMethods();
  47192. },
  47193. play: function () {
  47194. this.checkIfControllerPresent();
  47195. this.addControllersUpdateListener();
  47196. // Note that due to gamepadconnected event propagation issues, we don't rely on events.
  47197. window.addEventListener('gamepaddisconnected', this.checkIfControllerPresent, false);
  47198. },
  47199. pause: function () {
  47200. this.removeEventListeners();
  47201. this.removeControllersUpdateListener();
  47202. // Note that due to gamepadconnected event propagation issues, we don't rely on events.
  47203. window.removeEventListener('gamepaddisconnected', this.checkIfControllerPresent, false);
  47204. },
  47205. bindMethods: function () {
  47206. this.onModelLoaded = bind(this.onModelLoaded, this);
  47207. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  47208. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  47209. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  47210. this.onAxisMoved = bind(this.onAxisMoved, this);
  47211. },
  47212. addEventListeners: function () {
  47213. var el = this.el;
  47214. el.addEventListener('buttonchanged', this.onButtonChanged);
  47215. el.addEventListener('buttondown', this.onButtonDown);
  47216. el.addEventListener('buttonup', this.onButtonUp);
  47217. el.addEventListener('touchend', this.onButtonTouchEnd);
  47218. el.addEventListener('touchstart', this.onButtonTouchStart);
  47219. el.addEventListener('model-loaded', this.onModelLoaded);
  47220. el.addEventListener('axismove', this.onAxisMoved);
  47221. this.controllerEventsActive = true;
  47222. },
  47223. removeEventListeners: function () {
  47224. var el = this.el;
  47225. el.removeEventListener('buttonchanged', this.onButtonChanged);
  47226. el.removeEventListener('buttondown', this.onButtonDown);
  47227. el.removeEventListener('buttonup', this.onButtonUp);
  47228. el.removeEventListener('touchend', this.onButtonTouchEnd);
  47229. el.removeEventListener('touchstart', this.onButtonTouchStart);
  47230. el.removeEventListener('model-loaded', this.onModelLoaded);
  47231. el.removeEventListener('axismove', this.onAxisMoved);
  47232. this.controllerEventsActive = false;
  47233. },
  47234. /**
  47235. * Once OpenVR returns correct hand data in supporting browsers, we can use hand property.
  47236. * var isPresent = this.checkControllerPresentAndSetup(this.el.sceneEl, GAMEPAD_ID_PREFIX,
  47237. { hand: data.hand });
  47238. * Until then, use hardcoded index.
  47239. */
  47240. checkIfControllerPresent: function () {
  47241. var data = this.data;
  47242. var controllerIndex = data.hand === 'right' ? 0 : data.hand === 'left' ? 1 : 2;
  47243. this.checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {index: controllerIndex});
  47244. },
  47245. injectTrackedControls: function () {
  47246. var el = this.el;
  47247. var data = this.data;
  47248. // If we have an OpenVR Gamepad, use the fixed mapping.
  47249. el.setAttribute('tracked-controls', {
  47250. idPrefix: GAMEPAD_ID_PREFIX,
  47251. // Hand IDs: 0 = right, 1 = left, 2 = anything else.
  47252. controller: data.hand === 'right' ? 0 : data.hand === 'left' ? 1 : 2,
  47253. rotationOffset: data.rotationOffset
  47254. });
  47255. // Load model.
  47256. if (!this.data.model) { return; }
  47257. this.el.setAttribute('obj-model', {
  47258. obj: VIVE_CONTROLLER_MODEL_OBJ_URL,
  47259. mtl: VIVE_CONTROLLER_MODEL_OBJ_MTL
  47260. });
  47261. },
  47262. addControllersUpdateListener: function () {
  47263. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  47264. },
  47265. removeControllersUpdateListener: function () {
  47266. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  47267. },
  47268. onControllersUpdate: function () {
  47269. this.checkIfControllerPresent();
  47270. },
  47271. /**
  47272. * Rotate the trigger button based on how hard the trigger is pressed.
  47273. */
  47274. onButtonChanged: function (evt) {
  47275. var button = this.mapping.buttons[evt.detail.id];
  47276. var buttonMeshes = this.buttonMeshes;
  47277. var analogValue;
  47278. if (!button) { return; }
  47279. if (button === 'trigger') {
  47280. analogValue = evt.detail.state.value;
  47281. // Update trigger rotation depending on button value.
  47282. if (buttonMeshes && buttonMeshes.trigger) {
  47283. buttonMeshes.trigger.rotation.x = -analogValue * (Math.PI / 12);
  47284. }
  47285. }
  47286. // Pass along changed event with button state, using button mapping for convenience.
  47287. this.el.emit(button + 'changed', evt.detail.state);
  47288. },
  47289. onModelLoaded: function (evt) {
  47290. var buttonMeshes;
  47291. var controllerObject3D = evt.detail.model;
  47292. var self = this;
  47293. if (!this.data.model) { return; }
  47294. // Store button meshes object to be able to change their colors.
  47295. buttonMeshes = this.buttonMeshes = {};
  47296. buttonMeshes.grip = {
  47297. left: controllerObject3D.getObjectByName('leftgrip'),
  47298. right: controllerObject3D.getObjectByName('rightgrip')
  47299. };
  47300. buttonMeshes.menu = controllerObject3D.getObjectByName('menubutton');
  47301. buttonMeshes.system = controllerObject3D.getObjectByName('systembutton');
  47302. buttonMeshes.trackpad = controllerObject3D.getObjectByName('touchpad');
  47303. buttonMeshes.trigger = controllerObject3D.getObjectByName('trigger');
  47304. // Set default colors.
  47305. Object.keys(buttonMeshes).forEach(function (buttonName) {
  47306. self.setButtonColor(buttonName, self.data.buttonColor);
  47307. });
  47308. // Offset pivot point.
  47309. controllerObject3D.position.set(0, -0.015, 0.04);
  47310. },
  47311. onAxisMoved: function (evt) {
  47312. this.emitIfAxesChanged(this, this.mapping.axes, evt);
  47313. },
  47314. onButtonEvent: function (id, evtName) {
  47315. var buttonName = this.mapping.buttons[id];
  47316. var color;
  47317. var i;
  47318. var isTouch = evtName.indexOf('touch') !== -1;
  47319. // Emit events.
  47320. if (Array.isArray(buttonName)) {
  47321. for (i = 0; i < buttonName.length; i++) {
  47322. this.el.emit(buttonName[i] + evtName);
  47323. }
  47324. } else {
  47325. this.el.emit(buttonName + evtName);
  47326. }
  47327. if (!this.data.model) { return; }
  47328. // Don't change color for trackpad touch.
  47329. if (isTouch) { return; }
  47330. // Update colors.
  47331. color = evtName === 'up' ? this.data.buttonColor : this.data.buttonHighlightColor;
  47332. if (Array.isArray(buttonName)) {
  47333. for (i = 0; i < buttonName.length; i++) {
  47334. this.setButtonColor(buttonName[i], color);
  47335. }
  47336. } else {
  47337. this.setButtonColor(buttonName, color);
  47338. }
  47339. },
  47340. setButtonColor: function (buttonName, color) {
  47341. var buttonMeshes = this.buttonMeshes;
  47342. if (!buttonMeshes) { return; }
  47343. // Need to do both left and right sides for grip.
  47344. if (buttonName === 'grip') {
  47345. buttonMeshes.grip.left.material.color.set(color);
  47346. buttonMeshes.grip.right.material.color.set(color);
  47347. return;
  47348. }
  47349. buttonMeshes[buttonName].material.color.set(color);
  47350. }
  47351. });
  47352. },{"../core/component":126,"../utils/":197}],115:[function(_dereq_,module,exports){
  47353. var KEYCODE_TO_CODE = _dereq_('../constants').keyboardevent.KEYCODE_TO_CODE;
  47354. var registerComponent = _dereq_('../core/component').registerComponent;
  47355. var THREE = _dereq_('../lib/three');
  47356. var utils = _dereq_('../utils/');
  47357. var bind = utils.bind;
  47358. var shouldCaptureKeyEvent = utils.shouldCaptureKeyEvent;
  47359. var CLAMP_VELOCITY = 0.00001;
  47360. var MAX_DELTA = 0.2;
  47361. /**
  47362. * WASD component to control entities using WASD keys.
  47363. */
  47364. module.exports.Component = registerComponent('wasd-controls', {
  47365. schema: {
  47366. acceleration: {default: 65},
  47367. adAxis: {default: 'x', oneOf: ['x', 'y', 'z']},
  47368. adEnabled: {default: true},
  47369. adInverted: {default: false},
  47370. easing: {default: 20},
  47371. enabled: {default: true},
  47372. fly: {default: false},
  47373. wsAxis: {default: 'z', oneOf: ['x', 'y', 'z']},
  47374. wsEnabled: {default: true},
  47375. wsInverted: {default: false}
  47376. },
  47377. init: function () {
  47378. // To keep track of the pressed keys.
  47379. this.keys = {};
  47380. this.velocity = new THREE.Vector3();
  47381. // Bind methods and add event listeners.
  47382. this.onBlur = bind(this.onBlur, this);
  47383. this.onFocus = bind(this.onFocus, this);
  47384. this.onKeyDown = bind(this.onKeyDown, this);
  47385. this.onKeyUp = bind(this.onKeyUp, this);
  47386. this.onVisibilityChange = bind(this.onVisibilityChange, this);
  47387. this.attachVisibilityEventListeners();
  47388. },
  47389. tick: function (time, delta) {
  47390. var data = this.data;
  47391. var el = this.el;
  47392. var movementVector;
  47393. var position;
  47394. var velocity = this.velocity;
  47395. // Use seconds.
  47396. delta = delta / 1000;
  47397. // Get velocity.
  47398. this.updateVelocity(delta);
  47399. if (!velocity[data.adAxis] && !velocity[data.wsAxis]) { return; }
  47400. // Get movement vector and translate position.
  47401. movementVector = this.getMovementVector(delta);
  47402. position = el.getAttribute('position');
  47403. el.setAttribute('position', {
  47404. x: position.x + movementVector.x,
  47405. y: position.y + movementVector.y,
  47406. z: position.z + movementVector.z
  47407. });
  47408. },
  47409. remove: function () {
  47410. this.removeKeyEventListeners();
  47411. this.removeVisibilityEventListeners();
  47412. },
  47413. play: function () {
  47414. this.attachKeyEventListeners();
  47415. },
  47416. pause: function () {
  47417. this.keys = {};
  47418. this.removeKeyEventListeners();
  47419. },
  47420. updateVelocity: function (delta) {
  47421. var acceleration;
  47422. var adAxis;
  47423. var adSign;
  47424. var data = this.data;
  47425. var keys = this.keys;
  47426. var velocity = this.velocity;
  47427. var wsAxis;
  47428. var wsSign;
  47429. adAxis = data.adAxis;
  47430. wsAxis = data.wsAxis;
  47431. // If FPS too low, reset velocity.
  47432. if (delta > MAX_DELTA) {
  47433. velocity[adAxis] = 0;
  47434. velocity[wsAxis] = 0;
  47435. return;
  47436. }
  47437. // Decay velocity.
  47438. if (velocity[adAxis] !== 0) {
  47439. velocity[adAxis] -= velocity[adAxis] * data.easing * delta;
  47440. }
  47441. if (velocity[wsAxis] !== 0) {
  47442. velocity[wsAxis] -= velocity[wsAxis] * data.easing * delta;
  47443. }
  47444. // Clamp velocity easing.
  47445. if (Math.abs(velocity[adAxis]) < CLAMP_VELOCITY) { velocity[adAxis] = 0; }
  47446. if (Math.abs(velocity[wsAxis]) < CLAMP_VELOCITY) { velocity[wsAxis] = 0; }
  47447. if (!data.enabled) { return; }
  47448. // Update velocity using keys pressed.
  47449. acceleration = data.acceleration;
  47450. if (data.adEnabled) {
  47451. adSign = data.adInverted ? -1 : 1;
  47452. if (keys.KeyA || keys.ArrowLeft) { velocity[adAxis] -= adSign * acceleration * delta; }
  47453. if (keys.KeyD || keys.ArrowRight) { velocity[adAxis] += adSign * acceleration * delta; }
  47454. }
  47455. if (data.wsEnabled) {
  47456. wsSign = data.wsInverted ? -1 : 1;
  47457. if (keys.KeyW || keys.ArrowUp) { velocity[wsAxis] -= wsSign * acceleration * delta; }
  47458. if (keys.KeyS || keys.ArrowDown) { velocity[wsAxis] += wsSign * acceleration * delta; }
  47459. }
  47460. },
  47461. getMovementVector: (function () {
  47462. var directionVector = new THREE.Vector3(0, 0, 0);
  47463. var rotationEuler = new THREE.Euler(0, 0, 0, 'YXZ');
  47464. return function (delta) {
  47465. var rotation = this.el.getAttribute('rotation');
  47466. var velocity = this.velocity;
  47467. var xRotation;
  47468. directionVector.copy(velocity);
  47469. directionVector.multiplyScalar(delta);
  47470. // Absolute.
  47471. if (!rotation) { return directionVector; }
  47472. xRotation = this.data.fly ? rotation.x : 0;
  47473. // Transform direction relative to heading.
  47474. rotationEuler.set(THREE.Math.degToRad(xRotation), THREE.Math.degToRad(rotation.y), 0);
  47475. directionVector.applyEuler(rotationEuler);
  47476. return directionVector;
  47477. };
  47478. })(),
  47479. attachVisibilityEventListeners: function () {
  47480. window.addEventListener('blur', this.onBlur);
  47481. window.addEventListener('focus', this.onFocus);
  47482. document.addEventListener('visibilitychange', this.onVisibilityChange);
  47483. },
  47484. removeVisibilityEventListeners: function () {
  47485. window.removeEventListener('blur', this.onBlur);
  47486. window.removeEventListener('focus', this.onFocus);
  47487. document.removeEventListener('visibilitychange', this.onVisibilityChange);
  47488. },
  47489. attachKeyEventListeners: function () {
  47490. window.addEventListener('keydown', this.onKeyDown);
  47491. window.addEventListener('keyup', this.onKeyUp);
  47492. },
  47493. removeKeyEventListeners: function () {
  47494. window.removeEventListener('keydown', this.onKeyDown);
  47495. window.removeEventListener('keyup', this.onKeyUp);
  47496. },
  47497. onBlur: function () {
  47498. this.pause();
  47499. },
  47500. onFocus: function () {
  47501. this.play();
  47502. },
  47503. onVisibilityChange: function () {
  47504. if (document.hidden) {
  47505. this.onBlur();
  47506. } else {
  47507. this.onFocus();
  47508. }
  47509. },
  47510. onKeyDown: function (event) {
  47511. var code;
  47512. if (!shouldCaptureKeyEvent(event)) { return; }
  47513. code = event.code || KEYCODE_TO_CODE[event.keyCode];
  47514. this.keys[code] = true;
  47515. },
  47516. onKeyUp: function (event) {
  47517. var code;
  47518. code = event.code || KEYCODE_TO_CODE[event.keyCode];
  47519. this.keys[code] = false;
  47520. }
  47521. });
  47522. },{"../constants":117,"../core/component":126,"../lib/three":174,"../utils/":197}],116:[function(_dereq_,module,exports){
  47523. /**
  47524. * Animation configuration options for TWEEN.js animations.
  47525. * Used by `<a-animation>`.
  47526. */
  47527. var TWEEN = _dereq_('@tweenjs/tween.js');
  47528. var DIRECTIONS = {
  47529. alternate: 'alternate',
  47530. alternateReverse: 'alternate-reverse',
  47531. normal: 'normal',
  47532. reverse: 'reverse'
  47533. };
  47534. var EASING_FUNCTIONS = {
  47535. 'linear': TWEEN.Easing.Linear.None,
  47536. 'ease': TWEEN.Easing.Cubic.InOut,
  47537. 'ease-in': TWEEN.Easing.Cubic.In,
  47538. 'ease-out': TWEEN.Easing.Cubic.Out,
  47539. 'ease-in-out': TWEEN.Easing.Cubic.InOut,
  47540. 'ease-cubic': TWEEN.Easing.Cubic.In,
  47541. 'ease-in-cubic': TWEEN.Easing.Cubic.In,
  47542. 'ease-out-cubic': TWEEN.Easing.Cubic.Out,
  47543. 'ease-in-out-cubic': TWEEN.Easing.Cubic.InOut,
  47544. 'ease-quad': TWEEN.Easing.Quadratic.InOut,
  47545. 'ease-in-quad': TWEEN.Easing.Quadratic.In,
  47546. 'ease-out-quad': TWEEN.Easing.Quadratic.Out,
  47547. 'ease-in-out-quad': TWEEN.Easing.Quadratic.InOut,
  47548. 'ease-quart': TWEEN.Easing.Quartic.InOut,
  47549. 'ease-in-quart': TWEEN.Easing.Quartic.In,
  47550. 'ease-out-quart': TWEEN.Easing.Quartic.Out,
  47551. 'ease-in-out-quart': TWEEN.Easing.Quartic.InOut,
  47552. 'ease-quint': TWEEN.Easing.Quintic.InOut,
  47553. 'ease-in-quint': TWEEN.Easing.Quintic.In,
  47554. 'ease-out-quint': TWEEN.Easing.Quintic.Out,
  47555. 'ease-in-out-quint': TWEEN.Easing.Quintic.InOut,
  47556. 'ease-sine': TWEEN.Easing.Sinusoidal.InOut,
  47557. 'ease-in-sine': TWEEN.Easing.Sinusoidal.In,
  47558. 'ease-out-sine': TWEEN.Easing.Sinusoidal.Out,
  47559. 'ease-in-out-sine': TWEEN.Easing.Sinusoidal.InOut,
  47560. 'ease-expo': TWEEN.Easing.Exponential.InOut,
  47561. 'ease-in-expo': TWEEN.Easing.Exponential.In,
  47562. 'ease-out-expo': TWEEN.Easing.Exponential.Out,
  47563. 'ease-in-out-expo': TWEEN.Easing.Exponential.InOut,
  47564. 'ease-circ': TWEEN.Easing.Circular.InOut,
  47565. 'ease-in-circ': TWEEN.Easing.Circular.In,
  47566. 'ease-out-circ': TWEEN.Easing.Circular.Out,
  47567. 'ease-in-out-circ': TWEEN.Easing.Circular.InOut,
  47568. 'ease-elastic': TWEEN.Easing.Elastic.InOut,
  47569. 'ease-in-elastic': TWEEN.Easing.Elastic.In,
  47570. 'ease-out-elastic': TWEEN.Easing.Elastic.Out,
  47571. 'ease-in-out-elastic': TWEEN.Easing.Elastic.InOut,
  47572. 'ease-back': TWEEN.Easing.Back.InOut,
  47573. 'ease-in-back': TWEEN.Easing.Back.In,
  47574. 'ease-out-back': TWEEN.Easing.Back.Out,
  47575. 'ease-in-out-back': TWEEN.Easing.Back.InOut,
  47576. 'ease-bounce': TWEEN.Easing.Bounce.InOut,
  47577. 'ease-in-bounce': TWEEN.Easing.Bounce.In,
  47578. 'ease-out-bounce': TWEEN.Easing.Bounce.Out,
  47579. 'ease-in-out-bounce': TWEEN.Easing.Bounce.InOut
  47580. };
  47581. var FILLS = {
  47582. backwards: 'backwards',
  47583. both: 'both',
  47584. forwards: 'forwards',
  47585. none: 'none'
  47586. };
  47587. var REPEATS = {
  47588. indefinite: 'indefinite'
  47589. };
  47590. var DEFAULTS = {
  47591. attribute: 'rotation',
  47592. begin: '',
  47593. end: '',
  47594. delay: 0,
  47595. dur: 1000,
  47596. easing: 'ease',
  47597. direction: DIRECTIONS.normal,
  47598. fill: FILLS.forwards,
  47599. from: undefined,
  47600. repeat: 0,
  47601. to: undefined
  47602. };
  47603. module.exports.defaults = DEFAULTS;
  47604. module.exports.directions = DIRECTIONS;
  47605. module.exports.easingFunctions = EASING_FUNCTIONS;
  47606. module.exports.fills = FILLS;
  47607. module.exports.repeats = REPEATS;
  47608. },{"@tweenjs/tween.js":1}],117:[function(_dereq_,module,exports){
  47609. module.exports = {
  47610. AFRAME_INJECTED: 'aframe-injected',
  47611. DEFAULT_CAMERA_HEIGHT: 1.6,
  47612. DEFAULT_HANDEDNESS: 'right',
  47613. animation: _dereq_('./animation'),
  47614. keyboardevent: _dereq_('./keyboardevent')
  47615. };
  47616. },{"./animation":116,"./keyboardevent":118}],118:[function(_dereq_,module,exports){
  47617. module.exports = {
  47618. // Tiny KeyboardEvent.code polyfill.
  47619. KEYCODE_TO_CODE: {
  47620. '38': 'ArrowUp',
  47621. '37': 'ArrowLeft',
  47622. '40': 'ArrowDown',
  47623. '39': 'ArrowRight',
  47624. '87': 'KeyW',
  47625. '65': 'KeyA',
  47626. '83': 'KeyS',
  47627. '68': 'KeyD'
  47628. }
  47629. };
  47630. },{}],119:[function(_dereq_,module,exports){
  47631. var ANode = _dereq_('./a-node');
  47632. var animationConstants = _dereq_('../constants/animation');
  47633. var coordinates = _dereq_('../utils/').coordinates;
  47634. var parseProperty = _dereq_('./schema').parseProperty;
  47635. var registerElement = _dereq_('./a-register-element').registerElement;
  47636. var TWEEN = _dereq_('@tweenjs/tween.js');
  47637. var THREE = _dereq_('../lib/three');
  47638. var utils = _dereq_('../utils/');
  47639. var bind = utils.bind;
  47640. var getComponentProperty = utils.entity.getComponentProperty;
  47641. var DEFAULTS = animationConstants.defaults;
  47642. var DIRECTIONS = animationConstants.directions;
  47643. var EASING_FUNCTIONS = animationConstants.easingFunctions;
  47644. var FILLS = animationConstants.fills;
  47645. var REPEATS = animationConstants.repeats;
  47646. var isCoordinates = coordinates.isCoordinates;
  47647. /**
  47648. * Animation element that applies Tween animation to parent element (entity).
  47649. * Takes after the Web Animations spec.
  47650. *
  47651. * @member {number} count - Decrementing counter for how many cycles of animations left to
  47652. * run.
  47653. * @member {Element} el - Entity which the animation is modifying.
  47654. * @member initialValue - Value before animation started. Used to restore state.
  47655. * @member {bool} isRunning - Whether animation is currently running.
  47656. * @member {function} partialSetAttribute -
  47657. * setAttribute function that is agnostic to whether we are setting an attribute value
  47658. * or a component property value. The el and the attribute names are bundled with
  47659. * the function.
  47660. * @member {object} tween - tween.js object.
  47661. */
  47662. module.exports.AAnimation = registerElement('a-animation', {
  47663. prototype: Object.create(ANode.prototype, {
  47664. createdCallback: {
  47665. value: function () {
  47666. this.bindMethods();
  47667. this.isRunning = false;
  47668. this.partialSetAttribute = function () { /* no-op */ };
  47669. this.tween = null;
  47670. }
  47671. },
  47672. attachedCallback: {
  47673. value: function () {
  47674. this.el = this.parentNode;
  47675. this.handleMixinUpdate();
  47676. this.update();
  47677. this.load();
  47678. }
  47679. },
  47680. attributeChangedCallback: {
  47681. value: function (attr, oldVal, newVal) {
  47682. if (!this.hasLoaded || !this.isRunning) { return; }
  47683. this.stop();
  47684. this.handleMixinUpdate();
  47685. this.update();
  47686. }
  47687. },
  47688. detachedCallback: {
  47689. value: function () {
  47690. if (!this.isRunning) { return; }
  47691. this.stop();
  47692. }
  47693. },
  47694. /**
  47695. * Builds a Tween object to handle animations.
  47696. * Uses tween.js's from, to, delay, easing, repeat, onUpdate, and onComplete.
  47697. * Note: tween.js takes objects for its `from` and `to` values.
  47698. *
  47699. * @returns {object}
  47700. */
  47701. getTween: {
  47702. value: function () {
  47703. var self = this;
  47704. var data = self.data;
  47705. var el = self.el;
  47706. var animationValues;
  47707. var attribute = data.attribute;
  47708. var delay = parseInt(data.delay, 10);
  47709. var currentValue = getComponentProperty(el, attribute);
  47710. var direction = self.getDirection(data.direction);
  47711. var easing = EASING_FUNCTIONS[data.easing];
  47712. var fill = data.fill;
  47713. var from;
  47714. var repeat = data.repeat === REPEATS.indefinite ? Infinity : 0;
  47715. var to;
  47716. var toTemp;
  47717. var yoyo = false;
  47718. animationValues = getAnimationValues(el, attribute, data.from || self.initialValue, data.to, currentValue);
  47719. from = animationValues.from;
  47720. to = animationValues.to;
  47721. self.partialSetAttribute = animationValues.partialSetAttribute;
  47722. if (self.count === undefined) {
  47723. self.count = repeat === Infinity ? 0 : parseInt(data.repeat, 10);
  47724. }
  47725. if (isNaN(delay)) { delay = 0; }
  47726. // Store initial state.
  47727. self.initialValue = self.initialValue || cloneValue(currentValue);
  47728. // Handle indefinite + forwards + alternate yoyo edge-case (#405).
  47729. if (repeat === Infinity && fill === FILLS.forwards &&
  47730. [DIRECTIONS.alternate,
  47731. DIRECTIONS.alternateReverse].indexOf(data.direction) !== -1) {
  47732. yoyo = true;
  47733. }
  47734. // If reversing, swap from and to.
  47735. if (direction === DIRECTIONS.reverse) {
  47736. toTemp = to;
  47737. to = cloneValue(from);
  47738. from = cloneValue(toTemp);
  47739. }
  47740. // If fill is backwards or both, start animation at the specified from.
  47741. if ([FILLS.backwards, FILLS.both].indexOf(fill) !== -1) {
  47742. self.partialSetAttribute(from);
  47743. }
  47744. // Create Tween.
  47745. return new TWEEN.Tween(cloneValue(from))
  47746. .to(to, data.dur)
  47747. .delay(delay)
  47748. .easing(easing)
  47749. .repeat(repeat)
  47750. .yoyo(yoyo)
  47751. .onUpdate(function () {
  47752. self.partialSetAttribute(this);
  47753. })
  47754. .onComplete(bind(self.onCompleted, self));
  47755. }
  47756. },
  47757. /**
  47758. * Animation parameters changed. Stop current animation, get a new one, and start it.
  47759. */
  47760. update: {
  47761. value: function () {
  47762. var data = this.data;
  47763. // Terminology warning if infinite used instead of indefinite
  47764. if (data.repeat === 'infinite') {
  47765. console.warn("Using 'infinite' as 'repeat' value is invalid. Use 'indefinite' instead.");
  47766. }
  47767. // Deprecation warning for begin when used as a delay.
  47768. if (data.begin !== '' && !isNaN(data.begin)) {
  47769. console.warn("Using 'begin' to specify a delay is deprecated. Use 'delay' instead.");
  47770. data.delay = data.begin;
  47771. data.begin = '';
  47772. }
  47773. var begin = data.begin;
  47774. var end = data.end;
  47775. // Cancel previous event listeners
  47776. if (this.evt) { this.removeEventListeners(this.evt); }
  47777. // Store new event name.
  47778. this.evt = {begin: begin, end: end};
  47779. // Add new event listeners
  47780. this.addEventListeners(this.evt);
  47781. // If `begin` is not defined, start the animation right away.
  47782. if (begin === '') {
  47783. this.stop();
  47784. this.start();
  47785. }
  47786. },
  47787. writable: window.debug
  47788. },
  47789. /**
  47790. * Callback for when a cycle of an animation is complete. Handles when to completely
  47791. * finish the animation.
  47792. *
  47793. * If `repeat` is set to a value, this method is called after each repeat. Repeats are
  47794. * handled by ending the current animation and creating a new one with `count` updated.
  47795. * Note that this method is *not* called if repeat is set to `indefinite`.
  47796. */
  47797. onCompleted: {
  47798. value: function () {
  47799. var data = this.data;
  47800. this.isRunning = false;
  47801. if ([FILLS.backwards, FILLS.none].indexOf(data.fill) !== -1) {
  47802. this.partialSetAttribute(this.initialValue);
  47803. }
  47804. if (this.count === 0) {
  47805. this.count = undefined;
  47806. this.emit('animationend');
  47807. return;
  47808. }
  47809. this.isRunning = false;
  47810. this.count--;
  47811. this.start();
  47812. }
  47813. },
  47814. start: {
  47815. value: function () {
  47816. var self = this;
  47817. // Postpone animation start until the entity has loaded
  47818. if (!this.el.hasLoaded) {
  47819. this.el.addEventListener('loaded', function () { self.start(); });
  47820. return;
  47821. }
  47822. if (this.isRunning || !this.el.isPlaying) { return; }
  47823. this.tween = this.getTween();
  47824. this.isRunning = true;
  47825. this.tween.start();
  47826. this.emit('animationstart');
  47827. },
  47828. writable: true
  47829. },
  47830. stop: {
  47831. value: function () {
  47832. var tween = this.tween;
  47833. if (!tween) { return; }
  47834. tween.stop();
  47835. this.isRunning = false;
  47836. if ([FILLS.backwards, FILLS.none].indexOf(this.data.fill) !== -1) {
  47837. this.partialSetAttribute(this.initialValue);
  47838. }
  47839. this.emit('animationstop');
  47840. },
  47841. writable: true
  47842. },
  47843. /**
  47844. * Handle alternating directions. Given the current direction, calculate the next one,
  47845. * and store the current one.
  47846. *
  47847. * @param {string} direction
  47848. * @returns {string} Direction that the next individual cycle of the animation will go
  47849. * towards.
  47850. */
  47851. getDirection: {
  47852. value: function (direction) {
  47853. if (direction === DIRECTIONS.alternate) {
  47854. this.prevDirection =
  47855. this.prevDirection === DIRECTIONS.normal ? DIRECTIONS.reverse : DIRECTIONS.normal;
  47856. return this.prevDirection;
  47857. }
  47858. if (direction === DIRECTIONS.alternateReverse) {
  47859. this.prevDirection =
  47860. this.prevDirection === DIRECTIONS.reverse ? DIRECTIONS.normal : DIRECTIONS.reverse;
  47861. return this.prevDirection;
  47862. }
  47863. return direction;
  47864. }
  47865. },
  47866. /**
  47867. * Preemptive binding to attach/detach event listeners (see `update`).
  47868. */
  47869. bindMethods: {
  47870. value: function () {
  47871. this.start = bind(this.start, this);
  47872. this.stop = bind(this.stop, this);
  47873. this.onStateAdded = bind(this.onStateAdded, this);
  47874. this.onStateRemoved = bind(this.onStateRemoved, this);
  47875. }
  47876. },
  47877. addEventListeners: {
  47878. value: function (evts) {
  47879. var el = this.el;
  47880. var self = this;
  47881. utils.splitString(evts.begin).forEach(function (evt) {
  47882. el.addEventListener(evt, self.start);
  47883. });
  47884. utils.splitString(evts.end).forEach(function (evt) {
  47885. el.addEventListener(evt, self.stop);
  47886. });
  47887. // If "begin" is an event name, wait. If it is not defined, start.
  47888. if (evts.begin === '') { el.addEventListener('play', this.start); }
  47889. el.addEventListener('pause', this.stop);
  47890. el.addEventListener('stateadded', this.onStateAdded);
  47891. el.addEventListener('stateremoved', this.onStateRemoved);
  47892. }
  47893. },
  47894. removeEventListeners: {
  47895. value: function (evts) {
  47896. var el = this.el;
  47897. var start = this.start;
  47898. var stop = this.stop;
  47899. utils.splitString(evts.begin).forEach(function (evt) {
  47900. el.removeEventListener(evt, start);
  47901. });
  47902. utils.splitString(evts.end).forEach(function (evt) {
  47903. el.removeEventListener(evt, stop);
  47904. });
  47905. el.removeEventListener('stateadded', this.onStateAdded);
  47906. el.removeEventListener('stateremoved', this.onStateRemoved);
  47907. }
  47908. },
  47909. onStateAdded: {
  47910. value: function (evt) {
  47911. if (evt.detail.state === this.data.begin) { this.start(); }
  47912. },
  47913. writable: true
  47914. },
  47915. onStateRemoved: {
  47916. value: function (evt) {
  47917. if (evt.detail.state === this.data.begin) { this.stop(); }
  47918. },
  47919. writable: true
  47920. },
  47921. /**
  47922. * Applies animation data from a mixin element.
  47923. * Works the same as component mixins but reimplemented because animations
  47924. * aren't components.
  47925. */
  47926. handleMixinUpdate: {
  47927. value: function () {
  47928. var data = {};
  47929. var elData;
  47930. var mixinData;
  47931. var mixinEl;
  47932. // Get mixin data.
  47933. mixinEl = document.querySelector('#' + this.getAttribute('mixin'));
  47934. mixinData = mixinEl ? utils.getElData(mixinEl, DEFAULTS) : {};
  47935. elData = utils.getElData(this, DEFAULTS);
  47936. utils.extend(data, DEFAULTS, mixinData, elData);
  47937. this.data = data;
  47938. }
  47939. }
  47940. })
  47941. });
  47942. function cloneValue (val) {
  47943. return utils.extend({}, val);
  47944. }
  47945. /**
  47946. * Deduces different animation values based on whether we are:
  47947. * - animating an inner attribute of a component.
  47948. * - animating a coordinate component.
  47949. * - animating a boolean.
  47950. * - animating a number.
  47951. *
  47952. * @param {Element} el
  47953. * @param {string} attribute - Tells what to animate based on whether it is dot-separated.
  47954. * @param {string} dataFrom - Data `from` value.
  47955. * @param {string} dataTo - Data `to` value.
  47956. * @param currentValue
  47957. * @returns {object}
  47958. * Object with keys [from, to, partialSetAttribute].
  47959. * `from` and `to`
  47960. * Objects where key is attribute being animated and value is value.
  47961. * `partialSetAttribute`
  47962. * Closured-function that tells tween how to update the component.
  47963. */
  47964. function getAnimationValues (el, attribute, dataFrom, dataTo, currentValue) {
  47965. var attributeSplit = attribute.split('.');
  47966. var schema;
  47967. var component;
  47968. var componentPropName;
  47969. var componentName;
  47970. var from = {};
  47971. var partialSetAttribute;
  47972. var to = {};
  47973. if (attributeSplit.length === 2) {
  47974. if (isColor()) {
  47975. getForColorComponent();
  47976. } else {
  47977. getForComponentAttribute();
  47978. }
  47979. } else if (dataTo && isCoordinates(dataTo)) {
  47980. getForCoordinateComponent();
  47981. } else if (['true', 'false'].indexOf(dataTo) !== -1) {
  47982. getForBoolean();
  47983. } else if (isNaN(dataTo)) {
  47984. getForColorComponent();
  47985. } else {
  47986. getForNumber();
  47987. }
  47988. return {
  47989. from: from,
  47990. partialSetAttribute: partialSetAttribute,
  47991. to: to
  47992. };
  47993. /**
  47994. * Match the schema type to color
  47995. * @return {bool} if the schema is of type color
  47996. */
  47997. function isColor () {
  47998. var componentName = attributeSplit[0];
  47999. var propertyName = attributeSplit[1];
  48000. var component = el.components[componentName];
  48001. var schema = component && component.schema;
  48002. return schema && schema[propertyName] && schema[propertyName].type === 'color';
  48003. }
  48004. /**
  48005. * Animating a component that has multiple attributes (e.g., geometry.width).
  48006. */
  48007. function getForComponentAttribute () {
  48008. componentName = attributeSplit[0];
  48009. componentPropName = attributeSplit[1];
  48010. component = el.components[componentName];
  48011. if (!component) {
  48012. el.setAttribute(componentName, '');
  48013. component = el.components[componentName];
  48014. }
  48015. schema = component.schema;
  48016. if (dataFrom === undefined) { // dataFrom can be 0.
  48017. from[attribute] = getComponentProperty(el, attribute);
  48018. } else {
  48019. from[attribute] = dataFrom;
  48020. }
  48021. from[attribute] = parseProperty(from[attribute], schema[componentPropName]);
  48022. to[attribute] = parseProperty(dataTo, schema[componentPropName]);
  48023. partialSetAttribute = function (value) {
  48024. if (!(attribute in value)) { return; }
  48025. el.setAttribute(componentName, componentPropName, value[attribute]);
  48026. };
  48027. }
  48028. /**
  48029. * Animating a component that is an XYZ coordinate (e.g., position).
  48030. * Will be tweening {x, y, z} all at once.
  48031. */
  48032. function getForCoordinateComponent () {
  48033. from = dataFrom ? coordinates.parse(dataFrom) : currentValue;
  48034. to = coordinates.parse(dataTo);
  48035. partialSetAttribute = function (value) {
  48036. el.setAttribute(attribute, value);
  48037. };
  48038. }
  48039. /**
  48040. * Animation a boolean (e.g., visible).
  48041. * Have to convert from boolean to an integer (0 is false, > 0 is true) for tween.
  48042. */
  48043. function getForBoolean () {
  48044. if (dataFrom === undefined) {
  48045. from[attribute] = false;
  48046. } else {
  48047. from[attribute] = strToBool(dataFrom);
  48048. }
  48049. from[attribute] = boolToNum(from[attribute]);
  48050. to[attribute] = boolToNum(strToBool(dataTo));
  48051. partialSetAttribute = function (value) {
  48052. el.setAttribute(attribute, !!value[attribute]);
  48053. };
  48054. }
  48055. /**
  48056. * Animating a color component
  48057. * Will convert a hex value to a THREE.Color
  48058. * Then converts to hex for the setAttribute
  48059. */
  48060. function getForColorComponent () {
  48061. from = new THREE.Color(dataFrom || el.getAttribute(attribute));
  48062. to = new THREE.Color(dataTo);
  48063. partialSetAttribute = function (value) {
  48064. if (attributeSplit.length > 1) {
  48065. el.setAttribute(attributeSplit[0], attributeSplit[1], rgbVectorToHex(value));
  48066. }
  48067. el.setAttribute(attribute, rgbVectorToHex(value));
  48068. };
  48069. }
  48070. /**
  48071. * Animating a numbered attribute (e.g., opacity).
  48072. */
  48073. function getForNumber () {
  48074. if (dataFrom === undefined) { // dataFrom can be 0.
  48075. from[attribute] = parseFloat(el.getAttribute(attribute));
  48076. } else {
  48077. from[attribute] = parseFloat(dataFrom);
  48078. }
  48079. to[attribute] = parseFloat(dataTo);
  48080. partialSetAttribute = function (value) {
  48081. el.setAttribute(attribute, value[attribute]);
  48082. };
  48083. }
  48084. }
  48085. module.exports.getAnimationValues = getAnimationValues;
  48086. /**
  48087. * Converts string to bool.
  48088. *
  48089. * @param {string} str - `true` or `false`.
  48090. * @returns {bool}
  48091. */
  48092. function strToBool (str) {
  48093. if (str === 'true') { return true; }
  48094. return false;
  48095. }
  48096. /**
  48097. * Converts boolean to number.
  48098. *
  48099. * @param {bool}
  48100. * @returns {number}
  48101. */
  48102. function boolToNum (bool) {
  48103. return bool ? 1 : 0;
  48104. }
  48105. /**
  48106. * Converts a number 0-255 to hex
  48107. * @param {number} color number 0 - 255
  48108. * @returns {string} hex value of number bassed
  48109. */
  48110. function componentToHex (color) {
  48111. var hex = color.toString(16);
  48112. return hex.length === 1 ? '0' + hex : hex;
  48113. }
  48114. /**
  48115. * Clamps a number to 0-1
  48116. * Then converts that number to 0-255
  48117. * @param {number} color number 0 - 1
  48118. * @returns {number} color number 0 - 255
  48119. */
  48120. function convertToIntegerColor (color) {
  48121. return Math.floor(Math.min(Math.abs(color), 1) * 255);
  48122. }
  48123. /**
  48124. * Converts a rgb object into a hex string
  48125. * @param {object} color { r: 1, g: 1, b: 1 }
  48126. * @returns {string} hex value #ffffff
  48127. */
  48128. function rgbVectorToHex (color) {
  48129. return '#' + ['r', 'g', 'b'].map(function (prop) {
  48130. return componentToHex(convertToIntegerColor(color[prop]));
  48131. }).join('');
  48132. }
  48133. },{"../constants/animation":116,"../lib/three":174,"../utils/":197,"./a-node":124,"./a-register-element":125,"./schema":134,"@tweenjs/tween.js":1}],120:[function(_dereq_,module,exports){
  48134. var ANode = _dereq_('./a-node');
  48135. var bind = _dereq_('../utils/bind');
  48136. var debug = _dereq_('../utils/debug');
  48137. var registerElement = _dereq_('./a-register-element').registerElement;
  48138. var THREE = _dereq_('../lib/three');
  48139. var fileLoader = new THREE.FileLoader();
  48140. var warn = debug('core:a-assets:warn');
  48141. /**
  48142. * Asset management system. Handles blocking on asset loading.
  48143. */
  48144. module.exports = registerElement('a-assets', {
  48145. prototype: Object.create(ANode.prototype, {
  48146. createdCallback: {
  48147. value: function () {
  48148. this.isAssets = true;
  48149. this.fileLoader = fileLoader;
  48150. this.timeout = null;
  48151. }
  48152. },
  48153. attachedCallback: {
  48154. value: function () {
  48155. var self = this;
  48156. var i;
  48157. var loaded = [];
  48158. var mediaEl;
  48159. var mediaEls;
  48160. var imgEl;
  48161. var imgEls;
  48162. var timeout;
  48163. if (!this.parentNode.isScene) {
  48164. throw new Error('<a-assets> must be a child of a <a-scene>.');
  48165. }
  48166. // Wait for <img>s.
  48167. imgEls = this.querySelectorAll('img');
  48168. for (i = 0; i < imgEls.length; i++) {
  48169. imgEl = fixUpMediaElement(imgEls[i]);
  48170. loaded.push(new Promise(function (resolve, reject) {
  48171. // Set in cache because we won't be needing to call three.js loader if we have.
  48172. // a loaded media element.
  48173. THREE.Cache.files[imgEls[i].getAttribute('src')] = imgEl;
  48174. imgEl.onload = resolve;
  48175. imgEl.onerror = reject;
  48176. }));
  48177. }
  48178. // Wait for <audio>s and <video>s.
  48179. mediaEls = this.querySelectorAll('audio, video');
  48180. for (i = 0; i < mediaEls.length; i++) {
  48181. mediaEl = fixUpMediaElement(mediaEls[i]);
  48182. loaded.push(mediaElementLoaded(mediaEl));
  48183. }
  48184. // Trigger loaded for scene to start rendering.
  48185. Promise.all(loaded).then(bind(this.load, this));
  48186. // Timeout to start loading anyways.
  48187. timeout = parseInt(this.getAttribute('timeout'), 10) || 3000;
  48188. this.timeout = setTimeout(function () {
  48189. if (self.hasLoaded) { return; }
  48190. warn('Asset loading timed out in ', timeout, 'ms');
  48191. self.emit('timeout');
  48192. self.load();
  48193. }, timeout);
  48194. }
  48195. },
  48196. detachedCallback: {
  48197. value: function () {
  48198. if (this.timeout) { clearTimeout(this.timeout); }
  48199. }
  48200. },
  48201. load: {
  48202. value: function () {
  48203. ANode.prototype.load.call(this, null, function waitOnFilter (el) {
  48204. return el.isAssetItem && el.hasAttribute('src');
  48205. });
  48206. }
  48207. }
  48208. })
  48209. });
  48210. /**
  48211. * Preload using XHRLoader for any type of asset.
  48212. */
  48213. registerElement('a-asset-item', {
  48214. prototype: Object.create(ANode.prototype, {
  48215. createdCallback: {
  48216. value: function () {
  48217. this.data = null;
  48218. this.isAssetItem = true;
  48219. }
  48220. },
  48221. attachedCallback: {
  48222. value: function () {
  48223. var self = this;
  48224. var src = this.getAttribute('src');
  48225. fileLoader.setResponseType(
  48226. this.getAttribute('response-type') || inferResponseType(src));
  48227. fileLoader.load(src, function handleOnLoad (response) {
  48228. self.data = response;
  48229. /*
  48230. Workaround for a Chrome bug. If another XHR is sent to the same url before the
  48231. previous one closes, the second request never finishes.
  48232. setTimeout finishes the first request and lets the logic triggered by load open
  48233. subsequent requests.
  48234. setTimeout can be removed once the fix for the bug below ships:
  48235. 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
  48236. */
  48237. setTimeout(function load () { ANode.prototype.load.call(self); });
  48238. }, function handleOnProgress (xhr) {
  48239. self.emit('progress', {
  48240. loadedBytes: xhr.loaded,
  48241. totalBytes: xhr.total,
  48242. xhr: xhr
  48243. });
  48244. }, function handleOnError (xhr) {
  48245. self.emit('error', {xhr: xhr});
  48246. });
  48247. }
  48248. }
  48249. })
  48250. });
  48251. /**
  48252. * Create a Promise that resolves once the media element has finished buffering.
  48253. *
  48254. * @param {Element} el - HTMLMediaElement.
  48255. * @returns {Promise}
  48256. */
  48257. function mediaElementLoaded (el) {
  48258. if (!el.hasAttribute('autoplay') && el.getAttribute('preload') !== 'auto') {
  48259. return;
  48260. }
  48261. // If media specifies autoplay or preload, wait until media is completely buffered.
  48262. return new Promise(function (resolve, reject) {
  48263. if (el.readyState === 4) { return resolve(); } // Already loaded.
  48264. if (el.error) { return reject(); } // Error.
  48265. el.addEventListener('loadeddata', checkProgress, false);
  48266. el.addEventListener('progress', checkProgress, false);
  48267. el.addEventListener('error', reject, false);
  48268. function checkProgress () {
  48269. // Add up the seconds buffered.
  48270. var secondsBuffered = 0;
  48271. for (var i = 0; i < el.buffered.length; i++) {
  48272. secondsBuffered += el.buffered.end(i) - el.buffered.start(i);
  48273. }
  48274. // Compare seconds buffered to media duration.
  48275. if (secondsBuffered >= el.duration) {
  48276. // Set in cache because we won't be needing to call three.js loader if we have.
  48277. // a loaded media element.
  48278. THREE.Cache.files[el.getAttribute('src')] = el;
  48279. resolve();
  48280. }
  48281. }
  48282. });
  48283. }
  48284. /**
  48285. * Automatically add attributes to media elements where convenient.
  48286. * crossorigin, playsinline.
  48287. */
  48288. function fixUpMediaElement (mediaEl) {
  48289. // Cross-origin.
  48290. var newMediaEl = setCrossOrigin(mediaEl);
  48291. // Plays inline for mobile.
  48292. if (newMediaEl.tagName && newMediaEl.tagName.toLowerCase() === 'video') {
  48293. newMediaEl.setAttribute('playsinline', '');
  48294. newMediaEl.setAttribute('webkit-playsinline', '');
  48295. }
  48296. if (newMediaEl !== mediaEl) {
  48297. mediaEl.parentNode.appendChild(newMediaEl);
  48298. mediaEl.parentNode.removeChild(mediaEl);
  48299. }
  48300. return newMediaEl;
  48301. }
  48302. /**
  48303. * Automatically set `crossorigin` if not defined on the media element.
  48304. * If it is not defined, we must create and re-append a new media element <img> and
  48305. * have the browser re-request it with `crossorigin` set.
  48306. *
  48307. * @param {Element} Media element (e.g., <img>, <audio>, <video>).
  48308. * @returns {Element} Media element to be used to listen to for loaded events.
  48309. */
  48310. function setCrossOrigin (mediaEl) {
  48311. var newMediaEl;
  48312. var src;
  48313. // Already has crossorigin set.
  48314. if (mediaEl.hasAttribute('crossorigin')) { return mediaEl; }
  48315. src = mediaEl.getAttribute('src');
  48316. if (src !== null) {
  48317. // Does not have protocol.
  48318. if (src.indexOf('://') === -1) { return mediaEl; }
  48319. // Determine if cross origin is actually needed.
  48320. if (extractDomain(src) === window.location.host) { return mediaEl; }
  48321. }
  48322. warn('Cross-origin element (e.g., <img>) was requested without `crossorigin` set. ' +
  48323. 'A-Frame will re-request the asset with `crossorigin` attribute set. ' +
  48324. 'Please set `crossorigin` on the element (e.g., <img crossorigin="anonymous">)', src);
  48325. mediaEl.crossOrigin = 'anonymous';
  48326. newMediaEl = mediaEl.cloneNode(true);
  48327. return newMediaEl;
  48328. }
  48329. /**
  48330. * Extract domain out of URL.
  48331. *
  48332. * @param {string} url
  48333. * @returns {string}
  48334. */
  48335. function extractDomain (url) {
  48336. // Find and remove protocol (e.g., http, ftp, etc.) to get domain.
  48337. var domain = url.indexOf('://') > -1 ? url.split('/')[2] : url.split('/')[0];
  48338. // Find and remove port number.
  48339. return domain.split(':')[0];
  48340. }
  48341. /**
  48342. * Infer response-type attribute from src.
  48343. * Default is text(default XMLHttpRequest.responseType)
  48344. * but we use arraybuffer for .gltf and .glb files
  48345. * because of THREE.GLTFLoader specification.
  48346. *
  48347. * @param {string} src
  48348. * @returns {string}
  48349. */
  48350. function inferResponseType (src) {
  48351. var dotLastIndex = src.lastIndexOf('.');
  48352. if (dotLastIndex >= 0) {
  48353. var extension = src.slice(dotLastIndex, src.length);
  48354. if (extension === '.gltf' || extension === '.glb') {
  48355. return 'arraybuffer';
  48356. }
  48357. }
  48358. return 'text';
  48359. }
  48360. module.exports.inferResponseType = inferResponseType;
  48361. },{"../lib/three":174,"../utils/bind":191,"../utils/debug":193,"./a-node":124,"./a-register-element":125}],121:[function(_dereq_,module,exports){
  48362. var debug = _dereq_('../utils/debug');
  48363. var registerElement = _dereq_('./a-register-element').registerElement;
  48364. var warn = debug('core:cubemap:warn');
  48365. /**
  48366. * Cubemap element that handles validation and exposes list of URLs.
  48367. * Does not listen to updates.
  48368. */
  48369. module.exports = registerElement('a-cubemap', {
  48370. prototype: Object.create(window.HTMLElement.prototype, {
  48371. /**
  48372. * Calculates this.srcs.
  48373. */
  48374. attachedCallback: {
  48375. value: function () {
  48376. this.srcs = this.validate();
  48377. },
  48378. writable: window.debug
  48379. },
  48380. /**
  48381. * Checks for exactly six elements with [src].
  48382. * Does not check explicitly for <img>s in case user does not want
  48383. * prefetching.
  48384. *
  48385. * @returns {Array|null} - six URLs if valid, else null.
  48386. */
  48387. validate: {
  48388. value: function () {
  48389. var elements = this.querySelectorAll('[src]');
  48390. var i;
  48391. var srcs = [];
  48392. if (elements.length === 6) {
  48393. for (i = 0; i < elements.length; i++) {
  48394. srcs.push(elements[i].getAttribute('src'));
  48395. }
  48396. return srcs;
  48397. }
  48398. // Else if there are not six elements, throw a warning.
  48399. warn(
  48400. '<a-cubemap> did not contain exactly six elements each with a ' +
  48401. '`src` attribute.');
  48402. },
  48403. writable: window.debug
  48404. }
  48405. })
  48406. });
  48407. },{"../utils/debug":193,"./a-register-element":125}],122:[function(_dereq_,module,exports){
  48408. var ANode = _dereq_('./a-node');
  48409. var COMPONENTS = _dereq_('./component').components;
  48410. var registerElement = _dereq_('./a-register-element').registerElement;
  48411. var THREE = _dereq_('../lib/three');
  48412. var utils = _dereq_('../utils/');
  48413. var AEntity;
  48414. var bind = utils.bind;
  48415. var debug = utils.debug('core:a-entity:debug');
  48416. var warn = utils.debug('core:a-entity:warn');
  48417. var MULTIPLE_COMPONENT_DELIMITER = '__';
  48418. /**
  48419. * Entity is a container object that components are plugged into to comprise everything in
  48420. * the scene. In A-Frame, they inherently have position, rotation, and scale.
  48421. *
  48422. * To be able to take components, the scene element inherits from the entity definition.
  48423. *
  48424. * @member {object} components - entity's currently initialized components.
  48425. * @member {object} object3D - three.js object.
  48426. * @member {array} states
  48427. * @member {boolean} isPlaying - false if dynamic behavior of the entity is paused.
  48428. */
  48429. var proto = Object.create(ANode.prototype, {
  48430. defaultComponents: {
  48431. value: {
  48432. position: '',
  48433. rotation: '',
  48434. scale: '',
  48435. visible: ''
  48436. }
  48437. },
  48438. createdCallback: {
  48439. value: function () {
  48440. this.components = {};
  48441. // To avoid double initializations and infinite loops.
  48442. this.initializingComponents = {};
  48443. this.isEntity = true;
  48444. this.isPlaying = false;
  48445. this.object3D = new THREE.Group();
  48446. this.object3D.el = this;
  48447. this.object3DMap = {};
  48448. this.parentEl = null;
  48449. this.states = [];
  48450. }
  48451. },
  48452. /**
  48453. * Handle changes coming from the browser DOM inspector.
  48454. */
  48455. attributeChangedCallback: {
  48456. value: function (attr, oldVal, newVal) {
  48457. var component = this.components[attr];
  48458. // If the empty string is passed by the component initialization
  48459. // logic we ignore the component update.
  48460. if (component && component.justInitialized && newVal === '') {
  48461. delete component.justInitialized;
  48462. return;
  48463. }
  48464. // When a component is removed after calling el.removeAttribute('material')
  48465. if (!component && newVal === null) { return; }
  48466. this.setEntityAttribute(attr, oldVal, newVal);
  48467. }
  48468. },
  48469. /**
  48470. * Add to parent, load, play.
  48471. */
  48472. attachedCallback: {
  48473. value: function () {
  48474. var assetsEl; // Asset management system element.
  48475. var sceneEl = this.sceneEl;
  48476. var self = this; // Component.
  48477. this.addToParent();
  48478. // Don't .load() scene on attachedCallback.
  48479. if (this.isScene) { return; }
  48480. // Gracefully not error when outside of <a-scene> (e.g., tests).
  48481. if (!sceneEl) {
  48482. this.load();
  48483. return;
  48484. }
  48485. // Wait for asset management system to finish before loading.
  48486. assetsEl = sceneEl.querySelector('a-assets');
  48487. if (assetsEl && !assetsEl.hasLoaded) {
  48488. assetsEl.addEventListener('loaded', function () { self.load(); });
  48489. return;
  48490. }
  48491. this.load();
  48492. }
  48493. },
  48494. /**
  48495. * Tell parent to remove this element's object3D from its object3D.
  48496. * Do not call on scene element because that will cause a call to document.body.remove().
  48497. */
  48498. detachedCallback: {
  48499. value: function () {
  48500. if (!this.parentEl) { return; }
  48501. // Remove components.
  48502. Object.keys(this.components).forEach(bind(this.removeComponent, this));
  48503. if (this.isScene) { return; }
  48504. this.removeFromParent();
  48505. ANode.prototype.detachedCallback.call(this);
  48506. }
  48507. },
  48508. /**
  48509. * Apply mixin to component.
  48510. */
  48511. handleMixinUpdate: {
  48512. value: function (attrName) {
  48513. if (!attrName) {
  48514. this.updateComponents();
  48515. return;
  48516. }
  48517. this.updateComponent(attrName, this.getDOMAttribute(attrName));
  48518. }
  48519. },
  48520. mapStateMixins: {
  48521. value: function (state, op) {
  48522. var mixins = this.getAttribute('mixin');
  48523. var mixinIds;
  48524. if (!mixins) { return; }
  48525. mixinIds = mixins.split(' ');
  48526. mixinIds.forEach(function (id) {
  48527. var mixinId = id + '-' + state;
  48528. op(mixinId);
  48529. });
  48530. this.updateComponents();
  48531. }
  48532. },
  48533. /**
  48534. * Handle update of mixin states (e.g., `box-hovered` where `box` is the mixin ID and
  48535. * `hovered` is the entity state.
  48536. */
  48537. updateStateMixins: {
  48538. value: function (newMixins, oldMixins) {
  48539. var diff;
  48540. var newMixinsIds = newMixins.split(' ');
  48541. var oldMixinsIds = (oldMixins || '') ? oldMixins.split(' ') : [];
  48542. var self = this;
  48543. // List of mixins that might have been removed on update.
  48544. diff = oldMixinsIds.filter(function (i) { return newMixinsIds.indexOf(i) < 0; });
  48545. // Remove removed mixins.
  48546. diff.forEach(function (mixinId) {
  48547. // State Mixins
  48548. var stateMixinsEls = document.querySelectorAll('[id^=' + mixinId + '-]');
  48549. Array.prototype.forEach.call(stateMixinsEls, function (el) {
  48550. self.unregisterMixin(el.id);
  48551. });
  48552. });
  48553. // Add new mixins.
  48554. this.states.forEach(function (state) {
  48555. newMixinsIds.forEach(function (id) {
  48556. var mixinId = id + '-' + state;
  48557. self.registerMixin(mixinId);
  48558. });
  48559. });
  48560. }
  48561. },
  48562. getObject3D: {
  48563. value: function (type) {
  48564. return this.object3DMap[type];
  48565. }
  48566. },
  48567. /**
  48568. * Set a THREE.Object3D into the map.
  48569. *
  48570. * @param {string} type - Developer-set name of the type of object, will be unique per type.
  48571. * @param {object} obj - A THREE.Object3D.
  48572. */
  48573. setObject3D: {
  48574. value: function (type, obj) {
  48575. var oldObj;
  48576. var self = this;
  48577. if (!(obj instanceof THREE.Object3D)) {
  48578. throw new Error(
  48579. '`Entity.setObject3D` was called with an object that was not an instance of ' +
  48580. 'THREE.Object3D.'
  48581. );
  48582. }
  48583. // Remove existing object of the type.
  48584. oldObj = this.getObject3D(type);
  48585. if (oldObj) { this.object3D.remove(oldObj); }
  48586. // Set references to A-Frame entity.
  48587. obj.el = this;
  48588. if (obj.children.length) {
  48589. obj.traverse(function bindEl (child) {
  48590. child.el = self;
  48591. });
  48592. }
  48593. // Add.
  48594. this.object3D.add(obj);
  48595. this.object3DMap[type] = obj;
  48596. this.emit('object3dset', {object: obj, type: type});
  48597. }
  48598. },
  48599. /**
  48600. * Remove object from scene and entity object3D map.
  48601. */
  48602. removeObject3D: {
  48603. value: function (type) {
  48604. var obj = this.getObject3D(type);
  48605. if (!obj) {
  48606. warn('Tried to remove `Object3D` of type:', type, 'which was not defined.');
  48607. return;
  48608. }
  48609. this.object3D.remove(obj);
  48610. delete this.object3DMap[type];
  48611. this.emit('object3dremove', {type: type});
  48612. }
  48613. },
  48614. /**
  48615. * Gets or creates an object3D of a given type.
  48616. *
  48617. * @param {string} type - Type of the object3D.
  48618. * @param {string} Constructor - Constructor to use to create the object3D if needed.
  48619. * @returns {object}
  48620. */
  48621. getOrCreateObject3D: {
  48622. value: function (type, Constructor) {
  48623. var object3D = this.getObject3D(type);
  48624. if (!object3D && Constructor) {
  48625. object3D = new Constructor();
  48626. this.setObject3D(type, object3D);
  48627. }
  48628. return object3D;
  48629. }
  48630. },
  48631. /**
  48632. * Add child entity.
  48633. *
  48634. * @param {Element} el - Child entity.
  48635. */
  48636. add: {
  48637. value: function (el) {
  48638. if (!el.object3D) {
  48639. throw new Error("Trying to add an element that doesn't have an `object3D`");
  48640. }
  48641. this.object3D.add(el.object3D);
  48642. this.emit('child-attached', { el: el });
  48643. }
  48644. },
  48645. /**
  48646. * Tell parentNode to add this entity to itself.
  48647. */
  48648. addToParent: {
  48649. value: function () {
  48650. var parentNode = this.parentEl = this.parentNode;
  48651. // `!parentNode` check primarily for unit tests.
  48652. if (!parentNode || !parentNode.add || this.attachedToParent) { return; }
  48653. parentNode.add(this);
  48654. this.attachedToParent = true; // To prevent multiple attachments to same parent.
  48655. }
  48656. },
  48657. /**
  48658. * Tell parentNode to remove this entity from itself.
  48659. */
  48660. removeFromParent: {
  48661. value: function () {
  48662. var parentEl = this.parentEl;
  48663. this.parentEl.remove(this);
  48664. this.attachedToParent = false;
  48665. this.parentEl = this.parentNode = null;
  48666. parentEl.emit('child-detached', {el: this});
  48667. }
  48668. },
  48669. load: {
  48670. value: function () {
  48671. var self = this;
  48672. if (this.hasLoaded || !this.parentEl) { return; }
  48673. ANode.prototype.load.call(this, function entityLoadCallback () {
  48674. // Check if entity was detached while it was waiting to load.
  48675. if (!self.parentEl) { return; }
  48676. self.updateComponents();
  48677. if (self.isScene || self.parentEl.isPlaying) { self.play(); }
  48678. });
  48679. },
  48680. writable: window.debug
  48681. },
  48682. /**
  48683. * Remove child entity.
  48684. *
  48685. * @param {Element} el - Child entity.
  48686. */
  48687. remove: {
  48688. value: function (el) {
  48689. this.object3D.remove(el.object3D);
  48690. }
  48691. },
  48692. /**
  48693. * @returns {array} Direct children that are entities.
  48694. */
  48695. getChildEntities: {
  48696. value: function () {
  48697. var children = this.children;
  48698. var childEntities = [];
  48699. for (var i = 0; i < children.length; i++) {
  48700. var child = children[i];
  48701. if (child instanceof AEntity) {
  48702. childEntities.push(child);
  48703. }
  48704. }
  48705. return childEntities;
  48706. }
  48707. },
  48708. /**
  48709. * Initialize component.
  48710. *
  48711. * @param {string} attrName - Attribute name asociated to the component.
  48712. * @param {object} data - Component data
  48713. * @param {boolean} isDependency - True if the component is a dependency.
  48714. */
  48715. initComponent: {
  48716. value: function (attrName, data, isDependency) {
  48717. var component;
  48718. var componentInfo = attrName.split(MULTIPLE_COMPONENT_DELIMITER);
  48719. var componentId = componentInfo[1];
  48720. var componentName = componentInfo[0];
  48721. var isComponentDefined = checkComponentDefined(this, attrName) || data !== undefined;
  48722. // Not a registered component.
  48723. if (!COMPONENTS[componentName]) { return; }
  48724. // Component is not a dependency and is undefined.
  48725. // If a component is a dependency, then it is okay to have no data.
  48726. if (!isComponentDefined && !isDependency) { return; }
  48727. // Component already initialized.
  48728. if (attrName in this.components) { return; }
  48729. // Initialize dependencies first
  48730. this.initComponentDependencies(componentName);
  48731. // If component name has an id we check component type multiplic
  48732. if (componentId && !COMPONENTS[componentName].multiple) {
  48733. throw new Error('Trying to initialize multiple ' +
  48734. 'components of type `' + componentName +
  48735. '`. There can only be one component of this type per entity.');
  48736. }
  48737. component = new COMPONENTS[componentName].Component(this, data, componentId);
  48738. if (this.isPlaying) { component.play(); }
  48739. // Components are reflected in the DOM as attributes but the state is not shown
  48740. // hence we set the attribute to empty string.
  48741. // The flag justInitialized is for attributeChangedCallback to not overwrite
  48742. // the component with the empty string.
  48743. if (!this.hasAttribute(attrName)) {
  48744. component.justInitialized = true;
  48745. window.HTMLElement.prototype.setAttribute.call(this, attrName, '');
  48746. }
  48747. debug('Component initialized: %s', attrName);
  48748. },
  48749. writable: window.debug
  48750. },
  48751. /**
  48752. * Initialize dependencies of a component.
  48753. *
  48754. * @param {string} name - Root component name.
  48755. */
  48756. initComponentDependencies: {
  48757. value: function (name) {
  48758. var self = this;
  48759. var component = COMPONENTS[name];
  48760. var dependencies;
  48761. // Not a component.
  48762. if (!component) { return; }
  48763. // No dependencies.
  48764. dependencies = COMPONENTS[name].dependencies;
  48765. if (!dependencies) { return; }
  48766. // Initialize dependencies.
  48767. dependencies.forEach(function initializeDependency (componentName) {
  48768. // Call getAttribute to initialize the data from the DOM.
  48769. self.initComponent(
  48770. componentName,
  48771. window.HTMLElement.prototype.getAttribute.call(self, componentName) || undefined,
  48772. true
  48773. );
  48774. });
  48775. }
  48776. },
  48777. removeComponent: {
  48778. value: function (name) {
  48779. var component;
  48780. var isDefault;
  48781. var isMixedIn;
  48782. // Don't remove default or mixed-in components.
  48783. isDefault = name in this.defaultComponents;
  48784. isMixedIn = isComponentMixedIn(name, this.mixinEls);
  48785. if (isDefault || isMixedIn) { return; }
  48786. component = this.components[name];
  48787. if (!component) { return; }
  48788. // Wait for component to initialize.
  48789. if (!component.initialized) {
  48790. this.addEventListener('componentinitialized', function tryRemoveLater (evt) {
  48791. if (evt.detail.name !== name) { return; }
  48792. this.removeComponent(name);
  48793. this.removeEventListener('componentinitialized', tryRemoveLater);
  48794. });
  48795. return;
  48796. }
  48797. component.pause();
  48798. component.remove();
  48799. delete this.components[name];
  48800. this.emit('componentremoved', {
  48801. id: component.id,
  48802. name: name
  48803. });
  48804. },
  48805. writable: window.debug
  48806. },
  48807. /**
  48808. * Initialize or update all components.
  48809. * Build data using initial components, defined attributes, mixins, and defaults.
  48810. * Update default components before the rest.
  48811. *
  48812. * @member {function} getExtraComponents - Can be implemented to include component data
  48813. * from other sources (e.g., implemented by primitives).
  48814. */
  48815. updateComponents: {
  48816. value: function () {
  48817. var componentsToUpdate = {};
  48818. var extraComponents = {};
  48819. var i;
  48820. var self = this;
  48821. if (!this.hasLoaded) { return; }
  48822. // Gather mixin-defined components.
  48823. getMixedInComponents(this).forEach(addComponent);
  48824. // Gather from extra initial component data if defined (e.g., primitives).
  48825. if (this.getExtraComponents) {
  48826. extraComponents = this.getExtraComponents();
  48827. Object.keys(extraComponents).forEach(addComponent);
  48828. }
  48829. // Gather entity-defined components.
  48830. for (i = 0; i < this.attributes.length; ++i) {
  48831. addComponent(this.attributes[i].name);
  48832. }
  48833. // Initialze or update default components first.
  48834. Object.keys(this.defaultComponents).forEach(doUpdateComponent);
  48835. // Initialize or update rest of components.
  48836. Object.keys(componentsToUpdate).forEach(doUpdateComponent);
  48837. /**
  48838. * Add component to the list to initialize or update.
  48839. */
  48840. function addComponent (componentName) {
  48841. var name = componentName.split(MULTIPLE_COMPONENT_DELIMITER)[0];
  48842. if (!COMPONENTS[name]) { return; }
  48843. componentsToUpdate[componentName] = true;
  48844. }
  48845. /**
  48846. * Get component data and initialize or update component.
  48847. */
  48848. function doUpdateComponent (name) {
  48849. // Build defined component data.
  48850. var data = mergeComponentData(self.getDOMAttribute(name), extraComponents[name]);
  48851. delete componentsToUpdate[name];
  48852. self.updateComponent(name, data);
  48853. }
  48854. },
  48855. writable: window.debug
  48856. },
  48857. /**
  48858. * Initialize, update, or remove a single component.
  48859. *
  48860. * When initializing, we set the component on `this.components`.
  48861. *
  48862. * @param {string} attr - Component name.
  48863. * @param {object} attrValue - Value of the DOM attribute.
  48864. * @param {boolean} clobber - If new attrValue completely replaces previous properties.
  48865. */
  48866. updateComponent: {
  48867. value: function (attr, attrValue, clobber) {
  48868. var component = this.components[attr];
  48869. var isDefault = attr in this.defaultComponents;
  48870. if (component) {
  48871. // Remove component.
  48872. if (attrValue === null && !isDefault) {
  48873. this.removeComponent(attr);
  48874. return;
  48875. }
  48876. // Component already initialized. Update component.
  48877. component.updateProperties(attrValue, clobber);
  48878. return;
  48879. }
  48880. // Component not yet initialized. Initialize component.
  48881. this.initComponent(attr, attrValue, false);
  48882. }
  48883. },
  48884. /**
  48885. * If `attr` is a component name, detach the component from the entity.
  48886. *
  48887. * If `propertyName` is given, reset the component property value to its default.
  48888. *
  48889. * @param {string} attr - Attribute name, which could also be a component name.
  48890. * @param {string} propertyName - Component prop name, if resetting an individual prop.
  48891. */
  48892. removeAttribute: {
  48893. value: function (attr, propertyName) {
  48894. var component = this.components[attr];
  48895. // Remove component.
  48896. if (component && propertyName === undefined) {
  48897. this.setEntityAttribute(attr, undefined, null);
  48898. // Do not remove the component from the DOM if default component.
  48899. if (this.components[attr]) { return; }
  48900. }
  48901. // Reset component property value.
  48902. if (component && propertyName !== undefined) {
  48903. component.resetProperty(propertyName);
  48904. return;
  48905. }
  48906. // Remove mixins.
  48907. if (attr === 'mixin') {
  48908. this.mixinUpdate('');
  48909. }
  48910. window.HTMLElement.prototype.removeAttribute.call(this, attr);
  48911. }
  48912. },
  48913. /**
  48914. * Start dynamic behavior associated with entity such as dynamic components and animations.
  48915. * Tell all children entities to also play.
  48916. */
  48917. play: {
  48918. value: function () {
  48919. var components = this.components;
  48920. var componentKeys = Object.keys(components);
  48921. // Already playing.
  48922. if (this.isPlaying || !this.hasLoaded) { return; }
  48923. this.isPlaying = true;
  48924. // Wake up all components.
  48925. componentKeys.forEach(function playComponent (key) {
  48926. components[key].play();
  48927. });
  48928. // Tell all child entities to play.
  48929. this.getChildEntities().forEach(function play (entity) {
  48930. entity.play();
  48931. });
  48932. this.emit('play');
  48933. },
  48934. writable: true
  48935. },
  48936. /**
  48937. * Pause dynamic behavior associated with entity such as dynamic components and animations.
  48938. * Tell all children entities to also pause.
  48939. */
  48940. pause: {
  48941. value: function () {
  48942. var components = this.components;
  48943. var componentKeys = Object.keys(components);
  48944. if (!this.isPlaying) { return; }
  48945. this.isPlaying = false;
  48946. // Sleep all components.
  48947. componentKeys.forEach(function pauseComponent (key) {
  48948. components[key].pause();
  48949. });
  48950. // Tell all child entities to pause.
  48951. this.getChildEntities().forEach(function pause (obj) {
  48952. obj.pause();
  48953. });
  48954. this.emit('pause');
  48955. },
  48956. writable: true
  48957. },
  48958. /**
  48959. * Deals with updates on entity-specific attributes (i.e., components and mixins).
  48960. *
  48961. * @param {string} attr
  48962. * @param {string} oldVal
  48963. * @param {string|object} newVal
  48964. */
  48965. setEntityAttribute: {
  48966. value: function (attr, oldVal, newVal) {
  48967. if (COMPONENTS[attr] || this.components[attr]) {
  48968. this.updateComponent(attr, newVal);
  48969. return;
  48970. }
  48971. if (attr === 'mixin') {
  48972. this.mixinUpdate(newVal, oldVal);
  48973. return;
  48974. }
  48975. }
  48976. },
  48977. mixinUpdate: {
  48978. value: function (newMixins, oldMixins) {
  48979. oldMixins = oldMixins || this.getAttribute('mixin');
  48980. this.updateMixins(newMixins, oldMixins);
  48981. this.updateStateMixins(newMixins, oldMixins);
  48982. this.updateComponents();
  48983. }
  48984. },
  48985. /**
  48986. * setAttribute can:
  48987. *
  48988. * 1. Set a single property of a multi-property component.
  48989. * 2. Set multiple properties of a multi-property component.
  48990. * 3. Replace properties of a multi-property component.
  48991. * 4. Set a value for a single-property component, mixin, or normal HTML attribute.
  48992. *
  48993. * @param {string} attrName - Component or attribute name.
  48994. * @param {*} arg1 - Can be a value, property name, CSS-style property string, or
  48995. * object of properties.
  48996. * @param {*|bool} arg2 - If arg1 is a property name, this should be a value. Otherwise,
  48997. * it is a boolean indicating whether to clobber previous values (defaults to false).
  48998. */
  48999. setAttribute: {
  49000. value: function (attrName, arg1, arg2) {
  49001. var newAttrValue;
  49002. var clobber;
  49003. var componentName;
  49004. var delimiterIndex;
  49005. var isDebugMode;
  49006. delimiterIndex = attrName.indexOf(MULTIPLE_COMPONENT_DELIMITER);
  49007. componentName = delimiterIndex > 0 ? attrName.substring(0, delimiterIndex) : attrName;
  49008. // Not a component.
  49009. if (!COMPONENTS[componentName]) {
  49010. normalSetAttribute(this, attrName, arg1);
  49011. return;
  49012. }
  49013. // Initialize component first if not yet initialized.
  49014. if (!this.components[attrName] && this.hasAttribute(attrName)) {
  49015. this.updateComponent(attrName,
  49016. window.HTMLElement.prototype.getAttribute.call(this, attrName));
  49017. }
  49018. // Determine new attributes from the arguments
  49019. if (typeof arg2 !== 'undefined' &&
  49020. typeof arg1 === 'string' &&
  49021. arg1.length > 0 &&
  49022. typeof utils.styleParser.parse(arg1) === 'string') {
  49023. // Update a single property of a multi-property component
  49024. newAttrValue = {};
  49025. newAttrValue[arg1] = arg2;
  49026. clobber = false;
  49027. } else {
  49028. // Update with a value, object, or CSS-style property string, with the possiblity
  49029. // of clobbering previous values.
  49030. newAttrValue = arg1;
  49031. clobber = (arg2 === true);
  49032. }
  49033. // Update component
  49034. this.updateComponent(attrName, newAttrValue, clobber);
  49035. // In debug mode, write component data up to the DOM.
  49036. isDebugMode = this.sceneEl && this.sceneEl.getAttribute('debug');
  49037. if (isDebugMode) { this.components[attrName].flushToDOM(); }
  49038. /**
  49039. * Update a non-component attribute.
  49040. * >> setAttribute('id', 'myEntity')
  49041. */
  49042. function normalSetAttribute (el, attrName, value) {
  49043. ANode.prototype.setAttribute.call(el, attrName, value);
  49044. if (attrName === 'mixin') { el.mixinUpdate(value); }
  49045. }
  49046. },
  49047. writable: window.debug
  49048. },
  49049. /**
  49050. * Reflect component data in the DOM (as seen from the browser DOM Inspector).
  49051. *
  49052. * @param {bool} recursive - Also flushToDOM on the children.
  49053. **/
  49054. flushToDOM: {
  49055. value: function (recursive) {
  49056. var components = this.components;
  49057. var defaultComponents = this.defaultComponents;
  49058. var child;
  49059. var children = this.children;
  49060. var i;
  49061. // Flush entity's components to DOM.
  49062. Object.keys(components).forEach(function flushComponent (componentName) {
  49063. components[componentName].flushToDOM(componentName in defaultComponents);
  49064. });
  49065. // Recurse.
  49066. if (!recursive) { return; }
  49067. for (i = 0; i < children.length; ++i) {
  49068. child = children[i];
  49069. if (!child.flushToDOM) { continue; }
  49070. child.flushToDOM(recursive);
  49071. }
  49072. }
  49073. },
  49074. /**
  49075. * If `attr` is a component, returns ALL component data including applied mixins and
  49076. * defaults.
  49077. *
  49078. * If `attr` is not a component, fall back to HTML getAttribute.
  49079. *
  49080. * @param {string} attr
  49081. * @returns {object|string} Object if component, else string.
  49082. */
  49083. getAttribute: {
  49084. value: function (attr) {
  49085. // If component, return component data.
  49086. var component = this.components[attr];
  49087. if (component) { return component.data; }
  49088. return window.HTMLElement.prototype.getAttribute.call(this, attr);
  49089. },
  49090. writable: window.debug
  49091. },
  49092. /**
  49093. * `getAttribute` used to be `getDOMAttribute` and `getComputedAttribute` used to be
  49094. * what `getAttribute` is now. Now legacy code.
  49095. *
  49096. * @param {string} attr
  49097. * @returns {object|string} Object if component, else string.
  49098. */
  49099. getComputedAttribute: {
  49100. value: function (attr) {
  49101. warn('`getComputedAttribute` is deprecated. Use `getAttribute` instead.');
  49102. return this.getAttribute(attr);
  49103. }
  49104. },
  49105. /**
  49106. * If `attr` is a component, returns JUST the component data defined on the entity.
  49107. * Like a partial version of `getComputedAttribute` as returned component data
  49108. * does not include applied mixins or defaults.
  49109. *
  49110. * If `attr` is not a component, fall back to HTML getAttribute.
  49111. *
  49112. * @param {string} attr
  49113. * @returns {object|string} Object if component, else string.
  49114. */
  49115. getDOMAttribute: {
  49116. value: function (attr) {
  49117. // If cached value exists, return partial component data.
  49118. var component = this.components[attr];
  49119. if (component) { return component.attrValue; }
  49120. return window.HTMLElement.prototype.getAttribute.call(this, attr);
  49121. },
  49122. writable: window.debug
  49123. },
  49124. addState: {
  49125. value: function (state) {
  49126. if (this.is(state)) { return; }
  49127. this.states.push(state);
  49128. this.mapStateMixins(state, bind(this.registerMixin, this));
  49129. this.emit('stateadded', {state: state});
  49130. }
  49131. },
  49132. removeState: {
  49133. value: function (state) {
  49134. var stateIndex = this.states.indexOf(state);
  49135. if (stateIndex === -1) { return; }
  49136. this.states.splice(stateIndex, 1);
  49137. this.mapStateMixins(state, bind(this.unregisterMixin, this));
  49138. this.emit('stateremoved', {state: state});
  49139. }
  49140. },
  49141. /**
  49142. * Checks if the element is in a given state. e.g. el.is('alive');
  49143. * @type {string} state - Name of the state we want to check
  49144. */
  49145. is: {
  49146. value: function (state) {
  49147. return this.states.indexOf(state) !== -1;
  49148. }
  49149. }
  49150. });
  49151. /**
  49152. * Check if a component is *defined* for an entity, including defaults and mixins.
  49153. * Does not check whether the component has been *initialized* for an entity.
  49154. *
  49155. * @param {string} el - Entity.
  49156. * @param {string} name - Component name.
  49157. * @returns {boolean}
  49158. */
  49159. function checkComponentDefined (el, name) {
  49160. // Check if default components contain the component.
  49161. if (el.defaultComponents[name] !== undefined) { return true; }
  49162. // Check if element contains the component.
  49163. if (el.components[name] && el.components[name].attrValue) { return true; }
  49164. return isComponentMixedIn(name, el.mixinEls);
  49165. }
  49166. function getMixedInComponents (entityEl) {
  49167. var components = [];
  49168. entityEl.mixinEls.forEach(function getMixedComponents (mixinEl) {
  49169. Object.keys(mixinEl.componentCache).forEach(addComponent);
  49170. function addComponent (key) {
  49171. components.push(key);
  49172. }
  49173. });
  49174. return components;
  49175. }
  49176. /**
  49177. * Check if any mixins contains a component.
  49178. *
  49179. * @param {string} name - Component name.
  49180. * @param {array} mixinEls - Array of <a-mixin>s.
  49181. */
  49182. function isComponentMixedIn (name, mixinEls) {
  49183. var i;
  49184. var inMixin = false;
  49185. for (i = 0; i < mixinEls.length; ++i) {
  49186. inMixin = mixinEls[i].hasAttribute(name);
  49187. if (inMixin) { break; }
  49188. }
  49189. return inMixin;
  49190. }
  49191. /**
  49192. * Given entity defined value, merge in extra data if necessary.
  49193. * Handle both single and multi-property components.
  49194. *
  49195. * @param {string} attrValue - Entity data.
  49196. * @param extraData - Entity data from another source to merge in.
  49197. */
  49198. function mergeComponentData (attrValue, extraData) {
  49199. // Extra data not defined, just return attrValue.
  49200. if (!extraData) { return attrValue; }
  49201. // Merge multi-property data.
  49202. if (extraData.constructor === Object) {
  49203. return utils.extend(extraData, utils.styleParser.parse(attrValue || {}));
  49204. }
  49205. // Return data, precendence to the defined value.
  49206. return attrValue || extraData;
  49207. }
  49208. AEntity = registerElement('a-entity', {
  49209. prototype: proto
  49210. });
  49211. module.exports = AEntity;
  49212. },{"../lib/three":174,"../utils/":197,"./a-node":124,"./a-register-element":125,"./component":126}],123:[function(_dereq_,module,exports){
  49213. var ANode = _dereq_('./a-node');
  49214. var registerElement = _dereq_('./a-register-element').registerElement;
  49215. var components = _dereq_('./component').components;
  49216. var MULTIPLE_COMPONENT_DELIMITER = '__';
  49217. /**
  49218. * @member {object} componentCache - Cache of pre-parsed values. An object where the keys
  49219. * are component names and the values are already parsed by the component.
  49220. */
  49221. module.exports = registerElement('a-mixin', {
  49222. prototype: Object.create(ANode.prototype, {
  49223. createdCallback: {
  49224. value: function () {
  49225. this.componentCache = {};
  49226. this.id = this.getAttribute('id');
  49227. }
  49228. },
  49229. attributeChangedCallback: {
  49230. value: function (attr, oldVal, newVal) {
  49231. this.cacheAttribute(attr, newVal);
  49232. }
  49233. },
  49234. attachedCallback: {
  49235. value: function () {
  49236. this.sceneEl = this.closestScene();
  49237. this.cacheAttributes();
  49238. this.updateEntities();
  49239. this.load();
  49240. }
  49241. },
  49242. /**
  49243. * setAttribute that parses and caches component values.
  49244. */
  49245. setAttribute: {
  49246. value: function (attr, value) {
  49247. this.cacheAttribute(attr, value);
  49248. window.HTMLElement.prototype.setAttribute.call(this, attr, value);
  49249. }
  49250. },
  49251. /**
  49252. * If `attr` is a component, then parse the value using the schema and store it.
  49253. */
  49254. cacheAttribute: {
  49255. value: function (attr, value) {
  49256. var componentName = attr.split(MULTIPLE_COMPONENT_DELIMITER)[0];
  49257. var component = components[componentName];
  49258. if (!component) { return; }
  49259. if (value === undefined) {
  49260. value = window.HTMLElement.prototype.getAttribute.call(this, attr);
  49261. }
  49262. this.componentCache[attr] = component.parseAttrValueForCache(value);
  49263. }
  49264. },
  49265. /**
  49266. * If `attr` is a component, then grab pre-parsed value from the cache.
  49267. * Else do a normal getAttribute.
  49268. */
  49269. getAttribute: {
  49270. value: function (attr) {
  49271. return this.componentCache[attr] ||
  49272. window.HTMLElement.prototype.getAttribute.call(this, attr);
  49273. }
  49274. },
  49275. /**
  49276. * Parse and cache every component defined on the mixin.
  49277. */
  49278. cacheAttributes: {
  49279. value: function () {
  49280. var attributes = this.attributes;
  49281. var attrName;
  49282. var i;
  49283. for (i = 0; i < attributes.length; i++) {
  49284. attrName = attributes[i].name;
  49285. this.cacheAttribute(attrName);
  49286. }
  49287. }
  49288. },
  49289. /**
  49290. * For entities that already have been loaded by the time the mixin was attached, tell
  49291. * those entities to register the mixin and refresh their component data.
  49292. */
  49293. updateEntities: {
  49294. value: function () {
  49295. if (!this.sceneEl) { return; }
  49296. var entities = this.sceneEl.querySelectorAll('[mixin~=' + this.id + ']');
  49297. for (var i = 0; i < entities.length; i++) {
  49298. var entity = entities[i];
  49299. if (!entity.hasLoaded) { continue; }
  49300. entity.registerMixin(this.id);
  49301. Object.keys(this.componentCache).forEach(function updateComponent (componentName) {
  49302. entity.updateComponent(componentName);
  49303. });
  49304. }
  49305. }
  49306. }
  49307. })
  49308. });
  49309. },{"./a-node":124,"./a-register-element":125,"./component":126}],124:[function(_dereq_,module,exports){
  49310. /* global MutationObserver */
  49311. var registerElement = _dereq_('./a-register-element').registerElement;
  49312. var isNode = _dereq_('./a-register-element').isNode;
  49313. var utils = _dereq_('../utils/');
  49314. var bind = utils.bind;
  49315. var warn = utils.debug('core:a-node:warn');
  49316. /**
  49317. * Base class for A-Frame that manages loading of objects.
  49318. *
  49319. * Nodes can be modified using mixins.
  49320. * Nodes emit a `loaded` event when they and their children have initialized.
  49321. */
  49322. module.exports = registerElement('a-node', {
  49323. prototype: Object.create(window.HTMLElement.prototype, {
  49324. createdCallback: {
  49325. value: function () {
  49326. this.hasLoaded = false;
  49327. this.isNode = true;
  49328. this.mixinEls = [];
  49329. this.mixinObservers = {};
  49330. },
  49331. writable: window.debug
  49332. },
  49333. attachedCallback: {
  49334. value: function () {
  49335. var mixins;
  49336. this.sceneEl = this.closestScene();
  49337. if (!this.sceneEl) {
  49338. warn('You are attempting to attach <' + this.tagName + '> outside of an A-Frame ' +
  49339. 'scene. Append this element to `<a-scene>` instead.');
  49340. }
  49341. this.hasLoaded = false;
  49342. this.emit('nodeready', {}, false);
  49343. mixins = this.getAttribute('mixin');
  49344. if (mixins) { this.updateMixins(mixins); }
  49345. },
  49346. writable: window.debug
  49347. },
  49348. attributeChangedCallback: {
  49349. value: function (attr, oldVal, newVal) {
  49350. if (attr === 'mixin') { this.updateMixins(newVal, oldVal); }
  49351. }
  49352. },
  49353. /**
  49354. * Returns the first scene by traversing up the tree starting from and
  49355. * including receiver element.
  49356. */
  49357. closestScene: {
  49358. value: function closest () {
  49359. var element = this;
  49360. while (element) {
  49361. if (element.isScene) { break; }
  49362. element = element.parentElement;
  49363. }
  49364. return element;
  49365. }
  49366. },
  49367. /**
  49368. * Returns first element matching a selector by traversing up the tree starting
  49369. * from and including receiver element.
  49370. *
  49371. * @param {string} selector - Selector of element to find.
  49372. */
  49373. closest: {
  49374. value: function closest (selector) {
  49375. var matches = this.matches || this.mozMatchesSelector ||
  49376. this.msMatchesSelector || this.oMatchesSelector || this.webkitMatchesSelector;
  49377. var element = this;
  49378. while (element) {
  49379. if (matches.call(element, selector)) { break; }
  49380. element = element.parentElement;
  49381. }
  49382. return element;
  49383. }
  49384. },
  49385. detachedCallback: {
  49386. value: function () {
  49387. this.hasLoaded = false;
  49388. }
  49389. },
  49390. /**
  49391. * Wait for children to load, if any.
  49392. * Then emit `loaded` event and set `hasLoaded`.
  49393. */
  49394. load: {
  49395. value: function (cb, childFilter) {
  49396. var children;
  49397. var childrenLoaded;
  49398. var self = this;
  49399. if (this.hasLoaded) { return; }
  49400. // Default to waiting for all nodes.
  49401. childFilter = childFilter || isNode;
  49402. // Wait for children to load (if any), then load.
  49403. children = this.getChildren();
  49404. childrenLoaded = children.filter(childFilter).map(function (child) {
  49405. return new Promise(function waitForLoaded (resolve) {
  49406. if (child.hasLoaded) { return resolve(); }
  49407. child.addEventListener('loaded', resolve);
  49408. });
  49409. });
  49410. Promise.all(childrenLoaded).then(function emitLoaded () {
  49411. self.hasLoaded = true;
  49412. if (cb) { cb(); }
  49413. self.emit('loaded', {}, false);
  49414. });
  49415. },
  49416. writable: true
  49417. },
  49418. getChildren: {
  49419. value: function () {
  49420. return Array.prototype.slice.call(this.children, 0);
  49421. }
  49422. },
  49423. /**
  49424. * Remove old mixins and mixin listeners.
  49425. * Add new mixins and mixin listeners.
  49426. */
  49427. updateMixins: {
  49428. value: function (newMixins, oldMixins) {
  49429. var newMixinIds = newMixins ? newMixins.trim().split(/\s+/) : [];
  49430. var oldMixinIds = oldMixins ? oldMixins.trim().split(/\s+/) : [];
  49431. // Unregister old mixins.
  49432. oldMixinIds.filter(function (i) {
  49433. return newMixinIds.indexOf(i) < 0;
  49434. }).forEach(bind(this.unregisterMixin, this));
  49435. // Register new mixins.
  49436. this.mixinEls = [];
  49437. newMixinIds.forEach(bind(this.registerMixin, this));
  49438. }
  49439. },
  49440. registerMixin: {
  49441. value: function (mixinId) {
  49442. if (!this.sceneEl) { return; }
  49443. var mixinEl = this.sceneEl.querySelector('a-mixin#' + mixinId);
  49444. if (!mixinEl) { return; }
  49445. this.attachMixinListener(mixinEl);
  49446. this.mixinEls.push(mixinEl);
  49447. }
  49448. },
  49449. setAttribute: {
  49450. value: function (attr, newValue) {
  49451. if (attr === 'mixin') { this.updateMixins(newValue); }
  49452. window.HTMLElement.prototype.setAttribute.call(this, attr, newValue);
  49453. }
  49454. },
  49455. unregisterMixin: {
  49456. value: function (mixinId) {
  49457. var mixinEls = this.mixinEls;
  49458. var mixinEl;
  49459. var i;
  49460. for (i = 0; i < mixinEls.length; ++i) {
  49461. mixinEl = mixinEls[i];
  49462. if (mixinId === mixinEl.id) {
  49463. mixinEls.splice(i, 1);
  49464. break;
  49465. }
  49466. }
  49467. this.removeMixinListener(mixinId);
  49468. }
  49469. },
  49470. removeMixinListener: {
  49471. value: function (mixinId) {
  49472. var observer = this.mixinObservers[mixinId];
  49473. if (!observer) { return; }
  49474. observer.disconnect();
  49475. this.mixinObservers[mixinId] = null;
  49476. }
  49477. },
  49478. attachMixinListener: {
  49479. value: function (mixinEl) {
  49480. var self = this;
  49481. var mixinId = mixinEl.id;
  49482. var currentObserver = this.mixinObservers[mixinId];
  49483. if (!mixinEl) { return; }
  49484. if (currentObserver) { return; }
  49485. var observer = new MutationObserver(function (mutations) {
  49486. var attr = mutations[0].attributeName;
  49487. self.handleMixinUpdate(attr);
  49488. });
  49489. var config = { attributes: true };
  49490. observer.observe(mixinEl, config);
  49491. this.mixinObservers[mixinId] = observer;
  49492. }
  49493. },
  49494. handleMixinUpdate: {
  49495. value: function () { /* no-op */ }
  49496. },
  49497. /**
  49498. * Emits a DOM event.
  49499. *
  49500. * @param {String} name
  49501. * Name of event (use a space-delimited string for multiple events).
  49502. * @param {Object=} [detail={}]
  49503. * Custom data to pass as `detail` to the event.
  49504. * @param {Boolean=} [bubbles=true]
  49505. * Whether the event should bubble.
  49506. * @param {Object=} [extraData]
  49507. * Extra data to pass to the event, if any.
  49508. */
  49509. emit: {
  49510. value: function (name, detail, bubbles, extraData) {
  49511. var self = this;
  49512. detail = detail || {};
  49513. if (bubbles === undefined) { bubbles = true; }
  49514. var data = { bubbles: !!bubbles, detail: detail };
  49515. if (extraData) { utils.extend(data, extraData); }
  49516. return name.split(' ').map(function (eventName) {
  49517. return utils.fireEvent(self, eventName, data);
  49518. });
  49519. },
  49520. writable: window.debug
  49521. },
  49522. /**
  49523. * Returns a closure that emits a DOM event.
  49524. *
  49525. * @param {String} name
  49526. * Name of event (use a space-delimited string for multiple events).
  49527. * @param {Object} detail
  49528. * Custom data (optional) to pass as `detail` if the event is to
  49529. * be a `CustomEvent`.
  49530. * @param {Boolean} bubbles
  49531. * Whether the event should be bubble.
  49532. */
  49533. emitter: {
  49534. value: function (name, detail, bubbles) {
  49535. var self = this;
  49536. return function () {
  49537. self.emit(name, detail, bubbles);
  49538. };
  49539. }
  49540. }
  49541. })
  49542. });
  49543. },{"../utils/":197,"./a-register-element":125}],125:[function(_dereq_,module,exports){
  49544. /*
  49545. ------------------------------------------------------------
  49546. ------------- WARNING WARNING WARNING WARNING --------------
  49547. ------------------------------------------------------------
  49548. This module wraps registerElement to deal with components that inherit from
  49549. `ANode` and `AEntity`. It's a pass through in any other case.
  49550. It wraps some of the prototype methods of the created element to make sure
  49551. that the corresponding functions in the base prototypes (`AEntity` and `ANode`)
  49552. are also invoked. The method in the base prototype is always called before the one
  49553. in the derived prototype.
  49554. */
  49555. // Polyfill `document.registerElement`.
  49556. _dereq_('document-register-element');
  49557. var ANode; // Must declare before AEntity. Initialized at the bottom.
  49558. var AEntity;
  49559. var knownTags = module.exports.knownTags = {};
  49560. function addTagName (tagName) {
  49561. knownTags[tagName.toLowerCase()] = true;
  49562. }
  49563. /**
  49564. * Return whether the element type is one of our known registered ones.
  49565. *
  49566. * @param {string} node - The name of the tag to register.
  49567. * @returns {boolean} Whether the tag name matches that of our registered custom elements.
  49568. */
  49569. module.exports.isNode = function (node) {
  49570. return node.tagName.toLowerCase() in knownTags || node.isNode;
  49571. };
  49572. /**
  49573. * @param {string} tagName - The name of the tag to register.
  49574. * @param {object} obj - The prototype of the new element.
  49575. * @returns {object} The prototype of the new element.
  49576. */
  49577. module.exports.registerElement = function (tagName, obj) {
  49578. var proto = Object.getPrototypeOf(obj.prototype);
  49579. var newObj = obj;
  49580. var isANode = ANode && proto === ANode.prototype;
  49581. var isAEntity = AEntity && proto === AEntity.prototype;
  49582. if (isANode || isAEntity) { addTagName(tagName); }
  49583. // Wrap if element inherits from `ANode`.
  49584. if (isANode) {
  49585. newObj = wrapANodeMethods(obj.prototype);
  49586. newObj = {prototype: Object.create(proto, newObj)};
  49587. }
  49588. // Wrap if element inherits from `AEntity`.
  49589. if (isAEntity) {
  49590. newObj = wrapAEntityMethods(obj.prototype);
  49591. newObj = {prototype: Object.create(proto, newObj)};
  49592. }
  49593. return document.registerElement(tagName, newObj);
  49594. };
  49595. /**
  49596. * Wrap some obj methods to call those on `ANode` base prototype.
  49597. *
  49598. * @param {object} obj - Object that contains the methods that will be wrapped.
  49599. * @return {object} An object with the same properties as the input parameter but
  49600. * with some of methods wrapped.
  49601. */
  49602. function wrapANodeMethods (obj) {
  49603. var newObj = {};
  49604. var ANodeMethods = [
  49605. 'attachedCallback',
  49606. 'attributeChangedCallback',
  49607. 'createdCallback'
  49608. ];
  49609. wrapMethods(newObj, ANodeMethods, obj, ANode.prototype);
  49610. copyProperties(obj, newObj);
  49611. return newObj;
  49612. }
  49613. /**
  49614. * This wraps some of the obj methods to call those on `AEntity` base prototype.
  49615. *
  49616. * @param {object} obj - The objects that contains the methods that will be wrapped.
  49617. * @return {object} - An object with the same properties as the input parameter but
  49618. * with some of methods wrapped.
  49619. */
  49620. function wrapAEntityMethods (obj) {
  49621. var newObj = {};
  49622. var ANodeMethods = [
  49623. 'attachedCallback',
  49624. 'attributeChangedCallback',
  49625. 'createdCallback'
  49626. ];
  49627. var AEntityMethods = [
  49628. 'attachedCallback',
  49629. 'attributeChangedCallback',
  49630. 'createdCallback',
  49631. 'detachedCallback'
  49632. ];
  49633. wrapMethods(newObj, ANodeMethods, obj, ANode.prototype);
  49634. wrapMethods(newObj, AEntityMethods, obj, AEntity.prototype);
  49635. // Copies the remaining properties into the new object.
  49636. copyProperties(obj, newObj);
  49637. return newObj;
  49638. }
  49639. /**
  49640. * Wrap a list a methods to ensure that those in the base prototype are called
  49641. * before the derived one.
  49642. *
  49643. * @param {object} targetObj - Object that will contain the wrapped methods.
  49644. * @param {array} methodList - List of methods from the derivedObj that will be wrapped.
  49645. * @param {object} derivedObject - Object that inherits from the baseObj.
  49646. * @param {object} baseObj - Object that derivedObj inherits from.
  49647. */
  49648. function wrapMethods (targetObj, methodList, derivedObj, baseObj) {
  49649. methodList.forEach(function (methodName) {
  49650. wrapMethod(targetObj, methodName, derivedObj, baseObj);
  49651. });
  49652. }
  49653. module.exports.wrapMethods = wrapMethods;
  49654. /**
  49655. * Wrap one method to ensure that the one in the base prototype is called before
  49656. * the one in the derived one.
  49657. *
  49658. * @param {object} obj - Object that will contain the wrapped method.
  49659. * @param {string} methodName - The name of the method that will be wrapped.
  49660. * @param {object} derivedObject - Object that inherits from the baseObj.
  49661. * @param {object} baseObj - Object that derivedObj inherits from.
  49662. */
  49663. function wrapMethod (obj, methodName, derivedObj, baseObj) {
  49664. var derivedMethod = derivedObj[methodName];
  49665. var baseMethod = baseObj[methodName];
  49666. // Derived prototype does not define method, no need to wrap.
  49667. if (!derivedMethod || !baseMethod) { return; }
  49668. // Derived prototype doesn't override the one in the base one, no need to wrap.
  49669. if (derivedMethod === baseMethod) { return; }
  49670. // Wrap to ensure the base method is called before the one in the derived prototype.
  49671. obj[methodName] = {
  49672. value: function wrappedMethod () {
  49673. baseMethod.apply(this, arguments);
  49674. return derivedMethod.apply(this, arguments);
  49675. },
  49676. writable: window.debug
  49677. };
  49678. }
  49679. /**
  49680. * It copies the properties from source to destination object if they don't
  49681. * exist already.
  49682. *
  49683. * @param {object} source - The object where properties are copied from.
  49684. * @param {type} destination - The object where properties are copied to.
  49685. */
  49686. function copyProperties (source, destination) {
  49687. var props = Object.getOwnPropertyNames(source);
  49688. props.forEach(function (prop) {
  49689. var desc;
  49690. if (!destination[prop]) {
  49691. desc = Object.getOwnPropertyDescriptor(source, prop);
  49692. destination[prop] = {value: source[prop], writable: desc.writable};
  49693. }
  49694. });
  49695. }
  49696. ANode = _dereq_('./a-node');
  49697. AEntity = _dereq_('./a-entity');
  49698. },{"./a-entity":122,"./a-node":124,"document-register-element":11}],126:[function(_dereq_,module,exports){
  49699. /* global Node */
  49700. var schema = _dereq_('./schema');
  49701. var scenes = _dereq_('./scene/scenes');
  49702. var systems = _dereq_('./system');
  49703. var utils = _dereq_('../utils/');
  49704. var components = module.exports.components = {}; // Keep track of registered components.
  49705. var parseProperties = schema.parseProperties;
  49706. var parseProperty = schema.parseProperty;
  49707. var processSchema = schema.process;
  49708. var isSingleProp = schema.isSingleProperty;
  49709. var stringifyProperties = schema.stringifyProperties;
  49710. var stringifyProperty = schema.stringifyProperty;
  49711. var styleParser = utils.styleParser;
  49712. var warn = utils.debug('core:component:warn');
  49713. var aframeScript = document.currentScript;
  49714. var upperCaseRegExp = new RegExp('[A-Z]+');
  49715. /**
  49716. * Component class definition.
  49717. *
  49718. * Components configure appearance, modify behavior, or add functionality to
  49719. * entities. The behavior and appearance of an entity can be changed at runtime
  49720. * by adding, removing, or updating components. Entities do not share instances
  49721. * of components.
  49722. *
  49723. * @member {object} el - Reference to the entity element.
  49724. * @member {string} attrValue - Value of the corresponding HTML attribute.
  49725. * @member {object} data - Component data populated by parsing the
  49726. * mapped attribute of the component plus applying defaults and mixins.
  49727. */
  49728. var Component = module.exports.Component = function (el, attrValue, id) {
  49729. var self = this;
  49730. this.el = el;
  49731. this.id = id;
  49732. this.attrName = this.name + (id ? '__' + id : '');
  49733. this.initialized = false;
  49734. this.el.components[this.attrName] = this;
  49735. // Store component data from previous update call.
  49736. this.oldData = undefined;
  49737. // Last value passed to updateProperties.
  49738. this.previousAttrValue = undefined;
  49739. this.throttledEmitComponentChanged = utils.throttle(function emitComponentChange (oldData) {
  49740. el.emit('componentchanged', {
  49741. id: self.id,
  49742. name: self.name,
  49743. newData: self.data,
  49744. oldData: oldData
  49745. }, false);
  49746. }, 0);
  49747. this.updateProperties(attrValue);
  49748. };
  49749. Component.prototype = {
  49750. /**
  49751. * Contains the type schema and defaults for the data values.
  49752. * Data is coerced into the types of the values of the defaults.
  49753. */
  49754. schema: {},
  49755. /**
  49756. * Init handler. Similar to attachedCallback.
  49757. * Called during component initialization and is only run once.
  49758. * Components can use this to set initial state.
  49759. */
  49760. init: function () { /* no-op */ },
  49761. /**
  49762. * Update handler. Similar to attributeChangedCallback.
  49763. * Called whenever component's data changes.
  49764. * Also called on component initialization when the component receives initial data.
  49765. *
  49766. * @param {object} prevData - Previous attributes of the component.
  49767. */
  49768. update: function (prevData) { /* no-op */ },
  49769. updateSchema: undefined,
  49770. /**
  49771. * Tick handler.
  49772. * Called on each tick of the scene render loop.
  49773. * Affected by play and pause.
  49774. *
  49775. * @param {number} time - Scene tick time.
  49776. * @param {number} timeDelta - Difference in current render time and previous render time.
  49777. */
  49778. tick: undefined,
  49779. /**
  49780. * Tock handler.
  49781. * Called on each tock of the scene render loop.
  49782. * Affected by play and pause.
  49783. *
  49784. * @param {number} time - Scene tick time.
  49785. * @param {number} timeDelta - Difference in current render time and previous render time.
  49786. */
  49787. tock: undefined,
  49788. /**
  49789. * Called to start any dynamic behavior (e.g., animation, AI, events, physics).
  49790. */
  49791. play: function () { /* no-op */ },
  49792. /**
  49793. * Called to stop any dynamic behavior (e.g., animation, AI, events, physics).
  49794. */
  49795. pause: function () { /* no-op */ },
  49796. /**
  49797. * Remove handler. Similar to detachedCallback.
  49798. * Called whenever component is removed from the entity (i.e., removeAttribute).
  49799. * Components can use this to reset behavior on the entity.
  49800. */
  49801. remove: function () { /* no-op */ },
  49802. /**
  49803. * Parses each property based on property type.
  49804. * If component is single-property, then parses the single property value.
  49805. *
  49806. * @param {string} value - HTML attribute value.
  49807. * @param {boolean} silent - Suppress warning messages.
  49808. * @returns {object} Component data.
  49809. */
  49810. parse: function (value, silent) {
  49811. var schema = this.schema;
  49812. if (isSingleProp(schema)) { return parseProperty(value, schema); }
  49813. return parseProperties(styleParser.parse(value), schema, true, this.name, silent);
  49814. },
  49815. /**
  49816. * Stringify properties if necessary.
  49817. *
  49818. * Only called from `Entity.setAttribute` for properties whose parsers accept a non-string
  49819. * value (e.g., selector, vec3 property types).
  49820. *
  49821. * @param {object} data - Complete component data.
  49822. * @returns {string}
  49823. */
  49824. stringify: function (data) {
  49825. var schema = this.schema;
  49826. if (typeof data === 'string') { return data; }
  49827. if (isSingleProp(schema)) { return stringifyProperty(data, schema); }
  49828. data = stringifyProperties(data, schema);
  49829. return styleParser.stringify(data);
  49830. },
  49831. /**
  49832. * Returns a copy of data such that we don't expose the private this.data.
  49833. *
  49834. * @returns {object} data
  49835. */
  49836. getData: function () {
  49837. var data = this.data;
  49838. if (typeof data !== 'object') { return data; }
  49839. return utils.extend({}, data);
  49840. },
  49841. /**
  49842. * Update the cache of the pre-parsed attribute value.
  49843. *
  49844. * @param {string} value - New data.
  49845. * @param {boolean } clobber - Whether to wipe out and replace previous data.
  49846. */
  49847. updateCachedAttrValue: function (value, clobber) {
  49848. var attrValue = this.parseAttrValueForCache(value);
  49849. var isSinglePropSchema = isSingleProp(this.schema);
  49850. var property;
  49851. if (value === undefined) { return; }
  49852. // Merge new data with previous `attrValue` if updating and not clobbering.
  49853. if (!isSinglePropSchema && !clobber && this.attrValue) {
  49854. for (property in this.attrValue) {
  49855. if (!(property in attrValue)) {
  49856. attrValue[property] = this.attrValue[property];
  49857. }
  49858. }
  49859. }
  49860. this.attrValue = extendProperties({}, attrValue, isSinglePropSchema);
  49861. },
  49862. /**
  49863. * Given an HTML attribute value parses the string
  49864. * based on the component schema. To avoid double parsings of
  49865. * strings into strings we store the original instead
  49866. * of the parsed one
  49867. *
  49868. * @param {string} value - HTML attribute value
  49869. */
  49870. parseAttrValueForCache: function (value) {
  49871. var parsedValue;
  49872. if (typeof value !== 'string') { return value; }
  49873. if (isSingleProp(this.schema)) {
  49874. parsedValue = this.schema.parse(value);
  49875. /**
  49876. * To avoid bogus double parsings. Cached values will be parsed when building
  49877. * component data. For instance when parsing a src id to its url, we want to cache
  49878. * original string and not the parsed one (#monster -> models/monster.dae)
  49879. * so when building data we parse the expected value.
  49880. */
  49881. if (typeof parsedValue === 'string') { parsedValue = value; }
  49882. } else {
  49883. // Parse using the style parser to avoid double parsing of individual properties.
  49884. parsedValue = styleParser.parse(value);
  49885. }
  49886. return parsedValue;
  49887. },
  49888. /**
  49889. * Write cached attribute data to the entity DOM element.
  49890. *
  49891. * @param {boolean} isDefault - Whether component is a default component. Always flush for
  49892. * default components.
  49893. */
  49894. flushToDOM: function (isDefault) {
  49895. var attrValue = isDefault ? this.data : this.attrValue;
  49896. if (!attrValue) { return; }
  49897. window.HTMLElement.prototype.setAttribute.call(this.el, this.attrName,
  49898. this.stringify(attrValue));
  49899. },
  49900. /**
  49901. * Apply new component data if data has changed.
  49902. *
  49903. * @param {string} attrValue - HTML attribute value.
  49904. * If undefined, use the cached attribute value and continue updating properties.
  49905. * @param {boolean} clobber - The previous component data is overwritten by the atrrValue
  49906. */
  49907. updateProperties: function (attrValue, clobber) {
  49908. var el = this.el;
  49909. var isSinglePropSchema;
  49910. var skipTypeChecking;
  49911. var oldData = this.oldData;
  49912. // Just cache the attribute if the entity has not loaded
  49913. // Components are not initialized until the entity has loaded
  49914. if (!el.hasLoaded) {
  49915. this.updateCachedAttrValue(attrValue);
  49916. return;
  49917. }
  49918. isSinglePropSchema = isSingleProp(this.schema);
  49919. // Disable type checking if the passed attribute is an object and has not changed.
  49920. skipTypeChecking = attrValue !== null && typeof this.previousAttrValue === 'object' &&
  49921. attrValue === this.previousAttrValue;
  49922. // Cache previously passed attribute to decide if we skip type checking.
  49923. this.previousAttrValue = attrValue;
  49924. attrValue = this.parseAttrValueForCache(attrValue);
  49925. if (this.updateSchema) { this.updateSchema(this.buildData(attrValue, false, true)); }
  49926. this.data = this.buildData(attrValue, clobber, false, skipTypeChecking);
  49927. // Cache current attrValue for future updates.
  49928. this.updateCachedAttrValue(attrValue, clobber);
  49929. if (!this.initialized) {
  49930. // Component is being already initialized.
  49931. if (el.initializingComponents[this.name]) { return; }
  49932. // Prevent infinite loop in case of init method setting same component on the entity.
  49933. el.initializingComponents[this.name] = true;
  49934. // Initialize component.
  49935. this.init();
  49936. this.initialized = true;
  49937. delete el.initializingComponents[this.name];
  49938. // For oldData, pass empty object to multiple-prop schemas or object single-prop schema.
  49939. // Pass undefined to rest of types.
  49940. oldData = (!isSinglePropSchema ||
  49941. typeof parseProperty(undefined, this.schema) === 'object') ? {} : undefined;
  49942. // Store current data as previous data for future updates.
  49943. this.oldData = extendProperties({}, this.data, isSinglePropSchema);
  49944. this.update(oldData);
  49945. // Play the component if the entity is playing.
  49946. if (el.isPlaying) { this.play(); }
  49947. el.emit('componentinitialized', {
  49948. id: this.id,
  49949. name: this.name,
  49950. data: this.getData()
  49951. }, false);
  49952. } else {
  49953. // Don't update if properties haven't changed
  49954. if (utils.deepEqual(this.oldData, this.data)) { return; }
  49955. // Store current data as previous data for future updates.
  49956. this.oldData = extendProperties({}, this.data, isSinglePropSchema);
  49957. // Update component.
  49958. this.update(oldData);
  49959. // Limit event to fire once every 200ms.
  49960. this.throttledEmitComponentChanged(oldData);
  49961. }
  49962. },
  49963. /**
  49964. * Reset value of a property to the property's default value.
  49965. * If single-prop component, reset value to component's default value.
  49966. *
  49967. * @param {string} propertyName - Name of property to reset.
  49968. */
  49969. resetProperty: function (propertyName) {
  49970. if (isSingleProp(this.schema)) {
  49971. this.attrValue = undefined;
  49972. } else {
  49973. if (!(propertyName in this.attrValue)) { return; }
  49974. delete this.attrValue[propertyName];
  49975. }
  49976. this.updateProperties(this.attrValue);
  49977. },
  49978. /**
  49979. * Extend schema of component given a partial schema.
  49980. *
  49981. * Some components might want to mutate their schema based on certain properties.
  49982. * e.g., Material component changes its schema based on `shader` to account for different
  49983. * uniforms
  49984. *
  49985. * @param {object} schemaAddon - Schema chunk that extend base schema.
  49986. */
  49987. extendSchema: function (schemaAddon) {
  49988. // Clone base schema.
  49989. var extendedSchema = utils.extend({}, components[this.name].schema);
  49990. // Extend base schema with new schema chunk.
  49991. utils.extend(extendedSchema, schemaAddon);
  49992. this.schema = processSchema(extendedSchema);
  49993. this.el.emit('schemachanged', {component: this.name});
  49994. },
  49995. /**
  49996. * Builds component data from the current state of the entity, ultimately
  49997. * updating this.data.
  49998. *
  49999. * If the component was detached completely, set data to null.
  50000. *
  50001. * Precedence:
  50002. * 1. Defaults data
  50003. * 2. Mixin data.
  50004. * 3. Attribute data.
  50005. *
  50006. * Finally coerce the data to the types of the defaults.
  50007. *
  50008. * @param {object} newData - Element new data.
  50009. * @param {boolean} clobber - The previous data is completely replaced by the new one.
  50010. * @param {boolean} silent - Suppress warning messages.
  50011. * @param {boolean} skipTypeChecking - Skip type checking and cohercion.
  50012. * @return {object} The component data
  50013. */
  50014. buildData: function (newData, clobber, silent, skipTypeChecking) {
  50015. var componentDefined = newData !== undefined && newData !== null;
  50016. var data;
  50017. var defaultValue;
  50018. var keys;
  50019. var keysLength;
  50020. var mixinData;
  50021. var schema = this.schema;
  50022. var i;
  50023. var isSinglePropSchema = isSingleProp(schema);
  50024. var mixinEls = this.el.mixinEls;
  50025. var previousData;
  50026. // 1. Default values (lowest precendence).
  50027. if (isSinglePropSchema) {
  50028. // Clone default value if object so components don't share object.
  50029. data = typeof schema.default === 'object' ? utils.clone(schema.default) : schema.default;
  50030. } else {
  50031. // Preserve previously set properties if clobber not enabled.
  50032. previousData = !clobber && this.attrValue;
  50033. // Clone default value if object so components don't share object
  50034. data = typeof previousData === 'object' ? utils.clone(previousData) : {};
  50035. // Apply defaults.
  50036. for (i = 0, keys = Object.keys(schema), keysLength = keys.length; i < keysLength; i++) {
  50037. defaultValue = schema[keys[i]].default;
  50038. if (data[keys[i]] !== undefined) { continue; }
  50039. data[keys[i]] = defaultValue && defaultValue.constructor === Object
  50040. ? utils.clone(defaultValue)
  50041. : defaultValue;
  50042. }
  50043. }
  50044. // 2. Mixin values.
  50045. for (i = 0; i < mixinEls.length; i++) {
  50046. mixinData = mixinEls[i].getAttribute(this.attrName);
  50047. if (mixinData) {
  50048. data = extendProperties(data, mixinData, isSinglePropSchema);
  50049. }
  50050. }
  50051. // 3. Attribute values (highest precendence).
  50052. if (componentDefined) {
  50053. if (isSinglePropSchema) {
  50054. if (skipTypeChecking === true) { return newData; }
  50055. return parseProperty(newData, schema);
  50056. }
  50057. data = extendProperties(data, newData, isSinglePropSchema);
  50058. } else {
  50059. if (skipTypeChecking === true) { return data; }
  50060. // Parse and coerce using the schema.
  50061. if (isSinglePropSchema) { return parseProperty(data, schema); }
  50062. }
  50063. if (skipTypeChecking === true) { return data; }
  50064. return parseProperties(data, schema, undefined, this.name, silent);
  50065. }
  50066. };
  50067. // For testing.
  50068. if (window.debug) {
  50069. var registrationOrderWarnings = module.exports.registrationOrderWarnings = {};
  50070. }
  50071. /**
  50072. * Registers a component to A-Frame.
  50073. *
  50074. * @param {string} name - Component name.
  50075. * @param {object} definition - Component schema and lifecycle method handlers.
  50076. * @returns {object} Component.
  50077. */
  50078. module.exports.registerComponent = function (name, definition) {
  50079. var NewComponent;
  50080. var proto = {};
  50081. // Warning if component is statically registered after the scene.
  50082. if (document.currentScript && document.currentScript !== aframeScript) {
  50083. scenes.forEach(function checkPosition (sceneEl) {
  50084. // Okay to register component after the scene at runtime.
  50085. if (sceneEl.hasLoaded) { return; }
  50086. // Check that component is declared before the scene.
  50087. if (document.currentScript.compareDocumentPosition(sceneEl) ===
  50088. Node.DOCUMENT_POSITION_FOLLOWING) { return; }
  50089. warn('The component `' + name + '` was registered in a <script> tag after the scene. ' +
  50090. 'Component <script> tags in an HTML file should be declared *before* the scene ' +
  50091. 'such that the component is available to entities during scene initialization.');
  50092. // For testing.
  50093. if (window.debug) { registrationOrderWarnings[name] = true; }
  50094. });
  50095. }
  50096. if (upperCaseRegExp.test(name) === true) {
  50097. warn('The component name `' + name + '` contains uppercase characters, but ' +
  50098. 'HTML will ignore the capitalization of attribute names. ' +
  50099. 'Change the name to be lowercase: `' + name.toLowerCase() + '`');
  50100. }
  50101. if (name.indexOf('__') !== -1) {
  50102. throw new Error('The component name `' + name + '` is not allowed. ' +
  50103. 'The sequence __ (double underscore) is reserved to specify an id' +
  50104. ' for multiple components of the same type');
  50105. }
  50106. // Format definition object to prototype object.
  50107. Object.keys(definition).forEach(function (key) {
  50108. proto[key] = {
  50109. value: definition[key],
  50110. writable: true
  50111. };
  50112. });
  50113. if (components[name]) {
  50114. throw new Error('The component `' + name + '` has been already registered. ' +
  50115. 'Check that you are not loading two versions of the same component ' +
  50116. 'or two different components of the same name.');
  50117. }
  50118. NewComponent = function (el, attr, id) {
  50119. Component.call(this, el, attr, id);
  50120. };
  50121. NewComponent.prototype = Object.create(Component.prototype, proto);
  50122. NewComponent.prototype.name = name;
  50123. NewComponent.prototype.constructor = NewComponent;
  50124. NewComponent.prototype.system = systems && systems.systems[name];
  50125. NewComponent.prototype.play = wrapPlay(NewComponent.prototype.play);
  50126. NewComponent.prototype.pause = wrapPause(NewComponent.prototype.pause);
  50127. components[name] = {
  50128. Component: NewComponent,
  50129. dependencies: NewComponent.prototype.dependencies,
  50130. isSingleProp: isSingleProp(NewComponent.prototype.schema),
  50131. multiple: NewComponent.prototype.multiple,
  50132. parse: NewComponent.prototype.parse,
  50133. parseAttrValueForCache: NewComponent.prototype.parseAttrValueForCache,
  50134. schema: utils.extend(processSchema(NewComponent.prototype.schema, NewComponent.prototype.name)),
  50135. stringify: NewComponent.prototype.stringify,
  50136. type: NewComponent.prototype.type
  50137. };
  50138. return NewComponent;
  50139. };
  50140. /**
  50141. * Object extending with checking for single-property schema.
  50142. *
  50143. * @param dest - Destination object or value.
  50144. * @param source - Source object or value
  50145. * @param {boolean} isSinglePropSchema - Whether or not schema is only a single property.
  50146. * @returns Overridden object or value.
  50147. */
  50148. function extendProperties (dest, source, isSinglePropSchema) {
  50149. if (isSinglePropSchema && (source === null || typeof source !== 'object')) { return source; }
  50150. return utils.extend(dest, source);
  50151. }
  50152. /**
  50153. * Checks if a component has defined a method that needs to run every frame.
  50154. */
  50155. function hasBehavior (component) {
  50156. return component.tick || component.tock;
  50157. }
  50158. /**
  50159. * Wrapper for user defined pause method
  50160. * Pause component by removing tick behavior and calling user's pause method.
  50161. *
  50162. * @param pauseMethod {function} - user defined pause method
  50163. */
  50164. function wrapPause (pauseMethod) {
  50165. return function pause () {
  50166. var sceneEl = this.el.sceneEl;
  50167. if (!this.isPlaying) { return; }
  50168. pauseMethod.call(this);
  50169. this.isPlaying = false;
  50170. // Remove tick behavior.
  50171. if (!hasBehavior(this)) { return; }
  50172. sceneEl.removeBehavior(this);
  50173. };
  50174. }
  50175. /**
  50176. * Wrapper for user defined play method
  50177. * Play component by adding tick behavior and calling user's play method.
  50178. *
  50179. * @param playMethod {function} - user defined play method
  50180. *
  50181. */
  50182. function wrapPlay (playMethod) {
  50183. return function play () {
  50184. var sceneEl = this.el.sceneEl;
  50185. var shouldPlay = this.el.isPlaying && !this.isPlaying;
  50186. if (!this.initialized || !shouldPlay) { return; }
  50187. playMethod.call(this);
  50188. this.isPlaying = true;
  50189. // Add tick behavior.
  50190. if (!hasBehavior(this)) { return; }
  50191. sceneEl.addBehavior(this);
  50192. };
  50193. }
  50194. },{"../utils/":197,"./scene/scenes":132,"./schema":134,"./system":136}],127:[function(_dereq_,module,exports){
  50195. var schema = _dereq_('./schema');
  50196. var processSchema = schema.process;
  50197. var geometries = module.exports.geometries = {}; // Registered geometries.
  50198. var geometryNames = module.exports.geometryNames = []; // Names of registered geometries.
  50199. var THREE = _dereq_('../lib/three');
  50200. /**
  50201. * Geometry class definition.
  50202. *
  50203. * Geometries extend the geometry component API to create and register geometry types.
  50204. */
  50205. var Geometry = module.exports.Geometry = function () {};
  50206. Geometry.prototype = {
  50207. /**
  50208. * Contains the type schema and defaults for the data values.
  50209. * Data is coerced into the types of the values of the defaults.
  50210. */
  50211. schema: {},
  50212. /**
  50213. * Init handler. Similar to attachedCallback.
  50214. * Called during shader initialization and is only run once.
  50215. */
  50216. init: function (data) {
  50217. this.geometry = new THREE.Geometry();
  50218. return this.geometry;
  50219. },
  50220. /**
  50221. * Update handler. Similar to attributeChangedCallback.
  50222. * Called whenever the associated geometry data changes.
  50223. *
  50224. * @param {object} data - New geometry data.
  50225. */
  50226. update: function (data) { /* no-op */ }
  50227. };
  50228. /**
  50229. * Registers a geometry to A-Frame.
  50230. *
  50231. * @param {string} name - Geometry name.
  50232. * @param {object} definition - Geometry property and methods.
  50233. * @returns {object} Geometry.
  50234. */
  50235. module.exports.registerGeometry = function (name, definition) {
  50236. var NewGeometry;
  50237. var proto = {};
  50238. // Format definition object to prototype object.
  50239. Object.keys(definition).forEach(function expandDefinition (key) {
  50240. proto[key] = {
  50241. value: definition[key],
  50242. writable: true
  50243. };
  50244. });
  50245. if (geometries[name]) {
  50246. throw new Error('The geometry `' + name + '` has been already registered');
  50247. }
  50248. NewGeometry = function () { Geometry.call(this); };
  50249. NewGeometry.prototype = Object.create(Geometry.prototype, proto);
  50250. NewGeometry.prototype.name = name;
  50251. NewGeometry.prototype.constructor = NewGeometry;
  50252. geometries[name] = {
  50253. Geometry: NewGeometry,
  50254. schema: processSchema(NewGeometry.prototype.schema)
  50255. };
  50256. geometryNames.push(name);
  50257. return NewGeometry;
  50258. };
  50259. },{"../lib/three":174,"./schema":134}],128:[function(_dereq_,module,exports){
  50260. var coordinates = _dereq_('../utils/coordinates');
  50261. var debug = _dereq_('debug');
  50262. var error = debug('core:propertyTypes:warn');
  50263. var warn = debug('core:propertyTypes:warn');
  50264. var propertyTypes = module.exports.propertyTypes = {};
  50265. var nonCharRegex = /[,> .[\]:]/;
  50266. // Built-in property types.
  50267. registerPropertyType('audio', '', assetParse);
  50268. registerPropertyType('array', [], arrayParse, arrayStringify);
  50269. registerPropertyType('asset', '', assetParse);
  50270. registerPropertyType('boolean', false, boolParse);
  50271. registerPropertyType('color', '#FFF', defaultParse, defaultStringify);
  50272. registerPropertyType('int', 0, intParse);
  50273. registerPropertyType('number', 0, numberParse);
  50274. registerPropertyType('map', '', assetParse);
  50275. registerPropertyType('model', '', assetParse);
  50276. registerPropertyType('selector', null, selectorParse, selectorStringify);
  50277. registerPropertyType('selectorAll', null, selectorAllParse, selectorAllStringify);
  50278. registerPropertyType('src', '', srcParse);
  50279. registerPropertyType('string', '', defaultParse, defaultStringify);
  50280. registerPropertyType('time', 0, intParse);
  50281. registerPropertyType('vec2', {x: 0, y: 0}, vecParse, coordinates.stringify);
  50282. registerPropertyType('vec3', {x: 0, y: 0, z: 0}, vecParse, coordinates.stringify);
  50283. registerPropertyType('vec4', {x: 0, y: 0, z: 0, w: 0}, vecParse, coordinates.stringify);
  50284. /**
  50285. * Register a parser for re-use such that when someone uses `type` in the schema,
  50286. * `schema.process` will set the property `parse` and `stringify`.
  50287. *
  50288. * @param {string} type - Type name.
  50289. * @param [defaultValue=null] -
  50290. * Default value to use if component does not define default value.
  50291. * @param {function} [parse=defaultParse] - Parse string function.
  50292. * @param {function} [stringify=defaultStringify] - Stringify to DOM function.
  50293. */
  50294. function registerPropertyType (type, defaultValue, parse, stringify) {
  50295. if ('type' in propertyTypes) {
  50296. error('Property type ' + type + ' is already registered.');
  50297. return;
  50298. }
  50299. propertyTypes[type] = {
  50300. default: defaultValue,
  50301. parse: parse || defaultParse,
  50302. stringify: stringify || defaultStringify
  50303. };
  50304. }
  50305. module.exports.registerPropertyType = registerPropertyType;
  50306. function arrayParse (value) {
  50307. if (Array.isArray(value)) { return value; }
  50308. if (!value || typeof value !== 'string') { return []; }
  50309. return value.split(',').map(trim);
  50310. function trim (str) { return str.trim(); }
  50311. }
  50312. function arrayStringify (value) {
  50313. return value.join(', ');
  50314. }
  50315. /**
  50316. * For general assets.
  50317. *
  50318. * @param {string} value - Can either be `url(<value>)`, an ID selector to an asset, or
  50319. * just string.
  50320. * @returns {string} Parsed value from `url(<value>)`, src from `<someasset src>`, or
  50321. * just string.
  50322. */
  50323. function assetParse (value) {
  50324. var el;
  50325. var parsedUrl;
  50326. // If an element was provided (e.g. canvas or video), just return it.
  50327. if (typeof value !== 'string') { return value; }
  50328. // Wrapped `url()` in case of data URI.
  50329. parsedUrl = value.match(/\url\((.+)\)/);
  50330. if (parsedUrl) { return parsedUrl[1]; }
  50331. // ID.
  50332. if (value.charAt(0) === '#') {
  50333. el = document.getElementById(value.substring(1));
  50334. if (el) {
  50335. // Pass through media elements. If we have the elements, we don't have to call
  50336. // three.js loaders which would re-request the assets.
  50337. if (el.tagName === 'CANVAS' || el.tagName === 'VIDEO' || el.tagName === 'IMG') {
  50338. return el;
  50339. }
  50340. return el.getAttribute('src');
  50341. }
  50342. warn('"' + value + '" asset not found.');
  50343. return;
  50344. }
  50345. // Non-wrapped url().
  50346. return value;
  50347. }
  50348. function defaultParse (value) {
  50349. return value;
  50350. }
  50351. function defaultStringify (value) {
  50352. if (value === null) { return 'null'; }
  50353. return value.toString();
  50354. }
  50355. function boolParse (value) {
  50356. return value !== 'false' && value !== false;
  50357. }
  50358. function intParse (value) {
  50359. return parseInt(value, 10);
  50360. }
  50361. function numberParse (value) {
  50362. return parseFloat(value, 10);
  50363. }
  50364. function selectorParse (value) {
  50365. if (!value) { return null; }
  50366. if (typeof value !== 'string') { return value; }
  50367. if (value[0] === '#' && !nonCharRegex.test(value)) {
  50368. // When selecting element by ID only, use getElementById for better performance.
  50369. // Don't match like #myId .child.
  50370. return document.getElementById(value.substring(1));
  50371. }
  50372. return document.querySelector(value);
  50373. }
  50374. function selectorAllParse (value) {
  50375. if (!value) { return null; }
  50376. if (typeof value !== 'string') { return value; }
  50377. return Array.prototype.slice.call(document.querySelectorAll(value), 0);
  50378. }
  50379. function selectorStringify (value) {
  50380. if (value.getAttribute) {
  50381. return '#' + value.getAttribute('id');
  50382. }
  50383. return defaultStringify(value);
  50384. }
  50385. function selectorAllStringify (value) {
  50386. if (value instanceof Array) {
  50387. return value.map(function (element) {
  50388. return '#' + element.getAttribute('id');
  50389. }).join(', ');
  50390. }
  50391. return defaultStringify(value);
  50392. }
  50393. function srcParse (value) {
  50394. warn('`src` property type is deprecated. Use `asset` instead.');
  50395. return assetParse(value);
  50396. }
  50397. function vecParse (value) {
  50398. return coordinates.parse(value, this.default);
  50399. }
  50400. /**
  50401. * Validate the default values in a schema to match their type.
  50402. *
  50403. * @param {string} type - Property type name.
  50404. * @param defaultVal - Property type default value.
  50405. * @returns {boolean} Whether default value is accurate given the type.
  50406. */
  50407. function isValidDefaultValue (type, defaultVal) {
  50408. if (type === 'audio' && typeof defaultVal !== 'string') { return false; }
  50409. if (type === 'array' && !Array.isArray(defaultVal)) { return false; }
  50410. if (type === 'asset' && typeof defaultVal !== 'string') { return false; }
  50411. if (type === 'boolean' && typeof defaultVal !== 'boolean') { return false; }
  50412. if (type === 'color' && typeof defaultVal !== 'string') { return false; }
  50413. if (type === 'int' && typeof defaultVal !== 'number') { return false; }
  50414. if (type === 'number' && typeof defaultVal !== 'number') { return false; }
  50415. if (type === 'map' && typeof defaultVal !== 'string') { return false; }
  50416. if (type === 'model' && typeof defaultVal !== 'string') { return false; }
  50417. if (type === 'selector' && typeof defaultVal !== 'string') { return false; }
  50418. if (type === 'selectorAll' && typeof defaultVal !== 'string') { return false; }
  50419. if (type === 'src' && typeof defaultVal !== 'string') { return false; }
  50420. if (type === 'string' && typeof defaultVal !== 'string') { return false; }
  50421. if (type === 'time' && typeof defaultVal !== 'number') { return false; }
  50422. if (type === 'vec2') { return isValidDefaultCoordinate(defaultVal, 2); }
  50423. if (type === 'vec3') { return isValidDefaultCoordinate(defaultVal, 3); }
  50424. if (type === 'vec4') { return isValidDefaultCoordinate(defaultVal, 4); }
  50425. return true;
  50426. }
  50427. module.exports.isValidDefaultValue = isValidDefaultValue;
  50428. /**
  50429. * Checks if default coordinates are valid.
  50430. *
  50431. * @param possibleCoordinates
  50432. * @param {number} dimensions - 2 for 2D Vector, 3 for 3D vector.
  50433. * @returns {boolean} Whether coordinates are parsed correctly.
  50434. */
  50435. function isValidDefaultCoordinate (possibleCoordinates, dimensions) {
  50436. if (possibleCoordinates === null) { return true; }
  50437. if (typeof possibleCoordinates !== 'object') { return false; }
  50438. if (Object.keys(possibleCoordinates).length !== dimensions) {
  50439. return false;
  50440. } else {
  50441. var x = possibleCoordinates.x;
  50442. var y = possibleCoordinates.y;
  50443. var z = possibleCoordinates.z;
  50444. var w = possibleCoordinates.w;
  50445. if (typeof x !== 'number' || typeof y !== 'number') { return false; }
  50446. if (dimensions > 2 && typeof z !== 'number') { return false; }
  50447. if (dimensions > 3 && typeof w !== 'number') { return false; }
  50448. }
  50449. return true;
  50450. }
  50451. module.exports.isValidDefaultCoordinate = isValidDefaultCoordinate;
  50452. },{"../utils/coordinates":192,"debug":8}],129:[function(_dereq_,module,exports){
  50453. /* global Promise, screen */
  50454. var initMetaTags = _dereq_('./metaTags').inject;
  50455. var initWakelock = _dereq_('./wakelock');
  50456. var re = _dereq_('../a-register-element');
  50457. var scenes = _dereq_('./scenes');
  50458. var systems = _dereq_('../system').systems;
  50459. var THREE = _dereq_('../../lib/three');
  50460. var TWEEN = _dereq_('@tweenjs/tween.js');
  50461. var utils = _dereq_('../../utils/');
  50462. // Require after.
  50463. var AEntity = _dereq_('../a-entity');
  50464. var ANode = _dereq_('../a-node');
  50465. var initPostMessageAPI = _dereq_('./postMessage');
  50466. var bind = utils.bind;
  50467. var isIOS = utils.device.isIOS();
  50468. var isMobile = utils.device.isMobile();
  50469. var registerElement = re.registerElement;
  50470. var warn = utils.debug('core:a-scene:warn');
  50471. /**
  50472. * Scene element, holds all entities.
  50473. *
  50474. * @member {number} animationFrameID
  50475. * @member {array} behaviors - Component instances that have registered themselves to be
  50476. updated on every tick.
  50477. * @member {object} camera - three.js Camera object.
  50478. * @member {object} canvas
  50479. * @member {bool} isScene - Differentiates as scene entity as opposed to other entites.
  50480. * @member {bool} isMobile - Whether browser is mobile (via UA detection).
  50481. * @member {object} object3D - Root three.js Scene object.
  50482. * @member {object} renderer
  50483. * @member {bool} renderStarted
  50484. * @member (object) effect - three.js VREffect
  50485. * @member {object} systems - Registered instantiated systems.
  50486. * @member {number} time
  50487. */
  50488. module.exports.AScene = registerElement('a-scene', {
  50489. prototype: Object.create(AEntity.prototype, {
  50490. defaultComponents: {
  50491. value: {
  50492. 'canvas': '',
  50493. 'inspector': '',
  50494. 'keyboard-shortcuts': '',
  50495. 'screenshot': '',
  50496. 'vr-mode-ui': ''
  50497. }
  50498. },
  50499. createdCallback: {
  50500. value: function () {
  50501. this.isIOS = isIOS;
  50502. this.isMobile = isMobile;
  50503. this.isScene = true;
  50504. this.object3D = new THREE.Scene();
  50505. this.render = bind(this.render, this);
  50506. this.systems = {};
  50507. this.systemNames = [];
  50508. this.time = 0;
  50509. this.init();
  50510. }
  50511. },
  50512. init: {
  50513. value: function () {
  50514. this.behaviors = {tick: [], tock: []};
  50515. this.hasLoaded = false;
  50516. this.isPlaying = false;
  50517. this.originalHTML = this.innerHTML;
  50518. this.renderTarget = null;
  50519. this.addEventListener('render-target-loaded', function () {
  50520. this.setupRenderer();
  50521. this.resize();
  50522. });
  50523. this.addFullScreenStyles();
  50524. initPostMessageAPI(this);
  50525. },
  50526. writable: true
  50527. },
  50528. addFullScreenStyles: {
  50529. value: function () {
  50530. var htmlEl = document.documentElement;
  50531. htmlEl.classList.add('a-html');
  50532. document.body.classList.add('a-body');
  50533. this.classList.add('fullscreen');
  50534. }
  50535. },
  50536. removeFullScreenStyles: {
  50537. value: function () {
  50538. var htmlEl = document.documentElement;
  50539. htmlEl.classList.remove('a-html');
  50540. document.body.classList.remove('a-body');
  50541. this.classList.remove('fullscreen');
  50542. }
  50543. },
  50544. attachedCallback: {
  50545. value: function () {
  50546. var resize;
  50547. var self = this;
  50548. initMetaTags(this);
  50549. initWakelock(this);
  50550. this.initSystems();
  50551. resize = bind(this.resize, this);
  50552. window.addEventListener('load', resize);
  50553. window.addEventListener('resize', resize);
  50554. this.play();
  50555. // Add to scene index.
  50556. scenes.push(this);
  50557. // Handler to exit VR (e.g., Oculus Browser back button).
  50558. this.onVRPresentChangeBound = bind(this.onVRPresentChange, this);
  50559. window.addEventListener('vrdisplaypresentchange', this.onVRPresentChangeBound);
  50560. // Enter VR on `vrdisplayactivate` (e.g. putting on Rift headset).
  50561. window.addEventListener('vrdisplayactivate', function () { self.enterVR(); });
  50562. // Exit VR on `vrdisplaydeactivate` (e.g. taking off Rift headset).
  50563. window.addEventListener('vrdisplaydeactivate', function () { self.exitVR(); });
  50564. },
  50565. writable: window.debug
  50566. },
  50567. /**
  50568. * Initialize all systems.
  50569. */
  50570. initSystems: {
  50571. value: function () {
  50572. Object.keys(systems).forEach(bind(this.initSystem, this));
  50573. }
  50574. },
  50575. /**
  50576. * Initialize a system.
  50577. */
  50578. initSystem: {
  50579. value: function (name) {
  50580. if (this.systems[name]) { return; }
  50581. this.systems[name] = new systems[name](this);
  50582. this.systemNames.push(name);
  50583. }
  50584. },
  50585. /**
  50586. * Shut down scene on detach.
  50587. */
  50588. detachedCallback: {
  50589. value: function () {
  50590. var sceneIndex;
  50591. if (this.effect && this.effect.cancelAnimationFrame) {
  50592. this.effect.cancelAnimationFrame(this.animationFrameID);
  50593. } else {
  50594. window.cancelAnimationFrame(this.animationFrameID);
  50595. }
  50596. this.animationFrameID = null;
  50597. // Remove from scene index.
  50598. sceneIndex = scenes.indexOf(this);
  50599. scenes.splice(sceneIndex, 1);
  50600. window.removeEventListener('vrdisplaypresentchange', this.onVRPresentChangeBound);
  50601. }
  50602. },
  50603. /**
  50604. * Add ticks and tocks.
  50605. *
  50606. * @param {object} behavior - Generally a component. Must implement a .update() method
  50607. * to be called on every tick.
  50608. */
  50609. addBehavior: {
  50610. value: function (behavior) {
  50611. var self = this;
  50612. var behaviors = this.behaviors;
  50613. // Check if behavior has tick and/or tock and add the behavior to the appropriate list.
  50614. Object.keys(behaviors).forEach(function (behaviorType) {
  50615. if (!behavior[behaviorType]) { return; }
  50616. var behaviorArr = self.behaviors[behaviorType];
  50617. if (behaviorArr.indexOf(behavior) === -1) {
  50618. behaviorArr.push(behavior);
  50619. }
  50620. });
  50621. }
  50622. },
  50623. /**
  50624. * For tests.
  50625. */
  50626. checkHeadsetConnected: {
  50627. value: utils.device.checkHeadsetConnected,
  50628. writable: window.debug
  50629. },
  50630. /**
  50631. * Call `requestPresent` if WebVR or WebVR polyfill.
  50632. * Call `requestFullscreen` on desktop.
  50633. * Handle events, states, fullscreen styles.
  50634. *
  50635. * @param {bool} fromExternal - Whether exiting VR due to an external event (e.g.,
  50636. * manually calling requestPresent via WebVR API directly).
  50637. * @returns {Promise}
  50638. */
  50639. enterVR: {
  50640. value: function (fromExternal) {
  50641. var self = this;
  50642. // Don't enter VR if already in VR.
  50643. if (this.is('vr-mode')) { return Promise.resolve('Already in VR.'); }
  50644. // Enter VR via WebVR API.
  50645. if (!fromExternal && (this.checkHeadsetConnected() || this.isMobile)) {
  50646. return this.effect.requestPresent().then(enterVRSuccess, enterVRFailure);
  50647. }
  50648. // Either entered VR already via WebVR API or VR not supported.
  50649. enterVRSuccess();
  50650. return Promise.resolve();
  50651. function enterVRSuccess () {
  50652. self.addState('vr-mode');
  50653. self.emit('enter-vr', {target: self});
  50654. // Lock to landscape orientation on mobile.
  50655. if (self.isMobile && screen.orientation && screen.orientation.lock) {
  50656. screen.orientation.lock('landscape');
  50657. }
  50658. self.addFullScreenStyles();
  50659. // On mobile, the polyfill handles fullscreen.
  50660. // TODO: 07/16 Chromium builds break when `requestFullscreen`ing on a canvas
  50661. // that we are also `requestPresent`ing. Until then, don't fullscreen if headset
  50662. // connected.
  50663. if (!self.isMobile && !self.checkHeadsetConnected()) {
  50664. requestFullscreen(self.canvas);
  50665. }
  50666. self.resize();
  50667. }
  50668. function enterVRFailure (err) {
  50669. if (err && err.message) {
  50670. throw new Error('Failed to enter VR mode (`requestPresent`): ' + err.message);
  50671. } else {
  50672. throw new Error('Failed to enter VR mode (`requestPresent`).');
  50673. }
  50674. }
  50675. }
  50676. },
  50677. /**
  50678. * Call `exitPresent` if WebVR or WebVR polyfill.
  50679. * Handle events, states, fullscreen styles.
  50680. *
  50681. * @param {bool} fromExternal - Whether exiting VR due to an external event (e.g.,
  50682. * Oculus Browser GearVR back button).
  50683. * @returns {Promise}
  50684. */
  50685. exitVR: {
  50686. value: function (fromExternal) {
  50687. var self = this;
  50688. // Don't exit VR if not in VR.
  50689. if (!this.is('vr-mode')) { return Promise.resolve('Not in VR.'); }
  50690. exitFullscreen();
  50691. // Handle exiting VR if not yet already and in a headset or polyfill.
  50692. if (!fromExternal && (this.checkHeadsetConnected() || this.isMobile)) {
  50693. return this.effect.exitPresent().then(exitVRSuccess, exitVRFailure);
  50694. }
  50695. // Handle exiting VR in all other cases (2D fullscreen, external exit VR event).
  50696. exitVRSuccess();
  50697. return Promise.resolve();
  50698. function exitVRSuccess () {
  50699. self.removeState('vr-mode');
  50700. // Lock to landscape orientation on mobile.
  50701. if (self.isMobile && screen.orientation && screen.orientation.unlock) {
  50702. screen.orientation.unlock();
  50703. }
  50704. // Exiting VR in embedded mode, no longer need fullscreen styles.
  50705. if (self.hasAttribute('embedded')) { self.removeFullScreenStyles(); }
  50706. self.resize();
  50707. if (self.isIOS) { utils.forceCanvasResizeSafariMobile(this.canvas); }
  50708. self.emit('exit-vr', {target: self});
  50709. }
  50710. function exitVRFailure (err) {
  50711. if (err && err.message) {
  50712. throw new Error('Failed to exit VR mode (`exitPresent`): ' + err.message);
  50713. } else {
  50714. throw new Error('Failed to exit VR mode (`exitPresent`).');
  50715. }
  50716. }
  50717. }
  50718. },
  50719. /**
  50720. * Handle `vrdisplaypresentchange` event for exiting VR through other means than
  50721. * `<ESC>` key. For example, GearVR back button on Oculus Browser.
  50722. */
  50723. onVRPresentChange: {
  50724. value: function (evt) {
  50725. // Polyfill places display inside the detail property
  50726. var display = evt.display || evt.detail.display;
  50727. // Entering VR.
  50728. if (display.isPresenting) {
  50729. this.enterVR(true);
  50730. return;
  50731. }
  50732. // Exiting VR.
  50733. this.exitVR(true);
  50734. }
  50735. },
  50736. /**
  50737. * Wraps Entity.getAttribute to take into account for systems.
  50738. * If system exists, then return system data rather than possible component data.
  50739. */
  50740. getAttribute: {
  50741. value: function (attr) {
  50742. var system = this.systems[attr];
  50743. if (system) { return system.data; }
  50744. return AEntity.prototype.getAttribute.call(this, attr);
  50745. }
  50746. },
  50747. /**
  50748. * `getAttribute` used to be `getDOMAttribute` and `getComputedAttribute` used to be
  50749. * what `getAttribute` is now. Now legacy code.
  50750. */
  50751. getComputedAttribute: {
  50752. value: function (attr) {
  50753. warn('`getComputedAttribute` is deprecated. Use `getAttribute` instead.');
  50754. this.getAttribute(attr);
  50755. }
  50756. },
  50757. /**
  50758. * Wraps Entity.getDOMAttribute to take into account for systems.
  50759. * If system exists, then return system data rather than possible component data.
  50760. */
  50761. getDOMAttribute: {
  50762. value: function (attr) {
  50763. var system = this.systems[attr];
  50764. if (system) { return system.data; }
  50765. return AEntity.prototype.getDOMAttribute.call(this, attr);
  50766. }
  50767. },
  50768. /**
  50769. * Wrap Entity.setAttribute to take into account for systems.
  50770. * If system exists, then skip component initialization checks and do a normal
  50771. * setAttribute.
  50772. */
  50773. setAttribute: {
  50774. value: function (attr, value, componentPropValue) {
  50775. var system = this.systems[attr];
  50776. if (system) {
  50777. ANode.prototype.setAttribute.call(this, attr, value);
  50778. system.updateProperties(value);
  50779. return;
  50780. }
  50781. AEntity.prototype.setAttribute.call(this, attr, value, componentPropValue);
  50782. }
  50783. },
  50784. /**
  50785. * @param {object} behavior - Generally a component. Has registered itself to behaviors.
  50786. */
  50787. removeBehavior: {
  50788. value: function (behavior) {
  50789. var self = this;
  50790. var behaviors = this.behaviors;
  50791. // Check if behavior has tick and/or tock and remove the behavior from the appropriate array.
  50792. Object.keys(behaviors).forEach(function (behaviorType) {
  50793. if (!behavior[behaviorType]) { return; }
  50794. var behaviorArr = self.behaviors[behaviorType];
  50795. var index = behaviorArr.indexOf(behavior);
  50796. if (index !== -1) {
  50797. behaviorArr.splice(index, 1);
  50798. }
  50799. });
  50800. }
  50801. },
  50802. resize: {
  50803. value: function () {
  50804. var camera = this.camera;
  50805. var canvas = this.canvas;
  50806. var embedded = this.getAttribute('embedded') && !this.is('vr-mode');
  50807. var size;
  50808. // Possible camera or canvas not injected yet.
  50809. // ON MOBILE the webvr-polyfill relies on the fullscreen API to enter
  50810. // VR mode. The canvas is resized by VREffect following the values returned
  50811. // by getEyeParameters. We don't want to overwrite the size with the
  50812. // windows width and height.
  50813. if (!camera || !canvas || this.is('vr-mode') && isMobile) { return; }
  50814. // Update camera.
  50815. size = getCanvasSize(canvas, embedded);
  50816. camera.aspect = size.width / size.height;
  50817. camera.updateProjectionMatrix();
  50818. // Notify renderer of size change.
  50819. this.renderer.setSize(size.width, size.height);
  50820. },
  50821. writable: window.debug
  50822. },
  50823. setupRenderer: {
  50824. value: function () {
  50825. var renderer = this.renderer = new THREE.WebGLRenderer({
  50826. canvas: this.canvas,
  50827. antialias: shouldAntiAlias(this),
  50828. alpha: true
  50829. });
  50830. renderer.setPixelRatio(window.devicePixelRatio);
  50831. renderer.sortObjects = false;
  50832. this.effect = new THREE.VREffect(renderer);
  50833. this.effect.autoSubmitFrame = false;
  50834. },
  50835. writable: window.debug
  50836. },
  50837. /**
  50838. * Handler attached to elements to help scene know when to kick off.
  50839. * Scene waits for all entities to load.
  50840. */
  50841. play: {
  50842. value: function () {
  50843. var self = this;
  50844. if (this.renderStarted) {
  50845. AEntity.prototype.play.call(this);
  50846. return;
  50847. }
  50848. this.addEventListener('loaded', function () {
  50849. AEntity.prototype.play.call(this); // .play() *before* render.
  50850. // Wait for camera if necessary before rendering.
  50851. if (this.camera) {
  50852. startRender(this);
  50853. return;
  50854. }
  50855. this.addEventListener('camera-set-active', function () { startRender(this); });
  50856. function startRender (sceneEl) {
  50857. if (sceneEl.renderStarted) { return; }
  50858. sceneEl.resize();
  50859. // Kick off render loop.
  50860. if (sceneEl.renderer) {
  50861. if (window.performance) {
  50862. window.performance.mark('render-started');
  50863. }
  50864. sceneEl.clock = new THREE.Clock();
  50865. sceneEl.render();
  50866. sceneEl.renderStarted = true;
  50867. sceneEl.emit('renderstart');
  50868. }
  50869. }
  50870. });
  50871. // setTimeout to wait for all nodes to attach and run their callbacks.
  50872. setTimeout(function () {
  50873. AEntity.prototype.load.call(self);
  50874. });
  50875. }
  50876. },
  50877. /**
  50878. * Reload the scene to the original DOM content.
  50879. *
  50880. * @param {bool} doPause - Whether to reload the scene with all dynamic behavior paused.
  50881. */
  50882. reload: {
  50883. value: function (doPause) {
  50884. var self = this;
  50885. if (doPause) { this.pause(); }
  50886. this.innerHTML = this.originalHTML;
  50887. this.init();
  50888. ANode.prototype.load.call(this, play);
  50889. function play () {
  50890. if (!self.isPlaying) { return; }
  50891. AEntity.prototype.play.call(self);
  50892. }
  50893. }
  50894. },
  50895. /**
  50896. * Wrap `updateComponent` to not initialize the component if the component has a system
  50897. * (aframevr/aframe#2365).
  50898. */
  50899. updateComponent: {
  50900. value: function (componentName) {
  50901. if (componentName in systems) { return; }
  50902. AEntity.prototype.updateComponent.apply(this, arguments);
  50903. }
  50904. },
  50905. /**
  50906. * Behavior-updater meant to be called from scene render.
  50907. * Abstracted to a different function to facilitate unit testing (`scene.tick()`) without
  50908. * needing to render.
  50909. */
  50910. tick: {
  50911. value: function (time, timeDelta) {
  50912. var i;
  50913. var systems = this.systems;
  50914. // Animations.
  50915. TWEEN.update();
  50916. // Components.
  50917. for (i = 0; i < this.behaviors.tick.length; i++) {
  50918. if (!this.behaviors.tick[i].el.isPlaying) { continue; }
  50919. this.behaviors.tick[i].tick(time, timeDelta);
  50920. }
  50921. // Systems.
  50922. for (i = 0; i < this.systemNames.length; i++) {
  50923. if (!systems[this.systemNames[i]].tick) { continue; }
  50924. systems[this.systemNames[i]].tick(time, timeDelta);
  50925. }
  50926. }
  50927. },
  50928. /**
  50929. * Behavior-updater meant to be called after scene render for post processing purposes.
  50930. * Abstracted to a different function to facilitate unit testing (`scene.tock()`) without
  50931. * needing to render.
  50932. */
  50933. tock: {
  50934. value: function (time, timeDelta) {
  50935. var i;
  50936. var systems = this.systems;
  50937. // Components.
  50938. for (i = 0; i < this.behaviors.tock.length; i++) {
  50939. if (!this.behaviors.tock[i].el.isPlaying) { continue; }
  50940. this.behaviors.tock[i].tock(time, timeDelta);
  50941. }
  50942. // Systems.
  50943. for (i = 0; i < this.systemNames.length; i++) {
  50944. if (!systems[this.systemNames[i]].tock) { continue; }
  50945. systems[this.systemNames[i]].tock(time, timeDelta);
  50946. }
  50947. }
  50948. },
  50949. /**
  50950. * The render loop.
  50951. *
  50952. * Updates animations.
  50953. * Updates behaviors.
  50954. * Renders with request animation frame.
  50955. */
  50956. render: {
  50957. value: function () {
  50958. var effect = this.effect;
  50959. var delta = this.clock.getDelta() * 1000;
  50960. this.time = this.clock.elapsedTime * 1000;
  50961. if (this.isPlaying) { this.tick(this.time, delta); }
  50962. this.animationFrameID = effect.requestAnimationFrame(this.render);
  50963. effect.render(this.object3D, this.camera, this.renderTarget);
  50964. if (this.isPlaying) { this.tock(this.time, delta); }
  50965. this.effect.submitFrame();
  50966. },
  50967. writable: true
  50968. }
  50969. })
  50970. });
  50971. /**
  50972. * Return the canvas size where the scene will be rendered
  50973. * It will be always the window size except when the scene
  50974. * is embedded. The parent size will be returned in that case
  50975. *
  50976. * @param {object} canvasEl - the canvas element
  50977. * @param {boolean} embedded - Is the scene embedded?
  50978. */
  50979. function getCanvasSize (canvasEl, embedded) {
  50980. if (embedded) {
  50981. return {
  50982. height: canvasEl.parentElement.offsetHeight,
  50983. width: canvasEl.parentElement.offsetWidth
  50984. };
  50985. }
  50986. return {
  50987. height: window.innerHeight,
  50988. width: window.innerWidth
  50989. };
  50990. }
  50991. function requestFullscreen (canvas) {
  50992. var requestFullscreen =
  50993. canvas.requestFullscreen ||
  50994. canvas.webkitRequestFullscreen ||
  50995. canvas.mozRequestFullScreen || // The capitalized `S` is not a typo.
  50996. canvas.msRequestFullscreen;
  50997. requestFullscreen.apply(canvas);
  50998. }
  50999. function exitFullscreen () {
  51000. if (document.exitFullscreen) {
  51001. document.exitFullscreen();
  51002. } else if (document.mozCancelFullScreen) {
  51003. document.mozCancelFullScreen();
  51004. } else if (document.webkitExitFullscreen) {
  51005. document.webkitExitFullscreen();
  51006. }
  51007. }
  51008. /**
  51009. * Determines if renderer anti-aliasing should be enabled.
  51010. * Enabled by default if has native WebVR or is desktop.
  51011. *
  51012. * @returns {bool}
  51013. */
  51014. function shouldAntiAlias (sceneEl) {
  51015. // Explicitly set.
  51016. if (sceneEl.getAttribute('antialias') !== null) {
  51017. return sceneEl.getAttribute('antialias') === 'true';
  51018. }
  51019. // Default not AA for mobile.
  51020. return !sceneEl.isMobile;
  51021. }
  51022. module.exports.shouldAntiAlias = shouldAntiAlias; // For testing.
  51023. },{"../../lib/three":174,"../../utils/":197,"../a-entity":122,"../a-node":124,"../a-register-element":125,"../system":136,"./metaTags":130,"./postMessage":131,"./scenes":132,"./wakelock":133,"@tweenjs/tween.js":1}],130:[function(_dereq_,module,exports){
  51024. var constants = _dereq_('../../constants/');
  51025. var extend = _dereq_('../../utils').extend;
  51026. var MOBILE_HEAD_TAGS = module.exports.MOBILE_HEAD_TAGS = [
  51027. Meta({name: 'viewport', content: 'width=device-width,initial-scale=1,maximum-scale=1,shrink-to-fit=no,user-scalable=no,minimal-ui'}),
  51028. // W3C-standardised meta tags.
  51029. Meta({name: 'mobile-web-app-capable', content: 'yes'}),
  51030. Meta({name: 'theme-color', content: 'black'})
  51031. ];
  51032. var MOBILE_IOS_HEAD_TAGS = [
  51033. // iOS-specific meta tags for fullscreen when pinning to homescreen.
  51034. Meta({name: 'apple-mobile-web-app-capable', content: 'yes'}),
  51035. Meta({name: 'apple-mobile-web-app-status-bar-style', content: 'black'}),
  51036. Link({rel: 'apple-touch-icon', href: 'https://aframe.io/images/aframe-logo-152.png'})
  51037. ];
  51038. function Meta (attrs) {
  51039. return {
  51040. tagName: 'meta',
  51041. attributes: attrs,
  51042. exists: function () { return document.querySelector('meta[name="' + attrs.name + '"]'); }
  51043. };
  51044. }
  51045. function Link (attrs) {
  51046. return {
  51047. tagName: 'link',
  51048. attributes: attrs,
  51049. exists: function () { return document.querySelector('link[rel="' + attrs.rel + '"]'); }
  51050. };
  51051. }
  51052. /**
  51053. * Injects the necessary metatags in the document for mobile support:
  51054. * 1. Prevent the user to zoom in the document.
  51055. * 2. Ensure that window.innerWidth and window.innerHeight have the correct
  51056. * values and the canvas is properly scaled.
  51057. * 3. To allow fullscreen mode when pinning a web app on the home screen on
  51058. * iOS.
  51059. * Adapted from https://www.reddit.com/r/web_design/comments/3la04p/
  51060. *
  51061. * @param {object} scene - Scene element
  51062. * @returns {Array}
  51063. */
  51064. module.exports.inject = function injectHeadTags (scene) {
  51065. var headEl = document.head;
  51066. var headScriptEl = headEl.querySelector('script');
  51067. var tag;
  51068. var headTags = [];
  51069. MOBILE_HEAD_TAGS.forEach(createAndInjectTag);
  51070. if (scene.isIOS) {
  51071. MOBILE_IOS_HEAD_TAGS.forEach(createAndInjectTag);
  51072. }
  51073. return headTags;
  51074. function createAndInjectTag (tagObj) {
  51075. if (!tagObj || tagObj.exists()) { return; }
  51076. tag = createTag(tagObj);
  51077. if (!tag) { return; }
  51078. if (headScriptEl) {
  51079. headScriptEl.parentNode.insertBefore(tag, headScriptEl);
  51080. } else {
  51081. headEl.appendChild(tag);
  51082. }
  51083. headTags.push(tag);
  51084. }
  51085. };
  51086. function createTag (tagObj) {
  51087. if (!tagObj || !tagObj.tagName) { return; }
  51088. var meta = document.createElement(tagObj.tagName);
  51089. meta.setAttribute(constants.AFRAME_INJECTED, '');
  51090. return extend(meta, tagObj.attributes);
  51091. }
  51092. },{"../../constants/":117,"../../utils":197}],131:[function(_dereq_,module,exports){
  51093. var bind = _dereq_('../../utils/bind');
  51094. var isIframed = _dereq_('../../utils/').isIframed;
  51095. /**
  51096. * Provides a post message API for scenes contained
  51097. * in an iframe.
  51098. */
  51099. module.exports = function initPostMessageAPI (scene) {
  51100. // Handles fullscreen behavior when inside an iframe.
  51101. if (!isIframed()) { return; }
  51102. // postMessage API handler
  51103. window.addEventListener('message', bind(postMessageAPIHandler, scene));
  51104. };
  51105. function postMessageAPIHandler (event) {
  51106. var scene = this;
  51107. if (!event.data) { return; }
  51108. switch (event.data.type) {
  51109. case 'vr': {
  51110. switch (event.data.data) {
  51111. case 'enter':
  51112. scene.enterVR();
  51113. break;
  51114. case 'exit':
  51115. scene.exitVR();
  51116. break;
  51117. }
  51118. }
  51119. }
  51120. }
  51121. },{"../../utils/":197,"../../utils/bind":191}],132:[function(_dereq_,module,exports){
  51122. /*
  51123. Scene index for keeping track of created scenes.
  51124. */
  51125. module.exports = [];
  51126. },{}],133:[function(_dereq_,module,exports){
  51127. var Wakelock = _dereq_('../../../vendor/wakelock/wakelock');
  51128. module.exports = function initWakelock (scene) {
  51129. if (!scene.isMobile) { return; }
  51130. var wakelock = scene.wakelock = new Wakelock();
  51131. scene.addEventListener('enter-vr', function () { wakelock.request(); });
  51132. scene.addEventListener('exit-vr', function () { wakelock.release(); });
  51133. };
  51134. },{"../../../vendor/wakelock/wakelock":207}],134:[function(_dereq_,module,exports){
  51135. var utils = _dereq_('../utils/');
  51136. var PropertyTypes = _dereq_('./propertyTypes');
  51137. var debug = utils.debug;
  51138. var isValidDefaultValue = PropertyTypes.isValidDefaultValue;
  51139. var propertyTypes = PropertyTypes.propertyTypes;
  51140. var warn = debug('core:schema:warn');
  51141. /**
  51142. * A schema is classified as a schema for a single property if:
  51143. * - `type` is defined on the schema as a string.
  51144. * - OR `default` is defined on the schema, as a reserved keyword.
  51145. * - OR schema is empty.
  51146. */
  51147. function isSingleProperty (schema) {
  51148. if ('type' in schema) {
  51149. return typeof schema.type === 'string';
  51150. }
  51151. return 'default' in schema;
  51152. }
  51153. module.exports.isSingleProperty = isSingleProperty;
  51154. /**
  51155. * Build step to schema to use `type` to inject default value, parser, and stringifier.
  51156. *
  51157. * @param {object} schema
  51158. * @param {string} componentName
  51159. * @returns {object} Schema.
  51160. */
  51161. module.exports.process = function (schema, componentName) {
  51162. // For single property schema, run processPropDefinition over the whole schema.
  51163. if (isSingleProperty(schema)) {
  51164. return processPropertyDefinition(schema, componentName);
  51165. }
  51166. // For multi-property schema, run processPropDefinition over each property definition.
  51167. Object.keys(schema).forEach(function (propName) {
  51168. schema[propName] = processPropertyDefinition(schema[propName], componentName);
  51169. });
  51170. return schema;
  51171. };
  51172. /**
  51173. * Inject default value, parser, stringifier for single property.
  51174. *
  51175. * @param {object} propDefinition
  51176. * @param {string} componentName
  51177. */
  51178. function processPropertyDefinition (propDefinition, componentName) {
  51179. var defaultVal = propDefinition.default;
  51180. var propType;
  51181. var typeName = propDefinition.type;
  51182. // Type inference.
  51183. if (!propDefinition.type) {
  51184. if (defaultVal !== undefined && ['boolean', 'number'].indexOf(typeof defaultVal) !== -1) {
  51185. // Type inference.
  51186. typeName = typeof defaultVal;
  51187. } else if (Array.isArray(defaultVal)) {
  51188. typeName = 'array';
  51189. } else {
  51190. // Fall back to string.
  51191. typeName = 'string';
  51192. }
  51193. } else if (propDefinition.type === 'bool') {
  51194. typeName = 'boolean';
  51195. } else if (propDefinition.type === 'float') {
  51196. typeName = 'number';
  51197. }
  51198. propType = propertyTypes[typeName];
  51199. if (!propType) {
  51200. warn('Unknown property type for component `' + componentName + '`: ' + typeName);
  51201. }
  51202. // Fill in parse and stringify using property types.
  51203. propDefinition.parse = propDefinition.parse || propType.parse;
  51204. propDefinition.stringify = propDefinition.stringify || propType.stringify;
  51205. // Fill in type name.
  51206. propDefinition.type = typeName;
  51207. // Check that default value exists.
  51208. if ('default' in propDefinition) {
  51209. // Check that default values are valid.
  51210. if (!isValidDefaultValue(typeName, defaultVal) &&
  51211. typeName !== 'selector' && typeName !== 'selectorAll') {
  51212. warn('Default value `' + defaultVal + '` does not match type `' + typeName +
  51213. '` in component `' + componentName + '`');
  51214. }
  51215. } else {
  51216. // Fill in default value.
  51217. propDefinition.default = propType.default;
  51218. }
  51219. return propDefinition;
  51220. }
  51221. module.exports.processPropertyDefinition = processPropertyDefinition;
  51222. /**
  51223. * Parse propData using schema. Use default values if not existing in propData.
  51224. *
  51225. * @param {object} propData - Unparsed properties.
  51226. * @param {object} schema - Property types definition.
  51227. * @param {boolean} getPartialData - Whether to return full component data or just the data
  51228. * with keys in `propData`.
  51229. * @param {string } componentName - Name of the component, used for the property warning.
  51230. * @param {boolean} silent - Suppress warning messages.
  51231. */
  51232. module.exports.parseProperties = function (propData, schema, getPartialData, componentName,
  51233. silent) {
  51234. var propNames = Object.keys(getPartialData ? propData : schema);
  51235. if (propData === null || typeof propData !== 'object') { return propData; }
  51236. // Validation errors.
  51237. Object.keys(propData).forEach(function (propName) {
  51238. if (!schema[propName] && !silent) {
  51239. warn('Unknown property `' + propName +
  51240. '` for component/system `' + componentName + '`.');
  51241. }
  51242. });
  51243. propNames.forEach(function parse (propName) {
  51244. var propDefinition = schema[propName];
  51245. var propValue = propData[propName];
  51246. if (!(schema[propName])) { return; }
  51247. propData[propName] = parseProperty(propValue, propDefinition);
  51248. });
  51249. return propData;
  51250. };
  51251. /**
  51252. * Deserialize a single property.
  51253. */
  51254. function parseProperty (value, propDefinition) {
  51255. // Use default value if value is falsy.
  51256. if (value === undefined || value === null || value === '') {
  51257. value = propDefinition.default;
  51258. if (Array.isArray(value)) { value = value.slice(); }
  51259. }
  51260. // Invoke property type parser.
  51261. return propDefinition.parse(value, propDefinition.default);
  51262. }
  51263. module.exports.parseProperty = parseProperty;
  51264. /**
  51265. * Serialize a group of properties.
  51266. */
  51267. module.exports.stringifyProperties = function (propData, schema) {
  51268. var stringifiedData = {};
  51269. Object.keys(propData).forEach(function (propName) {
  51270. var propDefinition = schema[propName];
  51271. var propValue = propData[propName];
  51272. var value = propValue;
  51273. if (typeof value === 'object') {
  51274. value = stringifyProperty(propValue, propDefinition);
  51275. if (!propDefinition) { warn('Unknown component property: ' + propName); }
  51276. }
  51277. stringifiedData[propName] = value;
  51278. });
  51279. return stringifiedData;
  51280. };
  51281. /**
  51282. * Serialize a single property.
  51283. */
  51284. function stringifyProperty (value, propDefinition) {
  51285. // This function stringifies but it's used in a context where
  51286. // there's always second stringification pass. By returning the original
  51287. // value when it's not an object we save one unnecessary call
  51288. // to JSON.stringify.
  51289. if (typeof value !== 'object') { return value; }
  51290. // if there's no schema for the property we use standar JSON stringify
  51291. if (!propDefinition || value === null) { return JSON.stringify(value); }
  51292. return propDefinition.stringify(value);
  51293. }
  51294. module.exports.stringifyProperty = stringifyProperty;
  51295. },{"../utils/":197,"./propertyTypes":128}],135:[function(_dereq_,module,exports){
  51296. var schema = _dereq_('./schema');
  51297. var processSchema = schema.process;
  51298. var shaders = module.exports.shaders = {}; // Keep track of registered shaders.
  51299. var shaderNames = module.exports.shaderNames = []; // Keep track of the names of registered shaders.
  51300. var THREE = _dereq_('../lib/three');
  51301. var utils = _dereq_('../utils');
  51302. // A-Frame properties to three.js uniform types.
  51303. var propertyToThreeMapping = {
  51304. array: 'v3',
  51305. color: 'v3',
  51306. int: 'i',
  51307. number: 'f',
  51308. map: 't',
  51309. time: 'f',
  51310. vec2: 'v2',
  51311. vec3: 'v3',
  51312. vec4: 'v4'
  51313. };
  51314. /**
  51315. * Shader class definition.
  51316. *
  51317. * Shaders extend the material component API so you can create your own library
  51318. * of customized materials
  51319. *
  51320. */
  51321. var Shader = module.exports.Shader = function () {};
  51322. Shader.prototype = {
  51323. /**
  51324. * Contains the type schema and defaults for the data values.
  51325. * Data is coerced into the types of the values of the defaults.
  51326. */
  51327. schema: {},
  51328. vertexShader:
  51329. 'void main() {' +
  51330. 'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);' +
  51331. '}',
  51332. fragmentShader:
  51333. 'void main() {' +
  51334. 'gl_FragColor = vec4(1.0, 0.0, 1.0, 1.0);' +
  51335. '}',
  51336. /**
  51337. * Init handler. Similar to attachedCallback.
  51338. * Called during shader initialization and is only run once.
  51339. */
  51340. init: function (data) {
  51341. this.attributes = this.initVariables(data, 'attribute');
  51342. this.uniforms = this.initVariables(data, 'uniform');
  51343. this.material = new (this.raw ? THREE.RawShaderMaterial : THREE.ShaderMaterial)({
  51344. // attributes: this.attributes,
  51345. uniforms: this.uniforms,
  51346. vertexShader: this.vertexShader,
  51347. fragmentShader: this.fragmentShader
  51348. });
  51349. return this.material;
  51350. },
  51351. initVariables: function (data, type) {
  51352. var variables = {};
  51353. var schema = this.schema;
  51354. Object.keys(schema).forEach(function processSchema (key) {
  51355. if (schema[key].is !== type) { return; }
  51356. var varType = propertyToThreeMapping[schema[key].type];
  51357. variables[key] = {
  51358. type: varType,
  51359. value: undefined // Let updateVariables handle setting these.
  51360. };
  51361. });
  51362. return variables;
  51363. },
  51364. /**
  51365. * Update handler. Similar to attributeChangedCallback.
  51366. * Called whenever the associated material data changes.
  51367. *
  51368. * @param {object} data - New material data.
  51369. */
  51370. update: function (data) {
  51371. this.updateVariables(data, 'attribute');
  51372. this.updateVariables(data, 'uniform');
  51373. },
  51374. updateVariables: function (data, type) {
  51375. var self = this;
  51376. var variables = type === 'uniform' ? this.uniforms : this.attributes;
  51377. var schema = this.schema;
  51378. Object.keys(data).forEach(function processData (key) {
  51379. var materialKey;
  51380. if (!schema[key] || schema[key].is !== type) { return; }
  51381. if (schema[key].type === 'map') {
  51382. // If data unchanged, get out early.
  51383. if (!variables[key] || variables[key].value === data[key]) { return; }
  51384. // Special handling is needed for textures.
  51385. materialKey = '_texture_' + key;
  51386. // We can't actually set the variable correctly until we've loaded the texture.
  51387. self.el.addEventListener('materialtextureloaded', function () {
  51388. variables[key].value = self.material[materialKey];
  51389. variables[key].needsUpdate = true;
  51390. });
  51391. // Kick off the texture update now that handler is added.
  51392. utils.material.updateMapMaterialFromData(materialKey, key, self, data);
  51393. return;
  51394. }
  51395. variables[key].value = self.parseValue(schema[key].type, data[key]);
  51396. variables[key].needsUpdate = true;
  51397. });
  51398. },
  51399. parseValue: function (type, value) {
  51400. var color;
  51401. switch (type) {
  51402. case 'vec2': {
  51403. return new THREE.Vector2(value.x, value.y);
  51404. }
  51405. case 'vec3': {
  51406. return new THREE.Vector3(value.x, value.y, value.z);
  51407. }
  51408. case 'vec4': {
  51409. return new THREE.Vector4(value.x, value.y, value.z, value.w);
  51410. }
  51411. case 'color': {
  51412. color = new THREE.Color(value);
  51413. return new THREE.Vector3(color.r, color.g, color.b);
  51414. }
  51415. case 'map': {
  51416. return THREE.ImageUtils.loadTexture(value);
  51417. }
  51418. default: {
  51419. return value;
  51420. }
  51421. }
  51422. }
  51423. };
  51424. /**
  51425. * Registers a shader to A-Frame.
  51426. *
  51427. * @param {string} name - shader name.
  51428. * @param {object} definition - shader property and methods.
  51429. * @returns {object} Shader.
  51430. */
  51431. module.exports.registerShader = function (name, definition) {
  51432. var NewShader;
  51433. var proto = {};
  51434. // Format definition object to prototype object.
  51435. Object.keys(definition).forEach(function (key) {
  51436. proto[key] = {
  51437. value: definition[key],
  51438. writable: true
  51439. };
  51440. });
  51441. if (shaders[name]) {
  51442. throw new Error('The shader ' + name + ' has been already registered');
  51443. }
  51444. NewShader = function () { Shader.call(this); };
  51445. NewShader.prototype = Object.create(Shader.prototype, proto);
  51446. NewShader.prototype.name = name;
  51447. NewShader.prototype.constructor = NewShader;
  51448. shaders[name] = {
  51449. Shader: NewShader,
  51450. schema: processSchema(NewShader.prototype.schema)
  51451. };
  51452. shaderNames.push(name);
  51453. return NewShader;
  51454. };
  51455. },{"../lib/three":174,"../utils":197,"./schema":134}],136:[function(_dereq_,module,exports){
  51456. var components = _dereq_('./component');
  51457. var schema = _dereq_('./schema');
  51458. var utils = _dereq_('../utils/');
  51459. var parseProperties = schema.parseProperties;
  51460. var parseProperty = schema.parseProperty;
  51461. var processSchema = schema.process;
  51462. var isSingleProp = schema.isSingleProperty;
  51463. var styleParser = utils.styleParser;
  51464. var systems = module.exports.systems = {}; // Keep track of registered systems.
  51465. /**
  51466. * System class definition.
  51467. *
  51468. * Systems provide global scope and services to a group of instantiated components of the
  51469. * same class. They can also help abstract logic away from components such that components
  51470. * only have to worry about data.
  51471. *
  51472. * For example, a physics component that creates a physics world that oversees
  51473. * all entities with a physics or rigid body component.
  51474. *
  51475. * TODO: Have the System prototype reuse the Component prototype. Most code is copied
  51476. * and some pieces are missing from the Component facilities (e.g., attribute caching,
  51477. * setAttribute behavior).
  51478. *
  51479. * @member {string} name - Name that system is registered under.
  51480. * @member {Element} sceneEl - Handle to the scene element where system applies to.
  51481. */
  51482. var System = module.exports.System = function (sceneEl) {
  51483. var component = components && components.components[this.name];
  51484. // Set reference to scene.
  51485. this.el = sceneEl;
  51486. this.sceneEl = sceneEl;
  51487. // Set reference to matching component (if exists).
  51488. if (component) { component.Component.prototype.system = this; }
  51489. // Process system configuration.
  51490. this.buildData();
  51491. this.init();
  51492. this.update({});
  51493. };
  51494. System.prototype = {
  51495. /**
  51496. * Schema to configure system.
  51497. */
  51498. schema: {},
  51499. /**
  51500. * Init handler. Called during scene initialization and is only run once.
  51501. * Systems can use this to set initial state.
  51502. */
  51503. init: function () { /* no-op */ },
  51504. /**
  51505. * Update handler. Called during scene attribute updates.
  51506. * Systems can use this to dynamically update their state.
  51507. */
  51508. update: function (oldData) { /* no-op */ },
  51509. /**
  51510. * Build data and call update handler.
  51511. *
  51512. * @private
  51513. */
  51514. updateProperties: function (rawData) {
  51515. var oldData = this.data;
  51516. if (!Object.keys(schema).length) { return; }
  51517. this.buildData(rawData);
  51518. this.update(oldData);
  51519. },
  51520. /**
  51521. * Parse data.
  51522. */
  51523. buildData: function (rawData) {
  51524. var schema = this.schema;
  51525. if (!Object.keys(schema).length) { return; }
  51526. rawData = rawData || window.HTMLElement.prototype.getAttribute.call(this.sceneEl, this.name);
  51527. if (isSingleProp(schema)) {
  51528. this.data = parseProperty(rawData, schema);
  51529. } else {
  51530. this.data = parseProperties(styleParser.parse(rawData) || {}, schema);
  51531. }
  51532. },
  51533. /**
  51534. * Tick handler.
  51535. * Called on each tick of the scene render loop.
  51536. * Affected by play and pause.
  51537. *
  51538. * @param {number} time - Scene tick time.
  51539. * @param {number} timeDelta - Difference in current render time and previous render time.
  51540. */
  51541. tick: undefined,
  51542. /**
  51543. * Tock handler.
  51544. * Called on each tock of the scene render loop.
  51545. * Affected by play and pause.
  51546. *
  51547. * @param {number} time - Scene tick time.
  51548. * @param {number} timeDelta - Difference in current render time and previous render time.
  51549. */
  51550. tock: undefined,
  51551. /**
  51552. * Called to start any dynamic behavior (e.g., animation, AI, events, physics).
  51553. */
  51554. play: function () { /* no-op */ },
  51555. /**
  51556. * Called to stop any dynamic behavior (e.g., animation, AI, events, physics).
  51557. */
  51558. pause: function () { /* no-op */ }
  51559. };
  51560. /**
  51561. * Registers a system to A-Frame.
  51562. *
  51563. * @param {string} name - Component name.
  51564. * @param {object} definition - Component property and methods.
  51565. * @returns {object} Component.
  51566. */
  51567. module.exports.registerSystem = function (name, definition) {
  51568. var i;
  51569. var NewSystem;
  51570. var proto = {};
  51571. var scenes = utils.findAllScenes(document);
  51572. // Format definition object to prototype object.
  51573. Object.keys(definition).forEach(function (key) {
  51574. proto[key] = {
  51575. value: definition[key],
  51576. writable: true
  51577. };
  51578. });
  51579. if (systems[name]) {
  51580. throw new Error('The system `' + name + '` has been already registered. ' +
  51581. 'Check that you are not loading two versions of the same system ' +
  51582. 'or two different systems of the same name.');
  51583. }
  51584. NewSystem = function (sceneEl) { System.call(this, sceneEl); };
  51585. NewSystem.prototype = Object.create(System.prototype, proto);
  51586. NewSystem.prototype.name = name;
  51587. NewSystem.prototype.constructor = NewSystem;
  51588. NewSystem.prototype.schema = utils.extend(processSchema(NewSystem.prototype.schema));
  51589. systems[name] = NewSystem;
  51590. // Initialize systems for existing scenes
  51591. for (i = 0; i < scenes.length; i++) { scenes[i].initSystem(name); }
  51592. };
  51593. },{"../utils/":197,"./component":126,"./schema":134}],137:[function(_dereq_,module,exports){
  51594. _dereq_('./pivot');
  51595. },{"./pivot":138}],138:[function(_dereq_,module,exports){
  51596. var registerComponent = _dereq_('../../core/component').registerComponent;
  51597. var THREE = _dereq_('../../lib/three');
  51598. var originalPosition = new THREE.Vector3();
  51599. var originalRotation = new THREE.Vector3();
  51600. /**
  51601. * Wrap el.object3D within an outer group. Apply pivot to el.object3D as position.
  51602. */
  51603. registerComponent('pivot', {
  51604. dependencies: ['position'],
  51605. schema: {type: 'vec3'},
  51606. init: function () {
  51607. var data = this.data;
  51608. var el = this.el;
  51609. var originalParent = el.object3D.parent;
  51610. var originalGroup = el.object3D;
  51611. var outerGroup = new THREE.Group();
  51612. originalPosition.copy(originalGroup.position);
  51613. originalRotation.copy(originalGroup.rotation);
  51614. // Detach current group from parent.
  51615. originalParent.remove(originalGroup);
  51616. outerGroup.add(originalGroup);
  51617. // Set new group as the outer group.
  51618. originalParent.add(outerGroup);
  51619. // Set outer group as new object3D.
  51620. el.object3D = outerGroup;
  51621. // Apply pivot to original group.
  51622. originalGroup.position.set(-1 * data.x, -1 * data.y, -1 * data.z);
  51623. // Offset the pivot so that world position not affected.
  51624. // And restore position onto outer group.
  51625. outerGroup.position.set(data.x + originalPosition.x, data.y + originalPosition.y,
  51626. data.z + originalPosition.z);
  51627. // Transfer rotation to outer group.
  51628. outerGroup.rotation.copy(originalGroup.rotation);
  51629. originalGroup.rotation.set(0, 0, 0);
  51630. }
  51631. });
  51632. },{"../../core/component":126,"../../lib/three":174}],139:[function(_dereq_,module,exports){
  51633. /**
  51634. * Common mesh defaults, mappings, and transforms.
  51635. */
  51636. var components = _dereq_('../../core/component').components;
  51637. var shaders = _dereq_('../../core/shader').shaders;
  51638. var utils = _dereq_('../../utils/');
  51639. var materialMappings = {};
  51640. Object.keys(components.material.schema).forEach(addMapping);
  51641. Object.keys(shaders.standard.schema).forEach(addMapping);
  51642. function addMapping (prop) {
  51643. // To hyphenated.
  51644. var htmlAttrName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  51645. if (prop === 'fog') { htmlAttrName = 'material-fog'; }
  51646. if (prop === 'visible') { htmlAttrName = 'material-visible'; }
  51647. materialMappings[htmlAttrName] = 'material.' + prop;
  51648. }
  51649. module.exports = function getMeshMixin () {
  51650. return {
  51651. defaultComponents: {material: {}},
  51652. mappings: utils.extend({}, materialMappings)
  51653. };
  51654. };
  51655. },{"../../core/component":126,"../../core/shader":135,"../../utils/":197}],140:[function(_dereq_,module,exports){
  51656. _dereq_('./primitives/a-camera');
  51657. _dereq_('./primitives/a-collada-model');
  51658. _dereq_('./primitives/a-cursor');
  51659. _dereq_('./primitives/a-curvedimage');
  51660. _dereq_('./primitives/a-gltf-model');
  51661. _dereq_('./primitives/a-image');
  51662. _dereq_('./primitives/a-light');
  51663. _dereq_('./primitives/a-link');
  51664. _dereq_('./primitives/a-obj-model');
  51665. _dereq_('./primitives/a-sky');
  51666. _dereq_('./primitives/a-sound');
  51667. _dereq_('./primitives/a-text');
  51668. _dereq_('./primitives/a-video');
  51669. _dereq_('./primitives/a-videosphere');
  51670. _dereq_('./primitives/meshPrimitives');
  51671. },{"./primitives/a-camera":142,"./primitives/a-collada-model":143,"./primitives/a-cursor":144,"./primitives/a-curvedimage":145,"./primitives/a-gltf-model":146,"./primitives/a-image":147,"./primitives/a-light":148,"./primitives/a-link":149,"./primitives/a-obj-model":150,"./primitives/a-sky":151,"./primitives/a-sound":152,"./primitives/a-text":153,"./primitives/a-video":154,"./primitives/a-videosphere":155,"./primitives/meshPrimitives":156}],141:[function(_dereq_,module,exports){
  51672. var AEntity = _dereq_('../../core/a-entity');
  51673. var components = _dereq_('../../core/component').components;
  51674. var registerElement = _dereq_('../../core/a-register-element').registerElement;
  51675. var utils = _dereq_('../../utils/');
  51676. var debug = utils.debug;
  51677. var setComponentProperty = utils.entity.setComponentProperty;
  51678. var log = debug('extras:primitives:debug');
  51679. var warn = debug('extras:primitives:warn');
  51680. var primitives = module.exports.primitives = {};
  51681. module.exports.registerPrimitive = function registerPrimitive (name, definition) {
  51682. name = name.toLowerCase();
  51683. log('Registering <%s>', name);
  51684. // Deprecation warning for defaultAttributes usage.
  51685. if (definition.defaultAttributes) {
  51686. warn("The 'defaultAttributes' object is deprecated. Use 'defaultComponents' instead.");
  51687. }
  51688. var primitive = registerElement(name, {
  51689. prototype: Object.create(AEntity.prototype, {
  51690. defaultComponentsFromPrimitive: {
  51691. value: definition.defaultComponents || definition.defaultAttributes || {}
  51692. },
  51693. deprecated: {value: definition.deprecated || null},
  51694. deprecatedMappings: {value: definition.deprecatedMappings || {}},
  51695. mappings: {value: definition.mappings || {}},
  51696. createdCallback: {
  51697. value: function () {
  51698. if (definition.deprecated) { console.warn(definition.deprecated); }
  51699. this.resolveMappingCollisions();
  51700. }
  51701. },
  51702. /**
  51703. * If a mapping collides with a registered component name
  51704. * it renames the mapping to componentname-property
  51705. */
  51706. resolveMappingCollisions: {
  51707. value: function () {
  51708. var mappings = this.mappings;
  51709. var self = this;
  51710. Object.keys(mappings).forEach(function resolveCollision (key) {
  51711. var newAttribute;
  51712. if (key !== key.toLowerCase()) { warn('Mapping keys should be specified in lower case. The mapping key ' + key + ' may not be recognized'); }
  51713. if (components[key]) {
  51714. newAttribute = mappings[key].replace('.', '-');
  51715. mappings[newAttribute] = mappings[key];
  51716. delete mappings[key];
  51717. console.warn('The primitive ' + self.tagName.toLowerCase() + ' has a mapping collision. ' +
  51718. 'The attribute ' + key + ' has the same name as a registered component and' +
  51719. ' has been renamed to ' + newAttribute);
  51720. }
  51721. });
  51722. }
  51723. },
  51724. getExtraComponents: {
  51725. value: function () {
  51726. var attr;
  51727. var data;
  51728. var i;
  51729. var mapping;
  51730. var mixins;
  51731. var path;
  51732. var self = this;
  51733. // Gather component data from default components.
  51734. data = utils.clone(this.defaultComponentsFromPrimitive);
  51735. // Factor in mixins to overwrite default components.
  51736. mixins = this.getAttribute('mixin');
  51737. if (mixins) {
  51738. mixins = mixins.trim().split(' ');
  51739. mixins.forEach(function applyMixin (mixinId) {
  51740. var mixinComponents = self.sceneEl.querySelector('#' + mixinId).componentCache;
  51741. Object.keys(mixinComponents).forEach(function setComponent (name) {
  51742. data[name] = extend(data[name], mixinComponents[name]);
  51743. });
  51744. });
  51745. }
  51746. // Gather component data from mappings.
  51747. for (i = 0; i < this.attributes.length; i++) {
  51748. attr = this.attributes[i];
  51749. mapping = this.mappings[attr.name];
  51750. if (mapping) {
  51751. path = utils.entity.getComponentPropertyPath(mapping);
  51752. if (path.constructor === Array) {
  51753. data[path[0]] = data[path[0]] || {};
  51754. data[path[0]][path[1]] = attr.value;
  51755. } else {
  51756. data[path] = attr.value;
  51757. }
  51758. continue;
  51759. }
  51760. }
  51761. return data;
  51762. /**
  51763. * For the base to be extensible, both objects must be pure JavaScript objects.
  51764. * The function assumes that base is undefined, or null or a pure object.
  51765. */
  51766. function extend (base, extension) {
  51767. if (isUndefined(base)) {
  51768. return copy(extension);
  51769. }
  51770. if (isUndefined(extension)) {
  51771. return copy(base);
  51772. }
  51773. if (isPureObject(base) && isPureObject(extension)) {
  51774. return utils.extendDeep(base, extension);
  51775. }
  51776. return copy(extension);
  51777. }
  51778. function isUndefined (value) {
  51779. return typeof value === 'undefined';
  51780. }
  51781. function copy (value) {
  51782. if (isPureObject(value)) {
  51783. return utils.extendDeep({}, value);
  51784. }
  51785. return value;
  51786. }
  51787. function isPureObject (value) {
  51788. return value !== null && value.constructor === Object;
  51789. }
  51790. }
  51791. },
  51792. /**
  51793. * Sync to attribute to component property whenever mapped attribute changes.
  51794. * If attribute is mapped to a component property, set the component property using
  51795. * the attribute value.
  51796. */
  51797. attributeChangedCallback: {
  51798. value: function (attr, oldVal, value) {
  51799. var componentName = this.mappings[attr];
  51800. if (attr in this.deprecatedMappings) {
  51801. console.warn(this.deprecatedMappings[attr]);
  51802. }
  51803. if (!attr || !componentName) { return; }
  51804. // Set value.
  51805. setComponentProperty(this, componentName, value);
  51806. }
  51807. }
  51808. })
  51809. });
  51810. // Store.
  51811. primitives[name] = primitive;
  51812. return primitive;
  51813. };
  51814. /**
  51815. * Add component mappings using schema.
  51816. */
  51817. function addComponentMapping (componentName, mappings) {
  51818. var schema = components[componentName].schema;
  51819. Object.keys(schema).map(function (prop) {
  51820. // Hyphenate where there is camelCase.
  51821. var attrName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  51822. // If there is a mapping collision, prefix with component name and hyphen.
  51823. if (mappings[attrName] !== undefined) { attrName = componentName + '-' + prop; }
  51824. mappings[attrName] = componentName + '.' + prop;
  51825. });
  51826. }
  51827. /**
  51828. * Helper to define a primitive, building mappings using a component schema.
  51829. */
  51830. function definePrimitive (tagName, defaultComponents, mappings) {
  51831. // If no initial mappings provided, start from empty map.
  51832. mappings = mappings || {};
  51833. // From the default components, add mapping automagically.
  51834. Object.keys(defaultComponents).map(function buildMappings (componentName) {
  51835. addComponentMapping(componentName, mappings);
  51836. });
  51837. // Register the primitive.
  51838. module.exports.registerPrimitive(tagName, utils.extendDeep({}, null, {
  51839. defaultComponents: defaultComponents,
  51840. mappings: mappings
  51841. }));
  51842. }
  51843. module.exports.definePrimitive = definePrimitive;
  51844. },{"../../core/a-entity":122,"../../core/a-register-element":125,"../../core/component":126,"../../utils/":197}],142:[function(_dereq_,module,exports){
  51845. var DEFAULT_CAMERA_HEIGHT = _dereq_('../../../constants/').DEFAULT_CAMERA_HEIGHT;
  51846. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51847. registerPrimitive('a-camera', {
  51848. defaultComponents: {
  51849. camera: {
  51850. userHeight: DEFAULT_CAMERA_HEIGHT
  51851. },
  51852. 'look-controls': {},
  51853. 'wasd-controls': {}
  51854. },
  51855. mappings: {
  51856. active: 'camera.active',
  51857. far: 'camera.far',
  51858. fov: 'camera.fov',
  51859. 'look-controls-enabled': 'look-controls.enabled',
  51860. near: 'camera.near',
  51861. 'wasd-controls-enabled': 'wasd-controls.enabled',
  51862. 'reverse-mouse-drag': 'look-controls.reverseMouseDrag',
  51863. 'user-height': 'camera.userHeight',
  51864. zoom: 'camera.zoom'
  51865. },
  51866. deprecatedMappings: {
  51867. 'cursor-color': 'a-camera[cursor-color] has been removed. Use a-cursor[color] instead.',
  51868. 'cursor-maxdistance': 'a-camera[cursor-maxdistance] has been removed. Use a-cursor[max-distance] instead.',
  51869. 'cursor-offset': 'a-camera[cursor-offset] has been removed. Use a-cursor[position] instead.',
  51870. 'cursor-opacity': 'a-camera[cursor-offset] has been removed. Use a-cursor[opacity] instead.',
  51871. 'cursor-scale': 'a-camera[cursor-scale] has been removed. Use a-cursor[scale] instead.',
  51872. 'cursor-visible': 'a-camera[cursor-visible] has been removed. Use a-cursor[visible] instead.'
  51873. }
  51874. });
  51875. },{"../../../constants/":117,"../primitives":141}],143:[function(_dereq_,module,exports){
  51876. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51877. registerPrimitive('a-collada-model', {
  51878. mappings: {
  51879. src: 'collada-model'
  51880. }
  51881. });
  51882. },{"../primitives":141}],144:[function(_dereq_,module,exports){
  51883. var getMeshMixin = _dereq_('../getMeshMixin');
  51884. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51885. var utils = _dereq_('../../../utils/');
  51886. registerPrimitive('a-cursor', utils.extendDeep({}, getMeshMixin(), {
  51887. defaultComponents: {
  51888. cursor: {},
  51889. geometry: {
  51890. primitive: 'ring',
  51891. radiusOuter: 0.016,
  51892. radiusInner: 0.01,
  51893. segmentsTheta: 32
  51894. },
  51895. material: {
  51896. color: '#000',
  51897. shader: 'flat',
  51898. opacity: 0.8
  51899. },
  51900. position: {
  51901. x: 0,
  51902. y: 0,
  51903. z: -1
  51904. }
  51905. },
  51906. mappings: {
  51907. far: 'raycaster.far',
  51908. fuse: 'cursor.fuse',
  51909. 'fuse-timeout': 'cursor.fuseTimeout',
  51910. interval: 'raycaster.interval',
  51911. objects: 'raycaster.objects'
  51912. }
  51913. }));
  51914. },{"../../../utils/":197,"../getMeshMixin":139,"../primitives":141}],145:[function(_dereq_,module,exports){
  51915. var getMeshMixin = _dereq_('../getMeshMixin');
  51916. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51917. var utils = _dereq_('../../../utils/');
  51918. registerPrimitive('a-curvedimage', utils.extendDeep({}, getMeshMixin(), {
  51919. defaultComponents: {
  51920. geometry: {
  51921. height: 1,
  51922. primitive: 'cylinder',
  51923. radius: 2,
  51924. segmentsRadial: 48,
  51925. thetaLength: 270,
  51926. openEnded: true,
  51927. thetaStart: 0
  51928. },
  51929. material: {
  51930. color: '#FFF',
  51931. shader: 'flat',
  51932. side: 'double',
  51933. transparent: true,
  51934. repeat: '-1 1'
  51935. }
  51936. },
  51937. mappings: {
  51938. height: 'geometry.height',
  51939. 'open-ended': 'geometry.openEnded',
  51940. radius: 'geometry.radius',
  51941. segments: 'geometry.segmentsRadial',
  51942. start: 'geometry.thetaStart',
  51943. 'theta-length': 'geometry.thetaLength',
  51944. 'theta-start': 'geometry.thetaStart',
  51945. 'width': 'geometry.thetaLength'
  51946. }
  51947. }));
  51948. },{"../../../utils/":197,"../getMeshMixin":139,"../primitives":141}],146:[function(_dereq_,module,exports){
  51949. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51950. registerPrimitive('a-gltf-model', {
  51951. mappings: {
  51952. src: 'gltf-model'
  51953. }
  51954. });
  51955. },{"../primitives":141}],147:[function(_dereq_,module,exports){
  51956. var getMeshMixin = _dereq_('../getMeshMixin');
  51957. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51958. var utils = _dereq_('../../../utils/');
  51959. registerPrimitive('a-image', utils.extendDeep({}, getMeshMixin(), {
  51960. defaultComponents: {
  51961. geometry: {
  51962. primitive: 'plane'
  51963. },
  51964. material: {
  51965. color: '#FFF',
  51966. shader: 'flat',
  51967. side: 'double',
  51968. transparent: true
  51969. }
  51970. },
  51971. mappings: {
  51972. height: 'geometry.height',
  51973. width: 'geometry.width'
  51974. }
  51975. }));
  51976. },{"../../../utils/":197,"../getMeshMixin":139,"../primitives":141}],148:[function(_dereq_,module,exports){
  51977. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51978. registerPrimitive('a-light', {
  51979. defaultComponents: {
  51980. light: {}
  51981. },
  51982. mappings: {
  51983. angle: 'light.angle',
  51984. color: 'light.color',
  51985. 'ground-color': 'light.groundColor',
  51986. decay: 'light.decay',
  51987. distance: 'light.distance',
  51988. intensity: 'light.intensity',
  51989. penumbra: 'light.penumbra',
  51990. type: 'light.type',
  51991. target: 'light.target'
  51992. }
  51993. });
  51994. },{"../primitives":141}],149:[function(_dereq_,module,exports){
  51995. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51996. registerPrimitive('a-link', {
  51997. defaultComponents: {},
  51998. mappings: {
  51999. href: 'link.href',
  52000. image: 'link.image',
  52001. title: 'link.title'
  52002. }
  52003. });
  52004. },{"../primitives":141}],150:[function(_dereq_,module,exports){
  52005. var meshMixin = _dereq_('../getMeshMixin')();
  52006. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52007. var utils = _dereq_('../../../utils/');
  52008. registerPrimitive('a-obj-model', utils.extendDeep({}, meshMixin, {
  52009. defaultComponents: {
  52010. 'obj-model': {}
  52011. },
  52012. mappings: {
  52013. src: 'obj-model.obj',
  52014. mtl: 'obj-model.mtl'
  52015. }
  52016. }));
  52017. },{"../../../utils/":197,"../getMeshMixin":139,"../primitives":141}],151:[function(_dereq_,module,exports){
  52018. var getMeshMixin = _dereq_('../getMeshMixin');
  52019. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52020. var utils = _dereq_('../../../utils/');
  52021. var meshPrimitives = _dereq_('./meshPrimitives');
  52022. registerPrimitive('a-sky', utils.extendDeep({}, getMeshMixin(), {
  52023. defaultComponents: {
  52024. geometry: {
  52025. primitive: 'sphere',
  52026. radius: 5000,
  52027. segmentsWidth: 64,
  52028. segmentsHeight: 32
  52029. },
  52030. material: {
  52031. color: '#FFF',
  52032. shader: 'flat',
  52033. npot: true
  52034. },
  52035. scale: '-1 1 1'
  52036. },
  52037. mappings: utils.extendDeep({}, meshPrimitives['a-sphere'].prototype.mappings)
  52038. }));
  52039. },{"../../../utils/":197,"../getMeshMixin":139,"../primitives":141,"./meshPrimitives":156}],152:[function(_dereq_,module,exports){
  52040. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52041. registerPrimitive('a-sound', {
  52042. defaultComponents: {
  52043. sound: {}
  52044. },
  52045. mappings: {
  52046. src: 'sound.src',
  52047. on: 'sound.on',
  52048. autoplay: 'sound.autoplay',
  52049. loop: 'sound.loop',
  52050. volume: 'sound.volume'
  52051. }
  52052. });
  52053. },{"../primitives":141}],153:[function(_dereq_,module,exports){
  52054. // <a-text> using `definePrimitive` helper.
  52055. var definePrimitive = _dereq_('../primitives').definePrimitive;
  52056. definePrimitive('a-text', {text: {anchor: 'align', width: 5}});
  52057. },{"../primitives":141}],154:[function(_dereq_,module,exports){
  52058. var getMeshMixin = _dereq_('../getMeshMixin');
  52059. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52060. var utils = _dereq_('../../../utils/');
  52061. registerPrimitive('a-video', utils.extendDeep({}, getMeshMixin(), {
  52062. defaultComponents: {
  52063. geometry: {
  52064. primitive: 'plane'
  52065. },
  52066. material: {
  52067. color: '#FFF',
  52068. shader: 'flat',
  52069. side: 'double',
  52070. transparent: true
  52071. }
  52072. },
  52073. mappings: {
  52074. height: 'geometry.height',
  52075. width: 'geometry.width'
  52076. }
  52077. }));
  52078. },{"../../../utils/":197,"../getMeshMixin":139,"../primitives":141}],155:[function(_dereq_,module,exports){
  52079. var getMeshMixin = _dereq_('../getMeshMixin');
  52080. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52081. var utils = _dereq_('../../../utils/');
  52082. registerPrimitive('a-videosphere', utils.extendDeep({}, getMeshMixin(), {
  52083. defaultComponents: {
  52084. geometry: {
  52085. primitive: 'sphere',
  52086. radius: 5000,
  52087. segmentsWidth: 64,
  52088. segmentsHeight: 32
  52089. },
  52090. material: {
  52091. color: '#FFF',
  52092. shader: 'flat',
  52093. npot: true
  52094. },
  52095. scale: '-1 1 1'
  52096. },
  52097. mappings: {
  52098. radius: 'geometry.radius',
  52099. 'segments-height': 'geometry.segmentsHeight',
  52100. 'segments-width': 'geometry.segmentsWidth'
  52101. }
  52102. }));
  52103. },{"../../../utils/":197,"../getMeshMixin":139,"../primitives":141}],156:[function(_dereq_,module,exports){
  52104. /**
  52105. * Automated mesh primitive registration.
  52106. */
  52107. var getMeshMixin = _dereq_('../getMeshMixin');
  52108. var geometries = _dereq_('../../../core/geometry').geometries;
  52109. var geometryNames = _dereq_('../../../core/geometry').geometryNames;
  52110. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52111. var utils = _dereq_('../../../utils/');
  52112. // For testing.
  52113. var meshPrimitives = module.exports = {};
  52114. // Generate primitive for each geometry type.
  52115. geometryNames.forEach(function registerMeshPrimitive (geometryName) {
  52116. var geometry = geometries[geometryName];
  52117. var geometryHyphened = unCamelCase(geometryName);
  52118. // Generate mappings.
  52119. var mappings = {};
  52120. Object.keys(geometry.schema).forEach(function createMapping (property) {
  52121. mappings[unCamelCase(property)] = 'geometry.' + property;
  52122. });
  52123. // Register.
  52124. var tagName = 'a-' + geometryHyphened;
  52125. var primitive = registerPrimitive(tagName, utils.extendDeep({}, getMeshMixin(), {
  52126. defaultComponents: {geometry: {primitive: geometryName}},
  52127. mappings: mappings
  52128. }));
  52129. meshPrimitives[tagName] = primitive;
  52130. });
  52131. /**
  52132. * camelCase to hyphened-string.
  52133. */
  52134. function unCamelCase (str) {
  52135. return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  52136. }
  52137. },{"../../../core/geometry":127,"../../../utils/":197,"../getMeshMixin":139,"../primitives":141}],157:[function(_dereq_,module,exports){
  52138. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52139. var THREE = _dereq_('../lib/three');
  52140. registerGeometry('box', {
  52141. schema: {
  52142. depth: {default: 1, min: 0},
  52143. height: {default: 1, min: 0},
  52144. width: {default: 1, min: 0},
  52145. segmentsHeight: {default: 1, min: 1, max: 20, type: 'int'},
  52146. segmentsWidth: {default: 1, min: 1, max: 20, type: 'int'},
  52147. segmentsDepth: {default: 1, min: 1, max: 20, type: 'int'}
  52148. },
  52149. init: function (data) {
  52150. this.geometry = new THREE.BoxGeometry(
  52151. data.width, data.height, data.depth,
  52152. data.segmentsWidth, data.segmentsHeight, data.segmentsDepth);
  52153. }
  52154. });
  52155. },{"../core/geometry":127,"../lib/three":174}],158:[function(_dereq_,module,exports){
  52156. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52157. var THREE = _dereq_('../lib/three');
  52158. var degToRad = THREE.Math.degToRad;
  52159. registerGeometry('circle', {
  52160. schema: {
  52161. radius: {default: 1, min: 0},
  52162. segments: {default: 32, min: 3, type: 'int'},
  52163. thetaLength: {default: 360, min: 0},
  52164. thetaStart: {default: 0}
  52165. },
  52166. init: function (data) {
  52167. this.geometry = new THREE.CircleGeometry(
  52168. data.radius, data.segments, degToRad(data.thetaStart), degToRad(data.thetaLength));
  52169. }
  52170. });
  52171. },{"../core/geometry":127,"../lib/three":174}],159:[function(_dereq_,module,exports){
  52172. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52173. var THREE = _dereq_('../lib/three');
  52174. var degToRad = THREE.Math.degToRad;
  52175. registerGeometry('cone', {
  52176. schema: {
  52177. height: {default: 1, min: 0},
  52178. openEnded: {default: false},
  52179. radiusBottom: {default: 1, min: 0},
  52180. radiusTop: {default: 0.01, min: 0},
  52181. segmentsHeight: {default: 18, min: 1, type: 'int'},
  52182. segmentsRadial: {default: 36, min: 3, type: 'int'},
  52183. thetaLength: {default: 360, min: 0},
  52184. thetaStart: {default: 0}
  52185. },
  52186. init: function (data) {
  52187. this.geometry = new THREE.CylinderGeometry(
  52188. data.radiusTop, data.radiusBottom, data.height, data.segmentsRadial,
  52189. data.segmentsHeight, data.openEnded, degToRad(data.thetaStart),
  52190. degToRad(data.thetaLength));
  52191. }
  52192. });
  52193. },{"../core/geometry":127,"../lib/three":174}],160:[function(_dereq_,module,exports){
  52194. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52195. var THREE = _dereq_('../lib/three');
  52196. var degToRad = THREE.Math.degToRad;
  52197. registerGeometry('cylinder', {
  52198. schema: {
  52199. height: {default: 1, min: 0},
  52200. openEnded: {default: false},
  52201. radius: {default: 1, min: 0},
  52202. segmentsHeight: {default: 18, min: 1, type: 'int'},
  52203. segmentsRadial: {default: 36, min: 3, type: 'int'},
  52204. thetaLength: {default: 360, min: 0},
  52205. thetaStart: {default: 0}
  52206. },
  52207. init: function (data) {
  52208. this.geometry = new THREE.CylinderGeometry(
  52209. data.radius, data.radius, data.height, data.segmentsRadial, data.segmentsHeight,
  52210. data.openEnded, degToRad(data.thetaStart), degToRad(data.thetaLength));
  52211. }
  52212. });
  52213. },{"../core/geometry":127,"../lib/three":174}],161:[function(_dereq_,module,exports){
  52214. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52215. var THREE = _dereq_('../lib/three');
  52216. registerGeometry('dodecahedron', {
  52217. schema: {
  52218. detail: {default: 0, min: 0, max: 5, type: 'int'},
  52219. radius: {default: 1, min: 0}
  52220. },
  52221. init: function (data) {
  52222. this.geometry = new THREE.DodecahedronGeometry(data.radius, data.detail);
  52223. }
  52224. });
  52225. },{"../core/geometry":127,"../lib/three":174}],162:[function(_dereq_,module,exports){
  52226. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52227. var THREE = _dereq_('../lib/three');
  52228. registerGeometry('icosahedron', {
  52229. schema: {
  52230. detail: {default: 0, min: 0, max: 5, type: 'int'},
  52231. radius: {default: 1, min: 0}
  52232. },
  52233. init: function (data) {
  52234. this.geometry = new THREE.IcosahedronGeometry(data.radius, data.detail);
  52235. }
  52236. });
  52237. },{"../core/geometry":127,"../lib/three":174}],163:[function(_dereq_,module,exports){
  52238. _dereq_('./box.js');
  52239. _dereq_('./circle.js');
  52240. _dereq_('./cone.js');
  52241. _dereq_('./cylinder.js');
  52242. _dereq_('./dodecahedron.js');
  52243. _dereq_('./icosahedron.js');
  52244. _dereq_('./octahedron.js');
  52245. _dereq_('./plane.js');
  52246. _dereq_('./ring.js');
  52247. _dereq_('./sphere.js');
  52248. _dereq_('./tetrahedron.js');
  52249. _dereq_('./torus.js');
  52250. _dereq_('./torusKnot.js');
  52251. _dereq_('./triangle.js');
  52252. },{"./box.js":157,"./circle.js":158,"./cone.js":159,"./cylinder.js":160,"./dodecahedron.js":161,"./icosahedron.js":162,"./octahedron.js":164,"./plane.js":165,"./ring.js":166,"./sphere.js":167,"./tetrahedron.js":168,"./torus.js":169,"./torusKnot.js":170,"./triangle.js":171}],164:[function(_dereq_,module,exports){
  52253. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52254. var THREE = _dereq_('../lib/three');
  52255. registerGeometry('octahedron', {
  52256. schema: {
  52257. detail: {default: 0, min: 0, max: 5, type: 'int'},
  52258. radius: {default: 1, min: 0}
  52259. },
  52260. init: function (data) {
  52261. this.geometry = new THREE.OctahedronGeometry(data.radius, data.detail);
  52262. }
  52263. });
  52264. },{"../core/geometry":127,"../lib/three":174}],165:[function(_dereq_,module,exports){
  52265. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52266. var THREE = _dereq_('../lib/three');
  52267. registerGeometry('plane', {
  52268. schema: {
  52269. height: {default: 1, min: 0},
  52270. width: {default: 1, min: 0},
  52271. segmentsHeight: {default: 1, min: 1, max: 20, type: 'int'},
  52272. segmentsWidth: {default: 1, min: 1, max: 20, type: 'int'}
  52273. },
  52274. init: function (data) {
  52275. this.geometry = new THREE.PlaneGeometry(data.width, data.height, data.segmentsWidth, data.segmentsHeight);
  52276. }
  52277. });
  52278. },{"../core/geometry":127,"../lib/three":174}],166:[function(_dereq_,module,exports){
  52279. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52280. var THREE = _dereq_('../lib/three');
  52281. var degToRad = THREE.Math.degToRad;
  52282. registerGeometry('ring', {
  52283. schema: {
  52284. radiusInner: {default: 0.8, min: 0},
  52285. radiusOuter: {default: 1.2, min: 0},
  52286. segmentsPhi: {default: 10, min: 1, type: 'int'},
  52287. segmentsTheta: {default: 32, min: 3, type: 'int'},
  52288. thetaLength: {default: 360, min: 0},
  52289. thetaStart: {default: 0}
  52290. },
  52291. init: function (data) {
  52292. this.geometry = new THREE.RingGeometry(
  52293. data.radiusInner, data.radiusOuter, data.segmentsTheta, data.segmentsPhi,
  52294. degToRad(data.thetaStart), degToRad(data.thetaLength));
  52295. }
  52296. });
  52297. },{"../core/geometry":127,"../lib/three":174}],167:[function(_dereq_,module,exports){
  52298. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52299. var THREE = _dereq_('../lib/three');
  52300. var degToRad = THREE.Math.degToRad;
  52301. registerGeometry('sphere', {
  52302. schema: {
  52303. radius: {default: 1, min: 0},
  52304. phiLength: {default: 360},
  52305. phiStart: {default: 0, min: 0},
  52306. thetaLength: {default: 180, min: 0},
  52307. thetaStart: {default: 0},
  52308. segmentsHeight: {default: 18, min: 2, type: 'int'},
  52309. segmentsWidth: {default: 36, min: 3, type: 'int'}
  52310. },
  52311. init: function (data) {
  52312. this.geometry = new THREE.SphereGeometry(
  52313. data.radius, data.segmentsWidth, data.segmentsHeight, degToRad(data.phiStart),
  52314. degToRad(data.phiLength), degToRad(data.thetaStart), degToRad(data.thetaLength));
  52315. }
  52316. });
  52317. },{"../core/geometry":127,"../lib/three":174}],168:[function(_dereq_,module,exports){
  52318. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52319. var THREE = _dereq_('../lib/three');
  52320. registerGeometry('tetrahedron', {
  52321. schema: {
  52322. detail: {default: 0, min: 0, max: 5, type: 'int'},
  52323. radius: {default: 1, min: 0}
  52324. },
  52325. init: function (data) {
  52326. this.geometry = new THREE.TetrahedronGeometry(data.radius, data.detail);
  52327. }
  52328. });
  52329. },{"../core/geometry":127,"../lib/three":174}],169:[function(_dereq_,module,exports){
  52330. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52331. var THREE = _dereq_('../lib/three');
  52332. var degToRad = THREE.Math.degToRad;
  52333. registerGeometry('torus', {
  52334. schema: {
  52335. arc: {default: 360},
  52336. radius: {default: 1, min: 0},
  52337. radiusTubular: {default: 0.2, min: 0},
  52338. segmentsRadial: {default: 36, min: 2, type: 'int'},
  52339. segmentsTubular: {default: 32, min: 3, type: 'int'}
  52340. },
  52341. init: function (data) {
  52342. this.geometry = new THREE.TorusGeometry(
  52343. data.radius, data.radiusTubular * 2, data.segmentsRadial, data.segmentsTubular,
  52344. degToRad(data.arc));
  52345. }
  52346. });
  52347. },{"../core/geometry":127,"../lib/three":174}],170:[function(_dereq_,module,exports){
  52348. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52349. var THREE = _dereq_('../lib/three');
  52350. registerGeometry('torusKnot', {
  52351. schema: {
  52352. p: {default: 2, min: 1},
  52353. q: {default: 3, min: 1},
  52354. radius: {default: 1, min: 0},
  52355. radiusTubular: {default: 0.2, min: 0},
  52356. segmentsRadial: {default: 8, min: 3, type: 'int'},
  52357. segmentsTubular: {default: 100, min: 3, type: 'int'}
  52358. },
  52359. init: function (data) {
  52360. this.geometry = new THREE.TorusKnotGeometry(
  52361. data.radius, data.radiusTubular * 2, data.segmentsTubular, data.segmentsRadial,
  52362. data.p, data.q);
  52363. }
  52364. });
  52365. },{"../core/geometry":127,"../lib/three":174}],171:[function(_dereq_,module,exports){
  52366. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52367. var THREE = _dereq_('../lib/three');
  52368. var quaternion = new THREE.Quaternion();
  52369. var rotateVector = new THREE.Vector3(0, 0, 1);
  52370. var uvMinVector = new THREE.Vector2();
  52371. var uvMaxVector = new THREE.Vector2();
  52372. var uvScaleVector = new THREE.Vector2();
  52373. registerGeometry('triangle', {
  52374. schema: {
  52375. vertexA: {type: 'vec3', default: {x: 0, y: 0.5, z: 0}},
  52376. vertexB: {type: 'vec3', default: {x: -0.5, y: -0.5, z: 0}},
  52377. vertexC: {type: 'vec3', default: {x: 0.5, y: -0.5, z: 0}}
  52378. },
  52379. init: function (data) {
  52380. var geometry;
  52381. var normal;
  52382. var triangle;
  52383. var uvA;
  52384. var uvB;
  52385. var uvC;
  52386. triangle = new THREE.Triangle();
  52387. triangle.a.set(data.vertexA.x, data.vertexA.y, data.vertexA.z);
  52388. triangle.b.set(data.vertexB.x, data.vertexB.y, data.vertexB.z);
  52389. triangle.c.set(data.vertexC.x, data.vertexC.y, data.vertexC.z);
  52390. normal = triangle.normal();
  52391. // Rotate the 3D triangle to be parallel to XY plane.
  52392. quaternion.setFromUnitVectors(normal, rotateVector);
  52393. uvA = triangle.a.clone().applyQuaternion(quaternion);
  52394. uvB = triangle.b.clone().applyQuaternion(quaternion);
  52395. uvC = triangle.c.clone().applyQuaternion(quaternion);
  52396. // Compute UVs.
  52397. // Normalize x/y values of UV so they are within 0 to 1.
  52398. uvMinVector.set(Math.min(uvA.x, uvB.x, uvC.x), Math.min(uvA.y, uvB.y, uvC.y));
  52399. uvMaxVector.set(Math.max(uvA.x, uvB.x, uvC.x), Math.max(uvA.y, uvB.y, uvC.y));
  52400. uvScaleVector.set(0, 0).subVectors(uvMaxVector, uvMinVector);
  52401. uvA = new THREE.Vector2().subVectors(uvA, uvMinVector).divide(uvScaleVector);
  52402. uvB = new THREE.Vector2().subVectors(uvB, uvMinVector).divide(uvScaleVector);
  52403. uvC = new THREE.Vector2().subVectors(uvC, uvMinVector).divide(uvScaleVector);
  52404. geometry = this.geometry = new THREE.Geometry();
  52405. geometry.vertices.push(triangle.a);
  52406. geometry.vertices.push(triangle.b);
  52407. geometry.vertices.push(triangle.c);
  52408. geometry.faces.push(new THREE.Face3(0, 1, 2, normal));
  52409. geometry.faceVertexUvs[0] = [[uvA, uvB, uvC]];
  52410. }
  52411. });
  52412. },{"../core/geometry":127,"../lib/three":174}],172:[function(_dereq_,module,exports){
  52413. var utils = _dereq_('./utils/');
  52414. var debug = utils.debug;
  52415. var error = debug('A-Frame:error');
  52416. var warn = debug('A-Frame:warn');
  52417. if (window.document.currentScript && window.document.currentScript.parentNode !==
  52418. window.document.head && !window.debug) {
  52419. warn('Put the A-Frame <script> tag in the <head> of the HTML *before* the scene to ' +
  52420. 'ensure everything for A-Frame is properly registered before they are used from ' +
  52421. 'HTML.');
  52422. }
  52423. // Error if not using a server.
  52424. if (window.location.protocol === 'file:') {
  52425. error(
  52426. 'This HTML file is currently being served via the file:// protocol. ' +
  52427. 'Assets, textures, and models WILL NOT WORK due to cross-origin policy! ' +
  52428. 'Please use a local or hosted server: ' +
  52429. 'https://aframe.io/docs/0.5.0/introduction/getting-started.html#using-a-local-server.');
  52430. }
  52431. // Polyfill `Promise`.
  52432. window.Promise = window.Promise || _dereq_('promise-polyfill');
  52433. // Check before the polyfill runs.
  52434. window.hasNativeWebVRImplementation = !!window.navigator.getVRDisplays || !!window.navigator.getVRDevices;
  52435. window.WebVRConfig = window.WebVRConfig || {
  52436. BUFFER_SCALE: 1,
  52437. CARDBOARD_UI_DISABLED: true,
  52438. ROTATE_INSTRUCTIONS_DISABLED: true,
  52439. TOUCH_PANNER_DISABLED: true,
  52440. MOUSE_KEYBOARD_CONTROLS_DISABLED: true
  52441. };
  52442. // Workaround for iOS Safari canvas sizing issues in stereo (webvr-polyfill/issues/102).
  52443. // Only for iOS on versions older than 10.
  52444. if (utils.device.isIOSOlderThan10(window.navigator.userAgent)) {
  52445. window.WebVRConfig.BUFFER_SCALE = 1 / window.devicePixelRatio;
  52446. }
  52447. // WebVR polyfill
  52448. _dereq_('webvr-polyfill');
  52449. _dereq_('present'); // Polyfill `performance.now()`.
  52450. // CSS.
  52451. if (utils.device.isBrowserEnvironment) {
  52452. _dereq_('./style/aframe.css');
  52453. _dereq_('./style/rStats.css');
  52454. }
  52455. // Required before `AEntity` so that all components are registered.
  52456. var AScene = _dereq_('./core/scene/a-scene').AScene;
  52457. var components = _dereq_('./core/component').components;
  52458. var registerComponent = _dereq_('./core/component').registerComponent;
  52459. var registerGeometry = _dereq_('./core/geometry').registerGeometry;
  52460. var registerPrimitive = _dereq_('./extras/primitives/primitives').registerPrimitive;
  52461. var registerShader = _dereq_('./core/shader').registerShader;
  52462. var registerSystem = _dereq_('./core/system').registerSystem;
  52463. var shaders = _dereq_('./core/shader').shaders;
  52464. var systems = _dereq_('./core/system').systems;
  52465. // Exports THREE to window so three.js can be used without alteration.
  52466. var THREE = window.THREE = _dereq_('./lib/three');
  52467. var TWEEN = window.TWEEN = _dereq_('@tweenjs/tween.js');
  52468. var pkg = _dereq_('../package');
  52469. _dereq_('./components/index'); // Register standard components.
  52470. _dereq_('./geometries/index'); // Register standard geometries.
  52471. _dereq_('./shaders/index'); // Register standard shaders.
  52472. _dereq_('./systems/index'); // Register standard systems.
  52473. var ANode = _dereq_('./core/a-node');
  52474. var AEntity = _dereq_('./core/a-entity'); // Depends on ANode and core components.
  52475. _dereq_('./core/a-animation');
  52476. _dereq_('./core/a-assets');
  52477. _dereq_('./core/a-cubemap');
  52478. _dereq_('./core/a-mixin');
  52479. // Extras.
  52480. _dereq_('./extras/components/');
  52481. _dereq_('./extras/primitives/');
  52482. console.log('A-Frame Version: 0.6.1 (Date 07-08-2017, Commit #5e3e775)');
  52483. console.log('three Version:', pkg.dependencies['three']);
  52484. console.log('WebVR Polyfill Version:', pkg.dependencies['webvr-polyfill']);
  52485. module.exports = window.AFRAME = {
  52486. AComponent: _dereq_('./core/component').Component,
  52487. AEntity: AEntity,
  52488. ANode: ANode,
  52489. AScene: AScene,
  52490. components: components,
  52491. geometries: _dereq_('./core/geometry').geometries,
  52492. registerComponent: registerComponent,
  52493. registerElement: _dereq_('./core/a-register-element').registerElement,
  52494. registerGeometry: registerGeometry,
  52495. registerPrimitive: registerPrimitive,
  52496. registerShader: registerShader,
  52497. registerSystem: registerSystem,
  52498. primitives: {
  52499. getMeshMixin: _dereq_('./extras/primitives/getMeshMixin'),
  52500. primitives: _dereq_('./extras/primitives/primitives').primitives
  52501. },
  52502. scenes: _dereq_('./core/scene/scenes'),
  52503. schema: _dereq_('./core/schema'),
  52504. shaders: shaders,
  52505. systems: systems,
  52506. THREE: THREE,
  52507. TWEEN: TWEEN,
  52508. utils: utils,
  52509. version: pkg.version
  52510. };
  52511. },{"../package":77,"./components/index":86,"./core/a-animation":119,"./core/a-assets":120,"./core/a-cubemap":121,"./core/a-entity":122,"./core/a-mixin":123,"./core/a-node":124,"./core/a-register-element":125,"./core/component":126,"./core/geometry":127,"./core/scene/a-scene":129,"./core/scene/scenes":132,"./core/schema":134,"./core/shader":135,"./core/system":136,"./extras/components/":137,"./extras/primitives/":140,"./extras/primitives/getMeshMixin":139,"./extras/primitives/primitives":141,"./geometries/index":163,"./lib/three":174,"./shaders/index":176,"./style/aframe.css":181,"./style/rStats.css":182,"./systems/index":186,"./utils/":197,"@tweenjs/tween.js":1,"present":33,"promise-polyfill":35,"webvr-polyfill":62}],173:[function(_dereq_,module,exports){
  52512. window.aframeStats = function (scene) {
  52513. var _rS = null;
  52514. var _scene = scene;
  52515. var _values = {
  52516. te: {
  52517. caption: 'Entities'
  52518. },
  52519. lt: {
  52520. caption: 'Load Time'
  52521. }
  52522. };
  52523. var _groups = [ {
  52524. caption: 'A-Frame',
  52525. values: [ 'te', 'lt' ]
  52526. } ];
  52527. function _update () {
  52528. _rS('te').set(getEntityCount());
  52529. if (window.performance.getEntriesByName) {
  52530. _rS('lt').set(window.performance.getEntriesByName('render-started')[0].startTime.toFixed(0));
  52531. }
  52532. }
  52533. function getEntityCount () {
  52534. var elements = _scene.querySelectorAll('*');
  52535. Array.prototype.slice.call(elements).filter(function (el) {
  52536. return el.isEntity;
  52537. });
  52538. return elements.length;
  52539. }
  52540. function _start () {}
  52541. function _end () {}
  52542. function _attach (r) {
  52543. _rS = r;
  52544. }
  52545. return {
  52546. update: _update,
  52547. start: _start,
  52548. end: _end,
  52549. attach: _attach,
  52550. values: _values,
  52551. groups: _groups,
  52552. fractions: []
  52553. };
  52554. };
  52555. if (typeof module === 'object') {
  52556. module.exports = {
  52557. aframeStats: window.aframeStats
  52558. };
  52559. }
  52560. },{}],174:[function(_dereq_,module,exports){
  52561. (function (global){
  52562. var THREE = global.THREE = _dereq_('three');
  52563. // Allow cross-origin images to be loaded.
  52564. // This should not be on `THREE.Loader` nor `THREE.ImageUtils`.
  52565. // Must be on `THREE.TextureLoader`.
  52566. if (THREE.TextureLoader) {
  52567. THREE.TextureLoader.prototype.crossOrigin = 'anonymous';
  52568. }
  52569. // This is for images loaded from the model loaders.
  52570. if (THREE.ImageLoader) {
  52571. THREE.ImageLoader.prototype.crossOrigin = 'anonymous';
  52572. }
  52573. // In-memory caching for XHRs (for images, audio files, textures, etc.).
  52574. if (THREE.Cache) {
  52575. THREE.Cache.enabled = true;
  52576. }
  52577. // TODO: Eventually include these only if they are needed by a component.
  52578. _dereq_('three/examples/js/loaders/GLTFLoader'); // THREE.GLTFLoader
  52579. _dereq_('three/examples/js/loaders/OBJLoader'); // THREE.OBJLoader
  52580. _dereq_('three/examples/js/loaders/MTLLoader'); // THREE.MTLLoader
  52581. _dereq_('three/examples/js/loaders/ColladaLoader'); // THREE.ColladaLoader
  52582. _dereq_('../../vendor/VRControls'); // THREE.VRControls
  52583. _dereq_('../../vendor/VREffect'); // THREE.VREffect
  52584. THREE.ColladaLoader.prototype.crossOrigin = 'anonymous';
  52585. THREE.GLTFLoader.prototype.crossOrigin = 'anonymous';
  52586. THREE.MTLLoader.prototype.crossOrigin = 'anonymous';
  52587. THREE.OBJLoader.prototype.crossOrigin = 'anonymous';
  52588. module.exports = THREE;
  52589. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  52590. },{"../../vendor/VRControls":202,"../../vendor/VREffect":203,"three":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}],175:[function(_dereq_,module,exports){
  52591. var registerShader = _dereq_('../core/shader').registerShader;
  52592. var THREE = _dereq_('../lib/three');
  52593. var utils = _dereq_('../utils/');
  52594. /**
  52595. * Flat shader using THREE.MeshBasicMaterial.
  52596. */
  52597. module.exports.Shader = registerShader('flat', {
  52598. schema: {
  52599. color: {type: 'color'},
  52600. fog: {default: true},
  52601. height: {default: 256},
  52602. offset: {type: 'vec2', default: {x: 0, y: 0}},
  52603. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  52604. src: {type: 'map'},
  52605. width: {default: 512},
  52606. wireframe: {default: false},
  52607. wireframeLinewidth: {default: 2}
  52608. },
  52609. /**
  52610. * Initializes the shader.
  52611. * Adds a reference from the scene to this entity as the camera.
  52612. */
  52613. init: function (data) {
  52614. this.textureSrc = null;
  52615. this.material = new THREE.MeshBasicMaterial(getMaterialData(data));
  52616. utils.material.updateMap(this, data);
  52617. },
  52618. update: function (data) {
  52619. this.updateMaterial(data);
  52620. utils.material.updateMap(this, data);
  52621. },
  52622. /**
  52623. * Updating existing material.
  52624. *
  52625. * @param {object} data - Material component data.
  52626. */
  52627. updateMaterial: function (data) {
  52628. var material = this.material;
  52629. data = getMaterialData(data);
  52630. Object.keys(data).forEach(function (key) {
  52631. material[key] = data[key];
  52632. });
  52633. }
  52634. });
  52635. /**
  52636. * Builds and normalize material data, normalizing stuff along the way.
  52637. *
  52638. * @param {object} data - Material data.
  52639. * @returns {object} data - Processed material data.
  52640. */
  52641. function getMaterialData (data) {
  52642. return {
  52643. fog: data.fog,
  52644. color: new THREE.Color(data.color),
  52645. wireframe: data.wireframe,
  52646. wireframeLinewidth: data.wireframeLinewidth
  52647. };
  52648. }
  52649. },{"../core/shader":135,"../lib/three":174,"../utils/":197}],176:[function(_dereq_,module,exports){
  52650. _dereq_('./flat');
  52651. _dereq_('./standard');
  52652. _dereq_('./sdf');
  52653. _dereq_('./msdf');
  52654. _dereq_('./ios10hls');
  52655. },{"./flat":175,"./ios10hls":177,"./msdf":178,"./sdf":179,"./standard":180}],177:[function(_dereq_,module,exports){
  52656. var registerShader = _dereq_('../core/shader').registerShader;
  52657. /**
  52658. * Custom shader for iOS 10 HTTP Live Streaming (HLS).
  52659. * For more information on HLS, see https://datatracker.ietf.org/doc/draft-pantos-http-live-streaming/
  52660. */
  52661. module.exports.Shader = registerShader('ios10hls', {
  52662. schema: {
  52663. src: {type: 'map', is: 'uniform'},
  52664. opacity: {type: 'number', is: 'uniform', default: 1}
  52665. },
  52666. vertexShader: [
  52667. 'varying vec2 vUV;',
  52668. 'void main(void) {',
  52669. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  52670. ' vUV = uv;',
  52671. '}'
  52672. ].join('\n'),
  52673. fragmentShader: [
  52674. 'uniform sampler2D src;',
  52675. 'uniform float opacity;',
  52676. 'varying vec2 vUV;',
  52677. 'void main() {',
  52678. ' vec2 offset = vec2(0, 0);',
  52679. ' vec2 repeat = vec2(1, 1);',
  52680. ' vec4 color = texture2D(src, vec2(vUV.x / repeat.x + offset.x, (1.0 - vUV.y) / repeat.y + offset.y)).bgra;',
  52681. ' gl_FragColor = vec4(color.rgb, opacity);',
  52682. '}'
  52683. ].join('\n')
  52684. });
  52685. },{"../core/shader":135}],178:[function(_dereq_,module,exports){
  52686. var registerShader = _dereq_('../core/shader').registerShader;
  52687. /**
  52688. * Multi-channel signed distance field.
  52689. * Used by text component.
  52690. */
  52691. module.exports.Shader = registerShader('msdf', {
  52692. schema: {
  52693. alphaTest: {type: 'number', is: 'uniform', default: 0.5},
  52694. color: {type: 'color', is: 'uniform', default: 'white'},
  52695. map: {type: 'map', is: 'uniform'},
  52696. opacity: {type: 'number', is: 'uniform', default: 1.0}
  52697. },
  52698. raw: true,
  52699. vertexShader: [
  52700. 'attribute vec2 uv;',
  52701. 'attribute vec3 position;',
  52702. 'uniform mat4 projectionMatrix;',
  52703. 'uniform mat4 modelViewMatrix;',
  52704. 'varying vec2 vUV;',
  52705. 'void main(void) {',
  52706. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  52707. ' vUV = uv;',
  52708. '}'
  52709. ].join('\n'),
  52710. fragmentShader: [
  52711. '#ifdef GL_OES_standard_derivatives',
  52712. '#extension GL_OES_standard_derivatives: enable',
  52713. '#endif',
  52714. 'precision highp float;',
  52715. // FIXME: Experimentally determined constants.
  52716. '#define BIG_ENOUGH 0.001',
  52717. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  52718. '#define ALL_SMOOTH 0.4',
  52719. '#define ALL_ROUGH 0.02',
  52720. '#define DISCARD_ALPHA (alphaTest / (2.2 - 1.2 * ratio))',
  52721. 'uniform sampler2D map;',
  52722. 'uniform vec3 color;',
  52723. 'uniform float opacity;',
  52724. 'uniform float alphaTest;',
  52725. 'varying vec2 vUV;',
  52726. 'float median(float r, float g, float b) {',
  52727. ' return max(min(r, g), min(max(r, g), b));',
  52728. '}',
  52729. 'void main() {',
  52730. ' vec3 sample = 1.0 - texture2D(map, vUV).rgb;',
  52731. ' float sigDist = median(sample.r, sample.g, sample.b) - 0.5;',
  52732. ' float alpha = clamp(sigDist/fwidth(sigDist) + 0.5, 0.0, 1.0);',
  52733. ' float dscale = 0.353505;',
  52734. ' vec2 duv = dscale * (dFdx(vUV) + dFdy(vUV));',
  52735. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  52736. // When texel is too small, blend raw alpha value rather than supersampling.
  52737. // FIXME: Experimentally determined constant.
  52738. ' if (isBigEnough > BIG_ENOUGH) {',
  52739. ' float ratio = BIG_ENOUGH / isBigEnough;',
  52740. ' alpha = ratio * alpha + (1.0 - ratio) * (sigDist + 0.5);',
  52741. ' }',
  52742. // When texel is big enough, do standard alpha test.
  52743. // FIXME: Experimentally determined constant.
  52744. // Looks much better if we *don't* do this, but do we get Z fighting?
  52745. ' if (isBigEnough <= BIG_ENOUGH && alpha < alphaTest) { discard; return; }',
  52746. // Else, do modified alpha test.
  52747. // FIXME: Experimentally determined constant.
  52748. ' if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  52749. ' gl_FragColor = vec4(color.xyz, alpha * opacity);',
  52750. '}'
  52751. ].join('\n')
  52752. });
  52753. },{"../core/shader":135}],179:[function(_dereq_,module,exports){
  52754. var registerShader = _dereq_('../core/shader').registerShader;
  52755. /**
  52756. * Signed distance field.
  52757. * Used by text component.
  52758. */
  52759. module.exports.Shader = registerShader('sdf', {
  52760. schema: {
  52761. alphaTest: {type: 'number', is: 'uniform', default: 0.5},
  52762. color: {type: 'color', is: 'uniform', default: 'white'},
  52763. map: {type: 'map', is: 'uniform'},
  52764. opacity: {type: 'number', is: 'uniform', default: 1.0}
  52765. },
  52766. raw: true,
  52767. vertexShader: [
  52768. 'attribute vec2 uv;',
  52769. 'attribute vec3 position;',
  52770. 'uniform mat4 projectionMatrix;',
  52771. 'uniform mat4 modelViewMatrix;',
  52772. 'varying vec2 vUV;',
  52773. 'void main(void) {',
  52774. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  52775. ' vUV = uv;',
  52776. '}'
  52777. ].join('\n'),
  52778. fragmentShader: [
  52779. '#ifdef GL_OES_standard_derivatives',
  52780. '#extension GL_OES_standard_derivatives: enable',
  52781. '#endif',
  52782. 'precision highp float;',
  52783. // FIXME: experimentally determined constants
  52784. '#define BIG_ENOUGH 0.001',
  52785. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  52786. '#define ALL_SMOOTH 0.4',
  52787. '#define ALL_ROUGH 0.02',
  52788. '#define DISCARD_ALPHA (alphaTest / (2.2 - 1.2 * ratio))',
  52789. 'uniform sampler2D map;',
  52790. 'uniform vec3 color;',
  52791. 'uniform float opacity;',
  52792. 'uniform float alphaTest;',
  52793. 'varying vec2 vUV;',
  52794. '#ifdef GL_OES_standard_derivatives',
  52795. 'float contour(float width, float value) {',
  52796. ' return smoothstep(0.5 - value, 0.5 + value, width);',
  52797. '}',
  52798. '#else',
  52799. 'float aastep(float value, float afwidth) {',
  52800. ' return smoothstep(0.5 - afwidth, 0.5 + afwidth, value);',
  52801. '}',
  52802. '#endif',
  52803. 'void main() {',
  52804. '#ifdef GL_OES_standard_derivatives',
  52805. // when we have derivatives and can get texel size etc., that allows supersampling etc.
  52806. ' vec2 uv = vUV;',
  52807. ' vec4 texColor = texture2D(map, uv);',
  52808. ' float dist = texColor.a;',
  52809. ' float width = fwidth(dist);',
  52810. ' float alpha = contour(dist, width);',
  52811. ' float dscale = 0.353505;',
  52812. ' vec2 duv = dscale * (dFdx(uv) + dFdy(uv));',
  52813. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  52814. // when texel is too small, blend raw alpha value rather than supersampling etc.
  52815. // FIXME: experimentally determined constant
  52816. ' if (isBigEnough > BIG_ENOUGH) {',
  52817. ' float ratio = BIG_ENOUGH / isBigEnough;',
  52818. ' alpha = ratio * alpha + (1.0 - ratio) * dist;',
  52819. ' }',
  52820. // otherwise do weighted supersampling
  52821. // FIXME: why this weighting?
  52822. ' else if (isBigEnough <= BIG_ENOUGH) {',
  52823. ' vec4 box = vec4 (uv - duv, uv + duv);',
  52824. ' alpha = (alpha + 0.5 * (',
  52825. ' contour(texture2D(map, box.xy).a, width)',
  52826. ' + contour(texture2D(map, box.zw).a, width)',
  52827. ' + contour(texture2D(map, box.xw).a, width)',
  52828. ' + contour(texture2D(map, box.zy).a, width)',
  52829. ' )) / 3.0;',
  52830. ' }',
  52831. // when texel is big enough, do standard alpha test
  52832. // FIXME: experimentally determined constant
  52833. // looks much better if we DON'T do this, but do we get Z fighting etc.?
  52834. ' if (isBigEnough <= BIG_ENOUGH && alpha < alphaTest) { discard; return; }',
  52835. // else do modified alpha test
  52836. // FIXME: experimentally determined constant
  52837. ' if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  52838. '#else',
  52839. ' vec4 texColor = texture2D(map, vUV);',
  52840. ' float value = texColor.a;',
  52841. // when we don't have derivatives, use approximations
  52842. // FIXME: if we understood font pixel dimensions, this could probably be improved
  52843. ' float afwidth = (1.0 / 32.0) * (1.4142135623730951 / (2.0 * gl_FragCoord.w));',
  52844. ' float alpha = aastep(value, afwidth);',
  52845. // use gl_FragCoord.w to guess when we should blend
  52846. // FIXME: if we understood font pixel dimensions, this could probably be improved
  52847. ' 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);',
  52848. ' if (alpha < alphaTest) { if (ratio >= 1.0) { discard; return; } alpha = 0.0; }',
  52849. ' alpha = alpha * ratio + (1.0 - ratio) * value;',
  52850. ' if (ratio < 1.0)',
  52851. ' if (alpha <= DISCARD_ALPHA) { discard; return; }',
  52852. '#endif',
  52853. ' gl_FragColor = vec4(color, opacity * alpha);',
  52854. '}'
  52855. ].join('\n')
  52856. });
  52857. },{"../core/shader":135}],180:[function(_dereq_,module,exports){
  52858. var registerShader = _dereq_('../core/shader').registerShader;
  52859. var THREE = _dereq_('../lib/three');
  52860. var utils = _dereq_('../utils/');
  52861. var CubeLoader = new THREE.CubeTextureLoader();
  52862. var texturePromises = {};
  52863. /**
  52864. * Standard (physically-based) shader using THREE.MeshStandardMaterial.
  52865. */
  52866. module.exports.Shader = registerShader('standard', {
  52867. schema: {
  52868. ambientOcclusionMap: {type: 'map'},
  52869. ambientOcclusionMapIntensity: {default: 1},
  52870. ambientOcclusionTextureOffset: {type: 'vec2'},
  52871. ambientOcclusionTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  52872. color: {type: 'color'},
  52873. displacementMap: {type: 'map'},
  52874. displacementScale: {default: 1},
  52875. displacementBias: {default: 0.5},
  52876. displacementTextureOffset: {type: 'vec2'},
  52877. displacementTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  52878. emissive: {type: 'color', default: '#000'},
  52879. emissiveIntensity: {default: 1},
  52880. envMap: {default: ''},
  52881. fog: {default: true},
  52882. height: {default: 256},
  52883. metalness: {default: 0.0, min: 0.0, max: 1.0},
  52884. normalMap: {type: 'map'},
  52885. normalScale: {type: 'vec2', default: {x: 1, y: 1}},
  52886. normalTextureOffset: {type: 'vec2'},
  52887. normalTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  52888. offset: {type: 'vec2', default: {x: 0, y: 0}},
  52889. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  52890. roughness: {default: 0.5, min: 0.0, max: 1.0},
  52891. sphericalEnvMap: {type: 'map'},
  52892. src: {type: 'map'},
  52893. width: {default: 512},
  52894. wireframe: {default: false},
  52895. wireframeLinewidth: {default: 2}
  52896. },
  52897. /**
  52898. * Initializes the shader.
  52899. * Adds a reference from the scene to this entity as the camera.
  52900. */
  52901. init: function (data) {
  52902. this.material = new THREE.MeshStandardMaterial(getMaterialData(data));
  52903. utils.material.updateMap(this, data);
  52904. if (data.normalMap) { utils.material.updateDistortionMap('normal', this, data); }
  52905. if (data.displacementMap) { utils.material.updateDistortionMap('displacement', this, data); }
  52906. if (data.ambientOcclusionMap) { utils.material.updateDistortionMap('ambientOcclusion', this, data); }
  52907. this.updateEnvMap(data);
  52908. },
  52909. update: function (data) {
  52910. this.updateMaterial(data);
  52911. utils.material.updateMap(this, data);
  52912. if (data.normalMap) { utils.material.updateDistortionMap('normal', this, data); }
  52913. if (data.displacementMap) { utils.material.updateDistortionMap('displacement', this, data); }
  52914. if (data.ambientOcclusionMap) { utils.material.updateDistortionMap('ambientOcclusion', this, data); }
  52915. this.updateEnvMap(data);
  52916. },
  52917. /**
  52918. * Updating existing material.
  52919. *
  52920. * @param {object} data - Material component data.
  52921. * @returns {object} Material.
  52922. */
  52923. updateMaterial: function (data) {
  52924. var material = this.material;
  52925. data = getMaterialData(data);
  52926. Object.keys(data).forEach(function (key) {
  52927. material[key] = data[key];
  52928. });
  52929. },
  52930. /**
  52931. * Handle environment cubemap. Textures are cached in texturePromises.
  52932. */
  52933. updateEnvMap: function (data) {
  52934. var self = this;
  52935. var material = this.material;
  52936. var envMap = data.envMap;
  52937. var sphericalEnvMap = data.sphericalEnvMap;
  52938. // No envMap defined or already loading.
  52939. if ((!envMap && !sphericalEnvMap) || this.isLoadingEnvMap) {
  52940. material.envMap = null;
  52941. material.needsUpdate = true;
  52942. return;
  52943. }
  52944. this.isLoadingEnvMap = true;
  52945. // if a spherical env map is defined then use it.
  52946. if (sphericalEnvMap) {
  52947. this.el.sceneEl.systems.material.loadTexture(sphericalEnvMap, {src: sphericalEnvMap}, function textureLoaded (texture) {
  52948. self.isLoadingEnvMap = false;
  52949. texture.mapping = THREE.SphericalReflectionMapping;
  52950. material.envMap = texture;
  52951. utils.material.handleTextureEvents(self.el, texture);
  52952. material.needsUpdate = true;
  52953. });
  52954. return;
  52955. }
  52956. // Another material is already loading this texture. Wait on promise.
  52957. if (texturePromises[envMap]) {
  52958. texturePromises[envMap].then(function (cube) {
  52959. self.isLoadingEnvMap = false;
  52960. material.envMap = cube;
  52961. utils.material.handleTextureEvents(self.el, cube);
  52962. material.needsUpdate = true;
  52963. });
  52964. return;
  52965. }
  52966. // Material is first to load this texture. Load and resolve texture.
  52967. texturePromises[envMap] = new Promise(function (resolve) {
  52968. utils.srcLoader.validateCubemapSrc(envMap, function loadEnvMap (urls) {
  52969. CubeLoader.load(urls, function (cube) {
  52970. // Texture loaded.
  52971. self.isLoadingEnvMap = false;
  52972. material.envMap = cube;
  52973. utils.material.handleTextureEvents(self.el, cube);
  52974. resolve(cube);
  52975. });
  52976. });
  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. var newData = {
  52988. color: new THREE.Color(data.color),
  52989. emissive: new THREE.Color(data.emissive),
  52990. emissiveIntensity: data.emissiveIntensity,
  52991. fog: data.fog,
  52992. metalness: data.metalness,
  52993. roughness: data.roughness,
  52994. wireframe: data.wireframe,
  52995. wireframeLinewidth: data.wireframeLinewidth
  52996. };
  52997. if (data.normalMap) { newData.normalScale = data.normalScale; }
  52998. if (data.ambientOcclusionMap) { newData.aoMapIntensity = data.ambientOcclusionMapIntensity; }
  52999. if (data.displacementMap) {
  53000. newData.displacementScale = data.displacementScale;
  53001. newData.displacementBias = data.displacementBias;
  53002. }
  53003. return newData;
  53004. }
  53005. },{"../core/shader":135,"../lib/three":174,"../utils/":197}],181:[function(_dereq_,module,exports){
  53006. 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;
  53007. },{"browserify-css":5}],182:[function(_dereq_,module,exports){
  53008. 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;
  53009. },{"browserify-css":5}],183:[function(_dereq_,module,exports){
  53010. var bind = _dereq_('../utils/bind');
  53011. var constants = _dereq_('../constants/');
  53012. var registerSystem = _dereq_('../core/system').registerSystem;
  53013. var DEFAULT_CAMERA_ATTR = 'data-aframe-default-camera';
  53014. /**
  53015. * Camera system. Manages which camera is active among multiple cameras in scene.
  53016. *
  53017. * @member {object} activeCameraEl - Active camera entity.
  53018. */
  53019. module.exports.System = registerSystem('camera', {
  53020. init: function () {
  53021. this.activeCameraEl = null;
  53022. // Wait for all entities to fully load before checking for existence of camera.
  53023. // Since entities wait for <a-assets> to load, any cameras attaching to the scene
  53024. // will do so asynchronously.
  53025. this.sceneEl.addEventListener('loaded', bind(this.setupDefaultCamera, this));
  53026. },
  53027. /**
  53028. * Create a default camera if user has not added one during the initial scene traversal.
  53029. *
  53030. * Default camera offset height is at average eye level (~1.6m).
  53031. */
  53032. setupDefaultCamera: function () {
  53033. var sceneEl = this.sceneEl;
  53034. var defaultCameraEl;
  53035. // Camera already defined.
  53036. if (sceneEl.camera) {
  53037. sceneEl.emit('camera-ready', {cameraEl: sceneEl.camera.el});
  53038. return;
  53039. }
  53040. // Set up default camera.
  53041. defaultCameraEl = document.createElement('a-entity');
  53042. defaultCameraEl.setAttribute('position', '0 0 0');
  53043. defaultCameraEl.setAttribute(DEFAULT_CAMERA_ATTR, '');
  53044. defaultCameraEl.setAttribute('camera', {active: true, userHeight: constants.DEFAULT_CAMERA_HEIGHT});
  53045. defaultCameraEl.setAttribute('wasd-controls', '');
  53046. defaultCameraEl.setAttribute('look-controls', '');
  53047. defaultCameraEl.setAttribute(constants.AFRAME_INJECTED, '');
  53048. sceneEl.appendChild(defaultCameraEl);
  53049. sceneEl.addEventListener('enter-vr', this.removeDefaultOffset);
  53050. sceneEl.addEventListener('exit-vr', this.addDefaultOffset);
  53051. sceneEl.emit('camera-ready', {cameraEl: defaultCameraEl});
  53052. },
  53053. /**
  53054. * Set a different active camera.
  53055. * When we choose a (sort of) random scene camera as the replacement, set its `active` to
  53056. * true. The camera component will call `setActiveCamera` and handle passing the torch to
  53057. * the new camera.
  53058. */
  53059. disableActiveCamera: function () {
  53060. var cameraEls = this.sceneEl.querySelectorAll('[camera]');
  53061. var newActiveCameraEl = cameraEls[cameraEls.length - 1];
  53062. newActiveCameraEl.setAttribute('camera', 'active', true);
  53063. },
  53064. /**
  53065. * Set active camera to be used by renderer.
  53066. * Removes the default camera (if present).
  53067. * Disables all other cameras in the scene.
  53068. *
  53069. * @param {Element} newCameraEl - Entity with camera component.
  53070. */
  53071. setActiveCamera: function (newCameraEl) {
  53072. var cameraEl;
  53073. var cameraEls;
  53074. var i;
  53075. var newCamera;
  53076. var previousCamera = this.activeCameraEl;
  53077. var sceneEl = this.sceneEl;
  53078. // Same camera.
  53079. newCamera = newCameraEl.getObject3D('camera');
  53080. if (!newCamera || newCameraEl === this.activeCameraEl) { return; }
  53081. // Grab the default camera.
  53082. var defaultCameraWrapper = sceneEl.querySelector('[' + DEFAULT_CAMERA_ATTR + ']');
  53083. var defaultCameraEl = defaultCameraWrapper &&
  53084. defaultCameraWrapper.querySelector('[camera]');
  53085. // Remove default camera if new camera is not the default camera.
  53086. if (newCameraEl !== defaultCameraEl) { removeDefaultCamera(sceneEl); }
  53087. // Make new camera active.
  53088. this.activeCameraEl = newCameraEl;
  53089. this.activeCameraEl.play();
  53090. sceneEl.camera = newCamera;
  53091. // Disable current camera
  53092. if (previousCamera) {
  53093. previousCamera.setAttribute('camera', 'active', false);
  53094. }
  53095. // Disable other cameras in the scene
  53096. cameraEls = sceneEl.querySelectorAll('[camera]');
  53097. for (i = 0; i < cameraEls.length; i++) {
  53098. cameraEl = cameraEls[i];
  53099. if (newCameraEl === cameraEl) { continue; }
  53100. cameraEl.setAttribute('camera', 'active', false);
  53101. cameraEl.pause();
  53102. }
  53103. sceneEl.emit('camera-set-active', {cameraEl: newCameraEl});
  53104. }
  53105. });
  53106. /**
  53107. * Remove injected default camera from scene, if present.
  53108. *
  53109. * @param {Element} sceneEl
  53110. */
  53111. function removeDefaultCamera (sceneEl) {
  53112. var defaultCamera;
  53113. var camera = sceneEl.camera;
  53114. if (!camera) { return; }
  53115. // Remove default camera if present.
  53116. defaultCamera = sceneEl.querySelector('[' + DEFAULT_CAMERA_ATTR + ']');
  53117. if (!defaultCamera) { return; }
  53118. sceneEl.removeChild(defaultCamera);
  53119. }
  53120. },{"../constants/":117,"../core/system":136,"../utils/bind":191}],184:[function(_dereq_,module,exports){
  53121. var geometries = _dereq_('../core/geometry').geometries;
  53122. var registerSystem = _dereq_('../core/system').registerSystem;
  53123. var THREE = _dereq_('../lib/three');
  53124. /**
  53125. * System for geometry component.
  53126. * Handle geometry caching.
  53127. *
  53128. * @member {object} cache - Mapping of stringified component data to THREE.Geometry objects.
  53129. * @member {object} cacheCount - Keep track of number of entities using a geometry to
  53130. * know whether to dispose on removal.
  53131. */
  53132. module.exports.System = registerSystem('geometry', {
  53133. init: function () {
  53134. this.cache = {};
  53135. this.cacheCount = {};
  53136. },
  53137. /**
  53138. * Reset cache. Mainly for testing.
  53139. */
  53140. clearCache: function () {
  53141. this.cache = {};
  53142. this.cacheCount = {};
  53143. },
  53144. /**
  53145. * Attempt to retrieve from cache.
  53146. *
  53147. * @returns {Object|null} A geometry if it exists, else null.
  53148. */
  53149. getOrCreateGeometry: function (data) {
  53150. var cache = this.cache;
  53151. var cachedGeometry;
  53152. var hash;
  53153. // Skip all caching logic.
  53154. if (data.skipCache || data.mergeTo) { return createGeometry(data); }
  53155. // Try to retrieve from cache first.
  53156. hash = this.hash(data);
  53157. cachedGeometry = cache[hash];
  53158. incrementCacheCount(this.cacheCount, hash);
  53159. if (cachedGeometry) { return cachedGeometry; }
  53160. // Create geometry.
  53161. cachedGeometry = createGeometry(data);
  53162. // Cache and return geometry.
  53163. cache[hash] = cachedGeometry;
  53164. return cachedGeometry;
  53165. },
  53166. /**
  53167. * Let system know that an entity is no longer using a geometry.
  53168. */
  53169. unuseGeometry: function (data) {
  53170. var cache = this.cache;
  53171. var cacheCount = this.cacheCount;
  53172. var geometry;
  53173. var hash;
  53174. if (data.skipCache || data.mergeTo) { return; }
  53175. hash = this.hash(data);
  53176. if (!cache[hash]) { return; }
  53177. decrementCacheCount(cacheCount, hash);
  53178. // Another entity is still using this geometry. No need to do anything.
  53179. if (cacheCount[hash] > 0) { return; }
  53180. // No more entities are using this geometry. Dispose.
  53181. geometry = cache[hash];
  53182. geometry.dispose();
  53183. delete cache[hash];
  53184. delete cacheCount[hash];
  53185. },
  53186. /**
  53187. * Use JSON.stringify to turn component data into hash.
  53188. * Should be deterministic within a single browser engine.
  53189. * If not, then look into json-stable-stringify.
  53190. */
  53191. hash: function (data) {
  53192. return JSON.stringify(data);
  53193. }
  53194. });
  53195. /**
  53196. * Create geometry using component data.
  53197. *
  53198. * @param {object} data - Component data.
  53199. * @returns {object} Geometry.
  53200. */
  53201. function createGeometry (data) {
  53202. var geometryType = data.primitive;
  53203. var GeometryClass = geometries[geometryType] && geometries[geometryType].Geometry;
  53204. var geometryInstance = new GeometryClass();
  53205. if (!GeometryClass) { throw new Error('Unknown geometry `' + geometryType + '`'); }
  53206. geometryInstance.init(data);
  53207. return toBufferGeometry(geometryInstance.geometry, data.buffer);
  53208. }
  53209. /**
  53210. * Decreate count of entity using a geometry.
  53211. */
  53212. function decrementCacheCount (cacheCount, hash) {
  53213. cacheCount[hash]--;
  53214. }
  53215. /**
  53216. * Increase count of entity using a geometry.
  53217. */
  53218. function incrementCacheCount (cacheCount, hash) {
  53219. cacheCount[hash] = cacheCount[hash] === undefined ? 1 : cacheCount[hash] + 1;
  53220. }
  53221. /**
  53222. * Transform geometry to BufferGeometry if `doBuffer`.
  53223. *
  53224. * @param {object} geometry
  53225. * @param {boolean} doBuffer
  53226. * @returns {object} Geometry.
  53227. */
  53228. function toBufferGeometry (geometry, doBuffer) {
  53229. var bufferGeometry;
  53230. if (!doBuffer) { return geometry; }
  53231. bufferGeometry = new THREE.BufferGeometry().fromGeometry(geometry);
  53232. bufferGeometry.metadata = {type: geometry.type, parameters: geometry.parameters || {}};
  53233. geometry.dispose(); // Dispose no longer needed non-buffer geometry.
  53234. return bufferGeometry;
  53235. }
  53236. },{"../core/geometry":127,"../core/system":136,"../lib/three":174}],185:[function(_dereq_,module,exports){
  53237. var registerSystem = _dereq_('../core/system').registerSystem;
  53238. var THREE = _dereq_('../lib/three');
  53239. /**
  53240. * glTF model system.
  53241. */
  53242. module.exports.System = registerSystem('gltf-model', {
  53243. init: function () {
  53244. this.models = [];
  53245. },
  53246. /**
  53247. * Updates shaders for all glTF models in the system.
  53248. */
  53249. tick: function () {
  53250. var sceneEl = this.sceneEl;
  53251. if (sceneEl.hasLoaded && this.models.length) {
  53252. THREE.GLTFLoader.Shaders.update(sceneEl.object3D, sceneEl.camera);
  53253. }
  53254. },
  53255. /**
  53256. * Registers a glTF asset.
  53257. * @param {object} gltf Asset containing a scene and (optional) animations and cameras.
  53258. */
  53259. registerModel: function (gltf) {
  53260. this.models.push(gltf);
  53261. },
  53262. /**
  53263. * Unregisters a glTF asset.
  53264. * @param {object} gltf Asset containing a scene and (optional) animations and cameras.
  53265. */
  53266. unregisterModel: function (gltf) {
  53267. var models = this.models;
  53268. var index = models.indexOf(gltf);
  53269. if (index >= 0) {
  53270. models.splice(index, 1);
  53271. }
  53272. }
  53273. });
  53274. },{"../core/system":136,"../lib/three":174}],186:[function(_dereq_,module,exports){
  53275. _dereq_('./camera');
  53276. _dereq_('./geometry');
  53277. _dereq_('./gltf-model');
  53278. _dereq_('./light');
  53279. _dereq_('./material');
  53280. _dereq_('./shadow');
  53281. _dereq_('./tracked-controls');
  53282. },{"./camera":183,"./geometry":184,"./gltf-model":185,"./light":187,"./material":188,"./shadow":189,"./tracked-controls":190}],187:[function(_dereq_,module,exports){
  53283. var registerSystem = _dereq_('../core/system').registerSystem;
  53284. var bind = _dereq_('../utils/bind');
  53285. var constants = _dereq_('../constants/');
  53286. var DEFAULT_LIGHT_ATTR = 'data-aframe-default-light';
  53287. /**
  53288. * Light system.
  53289. *
  53290. * Prescribes default lighting if not specified (one ambient, one directional).
  53291. * Removes default lighting from the scene when a new light is added.
  53292. *
  53293. * @param {bool} defaultLights - Whether default lighting are defined.
  53294. * @param {bool} userDefinedLights - Whether user lighting is defined.
  53295. */
  53296. module.exports.System = registerSystem('light', {
  53297. schema: {
  53298. defaultLightsEnabled: {default: true}
  53299. },
  53300. init: function () {
  53301. this.defaultLights = false;
  53302. this.userDefinedLights = false;
  53303. // Wait for all entities to fully load before checking for existence of lights.
  53304. // Since entities wait for <a-assets> to load, any lights attaching to the scene
  53305. // will do so asynchronously.
  53306. this.sceneEl.addEventListener('loaded', bind(this.setupDefaultLights, this));
  53307. },
  53308. /**
  53309. * Notify scene that light has been added and to remove the default.
  53310. *
  53311. * @param {object} el - element holding the light component.
  53312. */
  53313. registerLight: function (el) {
  53314. if (!el.hasAttribute(DEFAULT_LIGHT_ATTR)) {
  53315. // User added a light, remove default lights through DOM.
  53316. this.removeDefaultLights();
  53317. this.userDefinedLights = true;
  53318. }
  53319. },
  53320. removeDefaultLights: function () {
  53321. var defaultLights;
  53322. var sceneEl = this.sceneEl;
  53323. if (!this.defaultLights) { return; }
  53324. defaultLights = document.querySelectorAll('[' + DEFAULT_LIGHT_ATTR + ']');
  53325. for (var i = 0; i < defaultLights.length; i++) {
  53326. sceneEl.removeChild(defaultLights[i]);
  53327. }
  53328. this.defaultLights = false;
  53329. },
  53330. /**
  53331. * Prescibe default lights to the scene.
  53332. * Does so by injecting markup such that this state is not invisible.
  53333. * These lights are removed if the user adds any lights.
  53334. */
  53335. setupDefaultLights: function () {
  53336. var sceneEl = this.sceneEl;
  53337. var ambientLight;
  53338. var directionalLight;
  53339. if (this.userDefinedLights || this.defaultLights || !this.data.defaultLightsEnabled) {
  53340. return;
  53341. }
  53342. ambientLight = document.createElement('a-entity');
  53343. ambientLight.setAttribute('light', {color: '#BBB', type: 'ambient'});
  53344. ambientLight.setAttribute(DEFAULT_LIGHT_ATTR, '');
  53345. ambientLight.setAttribute(constants.AFRAME_INJECTED, '');
  53346. sceneEl.appendChild(ambientLight);
  53347. directionalLight = document.createElement('a-entity');
  53348. directionalLight.setAttribute('light', {color: '#FFF', intensity: 0.6, castShadow: true});
  53349. directionalLight.setAttribute('position', {x: -0.5, y: 1, z: 1});
  53350. directionalLight.setAttribute(DEFAULT_LIGHT_ATTR, '');
  53351. directionalLight.setAttribute(constants.AFRAME_INJECTED, '');
  53352. sceneEl.appendChild(directionalLight);
  53353. this.defaultLights = true;
  53354. }
  53355. });
  53356. },{"../constants/":117,"../core/system":136,"../utils/bind":191}],188:[function(_dereq_,module,exports){
  53357. var registerSystem = _dereq_('../core/system').registerSystem;
  53358. var THREE = _dereq_('../lib/three');
  53359. var utils = _dereq_('../utils/');
  53360. var isHLS = _dereq_('../utils/material').isHLS;
  53361. var bind = utils.bind;
  53362. var debug = utils.debug;
  53363. var error = debug('components:texture:error');
  53364. var TextureLoader = new THREE.TextureLoader();
  53365. var warn = debug('components:texture:warn');
  53366. TextureLoader.setCrossOrigin('anonymous');
  53367. /**
  53368. * System for material component.
  53369. * Handle material registration, updates (for fog), and texture caching.
  53370. *
  53371. * @member {object} materials - Registered materials.
  53372. * @member {object} textureCounts - Number of times each texture is used. Tracked
  53373. * separately from textureCache, because the cache (1) is populated in
  53374. * multiple places, and (2) may be cleared at any time.
  53375. * @member {object} textureCache - Texture cache for:
  53376. * - Images: textureCache has mapping of src -> repeat -> cached three.js texture.
  53377. * - Videos: textureCache has mapping of videoElement -> cached three.js texture.
  53378. */
  53379. module.exports.System = registerSystem('material', {
  53380. init: function () {
  53381. this.materials = {};
  53382. this.textureCounts = {};
  53383. this.textureCache = {};
  53384. this.sceneEl.addEventListener(
  53385. 'materialtextureloaded',
  53386. bind(this.onMaterialTextureLoaded, this)
  53387. );
  53388. },
  53389. clearTextureCache: function () {
  53390. this.textureCache = {};
  53391. },
  53392. /**
  53393. * Determine whether `src` is a image or video. Then try to load the asset, then call back.
  53394. *
  53395. * @param {string, or element} src - Texture URL or element.
  53396. * @param {string} data - Relevant texture data used for caching.
  53397. * @param {function} cb - Callback to pass texture to.
  53398. */
  53399. loadTexture: function (src, data, cb) {
  53400. var self = this;
  53401. // Canvas.
  53402. if (src.tagName === 'CANVAS') {
  53403. this.loadCanvas(src, data, cb);
  53404. return;
  53405. }
  53406. // Video element.
  53407. if (src.tagName === 'VIDEO') {
  53408. if (!src.hasAttribute('src') && !src.hasAttribute('srcObject')) {
  53409. warn('Video element was defined without `src` nor `srcObject` attributes.');
  53410. }
  53411. this.loadVideo(src, data, cb);
  53412. return;
  53413. }
  53414. utils.srcLoader.validateSrc(src, loadImageCb, loadVideoCb);
  53415. function loadImageCb (src) { self.loadImage(src, data, cb); }
  53416. function loadVideoCb (src) { self.loadVideo(src, data, cb); }
  53417. },
  53418. /**
  53419. * High-level function for loading image textures (THREE.Texture).
  53420. *
  53421. * @param {Element|string} src - Texture source.
  53422. * @param {object} data - Texture data.
  53423. * @param {function} cb - Callback to pass texture to.
  53424. */
  53425. loadImage: function (src, data, handleImageTextureLoaded) {
  53426. var hash = this.hash(data);
  53427. var textureCache = this.textureCache;
  53428. // Texture already being loaded or already loaded. Wait on promise.
  53429. if (textureCache[hash]) {
  53430. textureCache[hash].then(handleImageTextureLoaded);
  53431. return;
  53432. }
  53433. // Texture not yet being loaded. Start loading it.
  53434. textureCache[hash] = loadImageTexture(src, data);
  53435. textureCache[hash].then(handleImageTextureLoaded);
  53436. },
  53437. /**
  53438. * High-level function for loading canvas textures (THREE.Texture).
  53439. *
  53440. * @param {Element|string} src - Texture source.
  53441. * @param {object} data - Texture data.
  53442. * @param {function} cb - Callback to pass texture to.
  53443. */
  53444. loadCanvas: function (src, data, cb) {
  53445. // Hack readyState and HAVE_CURRENT_DATA on canvas to work with THREE.VideoTexture
  53446. src.readyState = 2;
  53447. src.HAVE_CURRENT_DATA = 2;
  53448. this.loadVideo(src, data, cb);
  53449. },
  53450. /**
  53451. * Load video texture (THREE.VideoTexture).
  53452. * Which is just an image texture that RAFs + needsUpdate.
  53453. * Note that creating a video texture is synchronous unlike loading an image texture.
  53454. * Made asynchronous to be consistent with image textures.
  53455. *
  53456. * @param {Element|string} src - Texture source.
  53457. * @param {object} data - Texture data.
  53458. * @param {function} cb - Callback to pass texture to.
  53459. */
  53460. loadVideo: function (src, data, cb) {
  53461. var hash;
  53462. var texture;
  53463. var textureCache = this.textureCache;
  53464. var videoEl;
  53465. var videoTextureResult;
  53466. function handleVideoTextureLoaded (result) {
  53467. result.texture.needsUpdate = true;
  53468. cb(result.texture, result.videoEl);
  53469. }
  53470. // Video element provided.
  53471. if (typeof src !== 'string') {
  53472. // Check cache before creating texture.
  53473. videoEl = src;
  53474. hash = this.hashVideo(data, videoEl);
  53475. if (textureCache[hash]) {
  53476. textureCache[hash].then(handleVideoTextureLoaded);
  53477. return;
  53478. }
  53479. // If not in cache, fix up the attributes then start to create the texture.
  53480. fixVideoAttributes(videoEl);
  53481. }
  53482. // Only URL provided. Use video element to create texture.
  53483. videoEl = videoEl || createVideoEl(src, data.width, data.height);
  53484. // Generated video element already cached. Use that.
  53485. hash = this.hashVideo(data, videoEl);
  53486. if (textureCache[hash]) {
  53487. textureCache[hash].then(handleVideoTextureLoaded);
  53488. return;
  53489. }
  53490. // Create new video texture.
  53491. texture = new THREE.VideoTexture(videoEl);
  53492. texture.minFilter = THREE.LinearFilter;
  53493. setTextureProperties(texture, data);
  53494. // If iOS and video is HLS, do some hacks.
  53495. if (this.sceneEl.isIOS &&
  53496. isHLS(videoEl.src || videoEl.getAttribute('src'),
  53497. videoEl.type || videoEl.getAttribute('type'))) {
  53498. // Actually BGRA. Tell shader to correct later.
  53499. texture.format = THREE.RGBAFormat;
  53500. texture.needsCorrectionBGRA = true;
  53501. // Apparently needed for HLS. Tell shader to correct later.
  53502. texture.flipY = false;
  53503. texture.needsCorrectionFlipY = true;
  53504. }
  53505. // Cache as promise to be consistent with image texture caching.
  53506. videoTextureResult = {texture: texture, videoEl: videoEl};
  53507. textureCache[hash] = Promise.resolve(videoTextureResult);
  53508. handleVideoTextureLoaded(videoTextureResult);
  53509. },
  53510. /**
  53511. * Create a hash of the material properties for texture cache key.
  53512. */
  53513. hash: function (data) {
  53514. if (data.src.tagName) {
  53515. // Since `data.src` can be an element, parse out the string if necessary for the hash.
  53516. data = utils.extendDeep({}, data);
  53517. data.src = data.src.getAttribute('src');
  53518. }
  53519. return JSON.stringify(data);
  53520. },
  53521. hashVideo: function (data, videoEl) {
  53522. return calculateVideoCacheHash(data, videoEl);
  53523. },
  53524. /**
  53525. * Keep track of material in case an update trigger is needed (e.g., fog).
  53526. *
  53527. * @param {object} material
  53528. */
  53529. registerMaterial: function (material) {
  53530. this.materials[material.uuid] = material;
  53531. },
  53532. /**
  53533. * Stop tracking material, and dispose of any textures not being used by
  53534. * another material component.
  53535. *
  53536. * @param {object} material
  53537. */
  53538. unregisterMaterial: function (material) {
  53539. delete this.materials[material.uuid];
  53540. // If any textures on this material are no longer in use, dispose of them.
  53541. var textureCounts = this.textureCounts;
  53542. Object.keys(material)
  53543. .filter(function (propName) {
  53544. return material[propName] && material[propName].isTexture;
  53545. })
  53546. .forEach(function (mapName) {
  53547. textureCounts[material[mapName].uuid]--;
  53548. if (textureCounts[material[mapName].uuid] <= 0) {
  53549. material[mapName].dispose();
  53550. }
  53551. });
  53552. },
  53553. /**
  53554. * Trigger update to all registered materials.
  53555. */
  53556. updateMaterials: function (material) {
  53557. var materials = this.materials;
  53558. Object.keys(materials).forEach(function (uuid) {
  53559. materials[uuid].needsUpdate = true;
  53560. });
  53561. },
  53562. /**
  53563. * Track textures used by material components, so that they can be safely
  53564. * disposed when no longer in use. Textures must be registered here, and not
  53565. * through registerMaterial(), because textures may not be attached at the
  53566. * time the material is registered.
  53567. *
  53568. * @param {Event} e
  53569. */
  53570. onMaterialTextureLoaded: function (e) {
  53571. if (!this.textureCounts[e.detail.texture.uuid]) {
  53572. this.textureCounts[e.detail.texture.uuid] = 0;
  53573. }
  53574. this.textureCounts[e.detail.texture.uuid]++;
  53575. }
  53576. });
  53577. /**
  53578. * Calculates consistent hash from a video element using its attributes.
  53579. * If the video element has an ID, use that.
  53580. * Else build a hash that looks like `src:myvideo.mp4;height:200;width:400;`.
  53581. *
  53582. * @param data {object} - Texture data such as repeat.
  53583. * @param videoEl {Element} - Video element.
  53584. * @returns {string}
  53585. */
  53586. function calculateVideoCacheHash (data, videoEl) {
  53587. var i;
  53588. var id = videoEl.getAttribute('id');
  53589. var hash;
  53590. var videoAttributes;
  53591. if (id) { return id; }
  53592. // Calculate hash using sorted video attributes.
  53593. hash = '';
  53594. videoAttributes = data || {};
  53595. for (i = 0; i < videoEl.attributes.length; i++) {
  53596. videoAttributes[videoEl.attributes[i].name] = videoEl.attributes[i].value;
  53597. }
  53598. Object.keys(videoAttributes).sort().forEach(function (name) {
  53599. hash += name + ':' + videoAttributes[name] + ';';
  53600. });
  53601. return hash;
  53602. }
  53603. /**
  53604. * Load image texture.
  53605. *
  53606. * @private
  53607. * @param {string|object} src - An <img> element or url to an image file.
  53608. * @param {object} data - Data to set texture properties like `repeat`.
  53609. * @returns {Promise} Resolves once texture is loaded.
  53610. */
  53611. function loadImageTexture (src, data) {
  53612. return new Promise(doLoadImageTexture);
  53613. function doLoadImageTexture (resolve, reject) {
  53614. var isEl = typeof src !== 'string';
  53615. function resolveTexture (texture) {
  53616. setTextureProperties(texture, data);
  53617. texture.needsUpdate = true;
  53618. resolve(texture);
  53619. }
  53620. // Create texture from an element.
  53621. if (isEl) {
  53622. resolveTexture(new THREE.Texture(src));
  53623. return;
  53624. }
  53625. // Request and load texture from src string. THREE will create underlying element.
  53626. // Use THREE.TextureLoader (src, onLoad, onProgress, onError) to load texture.
  53627. TextureLoader.load(
  53628. src,
  53629. resolveTexture,
  53630. function () { /* no-op */ },
  53631. function (xhr) {
  53632. error('`$s` could not be fetched (Error code: %s; Response: %s)', xhr.status,
  53633. xhr.statusText);
  53634. }
  53635. );
  53636. }
  53637. }
  53638. /**
  53639. * Set texture properties such as repeat and offset.
  53640. *
  53641. * @param {object} data - With keys like `repeat`.
  53642. */
  53643. function setTextureProperties (texture, data) {
  53644. var offset = data.offset || {x: 0, y: 0};
  53645. var repeat = data.repeat || {x: 1, y: 1};
  53646. var npot = data.npot || false;
  53647. // To support NPOT textures, wrap must be ClampToEdge (not Repeat),
  53648. // and filters must not use mipmaps (i.e. Nearest or Linear).
  53649. if (npot) {
  53650. texture.wrapS = THREE.ClampToEdgeWrapping;
  53651. texture.wrapT = THREE.ClampToEdgeWrapping;
  53652. texture.magFilter = THREE.LinearFilter;
  53653. texture.minFilter = THREE.LinearFilter;
  53654. }
  53655. // Don't bother setting repeat if it is 1/1. Power-of-two is required to repeat.
  53656. if (repeat.x !== 1 || repeat.y !== 1) {
  53657. texture.wrapS = THREE.RepeatWrapping;
  53658. texture.wrapT = THREE.RepeatWrapping;
  53659. texture.repeat.set(repeat.x, repeat.y);
  53660. }
  53661. // Don't bother setting offset if it is 0/0.
  53662. if (offset.x !== 0 || offset.y !== 0) {
  53663. texture.offset.set(offset.x, offset.y);
  53664. }
  53665. }
  53666. /**
  53667. * Create video element to be used as a texture.
  53668. *
  53669. * @param {string} src - Url to a video file.
  53670. * @param {number} width - Width of the video.
  53671. * @param {number} height - Height of the video.
  53672. * @returns {Element} Video element.
  53673. */
  53674. function createVideoEl (src, width, height) {
  53675. var videoEl = document.createElement('video');
  53676. videoEl.width = width;
  53677. videoEl.height = height;
  53678. // Support inline videos for iOS webviews.
  53679. videoEl.setAttribute('playsinline', '');
  53680. videoEl.setAttribute('webkit-playsinline', '');
  53681. videoEl.autoplay = true;
  53682. videoEl.loop = true;
  53683. videoEl.crossOrigin = 'anonymous';
  53684. videoEl.addEventListener('error', function () {
  53685. warn('`$s` is not a valid video', src);
  53686. }, true);
  53687. videoEl.src = src;
  53688. return videoEl;
  53689. }
  53690. /**
  53691. * Fixes a video element's attributes to prevent developers from accidentally passing the
  53692. * wrong attribute values to commonly misused video attributes.
  53693. *
  53694. * <video> does not treat `autoplay`, `controls`, `crossorigin`, `loop`, and `preload` as
  53695. * as booleans. Existence of those attributes will mean truthy.
  53696. *
  53697. * For example, translates <video loop="false"> to <video>.
  53698. *
  53699. * @see https://developer.mozilla.org/docs/Web/HTML/Element/video#Attributes
  53700. * @param {Element} videoEl - Video element.
  53701. * @returns {Element} Video element with the correct properties updated.
  53702. */
  53703. function fixVideoAttributes (videoEl) {
  53704. videoEl.autoplay = videoEl.hasAttribute('autoplay') && videoEl.getAttribute('autoplay') !== 'false';
  53705. videoEl.controls = videoEl.hasAttribute('controls') && videoEl.getAttribute('controls') !== 'false';
  53706. if (videoEl.getAttribute('loop') === 'false') {
  53707. videoEl.removeAttribute('loop');
  53708. }
  53709. if (videoEl.getAttribute('preload') === 'false') {
  53710. videoEl.preload = 'none';
  53711. }
  53712. videoEl.crossOrigin = videoEl.crossOrigin || 'anonymous';
  53713. // To support inline videos in iOS webviews.
  53714. videoEl.setAttribute('playsinline', '');
  53715. videoEl.setAttribute('webkit-playsinline', '');
  53716. return videoEl;
  53717. }
  53718. },{"../core/system":136,"../lib/three":174,"../utils/":197,"../utils/material":198}],189:[function(_dereq_,module,exports){
  53719. var registerSystem = _dereq_('../core/system').registerSystem;
  53720. var bind = _dereq_('../utils/bind');
  53721. var THREE = _dereq_('../lib/three');
  53722. var SHADOW_MAP_TYPE_MAP = {
  53723. basic: THREE.BasicShadowMap,
  53724. pcf: THREE.PCFShadowMap,
  53725. pcfsoft: THREE.PCFSoftShadowMap
  53726. };
  53727. /**
  53728. * Shadow system.
  53729. *
  53730. * Enabled automatically when one or more shadow components are added to the scene, the system sets
  53731. * options on the WebGLRenderer for configuring shadow appearance.
  53732. */
  53733. module.exports.System = registerSystem('shadow', {
  53734. schema: {
  53735. type: {default: 'pcf', oneOf: ['basic', 'pcf', 'pcfsoft']},
  53736. renderReverseSided: {default: true},
  53737. renderSingleSided: {default: true}
  53738. },
  53739. init: function () {
  53740. var sceneEl = this.sceneEl;
  53741. var data = this.data;
  53742. this.shadowMapEnabled = false;
  53743. sceneEl.addEventListener('render-target-loaded', bind(function () {
  53744. // Renderer is not initialized in most tests.
  53745. if (!sceneEl.renderer) { return; }
  53746. sceneEl.renderer.shadowMap.type = SHADOW_MAP_TYPE_MAP[data.type];
  53747. sceneEl.renderer.shadowMap.renderReverseSided = data.renderReverseSided;
  53748. sceneEl.renderer.shadowMap.renderSingleSided = data.renderSingleSided;
  53749. this.setShadowMapEnabled(this.shadowMapEnabled);
  53750. }, this));
  53751. },
  53752. /**
  53753. * Enables/disables the renderer shadow map.
  53754. * @param {boolean} enabled
  53755. */
  53756. setShadowMapEnabled: function (enabled) {
  53757. var renderer = this.sceneEl.renderer;
  53758. this.shadowMapEnabled = enabled;
  53759. if (renderer) {
  53760. renderer.shadowMap.enabled = enabled;
  53761. }
  53762. }
  53763. });
  53764. },{"../core/system":136,"../lib/three":174,"../utils/bind":191}],190:[function(_dereq_,module,exports){
  53765. var registerSystem = _dereq_('../core/system').registerSystem;
  53766. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  53767. var utils = _dereq_('../utils');
  53768. /**
  53769. * Tracked controls system.
  53770. * It maintains a list with the available tracked controllers
  53771. */
  53772. module.exports.System = registerSystem('tracked-controls', {
  53773. init: function () {
  53774. var self = this;
  53775. this.controllers = [];
  53776. this.lastControllersUpdate = 0;
  53777. // Throttle the (renamed) tick handler to minimum 10ms interval.
  53778. this.tick = utils.throttle(this.throttledTick, 10, this);
  53779. if (!navigator.getVRDisplays) { return; }
  53780. this.sceneEl.addEventListener('enter-vr', function () {
  53781. navigator.getVRDisplays().then(function (displays) {
  53782. if (displays.length) { self.vrDisplay = displays[0]; }
  53783. });
  53784. });
  53785. },
  53786. updateControllerList: function () {
  53787. var controllers = this.controllers = [];
  53788. var gamepads = trackedControlsUtils.getGamepadsByPrefix('');
  53789. for (var i = 0; i < gamepads.length; i++) {
  53790. var gamepad = gamepads[i];
  53791. if (gamepad && gamepad.pose) { controllers.push(gamepad); }
  53792. }
  53793. },
  53794. /**
  53795. * Update controller list every 10 miliseconds.
  53796. */
  53797. throttledTick: function () {
  53798. this.updateControllerList();
  53799. this.sceneEl.emit('controllersupdated', { controllers: this.controllers });
  53800. }
  53801. });
  53802. },{"../core/system":136,"../utils":197,"../utils/tracked-controls":201}],191:[function(_dereq_,module,exports){
  53803. /**
  53804. * Faster version of Function.prototype.bind
  53805. * @param {Function} fn - Function to wrap.
  53806. * @param {Object} ctx - What to bind as context.
  53807. * @param {...*} arguments - Arguments to pass through.
  53808. */
  53809. module.exports = function bind (fn, ctx/* , arg1, arg2 */) {
  53810. return (function (prependedArgs) {
  53811. return function bound () {
  53812. // Concat the bound function arguments with those passed to original bind
  53813. var args = prependedArgs.concat(Array.prototype.slice.call(arguments, 0));
  53814. return fn.apply(ctx, args);
  53815. };
  53816. })(Array.prototype.slice.call(arguments, 2));
  53817. };
  53818. },{}],192:[function(_dereq_,module,exports){
  53819. /* global THREE */
  53820. var debug = _dereq_('./debug');
  53821. var extend = _dereq_('object-assign');
  53822. var warn = debug('utils:coordinates:warn');
  53823. // Coordinate string regex. Handles negative, positive, and decimals.
  53824. var regex = /^\s*((-?\d*\.{0,1}\d+(e-?\d+)?)\s+){2,3}(-?\d*\.{0,1}\d+(e-?\d+)?)\s*$/;
  53825. module.exports.regex = regex;
  53826. /**
  53827. * Parses coordinates from an "x y z" string.
  53828. * Example: "3 10 -5" to {x: 3, y: 10, z: -5}.
  53829. *
  53830. * @param {string} val - An "x y z" string.
  53831. * @param {string} defaults - fallback value.
  53832. * @returns {object} An object with keys [x, y, z].
  53833. */
  53834. function parse (value, defaultVec) {
  53835. var coordinate;
  53836. var vec = {};
  53837. if (value && typeof value === 'object') {
  53838. return vecParseFloat({
  53839. x: value.x !== undefined ? value.x : (defaultVec && defaultVec.x),
  53840. y: value.y !== undefined ? value.y : (defaultVec && defaultVec.y),
  53841. z: value.z !== undefined ? value.z : (defaultVec && defaultVec.z),
  53842. w: value.w !== undefined ? value.w : (defaultVec && defaultVec.w)
  53843. });
  53844. }
  53845. if (typeof value !== 'string' || value === null) {
  53846. return typeof defaultVec === 'object' ? extend({}, defaultVec) : defaultVec;
  53847. }
  53848. coordinate = value.trim().replace(/\s+/g, ' ').split(' ');
  53849. vec.x = coordinate[0] || defaultVec && defaultVec.x;
  53850. vec.y = coordinate[1] || defaultVec && defaultVec.y;
  53851. vec.z = coordinate[2] || defaultVec && defaultVec.z;
  53852. vec.w = coordinate[3] || defaultVec && defaultVec.w;
  53853. return vecParseFloat(vec);
  53854. }
  53855. module.exports.parse = parse;
  53856. /**
  53857. * Stringifies coordinates from an object with keys [x y z].
  53858. * Example: {x: 3, y: 10, z: -5} to "3 10 -5".
  53859. *
  53860. * @param {object|string} data - An object with keys [x y z].
  53861. * @returns {string} An "x y z" string.
  53862. */
  53863. function stringify (data) {
  53864. if (typeof data !== 'object') { return data; }
  53865. return [data.x, data.y, data.z, data.w].join(' ').trim();
  53866. }
  53867. module.exports.stringify = stringify;
  53868. /**
  53869. * @returns {bool}
  53870. */
  53871. function isCoordinates (value) {
  53872. return regex.test(value);
  53873. }
  53874. module.exports.isCoordinates = isCoordinates;
  53875. module.exports.isCoordinate = function (value) {
  53876. warn('`AFRAME.utils.isCoordinate` has been renamed to `AFRAME.utils.isCoordinates`');
  53877. return isCoordinates(value);
  53878. };
  53879. function vecParseFloat (vec) {
  53880. Object.keys(vec).forEach(function (key) {
  53881. if (vec[key] === undefined) {
  53882. delete vec[key];
  53883. return;
  53884. }
  53885. vec[key] = parseFloat(vec[key], 10);
  53886. });
  53887. return vec;
  53888. }
  53889. /**
  53890. * Converts {x, y, z} object to three.js Vector3.
  53891. */
  53892. module.exports.toVector3 = function (vec3) {
  53893. return new THREE.Vector3(vec3.x, vec3.y, vec3.z);
  53894. };
  53895. },{"./debug":193,"object-assign":26}],193:[function(_dereq_,module,exports){
  53896. (function (process){
  53897. var debugLib = _dereq_('debug');
  53898. var extend = _dereq_('object-assign');
  53899. var settings = {
  53900. colors: {
  53901. debug: 'gray',
  53902. error: 'red',
  53903. info: 'gray',
  53904. warn: 'orange'
  53905. }
  53906. };
  53907. /**
  53908. * Monkeypatches `debug` so we can colorize error/warning messages.
  53909. *
  53910. * (See issue: https://github.com/visionmedia/debug/issues/137)
  53911. */
  53912. var debug = function (namespace) {
  53913. var d = debugLib(namespace);
  53914. d.color = getDebugNamespaceColor(namespace);
  53915. return d;
  53916. };
  53917. extend(debug, debugLib);
  53918. /**
  53919. * Returns the type of the namespace (e.g., `error`, `warn`).
  53920. *
  53921. * @param {String} namespace
  53922. * The debug logger's namespace (e.g., `components:geometry:warn`).
  53923. * @returns {String} The type of the namespace (e.g., `warn`).
  53924. * @api private
  53925. */
  53926. function getDebugNamespaceType (namespace) {
  53927. var chunks = namespace.split(':');
  53928. return chunks[chunks.length - 1]; // Return the last one
  53929. }
  53930. /**
  53931. * Returns the color of the namespace (e.g., `orange`).
  53932. *
  53933. * @param {String} namespace
  53934. * The debug logger's namespace (e.g., `components:geometry:warn`).
  53935. * @returns {String} The color of the namespace (e.g., `orange`).
  53936. * @api private
  53937. */
  53938. function getDebugNamespaceColor (namespace) {
  53939. var type = getDebugNamespaceType(namespace);
  53940. var color = settings.colors && settings.colors[type];
  53941. return color || null;
  53942. }
  53943. /**
  53944. * Returns `localStorage` if possible.
  53945. *
  53946. * This is necessary because Safari throws when a user disables
  53947. * cookies or `localStorage` and you attempt to access it.
  53948. *
  53949. * @returns {localStorage}
  53950. * @api private
  53951. */
  53952. function storage () {
  53953. try {
  53954. return window.localStorage;
  53955. } catch (e) {
  53956. }
  53957. }
  53958. /**
  53959. * To enable console logging, type this in the Console of your Dev Tools:
  53960. *
  53961. * localStorage.logs = 1
  53962. *
  53963. * To disable console logging:
  53964. *
  53965. * localStorage.logs = 0
  53966. *
  53967. */
  53968. var ls = storage();
  53969. if (ls && (parseInt(ls.logs, 10) || ls.logs === 'true')) {
  53970. debug.enable('*');
  53971. } else {
  53972. debug.enable('*:error,*:info,*:warn');
  53973. }
  53974. if (process.browser) { window.logs = debug; }
  53975. module.exports = debug;
  53976. }).call(this,_dereq_('_process'))
  53977. },{"_process":34,"debug":8,"object-assign":26}],194:[function(_dereq_,module,exports){
  53978. (function (process){
  53979. var THREE = _dereq_('../lib/three');
  53980. var dolly = new THREE.Object3D();
  53981. var controls = new THREE.VRControls(dolly);
  53982. /**
  53983. * Determine if a headset is connected by checking if the orientation is available.
  53984. */
  53985. function checkHeadsetConnected () {
  53986. var orientation;
  53987. var vrDisplay = controls.getVRDisplay();
  53988. // If `isConnected` is available, just use that.
  53989. if (vrDisplay && 'isConnected' in vrDisplay) { return vrDisplay.isConnected; }
  53990. controls.update();
  53991. orientation = dolly.quaternion;
  53992. if (orientation._x !== 0 || orientation._y !== 0 || orientation._z !== 0) {
  53993. return true;
  53994. }
  53995. return false;
  53996. }
  53997. module.exports.checkHeadsetConnected = checkHeadsetConnected;
  53998. /**
  53999. * Check for positional tracking.
  54000. */
  54001. function checkHasPositionalTracking () {
  54002. var vrDisplay = controls.getVRDisplay();
  54003. if (isMobile() || isGearVR()) { return false; }
  54004. return vrDisplay && vrDisplay.capabilities.hasPosition;
  54005. }
  54006. module.exports.checkHasPositionalTracking = checkHasPositionalTracking;
  54007. /**
  54008. * Checks if browser is mobile.
  54009. * @return {Boolean} True if mobile browser detected.
  54010. */
  54011. var isMobile = (function () {
  54012. var _isMobile = false;
  54013. (function (a) {
  54014. // eslint-disable-next-line no-useless-escape
  54015. 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))) {
  54016. _isMobile = true;
  54017. }
  54018. if (isIOS() || isTablet()) {
  54019. _isMobile = true;
  54020. }
  54021. })(window.navigator.userAgent || window.navigator.vendor || window.opera);
  54022. return function () { return _isMobile; };
  54023. })();
  54024. module.exports.isMobile = isMobile;
  54025. /**
  54026. * Detect tablet devices.
  54027. * @param {string} mockUserAgent - Allow passing a mock user agent for testing.
  54028. */
  54029. function isTablet (mockUserAgent) {
  54030. var userAgent = mockUserAgent || window.navigator.userAgent;
  54031. return /ipad|Nexus (7|9)|xoom|sch-i800|playbook|tablet|kindle/i.test(userAgent);
  54032. }
  54033. module.exports.isTablet = isTablet;
  54034. function isIOS () {
  54035. return /iPad|iPhone|iPod/.test(window.navigator.platform);
  54036. }
  54037. module.exports.isIOS = isIOS;
  54038. function isGearVR () {
  54039. return /SamsungBrowser.+Mobile VR/i.test(window.navigator.userAgent);
  54040. }
  54041. module.exports.isGearVR = isGearVR;
  54042. /**
  54043. * Checks mobile device orientation.
  54044. * @return {Boolean} True if landscape orientation.
  54045. */
  54046. module.exports.isLandscape = function () {
  54047. return window.orientation === 90 || window.orientation === -90;
  54048. };
  54049. /**
  54050. * Check if device is iOS and older than version 10.
  54051. */
  54052. module.exports.isIOSOlderThan10 = function (userAgent) {
  54053. return /(iphone|ipod|ipad).*os.(7|8|9)/i.test(userAgent);
  54054. };
  54055. /**
  54056. * Check if running in a browser or spoofed browser (bundler).
  54057. * We need to check a node api that isn't mocked on either side.
  54058. * `require` and `module.exports` are mocked in browser by bundlers.
  54059. * `window` is mocked in node.
  54060. * `process` is also mocked by browserify, but has custom properties.
  54061. */
  54062. module.exports.isBrowserEnvironment = !!(!process || process.browser);
  54063. /**
  54064. * Check if running in node on the server.
  54065. */
  54066. module.exports.isNodeEnvironment = !module.exports.isBrowserEnvironment;
  54067. }).call(this,_dereq_('_process'))
  54068. },{"../lib/three":174,"_process":34}],195:[function(_dereq_,module,exports){
  54069. /**
  54070. * Split a delimited component property string (e.g., `material.color`) to an object
  54071. * containing `component` name and `property` name. If there is no delimiter, just return the
  54072. * string back.
  54073. */
  54074. module.exports.getComponentPropertyPath = function (str, delimiter) {
  54075. delimiter = delimiter || '.';
  54076. if (str.indexOf(delimiter) === -1) { return str; }
  54077. return str.split(delimiter);
  54078. };
  54079. /**
  54080. * Get component property using encoded component name + component property name with a
  54081. * delimiter.
  54082. */
  54083. module.exports.getComponentProperty = function (el, name, delimiter) {
  54084. var splitName;
  54085. delimiter = delimiter || '.';
  54086. if (name.indexOf(delimiter) !== -1) {
  54087. splitName = name.split(delimiter);
  54088. return el.getAttribute(splitName[0])[splitName[1]];
  54089. }
  54090. return el.getAttribute(name);
  54091. };
  54092. /**
  54093. * Set component property using encoded component name + component property name with a
  54094. * delimiter.
  54095. */
  54096. module.exports.setComponentProperty = function (el, name, value, delimiter) {
  54097. var data = {};
  54098. var splitName;
  54099. delimiter = delimiter || '.';
  54100. if (name.indexOf(delimiter) !== -1) {
  54101. splitName = name.split(delimiter);
  54102. data[splitName[1]] = value;
  54103. el.setAttribute(splitName[0], data);
  54104. return;
  54105. }
  54106. el.setAttribute(name, value);
  54107. };
  54108. },{}],196:[function(_dereq_,module,exports){
  54109. module.exports = function forceCanvasResizeSafariMobile (canvasEl) {
  54110. var width = canvasEl.style.width;
  54111. var height = canvasEl.style.height;
  54112. // Taken from webvr-polyfill (https://github.com/borismus/webvr-polyfill/blob/85f657cd502ec9417bf26b87c3cb2afa6a70e079/src/util.js#L200)
  54113. // iOS only workaround for https://bugs.webkit.org/show_bug.cgi?id=152556
  54114. // By changing the size 1 pixel and restoring the previous value
  54115. // we trigger a size recalculation cycle.
  54116. canvasEl.style.width = (parseInt(width, 10) + 1) + 'px';
  54117. canvasEl.style.height = (parseInt(height, 10) + 1) + 'px';
  54118. setTimeout(function () {
  54119. canvasEl.style.width = width;
  54120. canvasEl.style.height = height;
  54121. }, 200);
  54122. };
  54123. },{}],197:[function(_dereq_,module,exports){
  54124. /* global CustomEvent, location */
  54125. /* Centralized place to reference utilities since utils is exposed to the user. */
  54126. var debug = _dereq_('./debug');
  54127. var deepAssign = _dereq_('deep-assign');
  54128. var device = _dereq_('./device');
  54129. var objectAssign = _dereq_('object-assign');
  54130. var warn = debug('utils:warn');
  54131. module.exports.bind = _dereq_('./bind');
  54132. module.exports.coordinates = _dereq_('./coordinates');
  54133. module.exports.debug = debug;
  54134. module.exports.device = device;
  54135. module.exports.entity = _dereq_('./entity');
  54136. module.exports.forceCanvasResizeSafariMobile = _dereq_('./forceCanvasResizeSafariMobile');
  54137. module.exports.material = _dereq_('./material');
  54138. module.exports.styleParser = _dereq_('./styleParser');
  54139. module.exports.trackedControls = _dereq_('./tracked-controls');
  54140. module.exports.checkHeadsetConnected = function () {
  54141. warn('`utils.checkHeadsetConnected` has moved to `utils.device.checkHeadsetConnected`');
  54142. return device.checkHeadsetConnected(arguments);
  54143. };
  54144. module.exports.isGearVR = function () {
  54145. warn('`utils.isGearVR` has moved to `utils.device.isGearVR`');
  54146. return device.isGearVR(arguments);
  54147. };
  54148. module.exports.isIOS = function () {
  54149. warn('`utils.isIOS` has moved to `utils.device.isIOS`');
  54150. return device.isIOS(arguments);
  54151. };
  54152. module.exports.isMobile = function () {
  54153. warn('`utils.isMobile has moved to `utils.device.isMobile`');
  54154. return device.isMobile(arguments);
  54155. };
  54156. /**
  54157. * Returns throttle function that gets called at most once every interval.
  54158. *
  54159. * @param {function} functionToThrottle
  54160. * @param {number} minimumInterval - Minimal interval between calls (milliseconds).
  54161. * @param {object} optionalContext - If given, bind function to throttle to this context.
  54162. * @returns {function} Throttled function.
  54163. */
  54164. module.exports.throttle = function (functionToThrottle, minimumInterval, optionalContext) {
  54165. var lastTime;
  54166. if (optionalContext) {
  54167. functionToThrottle = module.exports.bind(functionToThrottle, optionalContext);
  54168. }
  54169. return function () {
  54170. var time = Date.now();
  54171. var sinceLastTime = typeof lastTime === 'undefined' ? minimumInterval : time - lastTime;
  54172. if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) {
  54173. lastTime = time;
  54174. functionToThrottle.apply(null, arguments);
  54175. }
  54176. };
  54177. };
  54178. /**
  54179. * Returns throttle function that gets called at most once every interval.
  54180. * Uses the time/timeDelta timestamps provided by the global render loop for better perf.
  54181. *
  54182. * @param {function} functionToThrottle
  54183. * @param {number} minimumInterval - Minimal interval between calls (milliseconds).
  54184. * @param {object} optionalContext - If given, bind function to throttle to this context.
  54185. * @returns {function} Throttled function.
  54186. */
  54187. module.exports.throttleTick = function (functionToThrottle, minimumInterval, optionalContext) {
  54188. var lastTime;
  54189. if (optionalContext) {
  54190. functionToThrottle = module.exports.bind(functionToThrottle, optionalContext);
  54191. }
  54192. return function (time, delta) {
  54193. var sinceLastTime = typeof lastTime === 'undefined' ? delta : time - lastTime;
  54194. if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) {
  54195. lastTime = time;
  54196. functionToThrottle(time, sinceLastTime);
  54197. }
  54198. };
  54199. };
  54200. /**
  54201. * Fires a custom DOM event.
  54202. *
  54203. * @param {Element} el Element on which to fire the event.
  54204. * @param {String} name Name of the event.
  54205. * @param {Object=} [data={bubbles: true, {detail: <el>}}]
  54206. * Data to pass as `customEventInit` to the event.
  54207. */
  54208. module.exports.fireEvent = function (el, name, data) {
  54209. data = data || {};
  54210. data.detail = data.detail || {};
  54211. data.detail.target = data.detail.target || el;
  54212. var evt = new CustomEvent(name, data);
  54213. el.dispatchEvent(evt);
  54214. };
  54215. /**
  54216. * Mix the properties of source object(s) into a destination object.
  54217. *
  54218. * @param {object} dest - The object to which properties will be copied.
  54219. * @param {...object} source - The object(s) from which properties will be copied.
  54220. */
  54221. module.exports.extend = objectAssign;
  54222. module.exports.extendDeep = deepAssign;
  54223. module.exports.clone = function (obj) {
  54224. return JSON.parse(JSON.stringify(obj));
  54225. };
  54226. /**
  54227. * Checks if two values are equal.
  54228. * Includes objects and arrays and nested objects and arrays.
  54229. * Try to keep this function performant as it will be called often to see if a component
  54230. * should be updated.
  54231. *
  54232. * @param {object} a - First object.
  54233. * @param {object} b - Second object.
  54234. * @returns {boolean} Whether two objects are deeply equal.
  54235. */
  54236. function deepEqual (a, b) {
  54237. var i;
  54238. var keysA;
  54239. var keysB;
  54240. var valA;
  54241. var valB;
  54242. // If not objects or arrays, compare as values.
  54243. if (a === undefined || b === undefined || a === null || b === null ||
  54244. !(a && b && (a.constructor === Object && b.constructor === Object) ||
  54245. (a.constructor === Array && b.constructor === Array))) {
  54246. return a === b;
  54247. }
  54248. // Different number of keys, not equal.
  54249. keysA = Object.keys(a);
  54250. keysB = Object.keys(b);
  54251. if (keysA.length !== keysB.length) { return false; }
  54252. // Return `false` at the first sign of inequality.
  54253. for (i = 0; i < keysA.length; ++i) {
  54254. valA = a[keysA[i]];
  54255. valB = b[keysA[i]];
  54256. // Check nested array and object.
  54257. if ((typeof valA === 'object' || typeof valB === 'object') ||
  54258. (Array.isArray(valA) && Array.isArray(valB))) {
  54259. if (valA === valB) { continue; }
  54260. if (!deepEqual(valA, valB)) { return false; }
  54261. } else if (valA !== valB) {
  54262. return false;
  54263. }
  54264. }
  54265. return true;
  54266. }
  54267. module.exports.deepEqual = deepEqual;
  54268. /**
  54269. * Computes the difference between two objects.
  54270. *
  54271. * @param {object} a - First object to compare (e.g., oldData).
  54272. * @param {object} b - Second object to compare (e.g., newData).
  54273. * @returns {object}
  54274. * Difference object where set of keys note which values were not equal, and values are
  54275. * `b`'s values.
  54276. */
  54277. module.exports.diff = function (a, b) {
  54278. var diff = {};
  54279. var keys = Object.keys(a);
  54280. if (!b) { return diff; }
  54281. Object.keys(b).forEach(function collectKeys (bKey) {
  54282. if (keys.indexOf(bKey) === -1) {
  54283. keys.push(bKey);
  54284. }
  54285. });
  54286. keys.forEach(function doDiff (key) {
  54287. var aVal = a[key];
  54288. var bVal = b[key];
  54289. var isComparingObjects = aVal && bVal &&
  54290. aVal.constructor === Object && bVal.constructor === Object;
  54291. if ((isComparingObjects && !deepEqual(aVal, bVal)) ||
  54292. (!isComparingObjects && aVal !== bVal)) {
  54293. diff[key] = bVal;
  54294. }
  54295. });
  54296. return diff;
  54297. };
  54298. /**
  54299. * Returns whether we should capture this keyboard event for keyboard shortcuts.
  54300. * @param {Event} event Event object.
  54301. * @returns {Boolean} Whether the key event should be captured.
  54302. */
  54303. module.exports.shouldCaptureKeyEvent = function (event) {
  54304. if (event.metaKey) { return false; }
  54305. return document.activeElement === document.body;
  54306. };
  54307. /**
  54308. * Splits a string into an array based on a delimiter.
  54309. *
  54310. * @param {string=} [str=''] Source string
  54311. * @param {string=} [delimiter=' '] Delimiter to use
  54312. * @returns {array} Array of delimited strings
  54313. */
  54314. module.exports.splitString = function (str, delimiter) {
  54315. if (typeof delimiter === 'undefined') { delimiter = ' '; }
  54316. // First collapse the whitespace (or whatever the delimiter is).
  54317. var regex = new RegExp(delimiter, 'g');
  54318. str = (str || '').replace(regex, delimiter);
  54319. // Then split.
  54320. return str.split(delimiter);
  54321. };
  54322. /**
  54323. * Extracts data from the element given an object that contains expected keys.
  54324. *
  54325. * @param {Element} Source element.
  54326. * @param {Object} [defaults={}] Object of default key-value pairs.
  54327. * @returns {Object}
  54328. */
  54329. module.exports.getElData = function (el, defaults) {
  54330. defaults = defaults || {};
  54331. var data = {};
  54332. Object.keys(defaults).forEach(copyAttribute);
  54333. function copyAttribute (key) {
  54334. if (el.hasAttribute(key)) {
  54335. data[key] = el.getAttribute(key);
  54336. }
  54337. }
  54338. return data;
  54339. };
  54340. /**
  54341. * Retrieves querystring value.
  54342. * @param {String} name Name of querystring key.
  54343. * @return {String} Value
  54344. */
  54345. module.exports.getUrlParameter = function (name) {
  54346. // eslint-disable-next-line no-useless-escape
  54347. name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
  54348. var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
  54349. var results = regex.exec(location.search);
  54350. return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
  54351. };
  54352. /**
  54353. * Detects whether context is within iframe.
  54354. */
  54355. module.exports.isIframed = function () {
  54356. return window.top !== window.self;
  54357. };
  54358. /**
  54359. * Finds all elements under the element that have the isScene
  54360. * property set to true
  54361. */
  54362. module.exports.findAllScenes = function (el) {
  54363. var matchingElements = [];
  54364. var allElements = el.getElementsByTagName('*');
  54365. for (var i = 0, n = allElements.length; i < n; i++) {
  54366. if (allElements[i].isScene) {
  54367. // Element exists with isScene set.
  54368. matchingElements.push(allElements[i]);
  54369. }
  54370. }
  54371. return matchingElements;
  54372. };
  54373. // Must be at bottom to avoid circular dependency.
  54374. module.exports.srcLoader = _dereq_('./src-loader');
  54375. },{"./bind":191,"./coordinates":192,"./debug":193,"./device":194,"./entity":195,"./forceCanvasResizeSafariMobile":196,"./material":198,"./src-loader":199,"./styleParser":200,"./tracked-controls":201,"deep-assign":10,"object-assign":26}],198:[function(_dereq_,module,exports){
  54376. var THREE = _dereq_('../lib/three');
  54377. var HLS_MIMETYPES = ['application/x-mpegurl', 'application/vnd.apple.mpegurl'];
  54378. /**
  54379. * Update `material` texture property (usually but not always `map`)
  54380. * from `data` property (usually but not always `src`)
  54381. *
  54382. * @param {object} shader - A-Frame shader instance.
  54383. * @param {object} data
  54384. */
  54385. module.exports.updateMapMaterialFromData = function (materialName, dataName, shader, data) {
  54386. var el = shader.el;
  54387. var material = shader.material;
  54388. var src = data[dataName];
  54389. // Because a single material / shader may have multiple textures,
  54390. // we need to remember the source value for this data property
  54391. // to avoid redundant operations which can be expensive otherwise
  54392. // (e.g. video texture loads).
  54393. if (!shader.materialSrcs) { shader.materialSrcs = {}; }
  54394. if (!src) {
  54395. // Forget the prior material src.
  54396. delete shader.materialSrcs[materialName];
  54397. // Remove the texture.
  54398. setMap(null);
  54399. return;
  54400. }
  54401. // Don't process if material src hasn't changed.
  54402. if (src === shader.materialSrcs[materialName]) { return; }
  54403. // Remember the new src for this texture (there may be multiple).
  54404. shader.materialSrcs[materialName] = src;
  54405. // If the new material src is already a texture, just use it.
  54406. if (src instanceof THREE.Texture) { setMap(src); } else {
  54407. // Load texture for the new material src.
  54408. // (And check if we should still use it once available in callback.)
  54409. el.sceneEl.systems.material.loadTexture(src,
  54410. {src: src, repeat: data.repeat, offset: data.offset, npot: data.npot},
  54411. checkSetMap);
  54412. }
  54413. function checkSetMap (texture) {
  54414. // If the source has been changed, don't use loaded texture.
  54415. if (shader.materialSrcs[materialName] !== src) { return; }
  54416. setMap(texture);
  54417. }
  54418. function setMap (texture) {
  54419. material[materialName] = texture;
  54420. material.needsUpdate = true;
  54421. handleTextureEvents(el, texture);
  54422. }
  54423. };
  54424. /**
  54425. * Update `material.map` given `data.src`. For standard and flat shaders.
  54426. *
  54427. * @param {object} shader - A-Frame shader instance.
  54428. * @param {object} data
  54429. */
  54430. module.exports.updateMap = function (shader, data) {
  54431. return module.exports.updateMapMaterialFromData('map', 'src', shader, data);
  54432. };
  54433. /**
  54434. * Updates the material's maps which give the illusion of extra geometry.
  54435. *
  54436. * @param {string} longType - The friendly name of the map from the component e.g. ambientOcclusionMap becomes aoMap in THREE.js
  54437. * @param {object} shader - A-Frame shader instance
  54438. * @param {object} data
  54439. */
  54440. module.exports.updateDistortionMap = function (longType, shader, data) {
  54441. var shortType = longType;
  54442. if (longType === 'ambientOcclusion') { shortType = 'ao'; }
  54443. var el = shader.el;
  54444. var material = shader.material;
  54445. var src = data[longType + 'Map'];
  54446. var info = {};
  54447. info.src = src;
  54448. // Pass through the repeat and offset to be handled by the material loader.
  54449. info.offset = data[longType + 'TextureOffset'];
  54450. info.repeat = data[longType + 'TextureRepeat'];
  54451. info.wrap = data[longType + 'TextureWrap'];
  54452. if (src) {
  54453. if (src === shader[longType + 'TextureSrc']) { return; }
  54454. // Texture added or changed.
  54455. shader[longType + 'TextureSrc'] = src;
  54456. el.sceneEl.systems.material.loadTexture(src, info, setMap);
  54457. return;
  54458. }
  54459. // Texture removed.
  54460. if (!material.map) { return; }
  54461. setMap(null);
  54462. function setMap (texture) {
  54463. material[shortType + 'Map'] = texture;
  54464. material.needsUpdate = true;
  54465. handleTextureEvents(el, texture);
  54466. }
  54467. };
  54468. /**
  54469. * Emit event on entities on texture-related events.
  54470. *
  54471. * @param {Element} el - Entity.
  54472. * @param {object} texture - three.js Texture.
  54473. */
  54474. function handleTextureEvents (el, texture) {
  54475. if (!texture) { return; }
  54476. el.emit('materialtextureloaded', {src: texture.image, texture: texture});
  54477. // Video events.
  54478. if (!texture.image || texture.image.tagName !== 'VIDEO') { return; }
  54479. texture.image.addEventListener('loadeddata', function emitVideoTextureLoadedDataAll () {
  54480. // Check to see if we need to use iOS 10 HLS shader.
  54481. // Only override the shader if it is stock shader that we know doesn't correct.
  54482. if (!el.components || !el.components.material) { return; }
  54483. if (texture.needsCorrectionBGRA && texture.needsCorrectionFlipY &&
  54484. ['standard', 'flat'].indexOf(el.components.material.data.shader) !== -1) {
  54485. el.setAttribute('material', 'shader', 'ios10hls');
  54486. }
  54487. el.emit('materialvideoloadeddata', {src: texture.image, texture: texture});
  54488. });
  54489. texture.image.addEventListener('ended', function emitVideoTextureEndedAll () {
  54490. // Works for non-looping videos only.
  54491. el.emit('materialvideoended', {src: texture.image, texture: texture});
  54492. });
  54493. }
  54494. module.exports.handleTextureEvents = handleTextureEvents;
  54495. /**
  54496. * Given video element src and type, guess whether stream is HLS.
  54497. *
  54498. * @param {string} src - src from video element (generally URL to content).
  54499. * @param {string} type - type from video element (generally MIME type if present).
  54500. */
  54501. module.exports.isHLS = function (src, type) {
  54502. if (type && HLS_MIMETYPES.includes(type.toLowerCase())) { return true; }
  54503. if (src && src.toLowerCase().indexOf('.m3u8') > 0) { return true; }
  54504. return false;
  54505. };
  54506. },{"../lib/three":174}],199:[function(_dereq_,module,exports){
  54507. /* global Image */
  54508. var debug = _dereq_('./debug');
  54509. var warn = debug('utils:src-loader:warn');
  54510. /**
  54511. * Validate a texture, either as a selector or as a URL.
  54512. * Detects whether `src` is pointing to an image or video and invokes the appropriate
  54513. * callback.
  54514. *
  54515. * `src` will be passed into the callback
  54516. *
  54517. * @params {string|Element} src - URL or media element.
  54518. * @params {function} isImageCb - callback if texture is an image.
  54519. * @params {function} isVideoCb - callback if texture is a video.
  54520. */
  54521. function validateSrc (src, isImageCb, isVideoCb) {
  54522. checkIsImage(src, function isAnImageUrl (isImage) {
  54523. if (isImage) {
  54524. isImageCb(src);
  54525. return;
  54526. }
  54527. isVideoCb(src);
  54528. });
  54529. }
  54530. /**
  54531. * Validates six images as a cubemap, either as selector or comma-separated
  54532. * URLs.
  54533. *
  54534. * @param {string} src - A selector or comma-separated image URLs. Image URLs
  54535. must be wrapped by `url()`.
  54536. * @param {string} src - A selector or comma-separated image URLs. Image URLs
  54537. must be wrapped by `url()`.
  54538. */
  54539. function validateCubemapSrc (src, cb) {
  54540. var aCubemap;
  54541. var cubemapSrcRegex = '';
  54542. var i;
  54543. var urls;
  54544. var validatedUrls = [];
  54545. for (i = 0; i < 5; i++) {
  54546. cubemapSrcRegex += '(url\\((?:[^\\)]+)\\),\\s*)';
  54547. }
  54548. cubemapSrcRegex += '(url\\((?:[^\\)]+)\\)\\s*)';
  54549. urls = src.match(new RegExp(cubemapSrcRegex));
  54550. // `src` is a comma-separated list of URLs.
  54551. // In this case, re-use validateSrc for each side of the cube.
  54552. function isImageCb (url) {
  54553. validatedUrls.push(url);
  54554. if (validatedUrls.length === 6) {
  54555. cb(validatedUrls);
  54556. }
  54557. }
  54558. if (urls) {
  54559. for (i = 1; i < 7; i++) {
  54560. validateSrc(parseUrl(urls[i]), isImageCb);
  54561. }
  54562. return;
  54563. }
  54564. // `src` is a query selector to <a-cubemap> containing six $([src])s.
  54565. aCubemap = validateAndGetQuerySelector(src);
  54566. if (!aCubemap) { return; }
  54567. if (aCubemap.tagName === 'A-CUBEMAP' && aCubemap.srcs) {
  54568. return cb(aCubemap.srcs);
  54569. }
  54570. // Else if aCubeMap is not a <a-cubemap>.
  54571. warn('Selector "%s" does not point to <a-cubemap>', src);
  54572. }
  54573. /**
  54574. * Parses src from `url(src)`.
  54575. * @param {string} src - String to parse.
  54576. * @return {string} The parsed src, if parseable.
  54577. */
  54578. function parseUrl (src) {
  54579. var parsedSrc = src.match(/\url\((.+)\)/);
  54580. if (!parsedSrc) { return; }
  54581. return parsedSrc[1];
  54582. }
  54583. /**
  54584. * Call back whether `src` is an image.
  54585. *
  54586. * @param {string|Element} src - URL or element that will be tested.
  54587. * @param {function} onResult - Callback with whether `src` is an image.
  54588. */
  54589. function checkIsImage (src, onResult) {
  54590. if (src.tagName) {
  54591. onResult(src.tagName === 'IMG');
  54592. return;
  54593. }
  54594. var tester = new Image();
  54595. tester.addEventListener('load', onLoad);
  54596. function onLoad () { onResult(true); }
  54597. tester.addEventListener('error', onError);
  54598. function onError () { onResult(false); }
  54599. tester.src = src;
  54600. }
  54601. /**
  54602. * Query and validate a query selector,
  54603. *
  54604. * @param {string} selector - DOM selector.
  54605. * @return {object|null|undefined} Selected DOM element if exists.
  54606. null if query yields no results.
  54607. undefined if `selector` is not a valid selector.
  54608. */
  54609. function validateAndGetQuerySelector (selector) {
  54610. try {
  54611. var el = document.querySelector(selector);
  54612. if (!el) {
  54613. warn('No element was found matching the selector: "%s"', selector);
  54614. }
  54615. return el;
  54616. } catch (e) { // Capture exception if it's not a valid selector.
  54617. warn('"%s" is not a valid selector', selector);
  54618. return undefined;
  54619. }
  54620. }
  54621. module.exports = {
  54622. parseUrl: parseUrl,
  54623. validateSrc: validateSrc,
  54624. validateCubemapSrc: validateCubemapSrc
  54625. };
  54626. },{"./debug":193}],200:[function(_dereq_,module,exports){
  54627. /* Utils for parsing style-like strings (e.g., "primitive: box; width: 5; height: 4.5"). */
  54628. var styleParser = _dereq_('style-attr');
  54629. /**
  54630. * Deserializes style-like string into an object of properties.
  54631. *
  54632. * @param {string} value - HTML attribute value.
  54633. * @returns {object} Property data.
  54634. */
  54635. module.exports.parse = function (value) {
  54636. var parsedData;
  54637. if (typeof value !== 'string') { return value; }
  54638. parsedData = styleParser.parse(value);
  54639. // The style parser returns an object { "" : "test"} when fed a string
  54640. if (parsedData['']) { return value; }
  54641. return transformKeysToCamelCase(parsedData);
  54642. };
  54643. /**
  54644. * Serialize an object of properties into a style-like string.
  54645. *
  54646. * @param {object} data - Property data.
  54647. * @returns {string}
  54648. */
  54649. module.exports.stringify = function (data) {
  54650. if (typeof data === 'string') { return data; }
  54651. return styleParser.stringify(data);
  54652. };
  54653. /**
  54654. * Converts string from hyphen to camelCase.
  54655. *
  54656. * @param {string} str - String to camelCase.
  54657. * @return {string} CamelCased string.
  54658. */
  54659. function toCamelCase (str) {
  54660. return str.replace(/-([a-z])/g, camelCase);
  54661. function camelCase (g) { return g[1].toUpperCase(); }
  54662. }
  54663. module.exports.toCamelCase = toCamelCase;
  54664. /**
  54665. * Converts object's keys from hyphens to camelCase (e.g., `max-value` to
  54666. * `maxValue`).
  54667. *
  54668. * @param {object} obj - The object to camelCase keys.
  54669. * @return {object} The object with keys camelCased.
  54670. */
  54671. function transformKeysToCamelCase (obj) {
  54672. var keys = Object.keys(obj);
  54673. var camelCaseObj = {};
  54674. keys.forEach(function (key) {
  54675. var camelCaseKey = toCamelCase(key);
  54676. camelCaseObj[camelCaseKey] = obj[key];
  54677. });
  54678. return camelCaseObj;
  54679. }
  54680. module.exports.transformKeysToCamelCase = transformKeysToCamelCase;
  54681. },{"style-attr":37}],201:[function(_dereq_,module,exports){
  54682. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  54683. var AXIS_LABELS = ['x', 'y', 'z', 'w'];
  54684. /**
  54685. * Return enumerated gamepads matching id prefix.
  54686. *
  54687. * @param {object} idPrefix - prefix to match in gamepad id, if any.
  54688. */
  54689. module.exports.getGamepadsByPrefix = function (idPrefix) {
  54690. var gamepadsList = [];
  54691. var gamepad;
  54692. var gamepads = navigator.getGamepads && navigator.getGamepads();
  54693. if (!gamepads) { return gamepadsList; }
  54694. for (var i = 0; i < gamepads.length; ++i) {
  54695. gamepad = gamepads[i];
  54696. // need to check that gamepad is valid, since browsers may return array of null values
  54697. if (gamepad) {
  54698. if (!idPrefix || gamepad.id.indexOf(idPrefix) === 0) {
  54699. gamepadsList.push(gamepad);
  54700. }
  54701. }
  54702. }
  54703. return gamepadsList;
  54704. };
  54705. /**
  54706. * Called on controller component `.play` handlers.
  54707. * Check if controller matches parameters and inject tracked-controls component.
  54708. * Handle event listeners.
  54709. * Generate controllerconnected or controllerdisconnected events.
  54710. *
  54711. * @param {object} component - the tracked controls component.
  54712. * @param {object} idPrefix - prefix to match in gamepad id, if any.
  54713. * @param {object} queryObject - map of values to match (hand; index among controllers with idPrefix)
  54714. */
  54715. module.exports.checkControllerPresentAndSetup = function (component, idPrefix, queryObject) {
  54716. var el = component.el;
  54717. var isPresent = isControllerPresent(component, idPrefix, queryObject);
  54718. // If component was previously paused and now playing, re-add event listeners.
  54719. // Handle the event listeners here since this helper method is control of calling
  54720. // `.addEventListeners` and `.removeEventListeners`.
  54721. if (component.controllerPresent && !component.controllerEventsActive) {
  54722. component.addEventListeners();
  54723. }
  54724. // Nothing changed, no need to do anything.
  54725. if (isPresent === component.controllerPresent) { return isPresent; }
  54726. component.controllerPresent = isPresent;
  54727. // Update controller presence.
  54728. if (isPresent) {
  54729. component.injectTrackedControls();
  54730. component.addEventListeners();
  54731. el.emit('controllerconnected', {name: component.name, component: component});
  54732. } else {
  54733. component.removeEventListeners();
  54734. el.emit('controllerdisconnected', {name: component.name, component: component});
  54735. }
  54736. };
  54737. /**
  54738. * Enumerate controllers (as built by system tick, e.g. that have pose) and check if they match parameters.
  54739. *
  54740. * @param {object} component - the tracked controls component.
  54741. * @param {object} idPrefix - prefix to match in gamepad id, if any.
  54742. * @param {object} queryObject - map of values to match (hand; index among controllers with idPrefix)
  54743. */
  54744. function isControllerPresent (component, idPrefix, queryObject) {
  54745. var isPresent = false;
  54746. var index = 0;
  54747. var gamepad;
  54748. var isPrefixMatch;
  54749. var gamepads;
  54750. var sceneEl = component.el.sceneEl;
  54751. var trackedControlsSystem = sceneEl && sceneEl.systems['tracked-controls'];
  54752. if (!trackedControlsSystem) { return isPresent; }
  54753. gamepads = trackedControlsSystem.controllers;
  54754. if (!gamepads || gamepads.length === 0) {
  54755. trackedControlsSystem.updateControllerList();
  54756. gamepads = trackedControlsSystem.controllers;
  54757. }
  54758. if (!gamepads) { return isPresent; }
  54759. for (var i = 0; i < gamepads.length; ++i) {
  54760. gamepad = gamepads[i];
  54761. isPrefixMatch = (!idPrefix || idPrefix === '' || gamepad.id.indexOf(idPrefix) === 0);
  54762. isPresent = isPrefixMatch;
  54763. if (isPresent && queryObject.hand) {
  54764. isPresent = (gamepad.hand || DEFAULT_HANDEDNESS) === queryObject.hand;
  54765. }
  54766. if (isPresent && queryObject.index) {
  54767. isPresent = index === queryObject.index; // need to use count of gamepads with idPrefix
  54768. }
  54769. if (isPresent) { break; }
  54770. if (isPrefixMatch) { index++; } // update count of gamepads with idPrefix
  54771. }
  54772. return isPresent;
  54773. }
  54774. module.exports.isControllerPresent = isControllerPresent;
  54775. /**
  54776. * Emit specific moved event(s) if axes changed, based on original axismoved event.
  54777. *
  54778. * @param {object} self - the component in use (e.g. oculus-touch-controls, vive-controls...)
  54779. * @param {array} axesMapping - the axes mapping to process
  54780. * @param {object} evt - the event to process
  54781. */
  54782. module.exports.emitIfAxesChanged = function (self, axesMapping, evt) {
  54783. Object.keys(axesMapping).forEach(function (key) {
  54784. var axes = axesMapping[key];
  54785. var changed = evt.detail.changed;
  54786. // If no changed axes given at all, or at least one changed value is true in the array,
  54787. if (axes.reduce(function (b, axis) { return b || changed[axis]; }, !changed)) {
  54788. // An axis has changed, so emit the specific moved event, detailing axis values.
  54789. var detail = {};
  54790. axes.forEach(function (axis) { detail[AXIS_LABELS[axis]] = evt.detail.axis[axis]; });
  54791. self.el.emit(key + 'moved', detail);
  54792. // If we updated the model based on axis values, that call would go here.
  54793. }
  54794. });
  54795. };
  54796. },{"../constants":117}],202:[function(_dereq_,module,exports){
  54797. /**
  54798. * @author dmarcos / https://github.com/dmarcos
  54799. * @author mrdoob / http://mrdoob.com
  54800. */
  54801. THREE.VRControls = function ( object, onError ) {
  54802. var scope = this;
  54803. var vrDisplay, vrDisplays;
  54804. var standingMatrix = new THREE.Matrix4();
  54805. var frameData = null;
  54806. if ( 'VRFrameData' in window ) {
  54807. frameData = new window.VRFrameData();
  54808. }
  54809. function gotVRDisplays( displays ) {
  54810. vrDisplays = displays;
  54811. if ( displays.length > 0 ) {
  54812. vrDisplay = displays[ 0 ];
  54813. } else {
  54814. if ( onError ) onError( 'VR input not available.' );
  54815. }
  54816. }
  54817. if ( navigator.getVRDisplays ) {
  54818. navigator.getVRDisplays().then( gotVRDisplays ).catch ( function () {
  54819. console.warn( 'THREE.VRControls: Unable to get VR Displays' );
  54820. } );
  54821. }
  54822. // the Rift SDK returns the position in meters
  54823. // this scale factor allows the user to define how meters
  54824. // are converted to scene units.
  54825. this.scale = 1;
  54826. // If true will use "standing space" coordinate system where y=0 is the
  54827. // floor and x=0, z=0 is the center of the room.
  54828. this.standing = false;
  54829. // Distance from the users eyes to the floor in meters. Used when
  54830. // standing=true but the VRDisplay doesn't provide stageParameters.
  54831. this.userHeight = 1.6;
  54832. this.getVRDisplay = function () {
  54833. return vrDisplay;
  54834. };
  54835. this.setVRDisplay = function ( value ) {
  54836. vrDisplay = value;
  54837. };
  54838. this.getVRDisplays = function () {
  54839. console.warn( 'THREE.VRControls: getVRDisplays() is being deprecated.' );
  54840. return vrDisplays;
  54841. };
  54842. this.getStandingMatrix = function () {
  54843. return standingMatrix;
  54844. };
  54845. this.update = function () {
  54846. if ( vrDisplay ) {
  54847. var pose;
  54848. if ( vrDisplay.getFrameData ) {
  54849. vrDisplay.getFrameData( frameData );
  54850. pose = frameData.pose;
  54851. } else if ( vrDisplay.getPose ) {
  54852. pose = vrDisplay.getPose();
  54853. }
  54854. if ( pose.orientation !== null ) {
  54855. object.quaternion.fromArray( pose.orientation );
  54856. }
  54857. if ( pose.position !== null ) {
  54858. object.position.fromArray( pose.position );
  54859. } else {
  54860. object.position.set( 0, 0, 0 );
  54861. }
  54862. if ( this.standing ) {
  54863. if ( vrDisplay.stageParameters ) {
  54864. object.updateMatrix();
  54865. standingMatrix.fromArray( vrDisplay.stageParameters.sittingToStandingTransform );
  54866. object.applyMatrix( standingMatrix );
  54867. } else {
  54868. object.position.setY( object.position.y + this.userHeight );
  54869. }
  54870. }
  54871. object.position.multiplyScalar( scope.scale );
  54872. }
  54873. };
  54874. this.resetPose = function () {
  54875. if ( vrDisplay ) {
  54876. vrDisplay.resetPose();
  54877. }
  54878. };
  54879. this.resetSensor = function () {
  54880. console.warn( 'THREE.VRControls: .resetSensor() is now .resetPose().' );
  54881. this.resetPose();
  54882. };
  54883. this.zeroSensor = function () {
  54884. console.warn( 'THREE.VRControls: .zeroSensor() is now .resetPose().' );
  54885. this.resetPose();
  54886. };
  54887. this.dispose = function () {
  54888. vrDisplay = null;
  54889. };
  54890. };
  54891. },{}],203:[function(_dereq_,module,exports){
  54892. /**
  54893. * @author dmarcos / https://github.com/dmarcos
  54894. * @author mrdoob / http://mrdoob.com
  54895. *
  54896. * WebVR Spec: http://mozvr.github.io/webvr-spec/webvr.html
  54897. *
  54898. * Firefox: http://mozvr.com/downloads/
  54899. * Chromium: https://webvr.info/get-chrome
  54900. *
  54901. */
  54902. THREE.VREffect = function( renderer, onError ) {
  54903. var vrDisplay, vrDisplays;
  54904. var eyeTranslationL = new THREE.Vector3();
  54905. var eyeTranslationR = new THREE.Vector3();
  54906. var renderRectL, renderRectR;
  54907. var frameData = null;
  54908. if ( 'VRFrameData' in window ) {
  54909. frameData = new window.VRFrameData();
  54910. }
  54911. function gotVRDisplays( displays ) {
  54912. vrDisplays = displays;
  54913. if ( displays.length > 0 ) {
  54914. vrDisplay = displays[ 0 ];
  54915. } else {
  54916. if ( onError ) onError( 'HMD not available' );
  54917. }
  54918. }
  54919. if ( navigator.getVRDisplays ) {
  54920. navigator.getVRDisplays().then( gotVRDisplays ).catch( function() {
  54921. console.warn( 'THREE.VREffect: Unable to get VR Displays' );
  54922. } );
  54923. }
  54924. //
  54925. this.isPresenting = false;
  54926. var scope = this;
  54927. var rendererSize = renderer.getSize();
  54928. var rendererUpdateStyle = false;
  54929. var rendererPixelRatio = renderer.getPixelRatio();
  54930. this.getVRDisplay = function() {
  54931. return vrDisplay;
  54932. };
  54933. this.setVRDisplay = function( value ) {
  54934. vrDisplay = value;
  54935. };
  54936. this.getVRDisplays = function() {
  54937. console.warn( 'THREE.VREffect: getVRDisplays() is being deprecated.' );
  54938. return vrDisplays;
  54939. };
  54940. this.setSize = function( width, height, updateStyle ) {
  54941. rendererSize = { width: width, height: height };
  54942. rendererUpdateStyle = updateStyle;
  54943. if ( scope.isPresenting ) {
  54944. var eyeParamsL = vrDisplay.getEyeParameters( 'left' );
  54945. renderer.setPixelRatio( 1 );
  54946. renderer.setSize( eyeParamsL.renderWidth * 2, eyeParamsL.renderHeight, false );
  54947. } else {
  54948. renderer.setPixelRatio( rendererPixelRatio );
  54949. renderer.setSize( width, height, updateStyle );
  54950. }
  54951. };
  54952. // VR presentation
  54953. var canvas = renderer.domElement;
  54954. var defaultLeftBounds = [ 0.0, 0.0, 0.5, 1.0 ];
  54955. var defaultRightBounds = [ 0.5, 0.0, 0.5, 1.0 ];
  54956. function onVRDisplayPresentChange() {
  54957. var wasPresenting = scope.isPresenting;
  54958. scope.isPresenting = vrDisplay !== undefined && vrDisplay.isPresenting;
  54959. if ( scope.isPresenting ) {
  54960. var eyeParamsL = vrDisplay.getEyeParameters( 'left' );
  54961. var eyeWidth = eyeParamsL.renderWidth;
  54962. var eyeHeight = eyeParamsL.renderHeight;
  54963. if ( ! wasPresenting ) {
  54964. rendererPixelRatio = renderer.getPixelRatio();
  54965. rendererSize = renderer.getSize();
  54966. renderer.setPixelRatio( 1 );
  54967. renderer.setSize( eyeWidth * 2, eyeHeight, false );
  54968. }
  54969. } else if ( wasPresenting ) {
  54970. renderer.setPixelRatio( rendererPixelRatio );
  54971. renderer.setSize( rendererSize.width, rendererSize.height, rendererUpdateStyle );
  54972. }
  54973. }
  54974. window.addEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange, false );
  54975. this.setFullScreen = function( boolean ) {
  54976. return new Promise( function( resolve, reject ) {
  54977. if ( vrDisplay === undefined ) {
  54978. reject( new Error( 'No VR hardware found.' ) );
  54979. return;
  54980. }
  54981. if ( scope.isPresenting === boolean ) {
  54982. resolve();
  54983. return;
  54984. }
  54985. if ( boolean ) {
  54986. resolve( vrDisplay.requestPresent( [ { source: canvas } ] ) );
  54987. } else {
  54988. resolve( vrDisplay.exitPresent() );
  54989. }
  54990. } );
  54991. };
  54992. this.requestPresent = function() {
  54993. return this.setFullScreen( true );
  54994. };
  54995. this.exitPresent = function() {
  54996. return this.setFullScreen( false );
  54997. };
  54998. this.requestAnimationFrame = function( f ) {
  54999. if ( vrDisplay !== undefined ) {
  55000. return vrDisplay.requestAnimationFrame( f );
  55001. } else {
  55002. return window.requestAnimationFrame( f );
  55003. }
  55004. };
  55005. this.cancelAnimationFrame = function( h ) {
  55006. if ( vrDisplay !== undefined ) {
  55007. vrDisplay.cancelAnimationFrame( h );
  55008. } else {
  55009. window.cancelAnimationFrame( h );
  55010. }
  55011. };
  55012. this.submitFrame = function() {
  55013. if ( vrDisplay !== undefined && scope.isPresenting ) {
  55014. vrDisplay.submitFrame();
  55015. }
  55016. };
  55017. this.autoSubmitFrame = true;
  55018. // render
  55019. var cameraL = new THREE.PerspectiveCamera();
  55020. cameraL.layers.enable( 1 );
  55021. var cameraR = new THREE.PerspectiveCamera();
  55022. cameraR.layers.enable( 2 );
  55023. this.render = function( scene, camera, renderTarget, forceClear ) {
  55024. if ( vrDisplay && scope.isPresenting ) {
  55025. var autoUpdate = scene.autoUpdate;
  55026. if ( autoUpdate ) {
  55027. scene.updateMatrixWorld();
  55028. scene.autoUpdate = false;
  55029. }
  55030. var eyeParamsL = vrDisplay.getEyeParameters( 'left' );
  55031. var eyeParamsR = vrDisplay.getEyeParameters( 'right' );
  55032. eyeTranslationL.fromArray( eyeParamsL.offset );
  55033. eyeTranslationR.fromArray( eyeParamsR.offset );
  55034. if ( Array.isArray( scene ) ) {
  55035. console.warn( 'THREE.VREffect.render() no longer supports arrays. Use object.layers instead.' );
  55036. scene = scene[ 0 ];
  55037. }
  55038. // When rendering we don't care what the recommended size is, only what the actual size
  55039. // of the backbuffer is.
  55040. var size = renderer.getSize();
  55041. var layers = vrDisplay.getLayers();
  55042. var leftBounds;
  55043. var rightBounds;
  55044. if ( layers.length ) {
  55045. var layer = layers[ 0 ];
  55046. leftBounds = layer.leftBounds !== null && layer.leftBounds.length === 4 ? layer.leftBounds : defaultLeftBounds;
  55047. rightBounds = layer.rightBounds !== null && layer.rightBounds.length === 4 ? layer.rightBounds : defaultRightBounds;
  55048. } else {
  55049. leftBounds = defaultLeftBounds;
  55050. rightBounds = defaultRightBounds;
  55051. }
  55052. renderRectL = {
  55053. x: Math.round( size.width * leftBounds[ 0 ] ),
  55054. y: Math.round( size.height * leftBounds[ 1 ] ),
  55055. width: Math.round( size.width * leftBounds[ 2 ] ),
  55056. height: Math.round( size.height * leftBounds[ 3 ] )
  55057. };
  55058. renderRectR = {
  55059. x: Math.round( size.width * rightBounds[ 0 ] ),
  55060. y: Math.round( size.height * rightBounds[ 1 ] ),
  55061. width: Math.round( size.width * rightBounds[ 2 ] ),
  55062. height: Math.round( size.height * rightBounds[ 3 ] )
  55063. };
  55064. if ( renderTarget ) {
  55065. renderer.setRenderTarget( renderTarget );
  55066. renderTarget.scissorTest = true;
  55067. } else {
  55068. renderer.setRenderTarget( null );
  55069. renderer.setScissorTest( true );
  55070. }
  55071. if ( renderer.autoClear || forceClear ) renderer.clear();
  55072. if ( camera.parent === null ) camera.updateMatrixWorld();
  55073. camera.matrixWorld.decompose( cameraL.position, cameraL.quaternion, cameraL.scale );
  55074. cameraR.position.copy(cameraL.position);
  55075. cameraR.quaternion.copy(cameraL.quaternion);
  55076. cameraR.scale.copy(cameraL.scale);
  55077. cameraL.translateOnAxis( eyeTranslationL, cameraL.scale.x );
  55078. cameraR.translateOnAxis( eyeTranslationR, cameraR.scale.x );
  55079. if ( vrDisplay.getFrameData ) {
  55080. vrDisplay.depthNear = camera.near;
  55081. vrDisplay.depthFar = camera.far;
  55082. vrDisplay.getFrameData( frameData );
  55083. cameraL.projectionMatrix.elements = frameData.leftProjectionMatrix;
  55084. cameraR.projectionMatrix.elements = frameData.rightProjectionMatrix;
  55085. } else {
  55086. cameraL.projectionMatrix = fovToProjection( eyeParamsL.fieldOfView, true, camera.near, camera.far );
  55087. cameraR.projectionMatrix = fovToProjection( eyeParamsR.fieldOfView, true, camera.near, camera.far );
  55088. }
  55089. // render left eye
  55090. if ( renderTarget ) {
  55091. renderTarget.viewport.set( renderRectL.x, renderRectL.y, renderRectL.width, renderRectL.height );
  55092. renderTarget.scissor.set( renderRectL.x, renderRectL.y, renderRectL.width, renderRectL.height );
  55093. } else {
  55094. renderer.setViewport( renderRectL.x, renderRectL.y, renderRectL.width, renderRectL.height );
  55095. renderer.setScissor( renderRectL.x, renderRectL.y, renderRectL.width, renderRectL.height );
  55096. }
  55097. renderer.render( scene, cameraL, renderTarget, forceClear );
  55098. // render right eye
  55099. if ( renderTarget ) {
  55100. renderTarget.viewport.set( renderRectR.x, renderRectR.y, renderRectR.width, renderRectR.height );
  55101. renderTarget.scissor.set( renderRectR.x, renderRectR.y, renderRectR.width, renderRectR.height );
  55102. } else {
  55103. renderer.setViewport( renderRectR.x, renderRectR.y, renderRectR.width, renderRectR.height );
  55104. renderer.setScissor( renderRectR.x, renderRectR.y, renderRectR.width, renderRectR.height );
  55105. }
  55106. renderer.render( scene, cameraR, renderTarget, forceClear );
  55107. if ( renderTarget ) {
  55108. renderTarget.viewport.set( 0, 0, size.width, size.height );
  55109. renderTarget.scissor.set( 0, 0, size.width, size.height );
  55110. renderTarget.scissorTest = false;
  55111. renderer.setRenderTarget( null );
  55112. } else {
  55113. renderer.setViewport( 0, 0, size.width, size.height );
  55114. renderer.setScissorTest( false );
  55115. }
  55116. if ( autoUpdate ) {
  55117. scene.autoUpdate = true;
  55118. }
  55119. if ( scope.autoSubmitFrame ) {
  55120. scope.submitFrame();
  55121. }
  55122. return;
  55123. }
  55124. // Regular render mode if not HMD
  55125. renderer.render( scene, camera, renderTarget, forceClear );
  55126. };
  55127. this.dispose = function() {
  55128. window.removeEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange, false );
  55129. };
  55130. //
  55131. function fovToNDCScaleOffset( fov ) {
  55132. var pxscale = 2.0 / ( fov.leftTan + fov.rightTan );
  55133. var pxoffset = ( fov.leftTan - fov.rightTan ) * pxscale * 0.5;
  55134. var pyscale = 2.0 / ( fov.upTan + fov.downTan );
  55135. var pyoffset = ( fov.upTan - fov.downTan ) * pyscale * 0.5;
  55136. return { scale: [ pxscale, pyscale ], offset: [ pxoffset, pyoffset ] };
  55137. }
  55138. function fovPortToProjection( fov, rightHanded, zNear, zFar ) {
  55139. rightHanded = rightHanded === undefined ? true : rightHanded;
  55140. zNear = zNear === undefined ? 0.01 : zNear;
  55141. zFar = zFar === undefined ? 10000.0 : zFar;
  55142. var handednessScale = rightHanded ? - 1.0 : 1.0;
  55143. // start with an identity matrix
  55144. var mobj = new THREE.Matrix4();
  55145. var m = mobj.elements;
  55146. // and with scale/offset info for normalized device coords
  55147. var scaleAndOffset = fovToNDCScaleOffset( fov );
  55148. // X result, map clip edges to [-w,+w]
  55149. m[ 0 * 4 + 0 ] = scaleAndOffset.scale[ 0 ];
  55150. m[ 0 * 4 + 1 ] = 0.0;
  55151. m[ 0 * 4 + 2 ] = scaleAndOffset.offset[ 0 ] * handednessScale;
  55152. m[ 0 * 4 + 3 ] = 0.0;
  55153. // Y result, map clip edges to [-w,+w]
  55154. // Y offset is negated because this proj matrix transforms from world coords with Y=up,
  55155. // but the NDC scaling has Y=down (thanks D3D?)
  55156. m[ 1 * 4 + 0 ] = 0.0;
  55157. m[ 1 * 4 + 1 ] = scaleAndOffset.scale[ 1 ];
  55158. m[ 1 * 4 + 2 ] = - scaleAndOffset.offset[ 1 ] * handednessScale;
  55159. m[ 1 * 4 + 3 ] = 0.0;
  55160. // Z result (up to the app)
  55161. m[ 2 * 4 + 0 ] = 0.0;
  55162. m[ 2 * 4 + 1 ] = 0.0;
  55163. m[ 2 * 4 + 2 ] = zFar / ( zNear - zFar ) * - handednessScale;
  55164. m[ 2 * 4 + 3 ] = ( zFar * zNear ) / ( zNear - zFar );
  55165. // W result (= Z in)
  55166. m[ 3 * 4 + 0 ] = 0.0;
  55167. m[ 3 * 4 + 1 ] = 0.0;
  55168. m[ 3 * 4 + 2 ] = handednessScale;
  55169. m[ 3 * 4 + 3 ] = 0.0;
  55170. mobj.transpose();
  55171. return mobj;
  55172. }
  55173. function fovToProjection( fov, rightHanded, zNear, zFar ) {
  55174. var DEG2RAD = Math.PI / 180.0;
  55175. var fovPort = {
  55176. upTan: Math.tan( fov.upDegrees * DEG2RAD ),
  55177. downTan: Math.tan( fov.downDegrees * DEG2RAD ),
  55178. leftTan: Math.tan( fov.leftDegrees * DEG2RAD ),
  55179. rightTan: Math.tan( fov.rightDegrees * DEG2RAD )
  55180. };
  55181. return fovPortToProjection( fovPort, rightHanded, zNear, zFar );
  55182. }
  55183. };
  55184. },{}],204:[function(_dereq_,module,exports){
  55185. window.glStats = function () {
  55186. var _rS = null;
  55187. var _totalDrawArraysCalls = 0,
  55188. _totalDrawElementsCalls = 0,
  55189. _totalUseProgramCalls = 0,
  55190. _totalFaces = 0,
  55191. _totalVertices = 0,
  55192. _totalPoints = 0,
  55193. _totalBindTexures = 0;
  55194. function _h ( f, c ) {
  55195. return function () {
  55196. c.apply( this, arguments );
  55197. f.apply( this, arguments );
  55198. };
  55199. }
  55200. WebGLRenderingContext.prototype.drawArrays = _h( WebGLRenderingContext.prototype.drawArrays, function () {
  55201. _totalDrawArraysCalls++;
  55202. if ( arguments[ 0 ] == this.POINTS ) _totalPoints += arguments[ 2 ];
  55203. else _totalVertices += arguments[ 2 ];
  55204. } );
  55205. WebGLRenderingContext.prototype.drawElements = _h( WebGLRenderingContext.prototype.drawElements, function () {
  55206. _totalDrawElementsCalls++;
  55207. _totalFaces += arguments[ 1 ] / 3;
  55208. _totalVertices += arguments[ 1 ];
  55209. } );
  55210. WebGLRenderingContext.prototype.useProgram = _h( WebGLRenderingContext.prototype.useProgram, function () {
  55211. _totalUseProgramCalls++;
  55212. } );
  55213. WebGLRenderingContext.prototype.bindTexture = _h( WebGLRenderingContext.prototype.bindTexture, function () {
  55214. _totalBindTexures++;
  55215. } );
  55216. var _values = {
  55217. allcalls: {
  55218. over: 3000,
  55219. caption: 'Calls (hook)'
  55220. },
  55221. drawelements: {
  55222. caption: 'drawElements (hook)'
  55223. },
  55224. drawarrays: {
  55225. caption: 'drawArrays (hook)'
  55226. }
  55227. };
  55228. var _groups = [ {
  55229. caption: 'WebGL',
  55230. values: [ 'allcalls', 'drawelements', 'drawarrays', 'useprogram', 'bindtexture', 'glfaces', 'glvertices', 'glpoints' ]
  55231. } ];
  55232. var _fractions = [ {
  55233. base: 'allcalls',
  55234. steps: [ 'drawelements', 'drawarrays' ]
  55235. } ];
  55236. function _update () {
  55237. _rS( 'allcalls' ).set( _totalDrawArraysCalls + _totalDrawElementsCalls );
  55238. _rS( 'drawElements' ).set( _totalDrawElementsCalls );
  55239. _rS( 'drawArrays' ).set( _totalDrawArraysCalls );
  55240. _rS( 'bindTexture' ).set( _totalBindTexures );
  55241. _rS( 'useProgram' ).set( _totalUseProgramCalls );
  55242. _rS( 'glfaces' ).set( _totalFaces );
  55243. _rS( 'glvertices' ).set( _totalVertices );
  55244. _rS( 'glpoints' ).set( _totalPoints );
  55245. }
  55246. function _start () {
  55247. _totalDrawArraysCalls = 0;
  55248. _totalDrawElementsCalls = 0;
  55249. _totalUseProgramCalls = 0;
  55250. _totalFaces = 0;
  55251. _totalVertices = 0;
  55252. _totalPoints = 0;
  55253. _totalBindTexures = 0;
  55254. }
  55255. function _end () {}
  55256. function _attach ( r ) {
  55257. _rS = r;
  55258. }
  55259. return {
  55260. update: _update,
  55261. start: _start,
  55262. end: _end,
  55263. attach: _attach,
  55264. values: _values,
  55265. groups: _groups,
  55266. fractions: _fractions
  55267. };
  55268. };
  55269. window.threeStats = function ( renderer ) {
  55270. var _rS = null;
  55271. var _values = {
  55272. 'renderer.info.memory.geometries': {
  55273. caption: 'Geometries'
  55274. },
  55275. 'renderer.info.memory.textures': {
  55276. caption: 'Textures'
  55277. },
  55278. 'renderer.info.programs': {
  55279. caption: 'Programs'
  55280. },
  55281. 'renderer.info.render.calls': {
  55282. caption: 'Calls'
  55283. },
  55284. 'renderer.info.render.faces': {
  55285. caption: 'Faces',
  55286. over: 1000
  55287. },
  55288. 'renderer.info.render.points': {
  55289. caption: 'Points'
  55290. },
  55291. 'renderer.info.render.vertices': {
  55292. caption: 'Vertices'
  55293. }
  55294. };
  55295. var _groups = [ {
  55296. caption: 'Three.js - Memory',
  55297. values: [ 'renderer.info.memory.geometries', 'renderer.info.programs', 'renderer.info.memory.textures' ]
  55298. }, {
  55299. caption: 'Three.js - Render',
  55300. values: [ 'renderer.info.render.calls', 'renderer.info.render.faces', 'renderer.info.render.points', 'renderer.info.render.vertices' ]
  55301. } ];
  55302. var _fractions = [];
  55303. function _update () {
  55304. _rS( 'renderer.info.memory.geometries' ).set( renderer.info.memory.geometries );
  55305. _rS( 'renderer.info.programs' ).set( renderer.info.programs.length );
  55306. _rS( 'renderer.info.memory.textures' ).set( renderer.info.memory.textures );
  55307. _rS( 'renderer.info.render.calls' ).set( renderer.info.render.calls );
  55308. _rS( 'renderer.info.render.faces' ).set( renderer.info.render.faces );
  55309. _rS( 'renderer.info.render.points' ).set( renderer.info.render.points );
  55310. _rS( 'renderer.info.render.vertices' ).set( renderer.info.render.vertices );
  55311. }
  55312. function _start () {}
  55313. function _end () {}
  55314. function _attach ( r ) {
  55315. _rS = r;
  55316. }
  55317. return {
  55318. update: _update,
  55319. start: _start,
  55320. end: _end,
  55321. attach: _attach,
  55322. values: _values,
  55323. groups: _groups,
  55324. fractions: _fractions
  55325. };
  55326. };
  55327. /*
  55328. * From https://github.com/paulirish/memory-stats.js
  55329. */
  55330. window.BrowserStats = function () {
  55331. var _rS = null;
  55332. var _usedJSHeapSize = 0,
  55333. _totalJSHeapSize = 0;
  55334. if ( window.performance && !performance.memory ) {
  55335. performance.memory = {
  55336. usedJSHeapSize: 0,
  55337. totalJSHeapSize: 0
  55338. };
  55339. }
  55340. if ( performance.memory.totalJSHeapSize === 0 ) {
  55341. console.warn( 'totalJSHeapSize === 0... performance.memory is only available in Chrome .' );
  55342. }
  55343. var _values = {
  55344. memory: {
  55345. caption: 'Used Memory',
  55346. average: true,
  55347. avgMs: 1000,
  55348. over: 22
  55349. },
  55350. total: {
  55351. caption: 'Total Memory'
  55352. }
  55353. };
  55354. var _groups = [ {
  55355. caption: 'Browser',
  55356. values: [ 'memory', 'total' ]
  55357. } ];
  55358. var _fractions = [ {
  55359. base: 'total',
  55360. steps: [ 'memory' ]
  55361. } ];
  55362. var log1024 = Math.log( 1024 );
  55363. function _size ( v ) {
  55364. var precision = 100; //Math.pow(10, 2);
  55365. var i = Math.floor( Math.log( v ) / log1024 );
  55366. return Math.round( v * precision / Math.pow( 1024, i ) ) / precision; // + ' ' + sizes[i];
  55367. }
  55368. function _update () {
  55369. _usedJSHeapSize = _size( performance.memory.usedJSHeapSize );
  55370. _totalJSHeapSize = _size( performance.memory.totalJSHeapSize );
  55371. _rS( 'memory' ).set( _usedJSHeapSize );
  55372. _rS( 'total' ).set( _totalJSHeapSize );
  55373. }
  55374. function _start () {
  55375. _usedJSHeapSize = 0;
  55376. }
  55377. function _end () {}
  55378. function _attach ( r ) {
  55379. _rS = r;
  55380. }
  55381. return {
  55382. update: _update,
  55383. start: _start,
  55384. end: _end,
  55385. attach: _attach,
  55386. values: _values,
  55387. groups: _groups,
  55388. fractions: _fractions
  55389. };
  55390. };
  55391. if (typeof module === 'object') {
  55392. module.exports = {
  55393. glStats: window.glStats,
  55394. threeStats: window.threeStats,
  55395. BrowserStats: window.BrowserStats
  55396. };
  55397. }
  55398. },{}],205:[function(_dereq_,module,exports){
  55399. // performance.now() polyfill from https://gist.github.com/paulirish/5438650
  55400. 'use strict';
  55401. ( function () {
  55402. if ( 'performance' in window == false ) {
  55403. window.performance = {};
  55404. }
  55405. var performance = window.performance;
  55406. if ( 'now' in performance == false ) {
  55407. var nowOffset = Date.now();
  55408. if ( performance.timing && performance.timing.navigationStart ) {
  55409. nowOffset = performance.timing.navigationStart;
  55410. }
  55411. performance.now = function now () {
  55412. return Date.now() - nowOffset;
  55413. };
  55414. }
  55415. if( !performance.mark ) {
  55416. performance.mark = function(){}
  55417. }
  55418. if( !performance.measure ) {
  55419. performance.measure = function(){}
  55420. }
  55421. } )();
  55422. window.rStats = function rStats ( settings ) {
  55423. function iterateKeys ( array, callback ) {
  55424. var keys = Object.keys( array );
  55425. for ( var j = 0, l = keys.length; j < l; j++ ) {
  55426. callback( keys[ j ] );
  55427. }
  55428. }
  55429. function importCSS ( url ) {
  55430. var element = document.createElement( 'link' );
  55431. element.href = url;
  55432. element.rel = 'stylesheet';
  55433. element.type = 'text/css';
  55434. document.getElementsByTagName( 'head' )[ 0 ].appendChild( element );
  55435. }
  55436. var _settings = settings || {};
  55437. var _colours = _settings.colours || [ '#850700', '#c74900', '#fcb300', '#284280', '#4c7c0c' ];
  55438. var _cssFont = 'https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700,300';
  55439. var _cssRStats = ( _settings.CSSPath ? _settings.CSSPath : '' ) + 'rStats.css';
  55440. var _css = _settings.css || [ _cssFont, _cssRStats ];
  55441. _css.forEach(function (uri) {
  55442. importCSS( uri );
  55443. });
  55444. if ( !_settings.values ) _settings.values = {};
  55445. var _base, _div, _elHeight = 10, _elWidth = 200;
  55446. var _perfCounters = {};
  55447. function Graph ( _dom, _id, _defArg ) {
  55448. var _def = _defArg || {};
  55449. var _canvas = document.createElement( 'canvas' ),
  55450. _ctx = _canvas.getContext( '2d' ),
  55451. _max = 0,
  55452. _current = 0;
  55453. var c = _def.color ? _def.color : '#666666';
  55454. var _dotCanvas = document.createElement( 'canvas' ),
  55455. _dotCtx = _dotCanvas.getContext( '2d' );
  55456. _dotCanvas.width = 1;
  55457. _dotCanvas.height = 2 * _elHeight;
  55458. _dotCtx.fillStyle = '#444444';
  55459. _dotCtx.fillRect( 0, 0, 1, 2 * _elHeight );
  55460. _dotCtx.fillStyle = c;
  55461. _dotCtx.fillRect( 0, _elHeight, 1, _elHeight );
  55462. _dotCtx.fillStyle = '#ffffff';
  55463. _dotCtx.globalAlpha = 0.5;
  55464. _dotCtx.fillRect( 0, _elHeight, 1, 1 );
  55465. _dotCtx.globalAlpha = 1;
  55466. var _alarmCanvas = document.createElement( 'canvas' ),
  55467. _alarmCtx = _alarmCanvas.getContext( '2d' );
  55468. _alarmCanvas.width = 1;
  55469. _alarmCanvas.height = 2 * _elHeight;
  55470. _alarmCtx.fillStyle = '#444444';
  55471. _alarmCtx.fillRect( 0, 0, 1, 2 * _elHeight );
  55472. _alarmCtx.fillStyle = '#b70000';
  55473. _alarmCtx.fillRect( 0, _elHeight, 1, _elHeight );
  55474. _alarmCtx.globalAlpha = 0.5;
  55475. _alarmCtx.fillStyle = '#ffffff';
  55476. _alarmCtx.fillRect( 0, _elHeight, 1, 1 );
  55477. _alarmCtx.globalAlpha = 1;
  55478. function _init () {
  55479. _canvas.width = _elWidth;
  55480. _canvas.height = _elHeight;
  55481. _canvas.style.width = _canvas.width + 'px';
  55482. _canvas.style.height = _canvas.height + 'px';
  55483. _canvas.className = 'rs-canvas';
  55484. _dom.appendChild( _canvas );
  55485. _ctx.fillStyle = '#444444';
  55486. _ctx.fillRect( 0, 0, _canvas.width, _canvas.height );
  55487. }
  55488. function _draw ( v, alarm ) {
  55489. _current += ( v - _current ) * 0.1;
  55490. _max *= 0.99;
  55491. if ( _current > _max ) _max = _current;
  55492. _ctx.drawImage( _canvas, 1, 0, _canvas.width - 1, _canvas.height, 0, 0, _canvas.width - 1, _canvas.height );
  55493. if ( alarm ) {
  55494. _ctx.drawImage( _alarmCanvas, _canvas.width - 1, _canvas.height - _current * _canvas.height / _max - _elHeight );
  55495. } else {
  55496. _ctx.drawImage( _dotCanvas, _canvas.width - 1, _canvas.height - _current * _canvas.height / _max - _elHeight );
  55497. }
  55498. }
  55499. _init();
  55500. return {
  55501. draw: _draw
  55502. };
  55503. }
  55504. function StackGraph ( _dom, _num ) {
  55505. var _canvas = document.createElement( 'canvas' ),
  55506. _ctx = _canvas.getContext( '2d' );
  55507. function _init () {
  55508. _canvas.width = _elWidth;
  55509. _canvas.height = _elHeight * _num;
  55510. _canvas.style.width = _canvas.width + 'px';
  55511. _canvas.style.height = _canvas.height + 'px';
  55512. _canvas.className = 'rs-canvas';
  55513. _dom.appendChild( _canvas );
  55514. _ctx.fillStyle = '#444444';
  55515. _ctx.fillRect( 0, 0, _canvas.width, _canvas.height );
  55516. }
  55517. function _draw ( v ) {
  55518. _ctx.drawImage( _canvas, 1, 0, _canvas.width - 1, _canvas.height, 0, 0, _canvas.width - 1, _canvas.height );
  55519. var th = 0;
  55520. iterateKeys( v, function ( j ) {
  55521. var h = v[ j ] * _canvas.height;
  55522. _ctx.fillStyle = _colours[ j ];
  55523. _ctx.fillRect( _canvas.width - 1, th, 1, h );
  55524. th += h;
  55525. } );
  55526. }
  55527. _init();
  55528. return {
  55529. draw: _draw
  55530. };
  55531. }
  55532. function PerfCounter ( id, group ) {
  55533. var _id = id,
  55534. _time,
  55535. _value = 0,
  55536. _total = 0,
  55537. _averageValue = 0,
  55538. _accumValue = 0,
  55539. _accumStart = performance.now(),
  55540. _accumSamples = 0,
  55541. _dom = document.createElement( 'div' ),
  55542. _spanId = document.createElement( 'span' ),
  55543. _spanValue = document.createElement( 'div' ),
  55544. _spanValueText = document.createTextNode( '' ),
  55545. _def = _settings ? _settings.values[ _id.toLowerCase() ] : null,
  55546. _graph = new Graph( _dom, _id, _def ),
  55547. _started = false;
  55548. _spanId.className = 'rs-counter-id';
  55549. _spanId.textContent = ( _def && _def.caption ) ? _def.caption : _id;
  55550. _spanValue.className = 'rs-counter-value';
  55551. _spanValue.appendChild( _spanValueText );
  55552. _dom.appendChild( _spanId );
  55553. _dom.appendChild( _spanValue );
  55554. if ( group ) group.div.appendChild( _dom );
  55555. else _div.appendChild( _dom );
  55556. _time = performance.now();
  55557. function _average ( v ) {
  55558. if ( _def && _def.average ) {
  55559. _accumValue += v;
  55560. _accumSamples++;
  55561. var t = performance.now();
  55562. if ( t - _accumStart >= ( _def.avgMs || 1000 ) ) {
  55563. _averageValue = _accumValue / _accumSamples;
  55564. _accumValue = 0;
  55565. _accumStart = t;
  55566. _accumSamples = 0;
  55567. }
  55568. }
  55569. }
  55570. function _start () {
  55571. _time = performance.now();
  55572. if( _settings.userTimingAPI ) performance.mark( _id + '-start' );
  55573. _started = true;
  55574. }
  55575. function _end () {
  55576. _value = performance.now() - _time;
  55577. if( _settings.userTimingAPI ) {
  55578. performance.mark( _id + '-end' );
  55579. if( _started ) {
  55580. performance.measure( _id, _id + '-start', _id + '-end' );
  55581. }
  55582. }
  55583. _average( _value );
  55584. }
  55585. function _tick () {
  55586. _end();
  55587. _start();
  55588. }
  55589. function _draw () {
  55590. var v = ( _def && _def.average ) ? _averageValue : _value;
  55591. _spanValueText.nodeValue = Math.round( v * 100 ) / 100;
  55592. var a = ( _def && ( ( _def.below && _value < _def.below ) || ( _def.over && _value > _def.over ) ) );
  55593. _graph.draw( _value, a );
  55594. _dom.className = a ? 'rs-counter-base alarm' : 'rs-counter-base';
  55595. }
  55596. function _frame () {
  55597. var t = performance.now();
  55598. var e = t - _time;
  55599. _total++;
  55600. if ( e > 1000 ) {
  55601. if ( _def && _def.interpolate === false ) {
  55602. _value = _total;
  55603. } else {
  55604. _value = _total * 1000 / e;
  55605. }
  55606. _total = 0;
  55607. _time = t;
  55608. _average( _value );
  55609. }
  55610. }
  55611. function _set ( v ) {
  55612. _value = v;
  55613. _average( _value );
  55614. }
  55615. return {
  55616. set: _set,
  55617. start: _start,
  55618. tick: _tick,
  55619. end: _end,
  55620. frame: _frame,
  55621. value: function () {
  55622. return _value;
  55623. },
  55624. draw: _draw
  55625. };
  55626. }
  55627. function sample () {
  55628. var _value = 0;
  55629. function _set ( v ) {
  55630. _value = v;
  55631. }
  55632. return {
  55633. set: _set,
  55634. value: function () {
  55635. return _value;
  55636. }
  55637. };
  55638. }
  55639. function _perf ( idArg ) {
  55640. var id = idArg.toLowerCase();
  55641. if ( id === undefined ) id = 'default';
  55642. if ( _perfCounters[ id ] ) return _perfCounters[ id ];
  55643. var group = null;
  55644. if ( _settings && _settings.groups ) {
  55645. iterateKeys( _settings.groups, function ( j ) {
  55646. var g = _settings.groups[ parseInt( j, 10 ) ];
  55647. if ( !group && g.values.indexOf( id.toLowerCase() ) !== -1 ) {
  55648. group = g;
  55649. }
  55650. } );
  55651. }
  55652. var p = new PerfCounter( id, group );
  55653. _perfCounters[ id ] = p;
  55654. return p;
  55655. }
  55656. function _init () {
  55657. if ( _settings.plugins ) {
  55658. if ( !_settings.values ) _settings.values = {};
  55659. if ( !_settings.groups ) _settings.groups = [];
  55660. if ( !_settings.fractions ) _settings.fractions = [];
  55661. for ( var j = 0; j < _settings.plugins.length; j++ ) {
  55662. _settings.plugins[ j ].attach( _perf );
  55663. iterateKeys( _settings.plugins[ j ].values, function ( k ) {
  55664. _settings.values[ k ] = _settings.plugins[ j ].values[ k ];
  55665. } );
  55666. _settings.groups = _settings.groups.concat( _settings.plugins[ j ].groups );
  55667. _settings.fractions = _settings.fractions.concat( _settings.plugins[ j ].fractions );
  55668. }
  55669. } else {
  55670. _settings.plugins = {};
  55671. }
  55672. _base = document.createElement( 'div' );
  55673. _base.className = 'rs-base';
  55674. _div = document.createElement( 'div' );
  55675. _div.className = 'rs-container';
  55676. _div.style.height = 'auto';
  55677. _base.appendChild( _div );
  55678. document.body.appendChild( _base );
  55679. if ( !_settings ) return;
  55680. if ( _settings.groups ) {
  55681. iterateKeys( _settings.groups, function ( j ) {
  55682. var g = _settings.groups[ parseInt( j, 10 ) ];
  55683. var div = document.createElement( 'div' );
  55684. div.className = 'rs-group';
  55685. g.div = div;
  55686. var h1 = document.createElement( 'h1' );
  55687. h1.textContent = g.caption;
  55688. h1.addEventListener( 'click', function ( e ) {
  55689. this.classList.toggle( 'hidden' );
  55690. e.preventDefault();
  55691. }.bind( div ) );
  55692. _div.appendChild( h1 );
  55693. _div.appendChild( div );
  55694. } );
  55695. }
  55696. if ( _settings.fractions ) {
  55697. iterateKeys( _settings.fractions, function ( j ) {
  55698. var f = _settings.fractions[ parseInt( j, 10 ) ];
  55699. var div = document.createElement( 'div' );
  55700. div.className = 'rs-fraction';
  55701. var legend = document.createElement( 'div' );
  55702. legend.className = 'rs-legend';
  55703. var h = 0;
  55704. iterateKeys( _settings.fractions[ j ].steps, function ( k ) {
  55705. var p = document.createElement( 'p' );
  55706. p.textContent = _settings.fractions[ j ].steps[ k ];
  55707. p.style.color = _colours[ h ];
  55708. legend.appendChild( p );
  55709. h++;
  55710. } );
  55711. div.appendChild( legend );
  55712. div.style.height = h * _elHeight + 'px';
  55713. f.div = div;
  55714. var graph = new StackGraph( div, h );
  55715. f.graph = graph;
  55716. _div.appendChild( div );
  55717. } );
  55718. }
  55719. }
  55720. function _update () {
  55721. iterateKeys( _settings.plugins, function ( j ) {
  55722. _settings.plugins[ j ].update();
  55723. } );
  55724. iterateKeys( _perfCounters, function ( j ) {
  55725. _perfCounters[ j ].draw();
  55726. } );
  55727. if ( _settings && _settings.fractions ) {
  55728. iterateKeys( _settings.fractions, function ( j ) {
  55729. var f = _settings.fractions[ parseInt( j, 10 ) ];
  55730. var v = [];
  55731. var base = _perfCounters[ f.base.toLowerCase() ];
  55732. if ( base ) {
  55733. base = base.value();
  55734. iterateKeys( _settings.fractions[ j ].steps, function ( k ) {
  55735. var s = _settings.fractions[ j ].steps[ parseInt( k, 10 ) ].toLowerCase();
  55736. var val = _perfCounters[ s ];
  55737. if ( val ) {
  55738. v.push( val.value() / base );
  55739. }
  55740. } );
  55741. }
  55742. f.graph.draw( v );
  55743. } );
  55744. }
  55745. /*if( _height != _div.clientHeight ) {
  55746. _height = _div.clientHeight;
  55747. _base.style.height = _height + 2 * _elHeight + 'px';
  55748. console.log( _base.clientHeight );
  55749. }*/
  55750. }
  55751. _init();
  55752. return function ( id ) {
  55753. if ( id ) return _perf( id );
  55754. return {
  55755. element: _base,
  55756. update: _update
  55757. };
  55758. };
  55759. }
  55760. if (typeof module === 'object') {
  55761. module.exports = window.rStats;
  55762. }
  55763. },{}],206:[function(_dereq_,module,exports){
  55764. /*
  55765. * Copyright 2015 Google Inc. All Rights Reserved.
  55766. * Licensed under the Apache License, Version 2.0 (the "License");
  55767. * you may not use this file except in compliance with the License.
  55768. * You may obtain a copy of the License at
  55769. *
  55770. * http://www.apache.org/licenses/LICENSE-2.0
  55771. *
  55772. * Unless required by applicable law or agreed to in writing, software
  55773. * distributed under the License is distributed on an "AS IS" BASIS,
  55774. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  55775. * See the License for the specific language governing permissions and
  55776. * limitations under the License.
  55777. */
  55778. var Util = {};
  55779. Util.base64 = function(mimeType, base64) {
  55780. return 'data:' + mimeType + ';base64,' + base64;
  55781. };
  55782. Util.isMobile = function() {
  55783. var check = false;
  55784. (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);
  55785. return check;
  55786. };
  55787. Util.isIOS = function() {
  55788. return /(iPad|iPhone|iPod)/g.test(navigator.userAgent);
  55789. };
  55790. Util.isIFrame = function() {
  55791. try {
  55792. return window.self !== window.top;
  55793. } catch (e) {
  55794. return true;
  55795. }
  55796. };
  55797. Util.appendQueryParameter = function(url, key, value) {
  55798. // Determine delimiter based on if the URL already GET parameters in it.
  55799. var delimiter = (url.indexOf('?') < 0 ? '?' : '&');
  55800. url += delimiter + key + '=' + value;
  55801. return url;
  55802. };
  55803. // From http://goo.gl/4WX3tg
  55804. Util.getQueryParameter = function(name) {
  55805. name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  55806. var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
  55807. results = regex.exec(location.search);
  55808. return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  55809. };
  55810. Util.isLandscapeMode = function() {
  55811. return (window.orientation == 90 || window.orientation == -90);
  55812. };
  55813. module.exports = Util;
  55814. },{}],207:[function(_dereq_,module,exports){
  55815. /*
  55816. * Copyright 2015 Google Inc. All Rights Reserved.
  55817. * Licensed under the Apache License, Version 2.0 (the "License");
  55818. * you may not use this file except in compliance with the License.
  55819. * You may obtain a copy of the License at
  55820. *
  55821. * http://www.apache.org/licenses/LICENSE-2.0
  55822. *
  55823. * Unless required by applicable law or agreed to in writing, software
  55824. * distributed under the License is distributed on an "AS IS" BASIS,
  55825. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  55826. * See the License for the specific language governing permissions and
  55827. * limitations under the License.
  55828. */
  55829. var Util = _dereq_('./util.js');
  55830. /**
  55831. * Android and iOS compatible wakelock implementation.
  55832. *
  55833. * Refactored thanks to dkovalev@.
  55834. */
  55835. function AndroidWakeLock() {
  55836. var video = document.createElement('video');
  55837. video.addEventListener('ended', function() {
  55838. video.play();
  55839. });
  55840. this.request = function() {
  55841. if (video.paused) {
  55842. // Base64 version of videos_src/no-sleep-60s.webm.
  55843. video.src = Util.base64('video/webm', 'GkXfowEAAAAAAAAfQoaBAUL3gQFC8oEEQvOBCEKChHdlYm1Ch4ECQoWBAhhTgGcBAAAAAAAH4xFNm3RALE27i1OrhBVJqWZTrIHfTbuMU6uEFlSua1OsggEwTbuMU6uEHFO7a1OsggfG7AEAAAAAAACkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmAQAAAAAAAEUq17GDD0JATYCNTGF2ZjU2LjQwLjEwMVdBjUxhdmY1Ni40MC4xMDFzpJAGSJTMbsLpDt/ySkipgX1fRImIQO1MAAAAAAAWVK5rAQAAAAAAADuuAQAAAAAAADLXgQFzxYEBnIEAIrWcg3VuZIaFVl9WUDmDgQEj44OEO5rKAOABAAAAAAAABrCBsLqBkB9DtnUBAAAAAAAAo+eBAKOmgQAAgKJJg0IAAV4BHsAHBIODCoAACmH2MAAAZxgz4dPSTFi5JACjloED6ACmAECSnABMQAADYAAAWi0quoCjloEH0ACmAECSnABNwAADYAAAWi0quoCjloELuACmAECSnABNgAADYAAAWi0quoCjloEPoACmAECSnABNYAADYAAAWi0quoCjloETiACmAECSnABNIAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTnghdwo5aBAAAApgBAkpwATOAAA2AAAFotKrqAo5aBA+gApgBAkpwATMAAA2AAAFotKrqAo5aBB9AApgBAkpwATIAAA2AAAFotKrqAo5aBC7gApgBAkpwATEAAA2AAAFotKrqAo5aBD6AApgDAkpwAQ2AAA2AAAFotKrqAo5aBE4gApgBAkpwATCAAA2AAAFotKrqAH0O2dQEAAAAAAACU54Iu4KOWgQAAAKYAQJKcAEvAAANgAABaLSq6gKOWgQPoAKYAQJKcAEtgAANgAABaLSq6gKOWgQfQAKYAQJKcAEsAAANgAABaLSq6gKOWgQu4AKYAQJKcAEqAAANgAABaLSq6gKOWgQ+gAKYAQJKcAEogAANgAABaLSq6gKOWgROIAKYAQJKcAEnAAANgAABaLSq6gB9DtnUBAAAAAAAAlOeCRlCjloEAAACmAECSnABJgAADYAAAWi0quoCjloED6ACmAECSnABJIAADYAAAWi0quoCjloEH0ACmAMCSnABDYAADYAAAWi0quoCjloELuACmAECSnABI4AADYAAAWi0quoCjloEPoACmAECSnABIoAADYAAAWi0quoCjloETiACmAECSnABIYAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTngl3Ao5aBAAAApgBAkpwASCAAA2AAAFotKrqAo5aBA+gApgBAkpwASAAAA2AAAFotKrqAo5aBB9AApgBAkpwAR8AAA2AAAFotKrqAo5aBC7gApgBAkpwAR4AAA2AAAFotKrqAo5aBD6AApgBAkpwAR2AAA2AAAFotKrqAo5aBE4gApgBAkpwARyAAA2AAAFotKrqAH0O2dQEAAAAAAACU54J1MKOWgQAAAKYAwJKcAENgAANgAABaLSq6gKOWgQPoAKYAQJKcAEbgAANgAABaLSq6gKOWgQfQAKYAQJKcAEagAANgAABaLSq6gKOWgQu4AKYAQJKcAEaAAANgAABaLSq6gKOWgQ+gAKYAQJKcAEZAAANgAABaLSq6gKOWgROIAKYAQJKcAEYAAANgAABaLSq6gB9DtnUBAAAAAAAAlOeCjKCjloEAAACmAECSnABF4AADYAAAWi0quoCjloED6ACmAECSnABFwAADYAAAWi0quoCjloEH0ACmAECSnABFoAADYAAAWi0quoCjloELuACmAECSnABFgAADYAAAWi0quoCjloEPoACmAMCSnABDYAADYAAAWi0quoCjloETiACmAECSnABFYAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTngqQQo5aBAAAApgBAkpwARUAAA2AAAFotKrqAo5aBA+gApgBAkpwARSAAA2AAAFotKrqAo5aBB9AApgBAkpwARQAAA2AAAFotKrqAo5aBC7gApgBAkpwARQAAA2AAAFotKrqAo5aBD6AApgBAkpwAROAAA2AAAFotKrqAo5aBE4gApgBAkpwARMAAA2AAAFotKrqAH0O2dQEAAAAAAACU54K7gKOWgQAAAKYAQJKcAESgAANgAABaLSq6gKOWgQPoAKYAQJKcAESAAANgAABaLSq6gKOWgQfQAKYAwJKcAENgAANgAABaLSq6gKOWgQu4AKYAQJKcAERgAANgAABaLSq6gKOWgQ+gAKYAQJKcAERAAANgAABaLSq6gKOWgROIAKYAQJKcAEQgAANgAABaLSq6gB9DtnUBAAAAAAAAlOeC0vCjloEAAACmAECSnABEIAADYAAAWi0quoCjloED6ACmAECSnABEAAADYAAAWi0quoCjloEH0ACmAECSnABD4AADYAAAWi0quoCjloELuACmAECSnABDwAADYAAAWi0quoCjloEPoACmAECSnABDoAADYAAAWi0quoCjloETiACmAECSnABDgAADYAAAWi0quoAcU7trAQAAAAAAABG7j7OBALeK94EB8YIBd/CBAw==');
  55844. video.play();
  55845. }
  55846. };
  55847. this.release = function() {
  55848. video.pause();
  55849. video.src = '';
  55850. };
  55851. }
  55852. function iOSWakeLock() {
  55853. var timer = null;
  55854. this.request = function() {
  55855. if (!timer) {
  55856. timer = setInterval(function() {
  55857. window.location.href = '/';
  55858. setTimeout(window.stop, 0);
  55859. }, 15000);
  55860. }
  55861. }
  55862. this.release = function() {
  55863. if (timer) {
  55864. clearInterval(timer);
  55865. timer = null;
  55866. }
  55867. }
  55868. }
  55869. function getWakeLock() {
  55870. var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  55871. if (userAgent.match(/iPhone/i) || userAgent.match(/iPod/i)) {
  55872. return iOSWakeLock;
  55873. } else {
  55874. return AndroidWakeLock;
  55875. }
  55876. }
  55877. module.exports = getWakeLock();
  55878. },{"./util.js":206}]},{},[172])(172)
  55879. });
  55880. //# sourceMappingURL=aframe-master.js.map