example.e31bb0bc.js 1.4 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862
  1. // modules are defined as an array
  2. // [ module function, map of requires ]
  3. //
  4. // map of requires is short require name -> numeric require
  5. //
  6. // anything defined in a previous bundle is accessed via the
  7. // orig method which is the require for previous bundles
  8. parcelRequire = (function (modules, cache, entry, globalName) {
  9. // Save the require from previous bundle to this closure if any
  10. var previousRequire = typeof parcelRequire === 'function' && parcelRequire;
  11. var nodeRequire = typeof require === 'function' && require;
  12. function newRequire(name, jumped) {
  13. if (!cache[name]) {
  14. if (!modules[name]) {
  15. // if we cannot find the module within our internal map or
  16. // cache jump to the current global require ie. the last bundle
  17. // that was added to the page.
  18. var currentRequire = typeof parcelRequire === 'function' && parcelRequire;
  19. if (!jumped && currentRequire) {
  20. return currentRequire(name, true);
  21. }
  22. // If there are other bundles on this page the require from the
  23. // previous one is saved to 'previousRequire'. Repeat this as
  24. // many times as there are bundles until the module is found or
  25. // we exhaust the require chain.
  26. if (previousRequire) {
  27. return previousRequire(name, true);
  28. }
  29. // Try the node require function if it exists.
  30. if (nodeRequire && typeof name === 'string') {
  31. return nodeRequire(name);
  32. }
  33. var err = new Error('Cannot find module \'' + name + '\'');
  34. err.code = 'MODULE_NOT_FOUND';
  35. throw err;
  36. }
  37. localRequire.resolve = resolve;
  38. localRequire.cache = {};
  39. var module = cache[name] = new newRequire.Module(name);
  40. modules[name][0].call(module.exports, localRequire, module, module.exports, this);
  41. }
  42. return cache[name].exports;
  43. function localRequire(x){
  44. return newRequire(localRequire.resolve(x));
  45. }
  46. function resolve(x){
  47. return modules[name][1][x] || x;
  48. }
  49. }
  50. function Module(moduleName) {
  51. this.id = moduleName;
  52. this.bundle = newRequire;
  53. this.exports = {};
  54. }
  55. newRequire.isParcelRequire = true;
  56. newRequire.Module = Module;
  57. newRequire.modules = modules;
  58. newRequire.cache = cache;
  59. newRequire.parent = previousRequire;
  60. newRequire.register = function (id, exports) {
  61. modules[id] = [function (require, module) {
  62. module.exports = exports;
  63. }, {}];
  64. };
  65. var error;
  66. for (var i = 0; i < entry.length; i++) {
  67. try {
  68. newRequire(entry[i]);
  69. } catch (e) {
  70. // Save first error but execute all entries
  71. if (!error) {
  72. error = e;
  73. }
  74. }
  75. }
  76. if (entry.length) {
  77. // Expose entry point to Node, AMD or browser globals
  78. // Based on https://github.com/ForbesLindesay/umd/blob/master/template.js
  79. var mainExports = newRequire(entry[entry.length - 1]);
  80. // CommonJS
  81. if (typeof exports === "object" && typeof module !== "undefined") {
  82. module.exports = mainExports;
  83. // RequireJS
  84. } else if (typeof define === "function" && define.amd) {
  85. define(function () {
  86. return mainExports;
  87. });
  88. // <script>
  89. } else if (globalName) {
  90. this[globalName] = mainExports;
  91. }
  92. }
  93. // Override the current require with this new one
  94. parcelRequire = newRequire;
  95. if (error) {
  96. // throw error from earlier, _after updating parcelRequire_
  97. throw error;
  98. }
  99. return newRequire;
  100. })({"../node_modules/process/browser.js":[function(require,module,exports) {
  101. // shim for using process in browser
  102. var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it
  103. // don't break things. But we need to wrap it in a try catch in case it is
  104. // wrapped in strict mode code which doesn't define any globals. It's inside a
  105. // function because try/catches deoptimize in certain engines.
  106. var cachedSetTimeout;
  107. var cachedClearTimeout;
  108. function defaultSetTimout() {
  109. throw new Error('setTimeout has not been defined');
  110. }
  111. function defaultClearTimeout() {
  112. throw new Error('clearTimeout has not been defined');
  113. }
  114. (function () {
  115. try {
  116. if (typeof setTimeout === 'function') {
  117. cachedSetTimeout = setTimeout;
  118. } else {
  119. cachedSetTimeout = defaultSetTimout;
  120. }
  121. } catch (e) {
  122. cachedSetTimeout = defaultSetTimout;
  123. }
  124. try {
  125. if (typeof clearTimeout === 'function') {
  126. cachedClearTimeout = clearTimeout;
  127. } else {
  128. cachedClearTimeout = defaultClearTimeout;
  129. }
  130. } catch (e) {
  131. cachedClearTimeout = defaultClearTimeout;
  132. }
  133. })();
  134. function runTimeout(fun) {
  135. if (cachedSetTimeout === setTimeout) {
  136. //normal enviroments in sane situations
  137. return setTimeout(fun, 0);
  138. } // if setTimeout wasn't available but was latter defined
  139. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  140. cachedSetTimeout = setTimeout;
  141. return setTimeout(fun, 0);
  142. }
  143. try {
  144. // when when somebody has screwed with setTimeout but no I.E. maddness
  145. return cachedSetTimeout(fun, 0);
  146. } catch (e) {
  147. try {
  148. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  149. return cachedSetTimeout.call(null, fun, 0);
  150. } catch (e) {
  151. // 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
  152. return cachedSetTimeout.call(this, fun, 0);
  153. }
  154. }
  155. }
  156. function runClearTimeout(marker) {
  157. if (cachedClearTimeout === clearTimeout) {
  158. //normal enviroments in sane situations
  159. return clearTimeout(marker);
  160. } // if clearTimeout wasn't available but was latter defined
  161. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  162. cachedClearTimeout = clearTimeout;
  163. return clearTimeout(marker);
  164. }
  165. try {
  166. // when when somebody has screwed with setTimeout but no I.E. maddness
  167. return cachedClearTimeout(marker);
  168. } catch (e) {
  169. try {
  170. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  171. return cachedClearTimeout.call(null, marker);
  172. } catch (e) {
  173. // 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.
  174. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  175. return cachedClearTimeout.call(this, marker);
  176. }
  177. }
  178. }
  179. var queue = [];
  180. var draining = false;
  181. var currentQueue;
  182. var queueIndex = -1;
  183. function cleanUpNextTick() {
  184. if (!draining || !currentQueue) {
  185. return;
  186. }
  187. draining = false;
  188. if (currentQueue.length) {
  189. queue = currentQueue.concat(queue);
  190. } else {
  191. queueIndex = -1;
  192. }
  193. if (queue.length) {
  194. drainQueue();
  195. }
  196. }
  197. function drainQueue() {
  198. if (draining) {
  199. return;
  200. }
  201. var timeout = runTimeout(cleanUpNextTick);
  202. draining = true;
  203. var len = queue.length;
  204. while (len) {
  205. currentQueue = queue;
  206. queue = [];
  207. while (++queueIndex < len) {
  208. if (currentQueue) {
  209. currentQueue[queueIndex].run();
  210. }
  211. }
  212. queueIndex = -1;
  213. len = queue.length;
  214. }
  215. currentQueue = null;
  216. draining = false;
  217. runClearTimeout(timeout);
  218. }
  219. process.nextTick = function (fun) {
  220. var args = new Array(arguments.length - 1);
  221. if (arguments.length > 1) {
  222. for (var i = 1; i < arguments.length; i++) {
  223. args[i - 1] = arguments[i];
  224. }
  225. }
  226. queue.push(new Item(fun, args));
  227. if (queue.length === 1 && !draining) {
  228. runTimeout(drainQueue);
  229. }
  230. }; // v8 likes predictible objects
  231. function Item(fun, array) {
  232. this.fun = fun;
  233. this.array = array;
  234. }
  235. Item.prototype.run = function () {
  236. this.fun.apply(null, this.array);
  237. };
  238. process.title = 'browser';
  239. process.env = {};
  240. process.argv = [];
  241. process.version = ''; // empty string to avoid regexp issues
  242. process.versions = {};
  243. function noop() {}
  244. process.on = noop;
  245. process.addListener = noop;
  246. process.once = noop;
  247. process.off = noop;
  248. process.removeListener = noop;
  249. process.removeAllListeners = noop;
  250. process.emit = noop;
  251. process.prependListener = noop;
  252. process.prependOnceListener = noop;
  253. process.listeners = function (name) {
  254. return [];
  255. };
  256. process.binding = function (name) {
  257. throw new Error('process.binding is not supported');
  258. };
  259. process.cwd = function () {
  260. return '/';
  261. };
  262. process.chdir = function (dir) {
  263. throw new Error('process.chdir is not supported');
  264. };
  265. process.umask = function () {
  266. return 0;
  267. };
  268. },{}],"../node_modules/path-browserify/index.js":[function(require,module,exports) {
  269. var process = require("process");
  270. // .dirname, .basename, and .extname methods are extracted from Node.js v8.11.1,
  271. // backported and transplited with Babel, with backwards-compat fixes
  272. // Copyright Joyent, Inc. and other Node contributors.
  273. //
  274. // Permission is hereby granted, free of charge, to any person obtaining a
  275. // copy of this software and associated documentation files (the
  276. // "Software"), to deal in the Software without restriction, including
  277. // without limitation the rights to use, copy, modify, merge, publish,
  278. // distribute, sublicense, and/or sell copies of the Software, and to permit
  279. // persons to whom the Software is furnished to do so, subject to the
  280. // following conditions:
  281. //
  282. // The above copyright notice and this permission notice shall be included
  283. // in all copies or substantial portions of the Software.
  284. //
  285. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  286. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  287. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  288. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  289. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  290. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  291. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  292. // resolves . and .. elements in a path array with directory names there
  293. // must be no slashes, empty elements, or device names (c:\) in the array
  294. // (so also no leading and trailing slashes - it does not distinguish
  295. // relative and absolute paths)
  296. function normalizeArray(parts, allowAboveRoot) {
  297. // if the path tries to go above the root, `up` ends up > 0
  298. var up = 0;
  299. for (var i = parts.length - 1; i >= 0; i--) {
  300. var last = parts[i];
  301. if (last === '.') {
  302. parts.splice(i, 1);
  303. } else if (last === '..') {
  304. parts.splice(i, 1);
  305. up++;
  306. } else if (up) {
  307. parts.splice(i, 1);
  308. up--;
  309. }
  310. }
  311. // if the path is allowed to go above the root, restore leading ..s
  312. if (allowAboveRoot) {
  313. for (; up--; up) {
  314. parts.unshift('..');
  315. }
  316. }
  317. return parts;
  318. }
  319. // path.resolve([from ...], to)
  320. // posix version
  321. exports.resolve = function() {
  322. var resolvedPath = '',
  323. resolvedAbsolute = false;
  324. for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
  325. var path = (i >= 0) ? arguments[i] : process.cwd();
  326. // Skip empty and invalid entries
  327. if (typeof path !== 'string') {
  328. throw new TypeError('Arguments to path.resolve must be strings');
  329. } else if (!path) {
  330. continue;
  331. }
  332. resolvedPath = path + '/' + resolvedPath;
  333. resolvedAbsolute = path.charAt(0) === '/';
  334. }
  335. // At this point the path should be resolved to a full absolute path, but
  336. // handle relative paths to be safe (might happen when process.cwd() fails)
  337. // Normalize the path
  338. resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
  339. return !!p;
  340. }), !resolvedAbsolute).join('/');
  341. return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
  342. };
  343. // path.normalize(path)
  344. // posix version
  345. exports.normalize = function(path) {
  346. var isAbsolute = exports.isAbsolute(path),
  347. trailingSlash = substr(path, -1) === '/';
  348. // Normalize the path
  349. path = normalizeArray(filter(path.split('/'), function(p) {
  350. return !!p;
  351. }), !isAbsolute).join('/');
  352. if (!path && !isAbsolute) {
  353. path = '.';
  354. }
  355. if (path && trailingSlash) {
  356. path += '/';
  357. }
  358. return (isAbsolute ? '/' : '') + path;
  359. };
  360. // posix version
  361. exports.isAbsolute = function(path) {
  362. return path.charAt(0) === '/';
  363. };
  364. // posix version
  365. exports.join = function() {
  366. var paths = Array.prototype.slice.call(arguments, 0);
  367. return exports.normalize(filter(paths, function(p, index) {
  368. if (typeof p !== 'string') {
  369. throw new TypeError('Arguments to path.join must be strings');
  370. }
  371. return p;
  372. }).join('/'));
  373. };
  374. // path.relative(from, to)
  375. // posix version
  376. exports.relative = function(from, to) {
  377. from = exports.resolve(from).substr(1);
  378. to = exports.resolve(to).substr(1);
  379. function trim(arr) {
  380. var start = 0;
  381. for (; start < arr.length; start++) {
  382. if (arr[start] !== '') break;
  383. }
  384. var end = arr.length - 1;
  385. for (; end >= 0; end--) {
  386. if (arr[end] !== '') break;
  387. }
  388. if (start > end) return [];
  389. return arr.slice(start, end - start + 1);
  390. }
  391. var fromParts = trim(from.split('/'));
  392. var toParts = trim(to.split('/'));
  393. var length = Math.min(fromParts.length, toParts.length);
  394. var samePartsLength = length;
  395. for (var i = 0; i < length; i++) {
  396. if (fromParts[i] !== toParts[i]) {
  397. samePartsLength = i;
  398. break;
  399. }
  400. }
  401. var outputParts = [];
  402. for (var i = samePartsLength; i < fromParts.length; i++) {
  403. outputParts.push('..');
  404. }
  405. outputParts = outputParts.concat(toParts.slice(samePartsLength));
  406. return outputParts.join('/');
  407. };
  408. exports.sep = '/';
  409. exports.delimiter = ':';
  410. exports.dirname = function (path) {
  411. if (typeof path !== 'string') path = path + '';
  412. if (path.length === 0) return '.';
  413. var code = path.charCodeAt(0);
  414. var hasRoot = code === 47 /*/*/;
  415. var end = -1;
  416. var matchedSlash = true;
  417. for (var i = path.length - 1; i >= 1; --i) {
  418. code = path.charCodeAt(i);
  419. if (code === 47 /*/*/) {
  420. if (!matchedSlash) {
  421. end = i;
  422. break;
  423. }
  424. } else {
  425. // We saw the first non-path separator
  426. matchedSlash = false;
  427. }
  428. }
  429. if (end === -1) return hasRoot ? '/' : '.';
  430. if (hasRoot && end === 1) {
  431. // return '//';
  432. // Backwards-compat fix:
  433. return '/';
  434. }
  435. return path.slice(0, end);
  436. };
  437. function basename(path) {
  438. if (typeof path !== 'string') path = path + '';
  439. var start = 0;
  440. var end = -1;
  441. var matchedSlash = true;
  442. var i;
  443. for (i = path.length - 1; i >= 0; --i) {
  444. if (path.charCodeAt(i) === 47 /*/*/) {
  445. // If we reached a path separator that was not part of a set of path
  446. // separators at the end of the string, stop now
  447. if (!matchedSlash) {
  448. start = i + 1;
  449. break;
  450. }
  451. } else if (end === -1) {
  452. // We saw the first non-path separator, mark this as the end of our
  453. // path component
  454. matchedSlash = false;
  455. end = i + 1;
  456. }
  457. }
  458. if (end === -1) return '';
  459. return path.slice(start, end);
  460. }
  461. // Uses a mixed approach for backwards-compatibility, as ext behavior changed
  462. // in new Node.js versions, so only basename() above is backported here
  463. exports.basename = function (path, ext) {
  464. var f = basename(path);
  465. if (ext && f.substr(-1 * ext.length) === ext) {
  466. f = f.substr(0, f.length - ext.length);
  467. }
  468. return f;
  469. };
  470. exports.extname = function (path) {
  471. if (typeof path !== 'string') path = path + '';
  472. var startDot = -1;
  473. var startPart = 0;
  474. var end = -1;
  475. var matchedSlash = true;
  476. // Track the state of characters (if any) we see before our first dot and
  477. // after any path separator we find
  478. var preDotState = 0;
  479. for (var i = path.length - 1; i >= 0; --i) {
  480. var code = path.charCodeAt(i);
  481. if (code === 47 /*/*/) {
  482. // If we reached a path separator that was not part of a set of path
  483. // separators at the end of the string, stop now
  484. if (!matchedSlash) {
  485. startPart = i + 1;
  486. break;
  487. }
  488. continue;
  489. }
  490. if (end === -1) {
  491. // We saw the first non-path separator, mark this as the end of our
  492. // extension
  493. matchedSlash = false;
  494. end = i + 1;
  495. }
  496. if (code === 46 /*.*/) {
  497. // If this is our first dot, mark it as the start of our extension
  498. if (startDot === -1)
  499. startDot = i;
  500. else if (preDotState !== 1)
  501. preDotState = 1;
  502. } else if (startDot !== -1) {
  503. // We saw a non-dot and non-path separator before our dot, so we should
  504. // have a good chance at having a non-empty extension
  505. preDotState = -1;
  506. }
  507. }
  508. if (startDot === -1 || end === -1 ||
  509. // We saw a non-dot character immediately before the dot
  510. preDotState === 0 ||
  511. // The (right-most) trimmed path component is exactly '..'
  512. preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
  513. return '';
  514. }
  515. return path.slice(startDot, end);
  516. };
  517. function filter (xs, f) {
  518. if (xs.filter) return xs.filter(f);
  519. var res = [];
  520. for (var i = 0; i < xs.length; i++) {
  521. if (f(xs[i], i, xs)) res.push(xs[i]);
  522. }
  523. return res;
  524. }
  525. // String.prototype.substr - negative index don't work in IE8
  526. var substr = 'ab'.substr(-1) === 'b'
  527. ? function (str, start, len) { return str.substr(start, len) }
  528. : function (str, start, len) {
  529. if (start < 0) start = str.length + start;
  530. return str.substr(start, len);
  531. }
  532. ;
  533. },{"process":"../node_modules/process/browser.js"}],"../src/LRUCache.js":[function(require,module,exports) {
  534. "use strict";
  535. Object.defineProperty(exports, "__esModule", {
  536. value: true
  537. });
  538. exports.LRUCache = void 0;
  539. class LRUCache {
  540. constructor() {
  541. // options
  542. this.maxSize = 800;
  543. this.minSize = 600;
  544. this.unloadPercent = 0.2;
  545. this.usedSet = new Set();
  546. this.itemSet = new Set();
  547. this.itemList = [];
  548. this.callbacks = new Map();
  549. } // Returns whether or not the cache has reached the maximum size
  550. isFull() {
  551. return this.itemSet.size >= this.maxSize;
  552. }
  553. add(item, removeCb) {
  554. const itemSet = this.itemSet;
  555. if (itemSet.has(item)) {
  556. return false;
  557. }
  558. if (this.isFull()) {
  559. return false;
  560. }
  561. const usedSet = this.usedSet;
  562. const itemList = this.itemList;
  563. const callbacks = this.callbacks;
  564. itemList.push(item);
  565. usedSet.add(item);
  566. itemSet.add(item);
  567. callbacks.set(item, removeCb);
  568. return true;
  569. }
  570. remove(item) {
  571. const usedSet = this.usedSet;
  572. const itemSet = this.itemSet;
  573. const itemList = this.itemList;
  574. const callbacks = this.callbacks;
  575. if (itemSet.has(item)) {
  576. callbacks.get(item)(item);
  577. const index = itemList.indexOf(item);
  578. itemList.splice(index, 1);
  579. usedSet.delete(item);
  580. itemSet.delete(item);
  581. callbacks.delete(item);
  582. return true;
  583. }
  584. return false;
  585. }
  586. markUsed(item) {
  587. const itemSet = this.itemSet;
  588. const usedSet = this.usedSet;
  589. if (itemSet.has(item) && !usedSet.has(item)) {
  590. const itemList = this.itemList;
  591. const index = itemList.indexOf(item);
  592. itemList.splice(index, 1);
  593. itemList.push(item);
  594. usedSet.add(item);
  595. }
  596. }
  597. markAllUnused() {
  598. this.usedSet.clear();
  599. }
  600. unloadUnusedContent(prioritySortCb) {
  601. const unloadPercent = this.unloadPercent;
  602. const targetSize = this.minSize;
  603. const itemList = this.itemList;
  604. const itemSet = this.itemSet;
  605. const usedSet = this.usedSet;
  606. const callbacks = this.callbacks;
  607. const unused = itemList.length - usedSet.size;
  608. if (itemList.length > targetSize && unused > 0) {
  609. // TODO: sort by priority
  610. let nodesToUnload = Math.max(itemList.length - targetSize, targetSize) * unloadPercent;
  611. nodesToUnload = Math.ceil(nodesToUnload);
  612. nodesToUnload = Math.min(unused, nodesToUnload);
  613. const removedItems = itemList.splice(0, nodesToUnload);
  614. for (let i = 0, l = removedItems.length; i < l; i++) {
  615. const item = removedItems[i];
  616. callbacks.get(item)(item);
  617. itemSet.delete(item);
  618. callbacks.delete(item);
  619. }
  620. }
  621. }
  622. scheduleUnload(prioritySortCb, markAllUnused = true) {
  623. if (!this.scheduled) {
  624. this.scheduled = true;
  625. Promise.resolve().then(() => {
  626. this.scheduled = false;
  627. this.unloadUnusedContent(prioritySortCb);
  628. if (markAllUnused) {
  629. this.markAllUnused();
  630. }
  631. });
  632. }
  633. }
  634. }
  635. exports.LRUCache = LRUCache;
  636. },{}],"../src/PriorityQueue.js":[function(require,module,exports) {
  637. "use strict";
  638. Object.defineProperty(exports, "__esModule", {
  639. value: true
  640. });
  641. exports.PriorityQueue = void 0;
  642. class PriorityQueue {
  643. constructor(maxJobs = 6) {
  644. // options
  645. this.maxJobs = maxJobs;
  646. this.items = [];
  647. this.currJobs = 0;
  648. this.scheduled = false;
  649. }
  650. add(item, priority, callback) {
  651. return new Promise((resolve, reject) => {
  652. const prCallback = (...args) => callback(...args).then(resolve).catch(reject);
  653. const items = this.items;
  654. for (let i = 0, l = items.length; i < l; i++) {
  655. const thisItem = items[i];
  656. if (thisItem.priority > priority) {
  657. items.splice(i, 0, {
  658. priority,
  659. item,
  660. callback: prCallback
  661. });
  662. this.scheduleJobRun();
  663. return;
  664. }
  665. }
  666. items.push({
  667. priority,
  668. item,
  669. callback: prCallback
  670. });
  671. this.scheduleJobRun();
  672. });
  673. }
  674. remove(item) {
  675. const items = this.items;
  676. for (let i = 0, l = items.length; i < l; i++) {
  677. const thisItem = items[i];
  678. if (thisItem.item === item) {
  679. items.splice(i, 1);
  680. break;
  681. }
  682. }
  683. }
  684. tryRunJobs() {
  685. const items = this.items;
  686. const maxJobs = this.maxJobs;
  687. while (maxJobs > this.currJobs && items.length > 0) {
  688. this.currJobs++;
  689. const {
  690. item,
  691. priority,
  692. callback
  693. } = items.pop();
  694. callback(item, priority).then(() => {
  695. this.currJobs--;
  696. this.scheduleJobRun();
  697. }).catch(() => {
  698. this.currJobs--;
  699. this.scheduleJobRun();
  700. });
  701. }
  702. }
  703. scheduleJobRun() {
  704. if (!this.scheduled) {
  705. Promise.resolve().then(() => {
  706. this.tryRunJobs();
  707. this.scheduled = false;
  708. });
  709. this.scheduled = true;
  710. }
  711. }
  712. }
  713. exports.PriorityQueue = PriorityQueue;
  714. },{}],"../src/TilesRenderer.js":[function(require,module,exports) {
  715. "use strict";
  716. Object.defineProperty(exports, "__esModule", {
  717. value: true
  718. });
  719. exports.TilesRenderer = void 0;
  720. var _path = _interopRequireDefault(require("path"));
  721. var _LRUCache = require("./LRUCache.js");
  722. var _PriorityQueue = require("./PriorityQueue.js");
  723. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  724. // TODO: find out why tiles are left dangling in the hierarchy
  725. // TODO: Address the issue of too many promises, garbage collection
  726. // TODO: remove more redundant computation
  727. // TODO: See if using classes improves performance
  728. // TODO: See if declaring function inline improves performance
  729. // TODO: Make sure active state works as expected
  730. const UNLOADED = 0;
  731. const LOADING = 1;
  732. const PARSING = 2;
  733. const LOADED = 3;
  734. const FAILED = 4;
  735. function traverseSet(tile, beforeCb = null, afterCb = null, parent = null, depth = 0) {
  736. if (beforeCb && beforeCb(tile, parent, depth)) {
  737. if (afterCb) {
  738. afterCb(tile, parent, depth);
  739. }
  740. return;
  741. }
  742. const children = tile.children;
  743. for (let i = 0, l = children.length; i < l; i++) {
  744. traverseSet(children[i], beforeCb, afterCb, tile, depth + 1);
  745. }
  746. if (afterCb) {
  747. afterCb(tile, parent, depth);
  748. }
  749. }
  750. function isUsedThisFrame(tile, frameCount) {
  751. return tile.__lastFrameVisited === frameCount && tile.__used;
  752. }
  753. function resetFrameState(tile, frameCount) {
  754. if (tile.__lastFrameVisited !== frameCount) {
  755. tile.__lastFrameVisited = frameCount;
  756. tile.__used = false;
  757. tile.__inFrustum = false;
  758. tile.__isLeaf = false;
  759. tile.__visible = false;
  760. tile.__active = false;
  761. tile.__error = 0;
  762. }
  763. }
  764. function recursivelyMarkUsed(tile, frameCount, lruCache) {
  765. resetFrameState(tile, frameCount);
  766. tile.__used = true;
  767. lruCache.markUsed(tile);
  768. if (tile.__contentEmpty) {
  769. const children = tile.children;
  770. for (let i = 0, l = children.length; i < l; i++) {
  771. recursivelyMarkUsed(children[i], frameCount, lruCache);
  772. }
  773. }
  774. } // TODO: include frustum mask here?
  775. function determineFrustumSet(tile, renderer) {
  776. const stats = renderer.stats;
  777. const frameCount = renderer.frameCount;
  778. const errorTarget = renderer.errorTarget;
  779. const maxDepth = renderer.maxDepth;
  780. const loadSiblings = renderer.loadSiblings;
  781. const lruCache = renderer.lruCache;
  782. resetFrameState(tile, frameCount);
  783. const inFrustum = renderer.tileInView(tile);
  784. if (inFrustum === false) {
  785. return false;
  786. }
  787. tile.__used = true;
  788. lruCache.markUsed(tile);
  789. tile.__inFrustum = true;
  790. stats.inFrustum++;
  791. if (!tile.__contentEmpty) {
  792. const error = renderer.calculateError(tile);
  793. tile.__error = error;
  794. if (error <= errorTarget) {
  795. return true;
  796. }
  797. }
  798. if (renderer.maxDepth > 0 && tile.__depth + 1 >= maxDepth) {
  799. return true;
  800. }
  801. let anyChildrenUsed = false;
  802. const children = tile.children;
  803. for (let i = 0, l = children.length; i < l; i++) {
  804. const c = children[i];
  805. const r = determineFrustumSet(c, renderer);
  806. anyChildrenUsed = anyChildrenUsed || r;
  807. }
  808. if (anyChildrenUsed && loadSiblings) {
  809. for (let i = 0, l = children.length; i < l; i++) {
  810. recursivelyMarkUsed(tile, frameCount, lruCache);
  811. }
  812. }
  813. return true;
  814. }
  815. function markUsedSetLeaves(tile, renderer) {
  816. const stats = renderer.stats;
  817. const frameCount = renderer.frameCount;
  818. if (!isUsedThisFrame(tile, frameCount)) {
  819. return;
  820. }
  821. stats.used++;
  822. const children = tile.children;
  823. let anyChildrenUsed = false;
  824. for (let i = 0, l = children.length; i < l; i++) {
  825. const c = children[i];
  826. anyChildrenUsed = anyChildrenUsed || isUsedThisFrame(c, frameCount);
  827. }
  828. if (!anyChildrenUsed) {
  829. tile.__isLeaf = true; // TODO: stats
  830. } else {
  831. for (let i = 0, l = children.length; i < l; i++) {
  832. const c = children[i];
  833. markUsedSetLeaves(c, renderer);
  834. }
  835. }
  836. }
  837. function skipTraversal(tile, renderer) {
  838. const stats = renderer.stats;
  839. const frameCount = renderer.frameCount;
  840. if (!isUsedThisFrame(tile, frameCount)) {
  841. return;
  842. }
  843. const lruCache = renderer.lruCache;
  844. if (tile.__isLeaf) {
  845. if (tile.__loadingState === LOADED) {
  846. if (tile.__inFrustum) {
  847. tile.__visible = true;
  848. stats.visible++;
  849. }
  850. tile.__active = true;
  851. stats.active++;
  852. } else if (!lruCache.isFull()) {
  853. renderer.requestTileContents(tile);
  854. }
  855. return;
  856. }
  857. const errorRequirement = renderer.errorTarget * renderer.errorThreshold;
  858. const meetsSSE = tile.__error < errorRequirement;
  859. const hasContent = tile.__loadingState === LOADED && !tile.__contentEmpty;
  860. const children = tile.children;
  861. let allChildrenHaveContent = true;
  862. for (let i = 0, l = children.length; i < l; i++) {
  863. const c = children[i];
  864. if (isUsedThisFrame(c, frameCount)) {
  865. const childContent = c.__loadingState === LOADED || tile.__contentEmpty;
  866. allChildrenHaveContent = allChildrenHaveContent && childContent;
  867. }
  868. }
  869. if (meetsSSE && !hasContent && !lruCache.isFull()) {
  870. renderer.requestTileContents(tile);
  871. }
  872. if (meetsSSE && hasContent && !allChildrenHaveContent) {
  873. if (tile.__inFrustum) {
  874. tile.__visible = true;
  875. stats.visible++;
  876. }
  877. tile.__active = true;
  878. stats.active++;
  879. for (let i = 0, l = children.length; i < l; i++) {
  880. const c = children[i];
  881. if (isUsedThisFrame(c, frameCount) && !lruCache.isFull()) {
  882. renderer.requestTileContents(c);
  883. }
  884. }
  885. return;
  886. }
  887. for (let i = 0, l = children.length; i < l; i++) {
  888. const c = children[i];
  889. if (isUsedThisFrame(c, frameCount)) {
  890. skipTraversal(c, renderer);
  891. }
  892. }
  893. }
  894. function toggleTiles(tile, renderer) {
  895. const frameCount = renderer.frameCount;
  896. const isUsed = isUsedThisFrame(tile, frameCount);
  897. if (isUsed || tile.__usedLastFrame) {
  898. if (!isUsed) {
  899. if (!tile.__contentEmpty && tile.__loadingState === LOADED) {
  900. renderer.setTileVisible(tile, false);
  901. renderer.setTileActive(tile, false);
  902. }
  903. tile.__usedLastFrame = false;
  904. } else {
  905. if (!tile.__contentEmpty && tile.__loadingState === LOADED) {
  906. // enable visibility if active due to shadows
  907. renderer.setTileActive(tile, tile.__active);
  908. renderer.setTileVisible(tile, tile.__active || tile.__visible);
  909. }
  910. tile.__usedLastFrame = true;
  911. }
  912. const children = tile.children;
  913. for (let i = 0, l = children.length; i < l; i++) {
  914. const c = children[i];
  915. toggleTiles(c, renderer);
  916. }
  917. }
  918. }
  919. class TilesRenderer {
  920. get root() {
  921. const tileSet = this.tileSets[this.rootSet];
  922. if (!tileSet || tileSet instanceof Promise) {
  923. return null;
  924. } else {
  925. return tileSet.root;
  926. }
  927. }
  928. constructor(url, cache = new _LRUCache.LRUCache(), downloadQueue = new _PriorityQueue.PriorityQueue(6), parseQueue = new _PriorityQueue.PriorityQueue(2)) {
  929. // state
  930. this.tileSets = {};
  931. this.rootSet = url;
  932. this.lruCache = cache;
  933. this.downloadQueue = downloadQueue;
  934. this.parseQueue = parseQueue;
  935. this.stats = {
  936. parsing: 0,
  937. downloading: 0,
  938. inFrustum: 0,
  939. used: 0,
  940. active: 0,
  941. visible: 0
  942. };
  943. this.frameCount = 0; // options
  944. this.errorTarget = 6.0;
  945. this.errorThreshold = 6.0;
  946. this.loadSiblings = true;
  947. this.maxDepth = Infinity;
  948. this.loadTileSet(url);
  949. }
  950. traverse(cb) {
  951. const tileSets = this.tileSets;
  952. const rootTileSet = tileSets[this.rootSet];
  953. if (!rootTileSet || !rootTileSet.root) return;
  954. traverseSet(rootTileSet.root, cb);
  955. } // Public API
  956. update() {
  957. const stats = this.stats;
  958. const lruCache = this.lruCache;
  959. const tileSets = this.tileSets;
  960. const rootTileSet = tileSets[this.rootSet];
  961. if (!rootTileSet || !rootTileSet.root) return;
  962. const root = rootTileSet.root;
  963. stats.inFrustum = 0, stats.used = 0, stats.active = 0, stats.visible = 0, this.frameCount++;
  964. determineFrustumSet(root, this);
  965. markUsedSetLeaves(root, this);
  966. skipTraversal(root, this);
  967. toggleTiles(root, this); // TODO: We may want to add this function in the requestTileContents function
  968. lruCache.scheduleUnload(null);
  969. } // Overrideable
  970. parseTile(buffer, tile) {
  971. return null;
  972. }
  973. disposeTile(tile) {}
  974. preprocessNode(tile, parentTile, tileSetDir) {
  975. if (tile.content) {
  976. if (!('uri' in tile.content) && 'url' in tile.content) {
  977. tile.content.uri = tile.content.url;
  978. delete tile.content.url;
  979. }
  980. if (tile.content.uri) {
  981. tile.content.uri = _path.default.join(tileSetDir, tile.content.uri);
  982. } // TODO: fix for some cases where tilesets provide the bounding volume
  983. // but volumes are not present. See
  984. if (tile.content.boundingVolume && !('box' in tile.content.boundingVolume || 'sphere' in tile.content.boundingVolume || 'region' in tile.content.boundingVolume)) {
  985. delete tile.content.boundingVolume;
  986. }
  987. }
  988. tile.parent = parentTile;
  989. tile.children = tile.children || [];
  990. tile.__contentEmpty = !tile.content || !tile.content.uri;
  991. tile.__error = 0.0;
  992. tile.__inFrustum = false;
  993. tile.__isLeaf = false;
  994. tile.__wasUsed = false;
  995. tile.__used = false;
  996. tile.__wasVisible = false;
  997. tile.__visible = false;
  998. tile.__wasActive = false;
  999. tile.__active = false;
  1000. tile.__childrenActive = false;
  1001. tile.__loadingState = UNLOADED;
  1002. tile.__loadIndex = 0;
  1003. tile.__loadAbort = null;
  1004. if (parentTile === null) {
  1005. tile.__depth = 0;
  1006. } else {
  1007. tile.__depth = parentTile.__depth + 1;
  1008. }
  1009. }
  1010. setTileActive(tile, state) {}
  1011. setTileVisible(tile, state) {}
  1012. calculateError(tile) {
  1013. return 0;
  1014. }
  1015. tileInView(tile) {
  1016. return true;
  1017. } // Private Functions
  1018. loadTileSet(url) {
  1019. const tileSets = this.tileSets;
  1020. if (!(url in tileSets)) {
  1021. const pr = fetch(url, {
  1022. credentials: 'same-origin'
  1023. }).then(res => {
  1024. if (res.ok) {
  1025. return res.json();
  1026. } else {
  1027. throw new Error(`Status ${res.status} (${res.statusText})`);
  1028. }
  1029. }).then(json => {
  1030. // TODO: Add version query?
  1031. const version = json.asset.version;
  1032. console.assert(version === '1.0' || version === '0.0');
  1033. const basePath = _path.default.dirname(url);
  1034. traverseSet(json.root, (node, parent) => this.preprocessNode(node, parent, basePath));
  1035. tileSets[url] = json; // TODO: schedule an update to avoid doing this too many times
  1036. this.update();
  1037. });
  1038. pr.catch(e => {
  1039. console.error(`TilesLoader: Failed to load tile set json "${url}"`);
  1040. console.error(e);
  1041. delete tileSets[url];
  1042. });
  1043. tileSets[url] = pr;
  1044. }
  1045. return Promise.resolve(tileSets[url]);
  1046. }
  1047. requestTileContents(tile) {
  1048. // If the tile is already being loaded then don't
  1049. // start it again.
  1050. if (tile.__loadingState !== UNLOADED) {
  1051. return;
  1052. } // TODO: reuse the functions created here?
  1053. const lruCache = this.lruCache;
  1054. const downloadQueue = this.downloadQueue;
  1055. const parseQueue = this.parseQueue;
  1056. lruCache.add(tile, t => {
  1057. if (t.__loadingState === LOADING) {
  1058. t.__loadAbort.abort();
  1059. t.__loadAbort = null;
  1060. } else {
  1061. this.disposeTile(t);
  1062. }
  1063. if (t.__loadingState === LOADING) {
  1064. stats.downloading--;
  1065. } else if (t.__loadingState === PARSING) {
  1066. stats.parsing--;
  1067. }
  1068. t.__loadingState = UNLOADED;
  1069. t.__loadIndex++; // TODO: Removing from the queues here is slow
  1070. // parseQueue.remove( t );
  1071. // downloadQueue.remove( t );
  1072. });
  1073. tile.__loadIndex++;
  1074. const loadIndex = tile.__loadIndex;
  1075. const priority = 1 / (tile.__depth + 1);
  1076. const stats = this.stats;
  1077. const controller = new AbortController();
  1078. const signal = controller.signal;
  1079. stats.downloading++;
  1080. tile.__loadAbort = controller;
  1081. tile.__loadingState = LOADING;
  1082. downloadQueue.add(tile, priority, tile => {
  1083. if (tile.__loadIndex !== loadIndex) {
  1084. return Promise.resolve();
  1085. }
  1086. return fetch(tile.content.uri, {
  1087. credentials: 'same-origin',
  1088. signal
  1089. });
  1090. }).then(res => {
  1091. if (tile.__loadIndex !== loadIndex) {
  1092. return;
  1093. }
  1094. if (res.ok) {
  1095. return res.arrayBuffer();
  1096. } else {
  1097. throw new Error(`Failed to load model with error code ${res.status}`);
  1098. }
  1099. }).then(buffer => {
  1100. if (tile.__loadIndex !== loadIndex) {
  1101. return;
  1102. }
  1103. stats.downloading--;
  1104. stats.parsing++;
  1105. tile.__loadAbort = null;
  1106. tile.__loadingState = PARSING;
  1107. return parseQueue.add(buffer, priority, buffer => {
  1108. if (tile.__loadIndex !== loadIndex) {
  1109. return Promise.resolve();
  1110. }
  1111. return this.parseTile(buffer, tile);
  1112. });
  1113. }).then(() => {
  1114. if (tile.__loadIndex !== loadIndex) {
  1115. return;
  1116. }
  1117. stats.parsing--;
  1118. tile.__loadingState = LOADED;
  1119. this.setTileActive(tile, tile.__active);
  1120. this.setTileVisible(tile, tile.__visible);
  1121. }).catch(e => {
  1122. // if it has been unloaded then the tile has been disposed
  1123. if (tile.__loadIndex !== loadIndex) {
  1124. return;
  1125. }
  1126. if (e.name !== 'AbortError') {
  1127. console.error('TilesRenderer : Failed to load tile.');
  1128. console.error(e);
  1129. tile.__loadingState = FAILED;
  1130. } else {
  1131. lruCache.remove(tile);
  1132. }
  1133. });
  1134. }
  1135. }
  1136. exports.TilesRenderer = TilesRenderer;
  1137. },{"path":"../node_modules/path-browserify/index.js","./LRUCache.js":"../src/LRUCache.js","./PriorityQueue.js":"../src/PriorityQueue.js"}],"../src/B3DMLoader.js":[function(require,module,exports) {
  1138. "use strict";
  1139. Object.defineProperty(exports, "__esModule", {
  1140. value: true
  1141. });
  1142. exports.B3DMLoader = void 0;
  1143. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/Batched3DModel/README.md
  1144. // convert an array of numbers to a string
  1145. function arrayToString(array) {
  1146. let str = '';
  1147. for (let i = 0, l = array.length; i < l; i++) {
  1148. str += String.fromCharCode(array[i]);
  1149. }
  1150. return str;
  1151. }
  1152. class B3DMLoader {
  1153. load(url) {
  1154. return fetch(url, {
  1155. credentials: 'same-origin'
  1156. }).then(res => res.arrayBuffer()).then(buffer => this.parse(buffer));
  1157. }
  1158. parse(buffer) {
  1159. const dataView = new DataView(buffer); // 28-byte header
  1160. // 4 bytes
  1161. const magic = String.fromCharCode(dataView.getUint8(0)) + String.fromCharCode(dataView.getUint8(1)) + String.fromCharCode(dataView.getUint8(2)) + String.fromCharCode(dataView.getUint8(3));
  1162. console.assert(magic === 'b3dm'); // 4 bytes
  1163. const version = dataView.getUint32(4, true);
  1164. console.assert(version === 1); // 4 bytes
  1165. const byteLength = dataView.getUint32(8, true);
  1166. console.assert(byteLength === buffer.byteLength); // 4 bytes
  1167. const featureTableJSONByteLength = dataView.getUint32(12, true); // 4 bytes
  1168. const featureTableBinaryByteLength = dataView.getUint32(16, true); // 4 bytes
  1169. const batchTableJSONByteLength = dataView.getUint32(20, true); // 4 bytes
  1170. const batchTableBinaryByteLength = dataView.getUint32(24, true); // Feature Table
  1171. const featureTableStart = 28;
  1172. const jsonFeatureTableData = new Uint8Array(buffer, featureTableStart, featureTableJSONByteLength);
  1173. const jsonFeatureTable = featureTableJSONByteLength === 0 ? {} : JSON.parse(arrayToString(jsonFeatureTableData));
  1174. const binFeatureTableData = new Uint8Array(buffer, featureTableStart + featureTableJSONByteLength, featureTableBinaryByteLength); // TODO: dereference the json feature table data in to the binary array.
  1175. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/FeatureTable/README.md#json-header
  1176. // Batch Table
  1177. const batchTableStart = featureTableStart + featureTableJSONByteLength + featureTableBinaryByteLength;
  1178. const jsonBatchTableData = new Uint8Array(buffer, batchTableStart, batchTableJSONByteLength);
  1179. const jsonBatchTable = batchTableJSONByteLength === 0 ? {} : JSON.parse(arrayToString(jsonBatchTableData));
  1180. const binBatchTableData = new Uint8Array(buffer, batchTableStart + batchTableJSONByteLength, batchTableBinaryByteLength); // TODO: dereference the json batch table data in to the binary array.
  1181. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/FeatureTable/README.md#json-header
  1182. const glbStart = batchTableStart + batchTableJSONByteLength + batchTableBinaryByteLength;
  1183. const glbBytes = new Uint8Array(buffer, glbStart, byteLength - glbStart); // TODO: Understand how to apply the batchId semantics
  1184. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/Batched3DModel/README.md#binary-gltf
  1185. return {
  1186. version,
  1187. featureTable: jsonFeatureTable,
  1188. batchTable: jsonBatchTable,
  1189. glbBytes
  1190. };
  1191. }
  1192. }
  1193. exports.B3DMLoader = B3DMLoader;
  1194. },{}],"../node_modules/three/build/three.module.js":[function(require,module,exports) {
  1195. "use strict";
  1196. Object.defineProperty(exports, "__esModule", {
  1197. value: true
  1198. });
  1199. exports.AmbientLight = AmbientLight;
  1200. exports.AmbientLightProbe = AmbientLightProbe;
  1201. exports.AnimationClip = AnimationClip;
  1202. exports.AnimationLoader = AnimationLoader;
  1203. exports.AnimationMixer = AnimationMixer;
  1204. exports.AnimationObjectGroup = AnimationObjectGroup;
  1205. exports.ArcCurve = ArcCurve;
  1206. exports.ArrayCamera = ArrayCamera;
  1207. exports.ArrowHelper = ArrowHelper;
  1208. exports.Audio = Audio;
  1209. exports.AudioAnalyser = AudioAnalyser;
  1210. exports.AudioListener = AudioListener;
  1211. exports.AudioLoader = AudioLoader;
  1212. exports.AxesHelper = AxesHelper;
  1213. exports.AxisHelper = AxisHelper;
  1214. exports.BinaryTextureLoader = BinaryTextureLoader;
  1215. exports.Bone = Bone;
  1216. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  1217. exports.BoundingBoxHelper = BoundingBoxHelper;
  1218. exports.Box2 = Box2;
  1219. exports.Box3 = Box3;
  1220. exports.Box3Helper = Box3Helper;
  1221. exports.BoxHelper = BoxHelper;
  1222. exports.BufferAttribute = BufferAttribute;
  1223. exports.BufferGeometry = BufferGeometry;
  1224. exports.BufferGeometryLoader = BufferGeometryLoader;
  1225. exports.Camera = Camera;
  1226. exports.CameraHelper = CameraHelper;
  1227. exports.CanvasRenderer = CanvasRenderer;
  1228. exports.CanvasTexture = CanvasTexture;
  1229. exports.CatmullRomCurve3 = CatmullRomCurve3;
  1230. exports.CircleBufferGeometry = CircleBufferGeometry;
  1231. exports.CircleGeometry = CircleGeometry;
  1232. exports.Clock = Clock;
  1233. exports.ClosedSplineCurve3 = ClosedSplineCurve3;
  1234. exports.Color = Color;
  1235. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  1236. exports.CompressedTexture = CompressedTexture;
  1237. exports.CompressedTextureLoader = CompressedTextureLoader;
  1238. exports.ConeBufferGeometry = ConeBufferGeometry;
  1239. exports.ConeGeometry = ConeGeometry;
  1240. exports.CubeCamera = CubeCamera;
  1241. exports.CubeTexture = CubeTexture;
  1242. exports.CubeTextureLoader = CubeTextureLoader;
  1243. exports.CubicBezierCurve = CubicBezierCurve;
  1244. exports.CubicBezierCurve3 = CubicBezierCurve3;
  1245. exports.CubicInterpolant = CubicInterpolant;
  1246. exports.Curve = Curve;
  1247. exports.CurvePath = CurvePath;
  1248. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  1249. exports.CylinderGeometry = CylinderGeometry;
  1250. exports.Cylindrical = Cylindrical;
  1251. exports.DataTexture = DataTexture;
  1252. exports.DataTexture2DArray = DataTexture2DArray;
  1253. exports.DataTexture3D = DataTexture3D;
  1254. exports.DataTextureLoader = DataTextureLoader;
  1255. exports.DepthTexture = DepthTexture;
  1256. exports.DirectionalLight = DirectionalLight;
  1257. exports.DirectionalLightHelper = DirectionalLightHelper;
  1258. exports.DirectionalLightShadow = DirectionalLightShadow;
  1259. exports.DiscreteInterpolant = DiscreteInterpolant;
  1260. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  1261. exports.DodecahedronGeometry = DodecahedronGeometry;
  1262. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  1263. exports.EdgesGeometry = EdgesGeometry;
  1264. exports.EdgesHelper = EdgesHelper;
  1265. exports.EllipseCurve = EllipseCurve;
  1266. exports.Euler = Euler;
  1267. exports.EventDispatcher = EventDispatcher;
  1268. exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry;
  1269. exports.ExtrudeGeometry = ExtrudeGeometry;
  1270. exports.Face3 = Face3;
  1271. exports.Face4 = Face4;
  1272. exports.FaceNormalsHelper = FaceNormalsHelper;
  1273. exports.FileLoader = FileLoader;
  1274. exports.Float32Attribute = Float32Attribute;
  1275. exports.Float32BufferAttribute = Float32BufferAttribute;
  1276. exports.Float64Attribute = Float64Attribute;
  1277. exports.Float64BufferAttribute = Float64BufferAttribute;
  1278. exports.Fog = Fog;
  1279. exports.FogExp2 = FogExp2;
  1280. exports.Font = Font;
  1281. exports.FontLoader = FontLoader;
  1282. exports.Frustum = Frustum;
  1283. exports.Geometry = Geometry;
  1284. exports.GridHelper = GridHelper;
  1285. exports.Group = Group;
  1286. exports.HemisphereLight = HemisphereLight;
  1287. exports.HemisphereLightHelper = HemisphereLightHelper;
  1288. exports.HemisphereLightProbe = HemisphereLightProbe;
  1289. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  1290. exports.IcosahedronGeometry = IcosahedronGeometry;
  1291. exports.ImageBitmapLoader = ImageBitmapLoader;
  1292. exports.ImageLoader = ImageLoader;
  1293. exports.ImmediateRenderObject = ImmediateRenderObject;
  1294. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  1295. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  1296. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  1297. exports.InstancedMesh = InstancedMesh;
  1298. exports.Int16Attribute = Int16Attribute;
  1299. exports.Int16BufferAttribute = Int16BufferAttribute;
  1300. exports.Int32Attribute = Int32Attribute;
  1301. exports.Int32BufferAttribute = Int32BufferAttribute;
  1302. exports.Int8Attribute = Int8Attribute;
  1303. exports.Int8BufferAttribute = Int8BufferAttribute;
  1304. exports.InterleavedBuffer = InterleavedBuffer;
  1305. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  1306. exports.Interpolant = Interpolant;
  1307. exports.JSONLoader = JSONLoader;
  1308. exports.KeyframeTrack = KeyframeTrack;
  1309. exports.LOD = LOD;
  1310. exports.LatheBufferGeometry = LatheBufferGeometry;
  1311. exports.LatheGeometry = LatheGeometry;
  1312. exports.Layers = Layers;
  1313. exports.LensFlare = LensFlare;
  1314. exports.Light = Light;
  1315. exports.LightProbe = LightProbe;
  1316. exports.LightProbeHelper = LightProbeHelper;
  1317. exports.LightShadow = LightShadow;
  1318. exports.Line = Line;
  1319. exports.Line3 = Line3;
  1320. exports.LineBasicMaterial = LineBasicMaterial;
  1321. exports.LineCurve = LineCurve;
  1322. exports.LineCurve3 = LineCurve3;
  1323. exports.LineDashedMaterial = LineDashedMaterial;
  1324. exports.LineLoop = LineLoop;
  1325. exports.LineSegments = LineSegments;
  1326. exports.LinearInterpolant = LinearInterpolant;
  1327. exports.Loader = Loader;
  1328. exports.LoadingManager = LoadingManager;
  1329. exports.Material = Material;
  1330. exports.MaterialLoader = MaterialLoader;
  1331. exports.Matrix3 = Matrix3;
  1332. exports.Matrix4 = Matrix4;
  1333. exports.Mesh = Mesh;
  1334. exports.MeshBasicMaterial = MeshBasicMaterial;
  1335. exports.MeshDepthMaterial = MeshDepthMaterial;
  1336. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  1337. exports.MeshFaceMaterial = MeshFaceMaterial;
  1338. exports.MeshLambertMaterial = MeshLambertMaterial;
  1339. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  1340. exports.MeshNormalMaterial = MeshNormalMaterial;
  1341. exports.MeshPhongMaterial = MeshPhongMaterial;
  1342. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  1343. exports.MeshStandardMaterial = MeshStandardMaterial;
  1344. exports.MeshToonMaterial = MeshToonMaterial;
  1345. exports.MultiMaterial = MultiMaterial;
  1346. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  1347. exports.Object3D = Object3D;
  1348. exports.ObjectLoader = ObjectLoader;
  1349. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  1350. exports.OctahedronGeometry = OctahedronGeometry;
  1351. exports.OrthographicCamera = OrthographicCamera;
  1352. exports.ParametricBufferGeometry = ParametricBufferGeometry;
  1353. exports.ParametricGeometry = ParametricGeometry;
  1354. exports.Particle = Particle;
  1355. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  1356. exports.ParticleSystem = ParticleSystem;
  1357. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  1358. exports.Path = Path;
  1359. exports.PerspectiveCamera = PerspectiveCamera;
  1360. exports.Plane = Plane;
  1361. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  1362. exports.PlaneGeometry = PlaneGeometry;
  1363. exports.PlaneHelper = PlaneHelper;
  1364. exports.PointCloud = PointCloud;
  1365. exports.PointCloudMaterial = PointCloudMaterial;
  1366. exports.PointLight = PointLight;
  1367. exports.PointLightHelper = PointLightHelper;
  1368. exports.Points = Points;
  1369. exports.PointsMaterial = PointsMaterial;
  1370. exports.PolarGridHelper = PolarGridHelper;
  1371. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  1372. exports.PolyhedronGeometry = PolyhedronGeometry;
  1373. exports.PositionalAudio = PositionalAudio;
  1374. exports.PositionalAudioHelper = PositionalAudioHelper;
  1375. exports.PropertyBinding = PropertyBinding;
  1376. exports.PropertyMixer = PropertyMixer;
  1377. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  1378. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  1379. exports.Quaternion = Quaternion;
  1380. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  1381. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  1382. exports.RawShaderMaterial = RawShaderMaterial;
  1383. exports.Ray = Ray;
  1384. exports.Raycaster = Raycaster;
  1385. exports.RectAreaLight = RectAreaLight;
  1386. exports.RectAreaLightHelper = RectAreaLightHelper;
  1387. exports.RingBufferGeometry = RingBufferGeometry;
  1388. exports.RingGeometry = RingGeometry;
  1389. exports.Scene = Scene;
  1390. exports.ShaderMaterial = ShaderMaterial;
  1391. exports.ShadowMaterial = ShadowMaterial;
  1392. exports.Shape = Shape;
  1393. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  1394. exports.ShapeGeometry = ShapeGeometry;
  1395. exports.ShapePath = ShapePath;
  1396. exports.Skeleton = Skeleton;
  1397. exports.SkeletonHelper = SkeletonHelper;
  1398. exports.SkinnedMesh = SkinnedMesh;
  1399. exports.Sphere = Sphere;
  1400. exports.SphereBufferGeometry = SphereBufferGeometry;
  1401. exports.SphereGeometry = SphereGeometry;
  1402. exports.Spherical = Spherical;
  1403. exports.SphericalHarmonics3 = SphericalHarmonics3;
  1404. exports.Spline = Spline;
  1405. exports.SplineCurve = SplineCurve;
  1406. exports.SplineCurve3 = SplineCurve3;
  1407. exports.SpotLight = SpotLight;
  1408. exports.SpotLightHelper = SpotLightHelper;
  1409. exports.SpotLightShadow = SpotLightShadow;
  1410. exports.Sprite = Sprite;
  1411. exports.SpriteMaterial = SpriteMaterial;
  1412. exports.StereoCamera = StereoCamera;
  1413. exports.StringKeyframeTrack = StringKeyframeTrack;
  1414. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  1415. exports.TetrahedronGeometry = TetrahedronGeometry;
  1416. exports.TextBufferGeometry = TextBufferGeometry;
  1417. exports.TextGeometry = TextGeometry;
  1418. exports.Texture = Texture;
  1419. exports.TextureLoader = TextureLoader;
  1420. exports.TorusBufferGeometry = TorusBufferGeometry;
  1421. exports.TorusGeometry = TorusGeometry;
  1422. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  1423. exports.TorusKnotGeometry = TorusKnotGeometry;
  1424. exports.Triangle = Triangle;
  1425. exports.TubeBufferGeometry = TubeBufferGeometry;
  1426. exports.TubeGeometry = TubeGeometry;
  1427. exports.Uint16Attribute = Uint16Attribute;
  1428. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  1429. exports.Uint32Attribute = Uint32Attribute;
  1430. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  1431. exports.Uint8Attribute = Uint8Attribute;
  1432. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  1433. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  1434. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  1435. exports.Uniform = Uniform;
  1436. exports.Vector2 = Vector2;
  1437. exports.Vector3 = Vector3;
  1438. exports.Vector4 = Vector4;
  1439. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  1440. exports.Vertex = Vertex;
  1441. exports.VertexNormalsHelper = VertexNormalsHelper;
  1442. exports.VideoTexture = VideoTexture;
  1443. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  1444. exports.WebGLRenderTarget = WebGLRenderTarget;
  1445. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  1446. exports.WebGLRenderer = WebGLRenderer;
  1447. exports.WebGLUtils = WebGLUtils;
  1448. exports.WireframeGeometry = WireframeGeometry;
  1449. exports.WireframeHelper = WireframeHelper;
  1450. exports.XHRLoader = XHRLoader;
  1451. exports.NoToneMapping = exports.NoColors = exports.NoBlending = exports.NeverStencilFunc = exports.NeverDepth = exports.NearestMipmapNearestFilter = exports.NearestMipmapLinearFilter = exports.NearestMipMapNearestFilter = exports.NearestMipMapLinearFilter = exports.NearestFilter = exports.MultiplyOperation = exports.MultiplyBlending = exports.MixOperation = exports.MirroredRepeatWrapping = exports.MinEquation = exports.MaxEquation = exports.Math = exports.MOUSE = exports.LuminanceFormat = exports.LuminanceAlphaFormat = exports.LoopRepeat = exports.LoopPingPong = exports.LoopOnce = exports.LogLuvEncoding = exports.LoaderUtils = exports.LinearToneMapping = exports.LinearMipmapNearestFilter = exports.LinearMipmapLinearFilter = exports.LinearMipMapNearestFilter = exports.LinearMipMapLinearFilter = exports.LinearFilter = exports.LinearEncoding = exports.LineStrip = exports.LinePieces = exports.LessStencilFunc = exports.LessEqualStencilFunc = exports.LessEqualDepth = exports.LessDepth = exports.KeepStencilOp = exports.InvertStencilOp = exports.InterpolateSmooth = exports.InterpolateLinear = exports.InterpolateDiscrete = exports.IntType = exports.IncrementWrapStencilOp = exports.IncrementStencilOp = exports.ImageUtils = exports.HalfFloatType = exports.GreaterStencilFunc = exports.GreaterEqualStencilFunc = exports.GreaterEqualDepth = exports.GreaterDepth = exports.GeometryUtils = exports.GammaEncoding = exports.FrontSide = exports.FrontFaceDirectionCW = exports.FrontFaceDirectionCCW = exports.FloatType = exports.FlatShading = exports.FaceColors = exports.EquirectangularRefractionMapping = exports.EquirectangularReflectionMapping = exports.EqualStencilFunc = exports.EqualDepth = exports.DstColorFactor = exports.DstAlphaFactor = exports.DoubleSide = exports.DepthStencilFormat = exports.DepthFormat = exports.DefaultLoadingManager = exports.DecrementWrapStencilOp = exports.DecrementStencilOp = exports.CustomBlending = exports.CullFaceNone = exports.CullFaceFrontBack = exports.CullFaceFront = exports.CullFaceBack = exports.CubeUVRefractionMapping = exports.CubeUVReflectionMapping = exports.CubeRefractionMapping = exports.CubeReflectionMapping = exports.ClampToEdgeWrapping = exports.CineonToneMapping = exports.Cache = exports.ByteType = exports.CubeGeometry = exports.BoxGeometry = exports.BoxBufferGeometry = exports.BasicShadowMap = exports.BasicDepthPacking = exports.BackSide = exports.AudioContext = exports.AnimationUtils = exports.AlwaysStencilFunc = exports.AlwaysDepth = exports.AlphaFormat = exports.AdditiveBlending = exports.AddOperation = exports.AddEquation = exports.ACESFilmicToneMapping = void 0;
  1452. exports.sRGBEncoding = exports.ZeroStencilOp = exports.ZeroSlopeEnding = exports.ZeroFactor = exports.ZeroCurvatureEnding = exports.WrapAroundEnding = exports.VertexColors = exports.VSMShadowMap = exports.UnsignedShortType = exports.UnsignedShort565Type = exports.UnsignedShort5551Type = exports.UnsignedShort4444Type = exports.UnsignedIntType = exports.UnsignedInt248Type = exports.UnsignedByteType = exports.UniformsUtils = exports.UniformsLib = exports.Uncharted2ToneMapping = exports.UVMapping = exports.TrianglesDrawMode = exports.TriangleStripDrawMode = exports.TriangleFanDrawMode = exports.TangentSpaceNormalMap = exports.TOUCH = exports.SubtractiveBlending = exports.SubtractEquation = exports.SrcColorFactor = exports.SrcAlphaSaturateFactor = exports.SrcAlphaFactor = exports.SphericalReflectionMapping = exports.SmoothShading = exports.ShortType = exports.ShapeUtils = exports.ShaderLib = exports.ShaderChunk = exports.SceneUtils = exports.ReverseSubtractEquation = exports.ReplaceStencilOp = exports.RepeatWrapping = exports.ReinhardToneMapping = exports.RedFormat = exports.RGB_S3TC_DXT1_Format = exports.RGB_PVRTC_4BPPV1_Format = exports.RGB_PVRTC_2BPPV1_Format = exports.RGB_ETC1_Format = exports.RGBM7Encoding = exports.RGBM16Encoding = exports.RGBFormat = exports.RGBEFormat = exports.RGBEEncoding = exports.RGBDEncoding = exports.RGBA_S3TC_DXT5_Format = exports.RGBA_S3TC_DXT3_Format = exports.RGBA_S3TC_DXT1_Format = exports.RGBA_PVRTC_4BPPV1_Format = exports.RGBA_PVRTC_2BPPV1_Format = exports.RGBA_ASTC_8x8_Format = exports.RGBA_ASTC_8x6_Format = exports.RGBA_ASTC_8x5_Format = exports.RGBA_ASTC_6x6_Format = exports.RGBA_ASTC_6x5_Format = exports.RGBA_ASTC_5x5_Format = exports.RGBA_ASTC_5x4_Format = exports.RGBA_ASTC_4x4_Format = exports.RGBA_ASTC_12x12_Format = exports.RGBA_ASTC_12x10_Format = exports.RGBA_ASTC_10x8_Format = exports.RGBA_ASTC_10x6_Format = exports.RGBA_ASTC_10x5_Format = exports.RGBA_ASTC_10x10_Format = exports.RGBAFormat = exports.RGBADepthPacking = exports.REVISION = exports.PCFSoftShadowMap = exports.PCFShadowMap = exports.OneMinusSrcColorFactor = exports.OneMinusSrcAlphaFactor = exports.OneMinusDstColorFactor = exports.OneMinusDstAlphaFactor = exports.OneFactor = exports.ObjectSpaceNormalMap = exports.NotEqualStencilFunc = exports.NotEqualDepth = exports.NormalBlending = void 0;
  1453. // Polyfills
  1454. if (Number.EPSILON === undefined) {
  1455. Number.EPSILON = Math.pow(2, -52);
  1456. }
  1457. if (Number.isInteger === undefined) {
  1458. // Missing in IE
  1459. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
  1460. Number.isInteger = function (value) {
  1461. return typeof value === 'number' && isFinite(value) && Math.floor(value) === value;
  1462. };
  1463. } //
  1464. if (Math.sign === undefined) {
  1465. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  1466. Math.sign = function (x) {
  1467. return x < 0 ? -1 : x > 0 ? 1 : +x;
  1468. };
  1469. }
  1470. if ('name' in Function.prototype === false) {
  1471. // Missing in IE
  1472. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  1473. Object.defineProperty(Function.prototype, 'name', {
  1474. get: function () {
  1475. return this.toString().match(/^\s*function\s*([^\(\s]*)/)[1];
  1476. }
  1477. });
  1478. }
  1479. if (Object.assign === undefined) {
  1480. // Missing in IE
  1481. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  1482. Object.assign = function (target) {
  1483. if (target === undefined || target === null) {
  1484. throw new TypeError('Cannot convert undefined or null to object');
  1485. }
  1486. var output = Object(target);
  1487. for (var index = 1; index < arguments.length; index++) {
  1488. var source = arguments[index];
  1489. if (source !== undefined && source !== null) {
  1490. for (var nextKey in source) {
  1491. if (Object.prototype.hasOwnProperty.call(source, nextKey)) {
  1492. output[nextKey] = source[nextKey];
  1493. }
  1494. }
  1495. }
  1496. }
  1497. return output;
  1498. };
  1499. }
  1500. var REVISION = '109';
  1501. exports.REVISION = REVISION;
  1502. var MOUSE = {
  1503. LEFT: 0,
  1504. MIDDLE: 1,
  1505. RIGHT: 2,
  1506. ROTATE: 0,
  1507. DOLLY: 1,
  1508. PAN: 2
  1509. };
  1510. exports.MOUSE = MOUSE;
  1511. var TOUCH = {
  1512. ROTATE: 0,
  1513. PAN: 1,
  1514. DOLLY_PAN: 2,
  1515. DOLLY_ROTATE: 3
  1516. };
  1517. exports.TOUCH = TOUCH;
  1518. var CullFaceNone = 0;
  1519. exports.CullFaceNone = CullFaceNone;
  1520. var CullFaceBack = 1;
  1521. exports.CullFaceBack = CullFaceBack;
  1522. var CullFaceFront = 2;
  1523. exports.CullFaceFront = CullFaceFront;
  1524. var CullFaceFrontBack = 3;
  1525. exports.CullFaceFrontBack = CullFaceFrontBack;
  1526. var FrontFaceDirectionCW = 0;
  1527. exports.FrontFaceDirectionCW = FrontFaceDirectionCW;
  1528. var FrontFaceDirectionCCW = 1;
  1529. exports.FrontFaceDirectionCCW = FrontFaceDirectionCCW;
  1530. var BasicShadowMap = 0;
  1531. exports.BasicShadowMap = BasicShadowMap;
  1532. var PCFShadowMap = 1;
  1533. exports.PCFShadowMap = PCFShadowMap;
  1534. var PCFSoftShadowMap = 2;
  1535. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  1536. var VSMShadowMap = 3;
  1537. exports.VSMShadowMap = VSMShadowMap;
  1538. var FrontSide = 0;
  1539. exports.FrontSide = FrontSide;
  1540. var BackSide = 1;
  1541. exports.BackSide = BackSide;
  1542. var DoubleSide = 2;
  1543. exports.DoubleSide = DoubleSide;
  1544. var FlatShading = 1;
  1545. exports.FlatShading = FlatShading;
  1546. var SmoothShading = 2;
  1547. exports.SmoothShading = SmoothShading;
  1548. var NoColors = 0;
  1549. exports.NoColors = NoColors;
  1550. var FaceColors = 1;
  1551. exports.FaceColors = FaceColors;
  1552. var VertexColors = 2;
  1553. exports.VertexColors = VertexColors;
  1554. var NoBlending = 0;
  1555. exports.NoBlending = NoBlending;
  1556. var NormalBlending = 1;
  1557. exports.NormalBlending = NormalBlending;
  1558. var AdditiveBlending = 2;
  1559. exports.AdditiveBlending = AdditiveBlending;
  1560. var SubtractiveBlending = 3;
  1561. exports.SubtractiveBlending = SubtractiveBlending;
  1562. var MultiplyBlending = 4;
  1563. exports.MultiplyBlending = MultiplyBlending;
  1564. var CustomBlending = 5;
  1565. exports.CustomBlending = CustomBlending;
  1566. var AddEquation = 100;
  1567. exports.AddEquation = AddEquation;
  1568. var SubtractEquation = 101;
  1569. exports.SubtractEquation = SubtractEquation;
  1570. var ReverseSubtractEquation = 102;
  1571. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  1572. var MinEquation = 103;
  1573. exports.MinEquation = MinEquation;
  1574. var MaxEquation = 104;
  1575. exports.MaxEquation = MaxEquation;
  1576. var ZeroFactor = 200;
  1577. exports.ZeroFactor = ZeroFactor;
  1578. var OneFactor = 201;
  1579. exports.OneFactor = OneFactor;
  1580. var SrcColorFactor = 202;
  1581. exports.SrcColorFactor = SrcColorFactor;
  1582. var OneMinusSrcColorFactor = 203;
  1583. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  1584. var SrcAlphaFactor = 204;
  1585. exports.SrcAlphaFactor = SrcAlphaFactor;
  1586. var OneMinusSrcAlphaFactor = 205;
  1587. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  1588. var DstAlphaFactor = 206;
  1589. exports.DstAlphaFactor = DstAlphaFactor;
  1590. var OneMinusDstAlphaFactor = 207;
  1591. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  1592. var DstColorFactor = 208;
  1593. exports.DstColorFactor = DstColorFactor;
  1594. var OneMinusDstColorFactor = 209;
  1595. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  1596. var SrcAlphaSaturateFactor = 210;
  1597. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  1598. var NeverDepth = 0;
  1599. exports.NeverDepth = NeverDepth;
  1600. var AlwaysDepth = 1;
  1601. exports.AlwaysDepth = AlwaysDepth;
  1602. var LessDepth = 2;
  1603. exports.LessDepth = LessDepth;
  1604. var LessEqualDepth = 3;
  1605. exports.LessEqualDepth = LessEqualDepth;
  1606. var EqualDepth = 4;
  1607. exports.EqualDepth = EqualDepth;
  1608. var GreaterEqualDepth = 5;
  1609. exports.GreaterEqualDepth = GreaterEqualDepth;
  1610. var GreaterDepth = 6;
  1611. exports.GreaterDepth = GreaterDepth;
  1612. var NotEqualDepth = 7;
  1613. exports.NotEqualDepth = NotEqualDepth;
  1614. var MultiplyOperation = 0;
  1615. exports.MultiplyOperation = MultiplyOperation;
  1616. var MixOperation = 1;
  1617. exports.MixOperation = MixOperation;
  1618. var AddOperation = 2;
  1619. exports.AddOperation = AddOperation;
  1620. var NoToneMapping = 0;
  1621. exports.NoToneMapping = NoToneMapping;
  1622. var LinearToneMapping = 1;
  1623. exports.LinearToneMapping = LinearToneMapping;
  1624. var ReinhardToneMapping = 2;
  1625. exports.ReinhardToneMapping = ReinhardToneMapping;
  1626. var Uncharted2ToneMapping = 3;
  1627. exports.Uncharted2ToneMapping = Uncharted2ToneMapping;
  1628. var CineonToneMapping = 4;
  1629. exports.CineonToneMapping = CineonToneMapping;
  1630. var ACESFilmicToneMapping = 5;
  1631. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  1632. var UVMapping = 300;
  1633. exports.UVMapping = UVMapping;
  1634. var CubeReflectionMapping = 301;
  1635. exports.CubeReflectionMapping = CubeReflectionMapping;
  1636. var CubeRefractionMapping = 302;
  1637. exports.CubeRefractionMapping = CubeRefractionMapping;
  1638. var EquirectangularReflectionMapping = 303;
  1639. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  1640. var EquirectangularRefractionMapping = 304;
  1641. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  1642. var SphericalReflectionMapping = 305;
  1643. exports.SphericalReflectionMapping = SphericalReflectionMapping;
  1644. var CubeUVReflectionMapping = 306;
  1645. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  1646. var CubeUVRefractionMapping = 307;
  1647. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  1648. var RepeatWrapping = 1000;
  1649. exports.RepeatWrapping = RepeatWrapping;
  1650. var ClampToEdgeWrapping = 1001;
  1651. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  1652. var MirroredRepeatWrapping = 1002;
  1653. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  1654. var NearestFilter = 1003;
  1655. exports.NearestFilter = NearestFilter;
  1656. var NearestMipmapNearestFilter = 1004;
  1657. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  1658. var NearestMipMapNearestFilter = 1004;
  1659. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  1660. var NearestMipmapLinearFilter = 1005;
  1661. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  1662. var NearestMipMapLinearFilter = 1005;
  1663. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  1664. var LinearFilter = 1006;
  1665. exports.LinearFilter = LinearFilter;
  1666. var LinearMipmapNearestFilter = 1007;
  1667. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  1668. var LinearMipMapNearestFilter = 1007;
  1669. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  1670. var LinearMipmapLinearFilter = 1008;
  1671. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  1672. var LinearMipMapLinearFilter = 1008;
  1673. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  1674. var UnsignedByteType = 1009;
  1675. exports.UnsignedByteType = UnsignedByteType;
  1676. var ByteType = 1010;
  1677. exports.ByteType = ByteType;
  1678. var ShortType = 1011;
  1679. exports.ShortType = ShortType;
  1680. var UnsignedShortType = 1012;
  1681. exports.UnsignedShortType = UnsignedShortType;
  1682. var IntType = 1013;
  1683. exports.IntType = IntType;
  1684. var UnsignedIntType = 1014;
  1685. exports.UnsignedIntType = UnsignedIntType;
  1686. var FloatType = 1015;
  1687. exports.FloatType = FloatType;
  1688. var HalfFloatType = 1016;
  1689. exports.HalfFloatType = HalfFloatType;
  1690. var UnsignedShort4444Type = 1017;
  1691. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  1692. var UnsignedShort5551Type = 1018;
  1693. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  1694. var UnsignedShort565Type = 1019;
  1695. exports.UnsignedShort565Type = UnsignedShort565Type;
  1696. var UnsignedInt248Type = 1020;
  1697. exports.UnsignedInt248Type = UnsignedInt248Type;
  1698. var AlphaFormat = 1021;
  1699. exports.AlphaFormat = AlphaFormat;
  1700. var RGBFormat = 1022;
  1701. exports.RGBFormat = RGBFormat;
  1702. var RGBAFormat = 1023;
  1703. exports.RGBAFormat = RGBAFormat;
  1704. var LuminanceFormat = 1024;
  1705. exports.LuminanceFormat = LuminanceFormat;
  1706. var LuminanceAlphaFormat = 1025;
  1707. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  1708. var RGBEFormat = RGBAFormat;
  1709. exports.RGBEFormat = RGBEFormat;
  1710. var DepthFormat = 1026;
  1711. exports.DepthFormat = DepthFormat;
  1712. var DepthStencilFormat = 1027;
  1713. exports.DepthStencilFormat = DepthStencilFormat;
  1714. var RedFormat = 1028;
  1715. exports.RedFormat = RedFormat;
  1716. var RGB_S3TC_DXT1_Format = 33776;
  1717. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  1718. var RGBA_S3TC_DXT1_Format = 33777;
  1719. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  1720. var RGBA_S3TC_DXT3_Format = 33778;
  1721. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  1722. var RGBA_S3TC_DXT5_Format = 33779;
  1723. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  1724. var RGB_PVRTC_4BPPV1_Format = 35840;
  1725. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  1726. var RGB_PVRTC_2BPPV1_Format = 35841;
  1727. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  1728. var RGBA_PVRTC_4BPPV1_Format = 35842;
  1729. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  1730. var RGBA_PVRTC_2BPPV1_Format = 35843;
  1731. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  1732. var RGB_ETC1_Format = 36196;
  1733. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  1734. var RGBA_ASTC_4x4_Format = 37808;
  1735. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  1736. var RGBA_ASTC_5x4_Format = 37809;
  1737. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  1738. var RGBA_ASTC_5x5_Format = 37810;
  1739. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  1740. var RGBA_ASTC_6x5_Format = 37811;
  1741. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  1742. var RGBA_ASTC_6x6_Format = 37812;
  1743. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  1744. var RGBA_ASTC_8x5_Format = 37813;
  1745. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  1746. var RGBA_ASTC_8x6_Format = 37814;
  1747. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  1748. var RGBA_ASTC_8x8_Format = 37815;
  1749. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  1750. var RGBA_ASTC_10x5_Format = 37816;
  1751. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  1752. var RGBA_ASTC_10x6_Format = 37817;
  1753. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  1754. var RGBA_ASTC_10x8_Format = 37818;
  1755. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  1756. var RGBA_ASTC_10x10_Format = 37819;
  1757. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  1758. var RGBA_ASTC_12x10_Format = 37820;
  1759. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  1760. var RGBA_ASTC_12x12_Format = 37821;
  1761. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  1762. var LoopOnce = 2200;
  1763. exports.LoopOnce = LoopOnce;
  1764. var LoopRepeat = 2201;
  1765. exports.LoopRepeat = LoopRepeat;
  1766. var LoopPingPong = 2202;
  1767. exports.LoopPingPong = LoopPingPong;
  1768. var InterpolateDiscrete = 2300;
  1769. exports.InterpolateDiscrete = InterpolateDiscrete;
  1770. var InterpolateLinear = 2301;
  1771. exports.InterpolateLinear = InterpolateLinear;
  1772. var InterpolateSmooth = 2302;
  1773. exports.InterpolateSmooth = InterpolateSmooth;
  1774. var ZeroCurvatureEnding = 2400;
  1775. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  1776. var ZeroSlopeEnding = 2401;
  1777. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  1778. var WrapAroundEnding = 2402;
  1779. exports.WrapAroundEnding = WrapAroundEnding;
  1780. var TrianglesDrawMode = 0;
  1781. exports.TrianglesDrawMode = TrianglesDrawMode;
  1782. var TriangleStripDrawMode = 1;
  1783. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  1784. var TriangleFanDrawMode = 2;
  1785. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  1786. var LinearEncoding = 3000;
  1787. exports.LinearEncoding = LinearEncoding;
  1788. var sRGBEncoding = 3001;
  1789. exports.sRGBEncoding = sRGBEncoding;
  1790. var GammaEncoding = 3007;
  1791. exports.GammaEncoding = GammaEncoding;
  1792. var RGBEEncoding = 3002;
  1793. exports.RGBEEncoding = RGBEEncoding;
  1794. var LogLuvEncoding = 3003;
  1795. exports.LogLuvEncoding = LogLuvEncoding;
  1796. var RGBM7Encoding = 3004;
  1797. exports.RGBM7Encoding = RGBM7Encoding;
  1798. var RGBM16Encoding = 3005;
  1799. exports.RGBM16Encoding = RGBM16Encoding;
  1800. var RGBDEncoding = 3006;
  1801. exports.RGBDEncoding = RGBDEncoding;
  1802. var BasicDepthPacking = 3200;
  1803. exports.BasicDepthPacking = BasicDepthPacking;
  1804. var RGBADepthPacking = 3201;
  1805. exports.RGBADepthPacking = RGBADepthPacking;
  1806. var TangentSpaceNormalMap = 0;
  1807. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  1808. var ObjectSpaceNormalMap = 1;
  1809. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  1810. var ZeroStencilOp = 0;
  1811. exports.ZeroStencilOp = ZeroStencilOp;
  1812. var KeepStencilOp = 7680;
  1813. exports.KeepStencilOp = KeepStencilOp;
  1814. var ReplaceStencilOp = 7681;
  1815. exports.ReplaceStencilOp = ReplaceStencilOp;
  1816. var IncrementStencilOp = 7682;
  1817. exports.IncrementStencilOp = IncrementStencilOp;
  1818. var DecrementStencilOp = 7683;
  1819. exports.DecrementStencilOp = DecrementStencilOp;
  1820. var IncrementWrapStencilOp = 34055;
  1821. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  1822. var DecrementWrapStencilOp = 34056;
  1823. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  1824. var InvertStencilOp = 5386;
  1825. exports.InvertStencilOp = InvertStencilOp;
  1826. var NeverStencilFunc = 512;
  1827. exports.NeverStencilFunc = NeverStencilFunc;
  1828. var LessStencilFunc = 513;
  1829. exports.LessStencilFunc = LessStencilFunc;
  1830. var EqualStencilFunc = 514;
  1831. exports.EqualStencilFunc = EqualStencilFunc;
  1832. var LessEqualStencilFunc = 515;
  1833. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  1834. var GreaterStencilFunc = 516;
  1835. exports.GreaterStencilFunc = GreaterStencilFunc;
  1836. var NotEqualStencilFunc = 517;
  1837. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  1838. var GreaterEqualStencilFunc = 518;
  1839. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  1840. var AlwaysStencilFunc = 519;
  1841. /**
  1842. * https://github.com/mrdoob/eventdispatcher.js/
  1843. */
  1844. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  1845. function EventDispatcher() {}
  1846. Object.assign(EventDispatcher.prototype, {
  1847. addEventListener: function (type, listener) {
  1848. if (this._listeners === undefined) this._listeners = {};
  1849. var listeners = this._listeners;
  1850. if (listeners[type] === undefined) {
  1851. listeners[type] = [];
  1852. }
  1853. if (listeners[type].indexOf(listener) === -1) {
  1854. listeners[type].push(listener);
  1855. }
  1856. },
  1857. hasEventListener: function (type, listener) {
  1858. if (this._listeners === undefined) return false;
  1859. var listeners = this._listeners;
  1860. return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
  1861. },
  1862. removeEventListener: function (type, listener) {
  1863. if (this._listeners === undefined) return;
  1864. var listeners = this._listeners;
  1865. var listenerArray = listeners[type];
  1866. if (listenerArray !== undefined) {
  1867. var index = listenerArray.indexOf(listener);
  1868. if (index !== -1) {
  1869. listenerArray.splice(index, 1);
  1870. }
  1871. }
  1872. },
  1873. dispatchEvent: function (event) {
  1874. if (this._listeners === undefined) return;
  1875. var listeners = this._listeners;
  1876. var listenerArray = listeners[event.type];
  1877. if (listenerArray !== undefined) {
  1878. event.target = this;
  1879. var array = listenerArray.slice(0);
  1880. for (var i = 0, l = array.length; i < l; i++) {
  1881. array[i].call(this, event);
  1882. }
  1883. }
  1884. }
  1885. });
  1886. /**
  1887. * @author alteredq / http://alteredqualia.com/
  1888. * @author mrdoob / http://mrdoob.com/
  1889. */
  1890. var _lut = [];
  1891. for (var i = 0; i < 256; i++) {
  1892. _lut[i] = (i < 16 ? '0' : '') + i.toString(16);
  1893. }
  1894. var _Math = {
  1895. DEG2RAD: Math.PI / 180,
  1896. RAD2DEG: 180 / Math.PI,
  1897. generateUUID: function () {
  1898. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  1899. var d0 = Math.random() * 0xffffffff | 0;
  1900. var d1 = Math.random() * 0xffffffff | 0;
  1901. var d2 = Math.random() * 0xffffffff | 0;
  1902. var d3 = Math.random() * 0xffffffff | 0;
  1903. var uuid = _lut[d0 & 0xff] + _lut[d0 >> 8 & 0xff] + _lut[d0 >> 16 & 0xff] + _lut[d0 >> 24 & 0xff] + '-' + _lut[d1 & 0xff] + _lut[d1 >> 8 & 0xff] + '-' + _lut[d1 >> 16 & 0x0f | 0x40] + _lut[d1 >> 24 & 0xff] + '-' + _lut[d2 & 0x3f | 0x80] + _lut[d2 >> 8 & 0xff] + '-' + _lut[d2 >> 16 & 0xff] + _lut[d2 >> 24 & 0xff] + _lut[d3 & 0xff] + _lut[d3 >> 8 & 0xff] + _lut[d3 >> 16 & 0xff] + _lut[d3 >> 24 & 0xff]; // .toUpperCase() here flattens concatenated strings to save heap memory space.
  1904. return uuid.toUpperCase();
  1905. },
  1906. clamp: function (value, min, max) {
  1907. return Math.max(min, Math.min(max, value));
  1908. },
  1909. // compute euclidian modulo of m % n
  1910. // https://en.wikipedia.org/wiki/Modulo_operation
  1911. euclideanModulo: function (n, m) {
  1912. return (n % m + m) % m;
  1913. },
  1914. // Linear mapping from range <a1, a2> to range <b1, b2>
  1915. mapLinear: function (x, a1, a2, b1, b2) {
  1916. return b1 + (x - a1) * (b2 - b1) / (a2 - a1);
  1917. },
  1918. // https://en.wikipedia.org/wiki/Linear_interpolation
  1919. lerp: function (x, y, t) {
  1920. return (1 - t) * x + t * y;
  1921. },
  1922. // http://en.wikipedia.org/wiki/Smoothstep
  1923. smoothstep: function (x, min, max) {
  1924. if (x <= min) return 0;
  1925. if (x >= max) return 1;
  1926. x = (x - min) / (max - min);
  1927. return x * x * (3 - 2 * x);
  1928. },
  1929. smootherstep: function (x, min, max) {
  1930. if (x <= min) return 0;
  1931. if (x >= max) return 1;
  1932. x = (x - min) / (max - min);
  1933. return x * x * x * (x * (x * 6 - 15) + 10);
  1934. },
  1935. // Random integer from <low, high> interval
  1936. randInt: function (low, high) {
  1937. return low + Math.floor(Math.random() * (high - low + 1));
  1938. },
  1939. // Random float from <low, high> interval
  1940. randFloat: function (low, high) {
  1941. return low + Math.random() * (high - low);
  1942. },
  1943. // Random float from <-range/2, range/2> interval
  1944. randFloatSpread: function (range) {
  1945. return range * (0.5 - Math.random());
  1946. },
  1947. degToRad: function (degrees) {
  1948. return degrees * _Math.DEG2RAD;
  1949. },
  1950. radToDeg: function (radians) {
  1951. return radians * _Math.RAD2DEG;
  1952. },
  1953. isPowerOfTwo: function (value) {
  1954. return (value & value - 1) === 0 && value !== 0;
  1955. },
  1956. ceilPowerOfTwo: function (value) {
  1957. return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
  1958. },
  1959. floorPowerOfTwo: function (value) {
  1960. return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
  1961. }
  1962. };
  1963. /**
  1964. * @author mrdoob / http://mrdoob.com/
  1965. * @author philogb / http://blog.thejit.org/
  1966. * @author egraether / http://egraether.com/
  1967. * @author zz85 / http://www.lab4games.net/zz85/blog
  1968. */
  1969. exports.Math = _Math;
  1970. function Vector2(x, y) {
  1971. this.x = x || 0;
  1972. this.y = y || 0;
  1973. }
  1974. Object.defineProperties(Vector2.prototype, {
  1975. "width": {
  1976. get: function () {
  1977. return this.x;
  1978. },
  1979. set: function (value) {
  1980. this.x = value;
  1981. }
  1982. },
  1983. "height": {
  1984. get: function () {
  1985. return this.y;
  1986. },
  1987. set: function (value) {
  1988. this.y = value;
  1989. }
  1990. }
  1991. });
  1992. Object.assign(Vector2.prototype, {
  1993. isVector2: true,
  1994. set: function (x, y) {
  1995. this.x = x;
  1996. this.y = y;
  1997. return this;
  1998. },
  1999. setScalar: function (scalar) {
  2000. this.x = scalar;
  2001. this.y = scalar;
  2002. return this;
  2003. },
  2004. setX: function (x) {
  2005. this.x = x;
  2006. return this;
  2007. },
  2008. setY: function (y) {
  2009. this.y = y;
  2010. return this;
  2011. },
  2012. setComponent: function (index, value) {
  2013. switch (index) {
  2014. case 0:
  2015. this.x = value;
  2016. break;
  2017. case 1:
  2018. this.y = value;
  2019. break;
  2020. default:
  2021. throw new Error('index is out of range: ' + index);
  2022. }
  2023. return this;
  2024. },
  2025. getComponent: function (index) {
  2026. switch (index) {
  2027. case 0:
  2028. return this.x;
  2029. case 1:
  2030. return this.y;
  2031. default:
  2032. throw new Error('index is out of range: ' + index);
  2033. }
  2034. },
  2035. clone: function () {
  2036. return new this.constructor(this.x, this.y);
  2037. },
  2038. copy: function (v) {
  2039. this.x = v.x;
  2040. this.y = v.y;
  2041. return this;
  2042. },
  2043. add: function (v, w) {
  2044. if (w !== undefined) {
  2045. console.warn('THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  2046. return this.addVectors(v, w);
  2047. }
  2048. this.x += v.x;
  2049. this.y += v.y;
  2050. return this;
  2051. },
  2052. addScalar: function (s) {
  2053. this.x += s;
  2054. this.y += s;
  2055. return this;
  2056. },
  2057. addVectors: function (a, b) {
  2058. this.x = a.x + b.x;
  2059. this.y = a.y + b.y;
  2060. return this;
  2061. },
  2062. addScaledVector: function (v, s) {
  2063. this.x += v.x * s;
  2064. this.y += v.y * s;
  2065. return this;
  2066. },
  2067. sub: function (v, w) {
  2068. if (w !== undefined) {
  2069. console.warn('THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  2070. return this.subVectors(v, w);
  2071. }
  2072. this.x -= v.x;
  2073. this.y -= v.y;
  2074. return this;
  2075. },
  2076. subScalar: function (s) {
  2077. this.x -= s;
  2078. this.y -= s;
  2079. return this;
  2080. },
  2081. subVectors: function (a, b) {
  2082. this.x = a.x - b.x;
  2083. this.y = a.y - b.y;
  2084. return this;
  2085. },
  2086. multiply: function (v) {
  2087. this.x *= v.x;
  2088. this.y *= v.y;
  2089. return this;
  2090. },
  2091. multiplyScalar: function (scalar) {
  2092. this.x *= scalar;
  2093. this.y *= scalar;
  2094. return this;
  2095. },
  2096. divide: function (v) {
  2097. this.x /= v.x;
  2098. this.y /= v.y;
  2099. return this;
  2100. },
  2101. divideScalar: function (scalar) {
  2102. return this.multiplyScalar(1 / scalar);
  2103. },
  2104. applyMatrix3: function (m) {
  2105. var x = this.x,
  2106. y = this.y;
  2107. var e = m.elements;
  2108. this.x = e[0] * x + e[3] * y + e[6];
  2109. this.y = e[1] * x + e[4] * y + e[7];
  2110. return this;
  2111. },
  2112. min: function (v) {
  2113. this.x = Math.min(this.x, v.x);
  2114. this.y = Math.min(this.y, v.y);
  2115. return this;
  2116. },
  2117. max: function (v) {
  2118. this.x = Math.max(this.x, v.x);
  2119. this.y = Math.max(this.y, v.y);
  2120. return this;
  2121. },
  2122. clamp: function (min, max) {
  2123. // assumes min < max, componentwise
  2124. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2125. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2126. return this;
  2127. },
  2128. clampScalar: function (minVal, maxVal) {
  2129. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2130. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2131. return this;
  2132. },
  2133. clampLength: function (min, max) {
  2134. var length = this.length();
  2135. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2136. },
  2137. floor: function () {
  2138. this.x = Math.floor(this.x);
  2139. this.y = Math.floor(this.y);
  2140. return this;
  2141. },
  2142. ceil: function () {
  2143. this.x = Math.ceil(this.x);
  2144. this.y = Math.ceil(this.y);
  2145. return this;
  2146. },
  2147. round: function () {
  2148. this.x = Math.round(this.x);
  2149. this.y = Math.round(this.y);
  2150. return this;
  2151. },
  2152. roundToZero: function () {
  2153. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2154. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2155. return this;
  2156. },
  2157. negate: function () {
  2158. this.x = -this.x;
  2159. this.y = -this.y;
  2160. return this;
  2161. },
  2162. dot: function (v) {
  2163. return this.x * v.x + this.y * v.y;
  2164. },
  2165. cross: function (v) {
  2166. return this.x * v.y - this.y * v.x;
  2167. },
  2168. lengthSq: function () {
  2169. return this.x * this.x + this.y * this.y;
  2170. },
  2171. length: function () {
  2172. return Math.sqrt(this.x * this.x + this.y * this.y);
  2173. },
  2174. manhattanLength: function () {
  2175. return Math.abs(this.x) + Math.abs(this.y);
  2176. },
  2177. normalize: function () {
  2178. return this.divideScalar(this.length() || 1);
  2179. },
  2180. angle: function () {
  2181. // computes the angle in radians with respect to the positive x-axis
  2182. var angle = Math.atan2(this.y, this.x);
  2183. if (angle < 0) angle += 2 * Math.PI;
  2184. return angle;
  2185. },
  2186. distanceTo: function (v) {
  2187. return Math.sqrt(this.distanceToSquared(v));
  2188. },
  2189. distanceToSquared: function (v) {
  2190. var dx = this.x - v.x,
  2191. dy = this.y - v.y;
  2192. return dx * dx + dy * dy;
  2193. },
  2194. manhattanDistanceTo: function (v) {
  2195. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
  2196. },
  2197. setLength: function (length) {
  2198. return this.normalize().multiplyScalar(length);
  2199. },
  2200. lerp: function (v, alpha) {
  2201. this.x += (v.x - this.x) * alpha;
  2202. this.y += (v.y - this.y) * alpha;
  2203. return this;
  2204. },
  2205. lerpVectors: function (v1, v2, alpha) {
  2206. return this.subVectors(v2, v1).multiplyScalar(alpha).add(v1);
  2207. },
  2208. equals: function (v) {
  2209. return v.x === this.x && v.y === this.y;
  2210. },
  2211. fromArray: function (array, offset) {
  2212. if (offset === undefined) offset = 0;
  2213. this.x = array[offset];
  2214. this.y = array[offset + 1];
  2215. return this;
  2216. },
  2217. toArray: function (array, offset) {
  2218. if (array === undefined) array = [];
  2219. if (offset === undefined) offset = 0;
  2220. array[offset] = this.x;
  2221. array[offset + 1] = this.y;
  2222. return array;
  2223. },
  2224. fromBufferAttribute: function (attribute, index, offset) {
  2225. if (offset !== undefined) {
  2226. console.warn('THREE.Vector2: offset has been removed from .fromBufferAttribute().');
  2227. }
  2228. this.x = attribute.getX(index);
  2229. this.y = attribute.getY(index);
  2230. return this;
  2231. },
  2232. rotateAround: function (center, angle) {
  2233. var c = Math.cos(angle),
  2234. s = Math.sin(angle);
  2235. var x = this.x - center.x;
  2236. var y = this.y - center.y;
  2237. this.x = x * c - y * s + center.x;
  2238. this.y = x * s + y * c + center.y;
  2239. return this;
  2240. }
  2241. });
  2242. /**
  2243. * @author mikael emtinger / http://gomo.se/
  2244. * @author alteredq / http://alteredqualia.com/
  2245. * @author WestLangley / http://github.com/WestLangley
  2246. * @author bhouston / http://clara.io
  2247. */
  2248. function Quaternion(x, y, z, w) {
  2249. this._x = x || 0;
  2250. this._y = y || 0;
  2251. this._z = z || 0;
  2252. this._w = w !== undefined ? w : 1;
  2253. }
  2254. Object.assign(Quaternion, {
  2255. slerp: function (qa, qb, qm, t) {
  2256. return qm.copy(qa).slerp(qb, t);
  2257. },
  2258. slerpFlat: function (dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
  2259. // fuzz-free, array-based Quaternion SLERP operation
  2260. var x0 = src0[srcOffset0 + 0],
  2261. y0 = src0[srcOffset0 + 1],
  2262. z0 = src0[srcOffset0 + 2],
  2263. w0 = src0[srcOffset0 + 3],
  2264. x1 = src1[srcOffset1 + 0],
  2265. y1 = src1[srcOffset1 + 1],
  2266. z1 = src1[srcOffset1 + 2],
  2267. w1 = src1[srcOffset1 + 3];
  2268. if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
  2269. var s = 1 - t,
  2270. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2271. dir = cos >= 0 ? 1 : -1,
  2272. sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems:
  2273. if (sqrSin > Number.EPSILON) {
  2274. var sin = Math.sqrt(sqrSin),
  2275. len = Math.atan2(sin, cos * dir);
  2276. s = Math.sin(s * len) / sin;
  2277. t = Math.sin(t * len) / sin;
  2278. }
  2279. var tDir = t * dir;
  2280. x0 = x0 * s + x1 * tDir;
  2281. y0 = y0 * s + y1 * tDir;
  2282. z0 = z0 * s + z1 * tDir;
  2283. w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp:
  2284. if (s === 1 - t) {
  2285. var f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
  2286. x0 *= f;
  2287. y0 *= f;
  2288. z0 *= f;
  2289. w0 *= f;
  2290. }
  2291. }
  2292. dst[dstOffset] = x0;
  2293. dst[dstOffset + 1] = y0;
  2294. dst[dstOffset + 2] = z0;
  2295. dst[dstOffset + 3] = w0;
  2296. }
  2297. });
  2298. Object.defineProperties(Quaternion.prototype, {
  2299. x: {
  2300. get: function () {
  2301. return this._x;
  2302. },
  2303. set: function (value) {
  2304. this._x = value;
  2305. this._onChangeCallback();
  2306. }
  2307. },
  2308. y: {
  2309. get: function () {
  2310. return this._y;
  2311. },
  2312. set: function (value) {
  2313. this._y = value;
  2314. this._onChangeCallback();
  2315. }
  2316. },
  2317. z: {
  2318. get: function () {
  2319. return this._z;
  2320. },
  2321. set: function (value) {
  2322. this._z = value;
  2323. this._onChangeCallback();
  2324. }
  2325. },
  2326. w: {
  2327. get: function () {
  2328. return this._w;
  2329. },
  2330. set: function (value) {
  2331. this._w = value;
  2332. this._onChangeCallback();
  2333. }
  2334. }
  2335. });
  2336. Object.assign(Quaternion.prototype, {
  2337. isQuaternion: true,
  2338. set: function (x, y, z, w) {
  2339. this._x = x;
  2340. this._y = y;
  2341. this._z = z;
  2342. this._w = w;
  2343. this._onChangeCallback();
  2344. return this;
  2345. },
  2346. clone: function () {
  2347. return new this.constructor(this._x, this._y, this._z, this._w);
  2348. },
  2349. copy: function (quaternion) {
  2350. this._x = quaternion.x;
  2351. this._y = quaternion.y;
  2352. this._z = quaternion.z;
  2353. this._w = quaternion.w;
  2354. this._onChangeCallback();
  2355. return this;
  2356. },
  2357. setFromEuler: function (euler, update) {
  2358. if (!(euler && euler.isEuler)) {
  2359. throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');
  2360. }
  2361. var x = euler._x,
  2362. y = euler._y,
  2363. z = euler._z,
  2364. order = euler.order; // http://www.mathworks.com/matlabcentral/fileexchange/
  2365. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2366. // content/SpinCalc.m
  2367. var cos = Math.cos;
  2368. var sin = Math.sin;
  2369. var c1 = cos(x / 2);
  2370. var c2 = cos(y / 2);
  2371. var c3 = cos(z / 2);
  2372. var s1 = sin(x / 2);
  2373. var s2 = sin(y / 2);
  2374. var s3 = sin(z / 2);
  2375. if (order === 'XYZ') {
  2376. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2377. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2378. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2379. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2380. } else if (order === 'YXZ') {
  2381. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2382. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2383. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2384. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2385. } else if (order === 'ZXY') {
  2386. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2387. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2388. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2389. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2390. } else if (order === 'ZYX') {
  2391. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2392. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2393. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2394. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2395. } else if (order === 'YZX') {
  2396. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2397. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2398. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2399. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2400. } else if (order === 'XZY') {
  2401. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2402. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2403. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2404. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2405. }
  2406. if (update !== false) this._onChangeCallback();
  2407. return this;
  2408. },
  2409. setFromAxisAngle: function (axis, angle) {
  2410. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2411. // assumes axis is normalized
  2412. var halfAngle = angle / 2,
  2413. s = Math.sin(halfAngle);
  2414. this._x = axis.x * s;
  2415. this._y = axis.y * s;
  2416. this._z = axis.z * s;
  2417. this._w = Math.cos(halfAngle);
  2418. this._onChangeCallback();
  2419. return this;
  2420. },
  2421. setFromRotationMatrix: function (m) {
  2422. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2423. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2424. var te = m.elements,
  2425. m11 = te[0],
  2426. m12 = te[4],
  2427. m13 = te[8],
  2428. m21 = te[1],
  2429. m22 = te[5],
  2430. m23 = te[9],
  2431. m31 = te[2],
  2432. m32 = te[6],
  2433. m33 = te[10],
  2434. trace = m11 + m22 + m33,
  2435. s;
  2436. if (trace > 0) {
  2437. s = 0.5 / Math.sqrt(trace + 1.0);
  2438. this._w = 0.25 / s;
  2439. this._x = (m32 - m23) * s;
  2440. this._y = (m13 - m31) * s;
  2441. this._z = (m21 - m12) * s;
  2442. } else if (m11 > m22 && m11 > m33) {
  2443. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2444. this._w = (m32 - m23) / s;
  2445. this._x = 0.25 * s;
  2446. this._y = (m12 + m21) / s;
  2447. this._z = (m13 + m31) / s;
  2448. } else if (m22 > m33) {
  2449. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2450. this._w = (m13 - m31) / s;
  2451. this._x = (m12 + m21) / s;
  2452. this._y = 0.25 * s;
  2453. this._z = (m23 + m32) / s;
  2454. } else {
  2455. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2456. this._w = (m21 - m12) / s;
  2457. this._x = (m13 + m31) / s;
  2458. this._y = (m23 + m32) / s;
  2459. this._z = 0.25 * s;
  2460. }
  2461. this._onChangeCallback();
  2462. return this;
  2463. },
  2464. setFromUnitVectors: function (vFrom, vTo) {
  2465. // assumes direction vectors vFrom and vTo are normalized
  2466. var EPS = 0.000001;
  2467. var r = vFrom.dot(vTo) + 1;
  2468. if (r < EPS) {
  2469. r = 0;
  2470. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  2471. this._x = -vFrom.y;
  2472. this._y = vFrom.x;
  2473. this._z = 0;
  2474. this._w = r;
  2475. } else {
  2476. this._x = 0;
  2477. this._y = -vFrom.z;
  2478. this._z = vFrom.y;
  2479. this._w = r;
  2480. }
  2481. } else {
  2482. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2483. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2484. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2485. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2486. this._w = r;
  2487. }
  2488. return this.normalize();
  2489. },
  2490. angleTo: function (q) {
  2491. return 2 * Math.acos(Math.abs(_Math.clamp(this.dot(q), -1, 1)));
  2492. },
  2493. rotateTowards: function (q, step) {
  2494. var angle = this.angleTo(q);
  2495. if (angle === 0) return this;
  2496. var t = Math.min(1, step / angle);
  2497. this.slerp(q, t);
  2498. return this;
  2499. },
  2500. inverse: function () {
  2501. // quaternion is assumed to have unit length
  2502. return this.conjugate();
  2503. },
  2504. conjugate: function () {
  2505. this._x *= -1;
  2506. this._y *= -1;
  2507. this._z *= -1;
  2508. this._onChangeCallback();
  2509. return this;
  2510. },
  2511. dot: function (v) {
  2512. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2513. },
  2514. lengthSq: function () {
  2515. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2516. },
  2517. length: function () {
  2518. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  2519. },
  2520. normalize: function () {
  2521. var l = this.length();
  2522. if (l === 0) {
  2523. this._x = 0;
  2524. this._y = 0;
  2525. this._z = 0;
  2526. this._w = 1;
  2527. } else {
  2528. l = 1 / l;
  2529. this._x = this._x * l;
  2530. this._y = this._y * l;
  2531. this._z = this._z * l;
  2532. this._w = this._w * l;
  2533. }
  2534. this._onChangeCallback();
  2535. return this;
  2536. },
  2537. multiply: function (q, p) {
  2538. if (p !== undefined) {
  2539. console.warn('THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.');
  2540. return this.multiplyQuaternions(q, p);
  2541. }
  2542. return this.multiplyQuaternions(this, q);
  2543. },
  2544. premultiply: function (q) {
  2545. return this.multiplyQuaternions(q, this);
  2546. },
  2547. multiplyQuaternions: function (a, b) {
  2548. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2549. var qax = a._x,
  2550. qay = a._y,
  2551. qaz = a._z,
  2552. qaw = a._w;
  2553. var qbx = b._x,
  2554. qby = b._y,
  2555. qbz = b._z,
  2556. qbw = b._w;
  2557. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2558. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2559. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2560. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2561. this._onChangeCallback();
  2562. return this;
  2563. },
  2564. slerp: function (qb, t) {
  2565. if (t === 0) return this;
  2566. if (t === 1) return this.copy(qb);
  2567. var x = this._x,
  2568. y = this._y,
  2569. z = this._z,
  2570. w = this._w; // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2571. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2572. if (cosHalfTheta < 0) {
  2573. this._w = -qb._w;
  2574. this._x = -qb._x;
  2575. this._y = -qb._y;
  2576. this._z = -qb._z;
  2577. cosHalfTheta = -cosHalfTheta;
  2578. } else {
  2579. this.copy(qb);
  2580. }
  2581. if (cosHalfTheta >= 1.0) {
  2582. this._w = w;
  2583. this._x = x;
  2584. this._y = y;
  2585. this._z = z;
  2586. return this;
  2587. }
  2588. var sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2589. if (sqrSinHalfTheta <= Number.EPSILON) {
  2590. var s = 1 - t;
  2591. this._w = s * w + t * this._w;
  2592. this._x = s * x + t * this._x;
  2593. this._y = s * y + t * this._y;
  2594. this._z = s * z + t * this._z;
  2595. this.normalize();
  2596. this._onChangeCallback();
  2597. return this;
  2598. }
  2599. var sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
  2600. var halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
  2601. var ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  2602. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  2603. this._w = w * ratioA + this._w * ratioB;
  2604. this._x = x * ratioA + this._x * ratioB;
  2605. this._y = y * ratioA + this._y * ratioB;
  2606. this._z = z * ratioA + this._z * ratioB;
  2607. this._onChangeCallback();
  2608. return this;
  2609. },
  2610. equals: function (quaternion) {
  2611. return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
  2612. },
  2613. fromArray: function (array, offset) {
  2614. if (offset === undefined) offset = 0;
  2615. this._x = array[offset];
  2616. this._y = array[offset + 1];
  2617. this._z = array[offset + 2];
  2618. this._w = array[offset + 3];
  2619. this._onChangeCallback();
  2620. return this;
  2621. },
  2622. toArray: function (array, offset) {
  2623. if (array === undefined) array = [];
  2624. if (offset === undefined) offset = 0;
  2625. array[offset] = this._x;
  2626. array[offset + 1] = this._y;
  2627. array[offset + 2] = this._z;
  2628. array[offset + 3] = this._w;
  2629. return array;
  2630. },
  2631. _onChange: function (callback) {
  2632. this._onChangeCallback = callback;
  2633. return this;
  2634. },
  2635. _onChangeCallback: function () {}
  2636. });
  2637. /**
  2638. * @author mrdoob / http://mrdoob.com/
  2639. * @author kile / http://kile.stravaganza.org/
  2640. * @author philogb / http://blog.thejit.org/
  2641. * @author mikael emtinger / http://gomo.se/
  2642. * @author egraether / http://egraether.com/
  2643. * @author WestLangley / http://github.com/WestLangley
  2644. */
  2645. var _vector = new Vector3();
  2646. var _quaternion = new Quaternion();
  2647. function Vector3(x, y, z) {
  2648. this.x = x || 0;
  2649. this.y = y || 0;
  2650. this.z = z || 0;
  2651. }
  2652. Object.assign(Vector3.prototype, {
  2653. isVector3: true,
  2654. set: function (x, y, z) {
  2655. this.x = x;
  2656. this.y = y;
  2657. this.z = z;
  2658. return this;
  2659. },
  2660. setScalar: function (scalar) {
  2661. this.x = scalar;
  2662. this.y = scalar;
  2663. this.z = scalar;
  2664. return this;
  2665. },
  2666. setX: function (x) {
  2667. this.x = x;
  2668. return this;
  2669. },
  2670. setY: function (y) {
  2671. this.y = y;
  2672. return this;
  2673. },
  2674. setZ: function (z) {
  2675. this.z = z;
  2676. return this;
  2677. },
  2678. setComponent: function (index, value) {
  2679. switch (index) {
  2680. case 0:
  2681. this.x = value;
  2682. break;
  2683. case 1:
  2684. this.y = value;
  2685. break;
  2686. case 2:
  2687. this.z = value;
  2688. break;
  2689. default:
  2690. throw new Error('index is out of range: ' + index);
  2691. }
  2692. return this;
  2693. },
  2694. getComponent: function (index) {
  2695. switch (index) {
  2696. case 0:
  2697. return this.x;
  2698. case 1:
  2699. return this.y;
  2700. case 2:
  2701. return this.z;
  2702. default:
  2703. throw new Error('index is out of range: ' + index);
  2704. }
  2705. },
  2706. clone: function () {
  2707. return new this.constructor(this.x, this.y, this.z);
  2708. },
  2709. copy: function (v) {
  2710. this.x = v.x;
  2711. this.y = v.y;
  2712. this.z = v.z;
  2713. return this;
  2714. },
  2715. add: function (v, w) {
  2716. if (w !== undefined) {
  2717. console.warn('THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  2718. return this.addVectors(v, w);
  2719. }
  2720. this.x += v.x;
  2721. this.y += v.y;
  2722. this.z += v.z;
  2723. return this;
  2724. },
  2725. addScalar: function (s) {
  2726. this.x += s;
  2727. this.y += s;
  2728. this.z += s;
  2729. return this;
  2730. },
  2731. addVectors: function (a, b) {
  2732. this.x = a.x + b.x;
  2733. this.y = a.y + b.y;
  2734. this.z = a.z + b.z;
  2735. return this;
  2736. },
  2737. addScaledVector: function (v, s) {
  2738. this.x += v.x * s;
  2739. this.y += v.y * s;
  2740. this.z += v.z * s;
  2741. return this;
  2742. },
  2743. sub: function (v, w) {
  2744. if (w !== undefined) {
  2745. console.warn('THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  2746. return this.subVectors(v, w);
  2747. }
  2748. this.x -= v.x;
  2749. this.y -= v.y;
  2750. this.z -= v.z;
  2751. return this;
  2752. },
  2753. subScalar: function (s) {
  2754. this.x -= s;
  2755. this.y -= s;
  2756. this.z -= s;
  2757. return this;
  2758. },
  2759. subVectors: function (a, b) {
  2760. this.x = a.x - b.x;
  2761. this.y = a.y - b.y;
  2762. this.z = a.z - b.z;
  2763. return this;
  2764. },
  2765. multiply: function (v, w) {
  2766. if (w !== undefined) {
  2767. console.warn('THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.');
  2768. return this.multiplyVectors(v, w);
  2769. }
  2770. this.x *= v.x;
  2771. this.y *= v.y;
  2772. this.z *= v.z;
  2773. return this;
  2774. },
  2775. multiplyScalar: function (scalar) {
  2776. this.x *= scalar;
  2777. this.y *= scalar;
  2778. this.z *= scalar;
  2779. return this;
  2780. },
  2781. multiplyVectors: function (a, b) {
  2782. this.x = a.x * b.x;
  2783. this.y = a.y * b.y;
  2784. this.z = a.z * b.z;
  2785. return this;
  2786. },
  2787. applyEuler: function (euler) {
  2788. if (!(euler && euler.isEuler)) {
  2789. console.error('THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.');
  2790. }
  2791. return this.applyQuaternion(_quaternion.setFromEuler(euler));
  2792. },
  2793. applyAxisAngle: function (axis, angle) {
  2794. return this.applyQuaternion(_quaternion.setFromAxisAngle(axis, angle));
  2795. },
  2796. applyMatrix3: function (m) {
  2797. var x = this.x,
  2798. y = this.y,
  2799. z = this.z;
  2800. var e = m.elements;
  2801. this.x = e[0] * x + e[3] * y + e[6] * z;
  2802. this.y = e[1] * x + e[4] * y + e[7] * z;
  2803. this.z = e[2] * x + e[5] * y + e[8] * z;
  2804. return this;
  2805. },
  2806. applyMatrix4: function (m) {
  2807. var x = this.x,
  2808. y = this.y,
  2809. z = this.z;
  2810. var e = m.elements;
  2811. var w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
  2812. this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
  2813. this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
  2814. this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
  2815. return this;
  2816. },
  2817. applyQuaternion: function (q) {
  2818. var x = this.x,
  2819. y = this.y,
  2820. z = this.z;
  2821. var qx = q.x,
  2822. qy = q.y,
  2823. qz = q.z,
  2824. qw = q.w; // calculate quat * vector
  2825. var ix = qw * x + qy * z - qz * y;
  2826. var iy = qw * y + qz * x - qx * z;
  2827. var iz = qw * z + qx * y - qy * x;
  2828. var iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  2829. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2830. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2831. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2832. return this;
  2833. },
  2834. project: function (camera) {
  2835. return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
  2836. },
  2837. unproject: function (camera) {
  2838. return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
  2839. },
  2840. transformDirection: function (m) {
  2841. // input: THREE.Matrix4 affine matrix
  2842. // vector interpreted as a direction
  2843. var x = this.x,
  2844. y = this.y,
  2845. z = this.z;
  2846. var e = m.elements;
  2847. this.x = e[0] * x + e[4] * y + e[8] * z;
  2848. this.y = e[1] * x + e[5] * y + e[9] * z;
  2849. this.z = e[2] * x + e[6] * y + e[10] * z;
  2850. return this.normalize();
  2851. },
  2852. divide: function (v) {
  2853. this.x /= v.x;
  2854. this.y /= v.y;
  2855. this.z /= v.z;
  2856. return this;
  2857. },
  2858. divideScalar: function (scalar) {
  2859. return this.multiplyScalar(1 / scalar);
  2860. },
  2861. min: function (v) {
  2862. this.x = Math.min(this.x, v.x);
  2863. this.y = Math.min(this.y, v.y);
  2864. this.z = Math.min(this.z, v.z);
  2865. return this;
  2866. },
  2867. max: function (v) {
  2868. this.x = Math.max(this.x, v.x);
  2869. this.y = Math.max(this.y, v.y);
  2870. this.z = Math.max(this.z, v.z);
  2871. return this;
  2872. },
  2873. clamp: function (min, max) {
  2874. // assumes min < max, componentwise
  2875. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2876. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2877. this.z = Math.max(min.z, Math.min(max.z, this.z));
  2878. return this;
  2879. },
  2880. clampScalar: function (minVal, maxVal) {
  2881. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2882. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2883. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  2884. return this;
  2885. },
  2886. clampLength: function (min, max) {
  2887. var length = this.length();
  2888. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2889. },
  2890. floor: function () {
  2891. this.x = Math.floor(this.x);
  2892. this.y = Math.floor(this.y);
  2893. this.z = Math.floor(this.z);
  2894. return this;
  2895. },
  2896. ceil: function () {
  2897. this.x = Math.ceil(this.x);
  2898. this.y = Math.ceil(this.y);
  2899. this.z = Math.ceil(this.z);
  2900. return this;
  2901. },
  2902. round: function () {
  2903. this.x = Math.round(this.x);
  2904. this.y = Math.round(this.y);
  2905. this.z = Math.round(this.z);
  2906. return this;
  2907. },
  2908. roundToZero: function () {
  2909. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2910. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2911. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  2912. return this;
  2913. },
  2914. negate: function () {
  2915. this.x = -this.x;
  2916. this.y = -this.y;
  2917. this.z = -this.z;
  2918. return this;
  2919. },
  2920. dot: function (v) {
  2921. return this.x * v.x + this.y * v.y + this.z * v.z;
  2922. },
  2923. // TODO lengthSquared?
  2924. lengthSq: function () {
  2925. return this.x * this.x + this.y * this.y + this.z * this.z;
  2926. },
  2927. length: function () {
  2928. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2929. },
  2930. manhattanLength: function () {
  2931. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  2932. },
  2933. normalize: function () {
  2934. return this.divideScalar(this.length() || 1);
  2935. },
  2936. setLength: function (length) {
  2937. return this.normalize().multiplyScalar(length);
  2938. },
  2939. lerp: function (v, alpha) {
  2940. this.x += (v.x - this.x) * alpha;
  2941. this.y += (v.y - this.y) * alpha;
  2942. this.z += (v.z - this.z) * alpha;
  2943. return this;
  2944. },
  2945. lerpVectors: function (v1, v2, alpha) {
  2946. return this.subVectors(v2, v1).multiplyScalar(alpha).add(v1);
  2947. },
  2948. cross: function (v, w) {
  2949. if (w !== undefined) {
  2950. console.warn('THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.');
  2951. return this.crossVectors(v, w);
  2952. }
  2953. return this.crossVectors(this, v);
  2954. },
  2955. crossVectors: function (a, b) {
  2956. var ax = a.x,
  2957. ay = a.y,
  2958. az = a.z;
  2959. var bx = b.x,
  2960. by = b.y,
  2961. bz = b.z;
  2962. this.x = ay * bz - az * by;
  2963. this.y = az * bx - ax * bz;
  2964. this.z = ax * by - ay * bx;
  2965. return this;
  2966. },
  2967. projectOnVector: function (v) {
  2968. // v cannot be the zero v
  2969. var scalar = v.dot(this) / v.lengthSq();
  2970. return this.copy(v).multiplyScalar(scalar);
  2971. },
  2972. projectOnPlane: function (planeNormal) {
  2973. _vector.copy(this).projectOnVector(planeNormal);
  2974. return this.sub(_vector);
  2975. },
  2976. reflect: function (normal) {
  2977. // reflect incident vector off plane orthogonal to normal
  2978. // normal is assumed to have unit length
  2979. return this.sub(_vector.copy(normal).multiplyScalar(2 * this.dot(normal)));
  2980. },
  2981. angleTo: function (v) {
  2982. var denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
  2983. if (denominator === 0) console.error('THREE.Vector3: angleTo() can\'t handle zero length vectors.');
  2984. var theta = this.dot(v) / denominator; // clamp, to handle numerical problems
  2985. return Math.acos(_Math.clamp(theta, -1, 1));
  2986. },
  2987. distanceTo: function (v) {
  2988. return Math.sqrt(this.distanceToSquared(v));
  2989. },
  2990. distanceToSquared: function (v) {
  2991. var dx = this.x - v.x,
  2992. dy = this.y - v.y,
  2993. dz = this.z - v.z;
  2994. return dx * dx + dy * dy + dz * dz;
  2995. },
  2996. manhattanDistanceTo: function (v) {
  2997. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
  2998. },
  2999. setFromSpherical: function (s) {
  3000. return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
  3001. },
  3002. setFromSphericalCoords: function (radius, phi, theta) {
  3003. var sinPhiRadius = Math.sin(phi) * radius;
  3004. this.x = sinPhiRadius * Math.sin(theta);
  3005. this.y = Math.cos(phi) * radius;
  3006. this.z = sinPhiRadius * Math.cos(theta);
  3007. return this;
  3008. },
  3009. setFromCylindrical: function (c) {
  3010. return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
  3011. },
  3012. setFromCylindricalCoords: function (radius, theta, y) {
  3013. this.x = radius * Math.sin(theta);
  3014. this.y = y;
  3015. this.z = radius * Math.cos(theta);
  3016. return this;
  3017. },
  3018. setFromMatrixPosition: function (m) {
  3019. var e = m.elements;
  3020. this.x = e[12];
  3021. this.y = e[13];
  3022. this.z = e[14];
  3023. return this;
  3024. },
  3025. setFromMatrixScale: function (m) {
  3026. var sx = this.setFromMatrixColumn(m, 0).length();
  3027. var sy = this.setFromMatrixColumn(m, 1).length();
  3028. var sz = this.setFromMatrixColumn(m, 2).length();
  3029. this.x = sx;
  3030. this.y = sy;
  3031. this.z = sz;
  3032. return this;
  3033. },
  3034. setFromMatrixColumn: function (m, index) {
  3035. return this.fromArray(m.elements, index * 4);
  3036. },
  3037. equals: function (v) {
  3038. return v.x === this.x && v.y === this.y && v.z === this.z;
  3039. },
  3040. fromArray: function (array, offset) {
  3041. if (offset === undefined) offset = 0;
  3042. this.x = array[offset];
  3043. this.y = array[offset + 1];
  3044. this.z = array[offset + 2];
  3045. return this;
  3046. },
  3047. toArray: function (array, offset) {
  3048. if (array === undefined) array = [];
  3049. if (offset === undefined) offset = 0;
  3050. array[offset] = this.x;
  3051. array[offset + 1] = this.y;
  3052. array[offset + 2] = this.z;
  3053. return array;
  3054. },
  3055. fromBufferAttribute: function (attribute, index, offset) {
  3056. if (offset !== undefined) {
  3057. console.warn('THREE.Vector3: offset has been removed from .fromBufferAttribute().');
  3058. }
  3059. this.x = attribute.getX(index);
  3060. this.y = attribute.getY(index);
  3061. this.z = attribute.getZ(index);
  3062. return this;
  3063. }
  3064. });
  3065. /**
  3066. * @author alteredq / http://alteredqualia.com/
  3067. * @author WestLangley / http://github.com/WestLangley
  3068. * @author bhouston / http://clara.io
  3069. * @author tschw
  3070. */
  3071. var _vector$1 = new Vector3();
  3072. function Matrix3() {
  3073. this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  3074. if (arguments.length > 0) {
  3075. console.error('THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.');
  3076. }
  3077. }
  3078. Object.assign(Matrix3.prototype, {
  3079. isMatrix3: true,
  3080. set: function (n11, n12, n13, n21, n22, n23, n31, n32, n33) {
  3081. var te = this.elements;
  3082. te[0] = n11;
  3083. te[1] = n21;
  3084. te[2] = n31;
  3085. te[3] = n12;
  3086. te[4] = n22;
  3087. te[5] = n32;
  3088. te[6] = n13;
  3089. te[7] = n23;
  3090. te[8] = n33;
  3091. return this;
  3092. },
  3093. identity: function () {
  3094. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  3095. return this;
  3096. },
  3097. clone: function () {
  3098. return new this.constructor().fromArray(this.elements);
  3099. },
  3100. copy: function (m) {
  3101. var te = this.elements;
  3102. var me = m.elements;
  3103. te[0] = me[0];
  3104. te[1] = me[1];
  3105. te[2] = me[2];
  3106. te[3] = me[3];
  3107. te[4] = me[4];
  3108. te[5] = me[5];
  3109. te[6] = me[6];
  3110. te[7] = me[7];
  3111. te[8] = me[8];
  3112. return this;
  3113. },
  3114. setFromMatrix4: function (m) {
  3115. var me = m.elements;
  3116. this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]);
  3117. return this;
  3118. },
  3119. applyToBufferAttribute: function (attribute) {
  3120. for (var i = 0, l = attribute.count; i < l; i++) {
  3121. _vector$1.x = attribute.getX(i);
  3122. _vector$1.y = attribute.getY(i);
  3123. _vector$1.z = attribute.getZ(i);
  3124. _vector$1.applyMatrix3(this);
  3125. attribute.setXYZ(i, _vector$1.x, _vector$1.y, _vector$1.z);
  3126. }
  3127. return attribute;
  3128. },
  3129. multiply: function (m) {
  3130. return this.multiplyMatrices(this, m);
  3131. },
  3132. premultiply: function (m) {
  3133. return this.multiplyMatrices(m, this);
  3134. },
  3135. multiplyMatrices: function (a, b) {
  3136. var ae = a.elements;
  3137. var be = b.elements;
  3138. var te = this.elements;
  3139. var a11 = ae[0],
  3140. a12 = ae[3],
  3141. a13 = ae[6];
  3142. var a21 = ae[1],
  3143. a22 = ae[4],
  3144. a23 = ae[7];
  3145. var a31 = ae[2],
  3146. a32 = ae[5],
  3147. a33 = ae[8];
  3148. var b11 = be[0],
  3149. b12 = be[3],
  3150. b13 = be[6];
  3151. var b21 = be[1],
  3152. b22 = be[4],
  3153. b23 = be[7];
  3154. var b31 = be[2],
  3155. b32 = be[5],
  3156. b33 = be[8];
  3157. te[0] = a11 * b11 + a12 * b21 + a13 * b31;
  3158. te[3] = a11 * b12 + a12 * b22 + a13 * b32;
  3159. te[6] = a11 * b13 + a12 * b23 + a13 * b33;
  3160. te[1] = a21 * b11 + a22 * b21 + a23 * b31;
  3161. te[4] = a21 * b12 + a22 * b22 + a23 * b32;
  3162. te[7] = a21 * b13 + a22 * b23 + a23 * b33;
  3163. te[2] = a31 * b11 + a32 * b21 + a33 * b31;
  3164. te[5] = a31 * b12 + a32 * b22 + a33 * b32;
  3165. te[8] = a31 * b13 + a32 * b23 + a33 * b33;
  3166. return this;
  3167. },
  3168. multiplyScalar: function (s) {
  3169. var te = this.elements;
  3170. te[0] *= s;
  3171. te[3] *= s;
  3172. te[6] *= s;
  3173. te[1] *= s;
  3174. te[4] *= s;
  3175. te[7] *= s;
  3176. te[2] *= s;
  3177. te[5] *= s;
  3178. te[8] *= s;
  3179. return this;
  3180. },
  3181. determinant: function () {
  3182. var te = this.elements;
  3183. var a = te[0],
  3184. b = te[1],
  3185. c = te[2],
  3186. d = te[3],
  3187. e = te[4],
  3188. f = te[5],
  3189. g = te[6],
  3190. h = te[7],
  3191. i = te[8];
  3192. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  3193. },
  3194. getInverse: function (matrix, throwOnDegenerate) {
  3195. if (matrix && matrix.isMatrix4) {
  3196. console.error("THREE.Matrix3: .getInverse() no longer takes a Matrix4 argument.");
  3197. }
  3198. var me = matrix.elements,
  3199. te = this.elements,
  3200. n11 = me[0],
  3201. n21 = me[1],
  3202. n31 = me[2],
  3203. n12 = me[3],
  3204. n22 = me[4],
  3205. n32 = me[5],
  3206. n13 = me[6],
  3207. n23 = me[7],
  3208. n33 = me[8],
  3209. t11 = n33 * n22 - n32 * n23,
  3210. t12 = n32 * n13 - n33 * n12,
  3211. t13 = n23 * n12 - n22 * n13,
  3212. det = n11 * t11 + n21 * t12 + n31 * t13;
  3213. if (det === 0) {
  3214. var msg = "THREE.Matrix3: .getInverse() can't invert matrix, determinant is 0";
  3215. if (throwOnDegenerate === true) {
  3216. throw new Error(msg);
  3217. } else {
  3218. console.warn(msg);
  3219. }
  3220. return this.identity();
  3221. }
  3222. var detInv = 1 / det;
  3223. te[0] = t11 * detInv;
  3224. te[1] = (n31 * n23 - n33 * n21) * detInv;
  3225. te[2] = (n32 * n21 - n31 * n22) * detInv;
  3226. te[3] = t12 * detInv;
  3227. te[4] = (n33 * n11 - n31 * n13) * detInv;
  3228. te[5] = (n31 * n12 - n32 * n11) * detInv;
  3229. te[6] = t13 * detInv;
  3230. te[7] = (n21 * n13 - n23 * n11) * detInv;
  3231. te[8] = (n22 * n11 - n21 * n12) * detInv;
  3232. return this;
  3233. },
  3234. transpose: function () {
  3235. var tmp,
  3236. m = this.elements;
  3237. tmp = m[1];
  3238. m[1] = m[3];
  3239. m[3] = tmp;
  3240. tmp = m[2];
  3241. m[2] = m[6];
  3242. m[6] = tmp;
  3243. tmp = m[5];
  3244. m[5] = m[7];
  3245. m[7] = tmp;
  3246. return this;
  3247. },
  3248. getNormalMatrix: function (matrix4) {
  3249. return this.setFromMatrix4(matrix4).getInverse(this).transpose();
  3250. },
  3251. transposeIntoArray: function (r) {
  3252. var m = this.elements;
  3253. r[0] = m[0];
  3254. r[1] = m[3];
  3255. r[2] = m[6];
  3256. r[3] = m[1];
  3257. r[4] = m[4];
  3258. r[5] = m[7];
  3259. r[6] = m[2];
  3260. r[7] = m[5];
  3261. r[8] = m[8];
  3262. return this;
  3263. },
  3264. setUvTransform: function (tx, ty, sx, sy, rotation, cx, cy) {
  3265. var c = Math.cos(rotation);
  3266. var s = Math.sin(rotation);
  3267. this.set(sx * c, sx * s, -sx * (c * cx + s * cy) + cx + tx, -sy * s, sy * c, -sy * (-s * cx + c * cy) + cy + ty, 0, 0, 1);
  3268. },
  3269. scale: function (sx, sy) {
  3270. var te = this.elements;
  3271. te[0] *= sx;
  3272. te[3] *= sx;
  3273. te[6] *= sx;
  3274. te[1] *= sy;
  3275. te[4] *= sy;
  3276. te[7] *= sy;
  3277. return this;
  3278. },
  3279. rotate: function (theta) {
  3280. var c = Math.cos(theta);
  3281. var s = Math.sin(theta);
  3282. var te = this.elements;
  3283. var a11 = te[0],
  3284. a12 = te[3],
  3285. a13 = te[6];
  3286. var a21 = te[1],
  3287. a22 = te[4],
  3288. a23 = te[7];
  3289. te[0] = c * a11 + s * a21;
  3290. te[3] = c * a12 + s * a22;
  3291. te[6] = c * a13 + s * a23;
  3292. te[1] = -s * a11 + c * a21;
  3293. te[4] = -s * a12 + c * a22;
  3294. te[7] = -s * a13 + c * a23;
  3295. return this;
  3296. },
  3297. translate: function (tx, ty) {
  3298. var te = this.elements;
  3299. te[0] += tx * te[2];
  3300. te[3] += tx * te[5];
  3301. te[6] += tx * te[8];
  3302. te[1] += ty * te[2];
  3303. te[4] += ty * te[5];
  3304. te[7] += ty * te[8];
  3305. return this;
  3306. },
  3307. equals: function (matrix) {
  3308. var te = this.elements;
  3309. var me = matrix.elements;
  3310. for (var i = 0; i < 9; i++) {
  3311. if (te[i] !== me[i]) return false;
  3312. }
  3313. return true;
  3314. },
  3315. fromArray: function (array, offset) {
  3316. if (offset === undefined) offset = 0;
  3317. for (var i = 0; i < 9; i++) {
  3318. this.elements[i] = array[i + offset];
  3319. }
  3320. return this;
  3321. },
  3322. toArray: function (array, offset) {
  3323. if (array === undefined) array = [];
  3324. if (offset === undefined) offset = 0;
  3325. var te = this.elements;
  3326. array[offset] = te[0];
  3327. array[offset + 1] = te[1];
  3328. array[offset + 2] = te[2];
  3329. array[offset + 3] = te[3];
  3330. array[offset + 4] = te[4];
  3331. array[offset + 5] = te[5];
  3332. array[offset + 6] = te[6];
  3333. array[offset + 7] = te[7];
  3334. array[offset + 8] = te[8];
  3335. return array;
  3336. }
  3337. });
  3338. /**
  3339. * @author mrdoob / http://mrdoob.com/
  3340. * @author alteredq / http://alteredqualia.com/
  3341. * @author szimek / https://github.com/szimek/
  3342. */
  3343. var _canvas;
  3344. var ImageUtils = {
  3345. getDataURL: function (image) {
  3346. var canvas;
  3347. if (typeof HTMLCanvasElement == 'undefined') {
  3348. return image.src;
  3349. } else if (image instanceof HTMLCanvasElement) {
  3350. canvas = image;
  3351. } else {
  3352. if (_canvas === undefined) _canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  3353. _canvas.width = image.width;
  3354. _canvas.height = image.height;
  3355. var context = _canvas.getContext('2d');
  3356. if (image instanceof ImageData) {
  3357. context.putImageData(image, 0, 0);
  3358. } else {
  3359. context.drawImage(image, 0, 0, image.width, image.height);
  3360. }
  3361. canvas = _canvas;
  3362. }
  3363. if (canvas.width > 2048 || canvas.height > 2048) {
  3364. return canvas.toDataURL('image/jpeg', 0.6);
  3365. } else {
  3366. return canvas.toDataURL('image/png');
  3367. }
  3368. }
  3369. };
  3370. /**
  3371. * @author mrdoob / http://mrdoob.com/
  3372. * @author alteredq / http://alteredqualia.com/
  3373. * @author szimek / https://github.com/szimek/
  3374. */
  3375. exports.ImageUtils = ImageUtils;
  3376. var textureId = 0;
  3377. function Texture(image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  3378. Object.defineProperty(this, 'id', {
  3379. value: textureId++
  3380. });
  3381. this.uuid = _Math.generateUUID();
  3382. this.name = '';
  3383. this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
  3384. this.mipmaps = [];
  3385. this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
  3386. this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
  3387. this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
  3388. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  3389. this.minFilter = minFilter !== undefined ? minFilter : LinearMipmapLinearFilter;
  3390. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  3391. this.format = format !== undefined ? format : RGBAFormat;
  3392. this.type = type !== undefined ? type : UnsignedByteType;
  3393. this.offset = new Vector2(0, 0);
  3394. this.repeat = new Vector2(1, 1);
  3395. this.center = new Vector2(0, 0);
  3396. this.rotation = 0;
  3397. this.matrixAutoUpdate = true;
  3398. this.matrix = new Matrix3();
  3399. this.generateMipmaps = true;
  3400. this.premultiplyAlpha = false;
  3401. this.flipY = true;
  3402. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  3403. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  3404. //
  3405. // Also changing the encoding after already used by a Material will not automatically make the Material
  3406. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  3407. this.encoding = encoding !== undefined ? encoding : LinearEncoding;
  3408. this.version = 0;
  3409. this.onUpdate = null;
  3410. }
  3411. Texture.DEFAULT_IMAGE = undefined;
  3412. Texture.DEFAULT_MAPPING = UVMapping;
  3413. Texture.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  3414. constructor: Texture,
  3415. isTexture: true,
  3416. updateMatrix: function () {
  3417. this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  3418. },
  3419. clone: function () {
  3420. return new this.constructor().copy(this);
  3421. },
  3422. copy: function (source) {
  3423. this.name = source.name;
  3424. this.image = source.image;
  3425. this.mipmaps = source.mipmaps.slice(0);
  3426. this.mapping = source.mapping;
  3427. this.wrapS = source.wrapS;
  3428. this.wrapT = source.wrapT;
  3429. this.magFilter = source.magFilter;
  3430. this.minFilter = source.minFilter;
  3431. this.anisotropy = source.anisotropy;
  3432. this.format = source.format;
  3433. this.type = source.type;
  3434. this.offset.copy(source.offset);
  3435. this.repeat.copy(source.repeat);
  3436. this.center.copy(source.center);
  3437. this.rotation = source.rotation;
  3438. this.matrixAutoUpdate = source.matrixAutoUpdate;
  3439. this.matrix.copy(source.matrix);
  3440. this.generateMipmaps = source.generateMipmaps;
  3441. this.premultiplyAlpha = source.premultiplyAlpha;
  3442. this.flipY = source.flipY;
  3443. this.unpackAlignment = source.unpackAlignment;
  3444. this.encoding = source.encoding;
  3445. return this;
  3446. },
  3447. toJSON: function (meta) {
  3448. var isRootObject = meta === undefined || typeof meta === 'string';
  3449. if (!isRootObject && meta.textures[this.uuid] !== undefined) {
  3450. return meta.textures[this.uuid];
  3451. }
  3452. var output = {
  3453. metadata: {
  3454. version: 4.5,
  3455. type: 'Texture',
  3456. generator: 'Texture.toJSON'
  3457. },
  3458. uuid: this.uuid,
  3459. name: this.name,
  3460. mapping: this.mapping,
  3461. repeat: [this.repeat.x, this.repeat.y],
  3462. offset: [this.offset.x, this.offset.y],
  3463. center: [this.center.x, this.center.y],
  3464. rotation: this.rotation,
  3465. wrap: [this.wrapS, this.wrapT],
  3466. format: this.format,
  3467. type: this.type,
  3468. encoding: this.encoding,
  3469. minFilter: this.minFilter,
  3470. magFilter: this.magFilter,
  3471. anisotropy: this.anisotropy,
  3472. flipY: this.flipY,
  3473. premultiplyAlpha: this.premultiplyAlpha,
  3474. unpackAlignment: this.unpackAlignment
  3475. };
  3476. if (this.image !== undefined) {
  3477. // TODO: Move to THREE.Image
  3478. var image = this.image;
  3479. if (image.uuid === undefined) {
  3480. image.uuid = _Math.generateUUID(); // UGH
  3481. }
  3482. if (!isRootObject && meta.images[image.uuid] === undefined) {
  3483. var url;
  3484. if (Array.isArray(image)) {
  3485. // process array of images e.g. CubeTexture
  3486. url = [];
  3487. for (var i = 0, l = image.length; i < l; i++) {
  3488. url.push(ImageUtils.getDataURL(image[i]));
  3489. }
  3490. } else {
  3491. // process single image
  3492. url = ImageUtils.getDataURL(image);
  3493. }
  3494. meta.images[image.uuid] = {
  3495. uuid: image.uuid,
  3496. url: url
  3497. };
  3498. }
  3499. output.image = image.uuid;
  3500. }
  3501. if (!isRootObject) {
  3502. meta.textures[this.uuid] = output;
  3503. }
  3504. return output;
  3505. },
  3506. dispose: function () {
  3507. this.dispatchEvent({
  3508. type: 'dispose'
  3509. });
  3510. },
  3511. transformUv: function (uv) {
  3512. if (this.mapping !== UVMapping) return uv;
  3513. uv.applyMatrix3(this.matrix);
  3514. if (uv.x < 0 || uv.x > 1) {
  3515. switch (this.wrapS) {
  3516. case RepeatWrapping:
  3517. uv.x = uv.x - Math.floor(uv.x);
  3518. break;
  3519. case ClampToEdgeWrapping:
  3520. uv.x = uv.x < 0 ? 0 : 1;
  3521. break;
  3522. case MirroredRepeatWrapping:
  3523. if (Math.abs(Math.floor(uv.x) % 2) === 1) {
  3524. uv.x = Math.ceil(uv.x) - uv.x;
  3525. } else {
  3526. uv.x = uv.x - Math.floor(uv.x);
  3527. }
  3528. break;
  3529. }
  3530. }
  3531. if (uv.y < 0 || uv.y > 1) {
  3532. switch (this.wrapT) {
  3533. case RepeatWrapping:
  3534. uv.y = uv.y - Math.floor(uv.y);
  3535. break;
  3536. case ClampToEdgeWrapping:
  3537. uv.y = uv.y < 0 ? 0 : 1;
  3538. break;
  3539. case MirroredRepeatWrapping:
  3540. if (Math.abs(Math.floor(uv.y) % 2) === 1) {
  3541. uv.y = Math.ceil(uv.y) - uv.y;
  3542. } else {
  3543. uv.y = uv.y - Math.floor(uv.y);
  3544. }
  3545. break;
  3546. }
  3547. }
  3548. if (this.flipY) {
  3549. uv.y = 1 - uv.y;
  3550. }
  3551. return uv;
  3552. }
  3553. });
  3554. Object.defineProperty(Texture.prototype, "needsUpdate", {
  3555. set: function (value) {
  3556. if (value === true) this.version++;
  3557. }
  3558. });
  3559. /**
  3560. * @author supereggbert / http://www.paulbrunt.co.uk/
  3561. * @author philogb / http://blog.thejit.org/
  3562. * @author mikael emtinger / http://gomo.se/
  3563. * @author egraether / http://egraether.com/
  3564. * @author WestLangley / http://github.com/WestLangley
  3565. */
  3566. function Vector4(x, y, z, w) {
  3567. this.x = x || 0;
  3568. this.y = y || 0;
  3569. this.z = z || 0;
  3570. this.w = w !== undefined ? w : 1;
  3571. }
  3572. Object.defineProperties(Vector4.prototype, {
  3573. "width": {
  3574. get: function () {
  3575. return this.z;
  3576. },
  3577. set: function (value) {
  3578. this.z = value;
  3579. }
  3580. },
  3581. "height": {
  3582. get: function () {
  3583. return this.w;
  3584. },
  3585. set: function (value) {
  3586. this.w = value;
  3587. }
  3588. }
  3589. });
  3590. Object.assign(Vector4.prototype, {
  3591. isVector4: true,
  3592. set: function (x, y, z, w) {
  3593. this.x = x;
  3594. this.y = y;
  3595. this.z = z;
  3596. this.w = w;
  3597. return this;
  3598. },
  3599. setScalar: function (scalar) {
  3600. this.x = scalar;
  3601. this.y = scalar;
  3602. this.z = scalar;
  3603. this.w = scalar;
  3604. return this;
  3605. },
  3606. setX: function (x) {
  3607. this.x = x;
  3608. return this;
  3609. },
  3610. setY: function (y) {
  3611. this.y = y;
  3612. return this;
  3613. },
  3614. setZ: function (z) {
  3615. this.z = z;
  3616. return this;
  3617. },
  3618. setW: function (w) {
  3619. this.w = w;
  3620. return this;
  3621. },
  3622. setComponent: function (index, value) {
  3623. switch (index) {
  3624. case 0:
  3625. this.x = value;
  3626. break;
  3627. case 1:
  3628. this.y = value;
  3629. break;
  3630. case 2:
  3631. this.z = value;
  3632. break;
  3633. case 3:
  3634. this.w = value;
  3635. break;
  3636. default:
  3637. throw new Error('index is out of range: ' + index);
  3638. }
  3639. return this;
  3640. },
  3641. getComponent: function (index) {
  3642. switch (index) {
  3643. case 0:
  3644. return this.x;
  3645. case 1:
  3646. return this.y;
  3647. case 2:
  3648. return this.z;
  3649. case 3:
  3650. return this.w;
  3651. default:
  3652. throw new Error('index is out of range: ' + index);
  3653. }
  3654. },
  3655. clone: function () {
  3656. return new this.constructor(this.x, this.y, this.z, this.w);
  3657. },
  3658. copy: function (v) {
  3659. this.x = v.x;
  3660. this.y = v.y;
  3661. this.z = v.z;
  3662. this.w = v.w !== undefined ? v.w : 1;
  3663. return this;
  3664. },
  3665. add: function (v, w) {
  3666. if (w !== undefined) {
  3667. console.warn('THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  3668. return this.addVectors(v, w);
  3669. }
  3670. this.x += v.x;
  3671. this.y += v.y;
  3672. this.z += v.z;
  3673. this.w += v.w;
  3674. return this;
  3675. },
  3676. addScalar: function (s) {
  3677. this.x += s;
  3678. this.y += s;
  3679. this.z += s;
  3680. this.w += s;
  3681. return this;
  3682. },
  3683. addVectors: function (a, b) {
  3684. this.x = a.x + b.x;
  3685. this.y = a.y + b.y;
  3686. this.z = a.z + b.z;
  3687. this.w = a.w + b.w;
  3688. return this;
  3689. },
  3690. addScaledVector: function (v, s) {
  3691. this.x += v.x * s;
  3692. this.y += v.y * s;
  3693. this.z += v.z * s;
  3694. this.w += v.w * s;
  3695. return this;
  3696. },
  3697. sub: function (v, w) {
  3698. if (w !== undefined) {
  3699. console.warn('THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  3700. return this.subVectors(v, w);
  3701. }
  3702. this.x -= v.x;
  3703. this.y -= v.y;
  3704. this.z -= v.z;
  3705. this.w -= v.w;
  3706. return this;
  3707. },
  3708. subScalar: function (s) {
  3709. this.x -= s;
  3710. this.y -= s;
  3711. this.z -= s;
  3712. this.w -= s;
  3713. return this;
  3714. },
  3715. subVectors: function (a, b) {
  3716. this.x = a.x - b.x;
  3717. this.y = a.y - b.y;
  3718. this.z = a.z - b.z;
  3719. this.w = a.w - b.w;
  3720. return this;
  3721. },
  3722. multiplyScalar: function (scalar) {
  3723. this.x *= scalar;
  3724. this.y *= scalar;
  3725. this.z *= scalar;
  3726. this.w *= scalar;
  3727. return this;
  3728. },
  3729. applyMatrix4: function (m) {
  3730. var x = this.x,
  3731. y = this.y,
  3732. z = this.z,
  3733. w = this.w;
  3734. var e = m.elements;
  3735. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  3736. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  3737. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  3738. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  3739. return this;
  3740. },
  3741. divideScalar: function (scalar) {
  3742. return this.multiplyScalar(1 / scalar);
  3743. },
  3744. setAxisAngleFromQuaternion: function (q) {
  3745. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  3746. // q is assumed to be normalized
  3747. this.w = 2 * Math.acos(q.w);
  3748. var s = Math.sqrt(1 - q.w * q.w);
  3749. if (s < 0.0001) {
  3750. this.x = 1;
  3751. this.y = 0;
  3752. this.z = 0;
  3753. } else {
  3754. this.x = q.x / s;
  3755. this.y = q.y / s;
  3756. this.z = q.z / s;
  3757. }
  3758. return this;
  3759. },
  3760. setAxisAngleFromRotationMatrix: function (m) {
  3761. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  3762. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3763. var angle,
  3764. x,
  3765. y,
  3766. z,
  3767. // variables for result
  3768. epsilon = 0.01,
  3769. // margin to allow for rounding errors
  3770. epsilon2 = 0.1,
  3771. // margin to distinguish between 0 and 180 degrees
  3772. te = m.elements,
  3773. m11 = te[0],
  3774. m12 = te[4],
  3775. m13 = te[8],
  3776. m21 = te[1],
  3777. m22 = te[5],
  3778. m23 = te[9],
  3779. m31 = te[2],
  3780. m32 = te[6],
  3781. m33 = te[10];
  3782. if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {
  3783. // singularity found
  3784. // first check for identity matrix which must have +1 for all terms
  3785. // in leading diagonal and zero in other terms
  3786. if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {
  3787. // this singularity is identity matrix so angle = 0
  3788. this.set(1, 0, 0, 0);
  3789. return this; // zero angle, arbitrary axis
  3790. } // otherwise this singularity is angle = 180
  3791. angle = Math.PI;
  3792. var xx = (m11 + 1) / 2;
  3793. var yy = (m22 + 1) / 2;
  3794. var zz = (m33 + 1) / 2;
  3795. var xy = (m12 + m21) / 4;
  3796. var xz = (m13 + m31) / 4;
  3797. var yz = (m23 + m32) / 4;
  3798. if (xx > yy && xx > zz) {
  3799. // m11 is the largest diagonal term
  3800. if (xx < epsilon) {
  3801. x = 0;
  3802. y = 0.707106781;
  3803. z = 0.707106781;
  3804. } else {
  3805. x = Math.sqrt(xx);
  3806. y = xy / x;
  3807. z = xz / x;
  3808. }
  3809. } else if (yy > zz) {
  3810. // m22 is the largest diagonal term
  3811. if (yy < epsilon) {
  3812. x = 0.707106781;
  3813. y = 0;
  3814. z = 0.707106781;
  3815. } else {
  3816. y = Math.sqrt(yy);
  3817. x = xy / y;
  3818. z = yz / y;
  3819. }
  3820. } else {
  3821. // m33 is the largest diagonal term so base result on this
  3822. if (zz < epsilon) {
  3823. x = 0.707106781;
  3824. y = 0.707106781;
  3825. z = 0;
  3826. } else {
  3827. z = Math.sqrt(zz);
  3828. x = xz / z;
  3829. y = yz / z;
  3830. }
  3831. }
  3832. this.set(x, y, z, angle);
  3833. return this; // return 180 deg rotation
  3834. } // as we have reached here there are no singularities so we can handle normally
  3835. var s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalize
  3836. if (Math.abs(s) < 0.001) s = 1; // prevent divide by zero, should not happen if matrix is orthogonal and should be
  3837. // caught by singularity test above, but I've left it in just in case
  3838. this.x = (m32 - m23) / s;
  3839. this.y = (m13 - m31) / s;
  3840. this.z = (m21 - m12) / s;
  3841. this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
  3842. return this;
  3843. },
  3844. min: function (v) {
  3845. this.x = Math.min(this.x, v.x);
  3846. this.y = Math.min(this.y, v.y);
  3847. this.z = Math.min(this.z, v.z);
  3848. this.w = Math.min(this.w, v.w);
  3849. return this;
  3850. },
  3851. max: function (v) {
  3852. this.x = Math.max(this.x, v.x);
  3853. this.y = Math.max(this.y, v.y);
  3854. this.z = Math.max(this.z, v.z);
  3855. this.w = Math.max(this.w, v.w);
  3856. return this;
  3857. },
  3858. clamp: function (min, max) {
  3859. // assumes min < max, componentwise
  3860. this.x = Math.max(min.x, Math.min(max.x, this.x));
  3861. this.y = Math.max(min.y, Math.min(max.y, this.y));
  3862. this.z = Math.max(min.z, Math.min(max.z, this.z));
  3863. this.w = Math.max(min.w, Math.min(max.w, this.w));
  3864. return this;
  3865. },
  3866. clampScalar: function (minVal, maxVal) {
  3867. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  3868. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  3869. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  3870. this.w = Math.max(minVal, Math.min(maxVal, this.w));
  3871. return this;
  3872. },
  3873. clampLength: function (min, max) {
  3874. var length = this.length();
  3875. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  3876. },
  3877. floor: function () {
  3878. this.x = Math.floor(this.x);
  3879. this.y = Math.floor(this.y);
  3880. this.z = Math.floor(this.z);
  3881. this.w = Math.floor(this.w);
  3882. return this;
  3883. },
  3884. ceil: function () {
  3885. this.x = Math.ceil(this.x);
  3886. this.y = Math.ceil(this.y);
  3887. this.z = Math.ceil(this.z);
  3888. this.w = Math.ceil(this.w);
  3889. return this;
  3890. },
  3891. round: function () {
  3892. this.x = Math.round(this.x);
  3893. this.y = Math.round(this.y);
  3894. this.z = Math.round(this.z);
  3895. this.w = Math.round(this.w);
  3896. return this;
  3897. },
  3898. roundToZero: function () {
  3899. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  3900. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  3901. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  3902. this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w);
  3903. return this;
  3904. },
  3905. negate: function () {
  3906. this.x = -this.x;
  3907. this.y = -this.y;
  3908. this.z = -this.z;
  3909. this.w = -this.w;
  3910. return this;
  3911. },
  3912. dot: function (v) {
  3913. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  3914. },
  3915. lengthSq: function () {
  3916. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  3917. },
  3918. length: function () {
  3919. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3920. },
  3921. manhattanLength: function () {
  3922. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  3923. },
  3924. normalize: function () {
  3925. return this.divideScalar(this.length() || 1);
  3926. },
  3927. setLength: function (length) {
  3928. return this.normalize().multiplyScalar(length);
  3929. },
  3930. lerp: function (v, alpha) {
  3931. this.x += (v.x - this.x) * alpha;
  3932. this.y += (v.y - this.y) * alpha;
  3933. this.z += (v.z - this.z) * alpha;
  3934. this.w += (v.w - this.w) * alpha;
  3935. return this;
  3936. },
  3937. lerpVectors: function (v1, v2, alpha) {
  3938. return this.subVectors(v2, v1).multiplyScalar(alpha).add(v1);
  3939. },
  3940. equals: function (v) {
  3941. return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
  3942. },
  3943. fromArray: function (array, offset) {
  3944. if (offset === undefined) offset = 0;
  3945. this.x = array[offset];
  3946. this.y = array[offset + 1];
  3947. this.z = array[offset + 2];
  3948. this.w = array[offset + 3];
  3949. return this;
  3950. },
  3951. toArray: function (array, offset) {
  3952. if (array === undefined) array = [];
  3953. if (offset === undefined) offset = 0;
  3954. array[offset] = this.x;
  3955. array[offset + 1] = this.y;
  3956. array[offset + 2] = this.z;
  3957. array[offset + 3] = this.w;
  3958. return array;
  3959. },
  3960. fromBufferAttribute: function (attribute, index, offset) {
  3961. if (offset !== undefined) {
  3962. console.warn('THREE.Vector4: offset has been removed from .fromBufferAttribute().');
  3963. }
  3964. this.x = attribute.getX(index);
  3965. this.y = attribute.getY(index);
  3966. this.z = attribute.getZ(index);
  3967. this.w = attribute.getW(index);
  3968. return this;
  3969. }
  3970. });
  3971. /**
  3972. * @author szimek / https://github.com/szimek/
  3973. * @author alteredq / http://alteredqualia.com/
  3974. * @author Marius Kintel / https://github.com/kintel
  3975. */
  3976. /*
  3977. In options, we can specify:
  3978. * Texture parameters for an auto-generated target texture
  3979. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  3980. */
  3981. function WebGLRenderTarget(width, height, options) {
  3982. this.width = width;
  3983. this.height = height;
  3984. this.scissor = new Vector4(0, 0, width, height);
  3985. this.scissorTest = false;
  3986. this.viewport = new Vector4(0, 0, width, height);
  3987. options = options || {};
  3988. this.texture = new Texture(undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  3989. this.texture.image = {};
  3990. this.texture.image.width = width;
  3991. this.texture.image.height = height;
  3992. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  3993. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  3994. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  3995. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  3996. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  3997. }
  3998. WebGLRenderTarget.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  3999. constructor: WebGLRenderTarget,
  4000. isWebGLRenderTarget: true,
  4001. setSize: function (width, height) {
  4002. if (this.width !== width || this.height !== height) {
  4003. this.width = width;
  4004. this.height = height;
  4005. this.texture.image.width = width;
  4006. this.texture.image.height = height;
  4007. this.dispose();
  4008. }
  4009. this.viewport.set(0, 0, width, height);
  4010. this.scissor.set(0, 0, width, height);
  4011. },
  4012. clone: function () {
  4013. return new this.constructor().copy(this);
  4014. },
  4015. copy: function (source) {
  4016. this.width = source.width;
  4017. this.height = source.height;
  4018. this.viewport.copy(source.viewport);
  4019. this.texture = source.texture.clone();
  4020. this.depthBuffer = source.depthBuffer;
  4021. this.stencilBuffer = source.stencilBuffer;
  4022. this.depthTexture = source.depthTexture;
  4023. return this;
  4024. },
  4025. dispose: function () {
  4026. this.dispatchEvent({
  4027. type: 'dispose'
  4028. });
  4029. }
  4030. });
  4031. /**
  4032. * @author Mugen87 / https://github.com/Mugen87
  4033. * @author Matt DesLauriers / @mattdesl
  4034. */
  4035. function WebGLMultisampleRenderTarget(width, height, options) {
  4036. WebGLRenderTarget.call(this, width, height, options);
  4037. this.samples = 4;
  4038. }
  4039. WebGLMultisampleRenderTarget.prototype = Object.assign(Object.create(WebGLRenderTarget.prototype), {
  4040. constructor: WebGLMultisampleRenderTarget,
  4041. isWebGLMultisampleRenderTarget: true,
  4042. copy: function (source) {
  4043. WebGLRenderTarget.prototype.copy.call(this, source);
  4044. this.samples = source.samples;
  4045. return this;
  4046. }
  4047. });
  4048. var _v1 = new Vector3();
  4049. var _m1 = new Matrix4();
  4050. var _zero = new Vector3(0, 0, 0);
  4051. var _one = new Vector3(1, 1, 1);
  4052. var _x = new Vector3();
  4053. var _y = new Vector3();
  4054. var _z = new Vector3();
  4055. /**
  4056. * @author mrdoob / http://mrdoob.com/
  4057. * @author supereggbert / http://www.paulbrunt.co.uk/
  4058. * @author philogb / http://blog.thejit.org/
  4059. * @author jordi_ros / http://plattsoft.com
  4060. * @author D1plo1d / http://github.com/D1plo1d
  4061. * @author alteredq / http://alteredqualia.com/
  4062. * @author mikael emtinger / http://gomo.se/
  4063. * @author timknip / http://www.floorplanner.com/
  4064. * @author bhouston / http://clara.io
  4065. * @author WestLangley / http://github.com/WestLangley
  4066. */
  4067. function Matrix4() {
  4068. this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  4069. if (arguments.length > 0) {
  4070. console.error('THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.');
  4071. }
  4072. }
  4073. Object.assign(Matrix4.prototype, {
  4074. isMatrix4: true,
  4075. set: function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  4076. var te = this.elements;
  4077. te[0] = n11;
  4078. te[4] = n12;
  4079. te[8] = n13;
  4080. te[12] = n14;
  4081. te[1] = n21;
  4082. te[5] = n22;
  4083. te[9] = n23;
  4084. te[13] = n24;
  4085. te[2] = n31;
  4086. te[6] = n32;
  4087. te[10] = n33;
  4088. te[14] = n34;
  4089. te[3] = n41;
  4090. te[7] = n42;
  4091. te[11] = n43;
  4092. te[15] = n44;
  4093. return this;
  4094. },
  4095. identity: function () {
  4096. this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  4097. return this;
  4098. },
  4099. clone: function () {
  4100. return new Matrix4().fromArray(this.elements);
  4101. },
  4102. copy: function (m) {
  4103. var te = this.elements;
  4104. var me = m.elements;
  4105. te[0] = me[0];
  4106. te[1] = me[1];
  4107. te[2] = me[2];
  4108. te[3] = me[3];
  4109. te[4] = me[4];
  4110. te[5] = me[5];
  4111. te[6] = me[6];
  4112. te[7] = me[7];
  4113. te[8] = me[8];
  4114. te[9] = me[9];
  4115. te[10] = me[10];
  4116. te[11] = me[11];
  4117. te[12] = me[12];
  4118. te[13] = me[13];
  4119. te[14] = me[14];
  4120. te[15] = me[15];
  4121. return this;
  4122. },
  4123. copyPosition: function (m) {
  4124. var te = this.elements,
  4125. me = m.elements;
  4126. te[12] = me[12];
  4127. te[13] = me[13];
  4128. te[14] = me[14];
  4129. return this;
  4130. },
  4131. extractBasis: function (xAxis, yAxis, zAxis) {
  4132. xAxis.setFromMatrixColumn(this, 0);
  4133. yAxis.setFromMatrixColumn(this, 1);
  4134. zAxis.setFromMatrixColumn(this, 2);
  4135. return this;
  4136. },
  4137. makeBasis: function (xAxis, yAxis, zAxis) {
  4138. this.set(xAxis.x, yAxis.x, zAxis.x, 0, xAxis.y, yAxis.y, zAxis.y, 0, xAxis.z, yAxis.z, zAxis.z, 0, 0, 0, 0, 1);
  4139. return this;
  4140. },
  4141. extractRotation: function (m) {
  4142. // this method does not support reflection matrices
  4143. var te = this.elements;
  4144. var me = m.elements;
  4145. var scaleX = 1 / _v1.setFromMatrixColumn(m, 0).length();
  4146. var scaleY = 1 / _v1.setFromMatrixColumn(m, 1).length();
  4147. var scaleZ = 1 / _v1.setFromMatrixColumn(m, 2).length();
  4148. te[0] = me[0] * scaleX;
  4149. te[1] = me[1] * scaleX;
  4150. te[2] = me[2] * scaleX;
  4151. te[3] = 0;
  4152. te[4] = me[4] * scaleY;
  4153. te[5] = me[5] * scaleY;
  4154. te[6] = me[6] * scaleY;
  4155. te[7] = 0;
  4156. te[8] = me[8] * scaleZ;
  4157. te[9] = me[9] * scaleZ;
  4158. te[10] = me[10] * scaleZ;
  4159. te[11] = 0;
  4160. te[12] = 0;
  4161. te[13] = 0;
  4162. te[14] = 0;
  4163. te[15] = 1;
  4164. return this;
  4165. },
  4166. makeRotationFromEuler: function (euler) {
  4167. if (!(euler && euler.isEuler)) {
  4168. console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');
  4169. }
  4170. var te = this.elements;
  4171. var x = euler.x,
  4172. y = euler.y,
  4173. z = euler.z;
  4174. var a = Math.cos(x),
  4175. b = Math.sin(x);
  4176. var c = Math.cos(y),
  4177. d = Math.sin(y);
  4178. var e = Math.cos(z),
  4179. f = Math.sin(z);
  4180. if (euler.order === 'XYZ') {
  4181. var ae = a * e,
  4182. af = a * f,
  4183. be = b * e,
  4184. bf = b * f;
  4185. te[0] = c * e;
  4186. te[4] = -c * f;
  4187. te[8] = d;
  4188. te[1] = af + be * d;
  4189. te[5] = ae - bf * d;
  4190. te[9] = -b * c;
  4191. te[2] = bf - ae * d;
  4192. te[6] = be + af * d;
  4193. te[10] = a * c;
  4194. } else if (euler.order === 'YXZ') {
  4195. var ce = c * e,
  4196. cf = c * f,
  4197. de = d * e,
  4198. df = d * f;
  4199. te[0] = ce + df * b;
  4200. te[4] = de * b - cf;
  4201. te[8] = a * d;
  4202. te[1] = a * f;
  4203. te[5] = a * e;
  4204. te[9] = -b;
  4205. te[2] = cf * b - de;
  4206. te[6] = df + ce * b;
  4207. te[10] = a * c;
  4208. } else if (euler.order === 'ZXY') {
  4209. var ce = c * e,
  4210. cf = c * f,
  4211. de = d * e,
  4212. df = d * f;
  4213. te[0] = ce - df * b;
  4214. te[4] = -a * f;
  4215. te[8] = de + cf * b;
  4216. te[1] = cf + de * b;
  4217. te[5] = a * e;
  4218. te[9] = df - ce * b;
  4219. te[2] = -a * d;
  4220. te[6] = b;
  4221. te[10] = a * c;
  4222. } else if (euler.order === 'ZYX') {
  4223. var ae = a * e,
  4224. af = a * f,
  4225. be = b * e,
  4226. bf = b * f;
  4227. te[0] = c * e;
  4228. te[4] = be * d - af;
  4229. te[8] = ae * d + bf;
  4230. te[1] = c * f;
  4231. te[5] = bf * d + ae;
  4232. te[9] = af * d - be;
  4233. te[2] = -d;
  4234. te[6] = b * c;
  4235. te[10] = a * c;
  4236. } else if (euler.order === 'YZX') {
  4237. var ac = a * c,
  4238. ad = a * d,
  4239. bc = b * c,
  4240. bd = b * d;
  4241. te[0] = c * e;
  4242. te[4] = bd - ac * f;
  4243. te[8] = bc * f + ad;
  4244. te[1] = f;
  4245. te[5] = a * e;
  4246. te[9] = -b * e;
  4247. te[2] = -d * e;
  4248. te[6] = ad * f + bc;
  4249. te[10] = ac - bd * f;
  4250. } else if (euler.order === 'XZY') {
  4251. var ac = a * c,
  4252. ad = a * d,
  4253. bc = b * c,
  4254. bd = b * d;
  4255. te[0] = c * e;
  4256. te[4] = -f;
  4257. te[8] = d * e;
  4258. te[1] = ac * f + bd;
  4259. te[5] = a * e;
  4260. te[9] = ad * f - bc;
  4261. te[2] = bc * f - ad;
  4262. te[6] = b * e;
  4263. te[10] = bd * f + ac;
  4264. } // bottom row
  4265. te[3] = 0;
  4266. te[7] = 0;
  4267. te[11] = 0; // last column
  4268. te[12] = 0;
  4269. te[13] = 0;
  4270. te[14] = 0;
  4271. te[15] = 1;
  4272. return this;
  4273. },
  4274. makeRotationFromQuaternion: function (q) {
  4275. return this.compose(_zero, q, _one);
  4276. },
  4277. lookAt: function (eye, target, up) {
  4278. var te = this.elements;
  4279. _z.subVectors(eye, target);
  4280. if (_z.lengthSq() === 0) {
  4281. // eye and target are in the same position
  4282. _z.z = 1;
  4283. }
  4284. _z.normalize();
  4285. _x.crossVectors(up, _z);
  4286. if (_x.lengthSq() === 0) {
  4287. // up and z are parallel
  4288. if (Math.abs(up.z) === 1) {
  4289. _z.x += 0.0001;
  4290. } else {
  4291. _z.z += 0.0001;
  4292. }
  4293. _z.normalize();
  4294. _x.crossVectors(up, _z);
  4295. }
  4296. _x.normalize();
  4297. _y.crossVectors(_z, _x);
  4298. te[0] = _x.x;
  4299. te[4] = _y.x;
  4300. te[8] = _z.x;
  4301. te[1] = _x.y;
  4302. te[5] = _y.y;
  4303. te[9] = _z.y;
  4304. te[2] = _x.z;
  4305. te[6] = _y.z;
  4306. te[10] = _z.z;
  4307. return this;
  4308. },
  4309. multiply: function (m, n) {
  4310. if (n !== undefined) {
  4311. console.warn('THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.');
  4312. return this.multiplyMatrices(m, n);
  4313. }
  4314. return this.multiplyMatrices(this, m);
  4315. },
  4316. premultiply: function (m) {
  4317. return this.multiplyMatrices(m, this);
  4318. },
  4319. multiplyMatrices: function (a, b) {
  4320. var ae = a.elements;
  4321. var be = b.elements;
  4322. var te = this.elements;
  4323. var a11 = ae[0],
  4324. a12 = ae[4],
  4325. a13 = ae[8],
  4326. a14 = ae[12];
  4327. var a21 = ae[1],
  4328. a22 = ae[5],
  4329. a23 = ae[9],
  4330. a24 = ae[13];
  4331. var a31 = ae[2],
  4332. a32 = ae[6],
  4333. a33 = ae[10],
  4334. a34 = ae[14];
  4335. var a41 = ae[3],
  4336. a42 = ae[7],
  4337. a43 = ae[11],
  4338. a44 = ae[15];
  4339. var b11 = be[0],
  4340. b12 = be[4],
  4341. b13 = be[8],
  4342. b14 = be[12];
  4343. var b21 = be[1],
  4344. b22 = be[5],
  4345. b23 = be[9],
  4346. b24 = be[13];
  4347. var b31 = be[2],
  4348. b32 = be[6],
  4349. b33 = be[10],
  4350. b34 = be[14];
  4351. var b41 = be[3],
  4352. b42 = be[7],
  4353. b43 = be[11],
  4354. b44 = be[15];
  4355. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  4356. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  4357. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  4358. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  4359. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  4360. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  4361. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  4362. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  4363. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  4364. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  4365. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  4366. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  4367. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  4368. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  4369. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  4370. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  4371. return this;
  4372. },
  4373. multiplyScalar: function (s) {
  4374. var te = this.elements;
  4375. te[0] *= s;
  4376. te[4] *= s;
  4377. te[8] *= s;
  4378. te[12] *= s;
  4379. te[1] *= s;
  4380. te[5] *= s;
  4381. te[9] *= s;
  4382. te[13] *= s;
  4383. te[2] *= s;
  4384. te[6] *= s;
  4385. te[10] *= s;
  4386. te[14] *= s;
  4387. te[3] *= s;
  4388. te[7] *= s;
  4389. te[11] *= s;
  4390. te[15] *= s;
  4391. return this;
  4392. },
  4393. applyToBufferAttribute: function (attribute) {
  4394. for (var i = 0, l = attribute.count; i < l; i++) {
  4395. _v1.x = attribute.getX(i);
  4396. _v1.y = attribute.getY(i);
  4397. _v1.z = attribute.getZ(i);
  4398. _v1.applyMatrix4(this);
  4399. attribute.setXYZ(i, _v1.x, _v1.y, _v1.z);
  4400. }
  4401. return attribute;
  4402. },
  4403. determinant: function () {
  4404. var te = this.elements;
  4405. var n11 = te[0],
  4406. n12 = te[4],
  4407. n13 = te[8],
  4408. n14 = te[12];
  4409. var n21 = te[1],
  4410. n22 = te[5],
  4411. n23 = te[9],
  4412. n24 = te[13];
  4413. var n31 = te[2],
  4414. n32 = te[6],
  4415. n33 = te[10],
  4416. n34 = te[14];
  4417. var n41 = te[3],
  4418. n42 = te[7],
  4419. n43 = te[11],
  4420. n44 = te[15]; //TODO: make this more efficient
  4421. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  4422. return n41 * (+n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34) + n42 * (+n11 * n23 * n34 - n11 * n24 * n33 + n14 * n21 * n33 - n13 * n21 * n34 + n13 * n24 * n31 - n14 * n23 * n31) + n43 * (+n11 * n24 * n32 - n11 * n22 * n34 - n14 * n21 * n32 + n12 * n21 * n34 + n14 * n22 * n31 - n12 * n24 * n31) + n44 * (-n13 * n22 * n31 - n11 * n23 * n32 + n11 * n22 * n33 + n13 * n21 * n32 - n12 * n21 * n33 + n12 * n23 * n31);
  4423. },
  4424. transpose: function () {
  4425. var te = this.elements;
  4426. var tmp;
  4427. tmp = te[1];
  4428. te[1] = te[4];
  4429. te[4] = tmp;
  4430. tmp = te[2];
  4431. te[2] = te[8];
  4432. te[8] = tmp;
  4433. tmp = te[6];
  4434. te[6] = te[9];
  4435. te[9] = tmp;
  4436. tmp = te[3];
  4437. te[3] = te[12];
  4438. te[12] = tmp;
  4439. tmp = te[7];
  4440. te[7] = te[13];
  4441. te[13] = tmp;
  4442. tmp = te[11];
  4443. te[11] = te[14];
  4444. te[14] = tmp;
  4445. return this;
  4446. },
  4447. setPosition: function (x, y, z) {
  4448. var te = this.elements;
  4449. if (x.isVector3) {
  4450. te[12] = x.x;
  4451. te[13] = x.y;
  4452. te[14] = x.z;
  4453. } else {
  4454. te[12] = x;
  4455. te[13] = y;
  4456. te[14] = z;
  4457. }
  4458. return this;
  4459. },
  4460. getInverse: function (m, throwOnDegenerate) {
  4461. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  4462. var te = this.elements,
  4463. me = m.elements,
  4464. n11 = me[0],
  4465. n21 = me[1],
  4466. n31 = me[2],
  4467. n41 = me[3],
  4468. n12 = me[4],
  4469. n22 = me[5],
  4470. n32 = me[6],
  4471. n42 = me[7],
  4472. n13 = me[8],
  4473. n23 = me[9],
  4474. n33 = me[10],
  4475. n43 = me[11],
  4476. n14 = me[12],
  4477. n24 = me[13],
  4478. n34 = me[14],
  4479. n44 = me[15],
  4480. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  4481. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  4482. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  4483. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  4484. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  4485. if (det === 0) {
  4486. var msg = "THREE.Matrix4: .getInverse() can't invert matrix, determinant is 0";
  4487. if (throwOnDegenerate === true) {
  4488. throw new Error(msg);
  4489. } else {
  4490. console.warn(msg);
  4491. }
  4492. return this.identity();
  4493. }
  4494. var detInv = 1 / det;
  4495. te[0] = t11 * detInv;
  4496. te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
  4497. te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
  4498. te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
  4499. te[4] = t12 * detInv;
  4500. te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
  4501. te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
  4502. te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
  4503. te[8] = t13 * detInv;
  4504. te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
  4505. te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
  4506. te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
  4507. te[12] = t14 * detInv;
  4508. te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
  4509. te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
  4510. te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
  4511. return this;
  4512. },
  4513. scale: function (v) {
  4514. var te = this.elements;
  4515. var x = v.x,
  4516. y = v.y,
  4517. z = v.z;
  4518. te[0] *= x;
  4519. te[4] *= y;
  4520. te[8] *= z;
  4521. te[1] *= x;
  4522. te[5] *= y;
  4523. te[9] *= z;
  4524. te[2] *= x;
  4525. te[6] *= y;
  4526. te[10] *= z;
  4527. te[3] *= x;
  4528. te[7] *= y;
  4529. te[11] *= z;
  4530. return this;
  4531. },
  4532. getMaxScaleOnAxis: function () {
  4533. var te = this.elements;
  4534. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  4535. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  4536. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  4537. return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  4538. },
  4539. makeTranslation: function (x, y, z) {
  4540. this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
  4541. return this;
  4542. },
  4543. makeRotationX: function (theta) {
  4544. var c = Math.cos(theta),
  4545. s = Math.sin(theta);
  4546. this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
  4547. return this;
  4548. },
  4549. makeRotationY: function (theta) {
  4550. var c = Math.cos(theta),
  4551. s = Math.sin(theta);
  4552. this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
  4553. return this;
  4554. },
  4555. makeRotationZ: function (theta) {
  4556. var c = Math.cos(theta),
  4557. s = Math.sin(theta);
  4558. this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  4559. return this;
  4560. },
  4561. makeRotationAxis: function (axis, angle) {
  4562. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  4563. var c = Math.cos(angle);
  4564. var s = Math.sin(angle);
  4565. var t = 1 - c;
  4566. var x = axis.x,
  4567. y = axis.y,
  4568. z = axis.z;
  4569. var tx = t * x,
  4570. ty = t * y;
  4571. this.set(tx * x + c, tx * y - s * z, tx * z + s * y, 0, tx * y + s * z, ty * y + c, ty * z - s * x, 0, tx * z - s * y, ty * z + s * x, t * z * z + c, 0, 0, 0, 0, 1);
  4572. return this;
  4573. },
  4574. makeScale: function (x, y, z) {
  4575. this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
  4576. return this;
  4577. },
  4578. makeShear: function (x, y, z) {
  4579. this.set(1, y, z, 0, x, 1, z, 0, x, y, 1, 0, 0, 0, 0, 1);
  4580. return this;
  4581. },
  4582. compose: function (position, quaternion, scale) {
  4583. var te = this.elements;
  4584. var x = quaternion._x,
  4585. y = quaternion._y,
  4586. z = quaternion._z,
  4587. w = quaternion._w;
  4588. var x2 = x + x,
  4589. y2 = y + y,
  4590. z2 = z + z;
  4591. var xx = x * x2,
  4592. xy = x * y2,
  4593. xz = x * z2;
  4594. var yy = y * y2,
  4595. yz = y * z2,
  4596. zz = z * z2;
  4597. var wx = w * x2,
  4598. wy = w * y2,
  4599. wz = w * z2;
  4600. var sx = scale.x,
  4601. sy = scale.y,
  4602. sz = scale.z;
  4603. te[0] = (1 - (yy + zz)) * sx;
  4604. te[1] = (xy + wz) * sx;
  4605. te[2] = (xz - wy) * sx;
  4606. te[3] = 0;
  4607. te[4] = (xy - wz) * sy;
  4608. te[5] = (1 - (xx + zz)) * sy;
  4609. te[6] = (yz + wx) * sy;
  4610. te[7] = 0;
  4611. te[8] = (xz + wy) * sz;
  4612. te[9] = (yz - wx) * sz;
  4613. te[10] = (1 - (xx + yy)) * sz;
  4614. te[11] = 0;
  4615. te[12] = position.x;
  4616. te[13] = position.y;
  4617. te[14] = position.z;
  4618. te[15] = 1;
  4619. return this;
  4620. },
  4621. decompose: function (position, quaternion, scale) {
  4622. var te = this.elements;
  4623. var sx = _v1.set(te[0], te[1], te[2]).length();
  4624. var sy = _v1.set(te[4], te[5], te[6]).length();
  4625. var sz = _v1.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale
  4626. var det = this.determinant();
  4627. if (det < 0) sx = -sx;
  4628. position.x = te[12];
  4629. position.y = te[13];
  4630. position.z = te[14]; // scale the rotation part
  4631. _m1.copy(this);
  4632. var invSX = 1 / sx;
  4633. var invSY = 1 / sy;
  4634. var invSZ = 1 / sz;
  4635. _m1.elements[0] *= invSX;
  4636. _m1.elements[1] *= invSX;
  4637. _m1.elements[2] *= invSX;
  4638. _m1.elements[4] *= invSY;
  4639. _m1.elements[5] *= invSY;
  4640. _m1.elements[6] *= invSY;
  4641. _m1.elements[8] *= invSZ;
  4642. _m1.elements[9] *= invSZ;
  4643. _m1.elements[10] *= invSZ;
  4644. quaternion.setFromRotationMatrix(_m1);
  4645. scale.x = sx;
  4646. scale.y = sy;
  4647. scale.z = sz;
  4648. return this;
  4649. },
  4650. makePerspective: function (left, right, top, bottom, near, far) {
  4651. if (far === undefined) {
  4652. console.warn('THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.');
  4653. }
  4654. var te = this.elements;
  4655. var x = 2 * near / (right - left);
  4656. var y = 2 * near / (top - bottom);
  4657. var a = (right + left) / (right - left);
  4658. var b = (top + bottom) / (top - bottom);
  4659. var c = -(far + near) / (far - near);
  4660. var d = -2 * far * near / (far - near);
  4661. te[0] = x;
  4662. te[4] = 0;
  4663. te[8] = a;
  4664. te[12] = 0;
  4665. te[1] = 0;
  4666. te[5] = y;
  4667. te[9] = b;
  4668. te[13] = 0;
  4669. te[2] = 0;
  4670. te[6] = 0;
  4671. te[10] = c;
  4672. te[14] = d;
  4673. te[3] = 0;
  4674. te[7] = 0;
  4675. te[11] = -1;
  4676. te[15] = 0;
  4677. return this;
  4678. },
  4679. makeOrthographic: function (left, right, top, bottom, near, far) {
  4680. var te = this.elements;
  4681. var w = 1.0 / (right - left);
  4682. var h = 1.0 / (top - bottom);
  4683. var p = 1.0 / (far - near);
  4684. var x = (right + left) * w;
  4685. var y = (top + bottom) * h;
  4686. var z = (far + near) * p;
  4687. te[0] = 2 * w;
  4688. te[4] = 0;
  4689. te[8] = 0;
  4690. te[12] = -x;
  4691. te[1] = 0;
  4692. te[5] = 2 * h;
  4693. te[9] = 0;
  4694. te[13] = -y;
  4695. te[2] = 0;
  4696. te[6] = 0;
  4697. te[10] = -2 * p;
  4698. te[14] = -z;
  4699. te[3] = 0;
  4700. te[7] = 0;
  4701. te[11] = 0;
  4702. te[15] = 1;
  4703. return this;
  4704. },
  4705. equals: function (matrix) {
  4706. var te = this.elements;
  4707. var me = matrix.elements;
  4708. for (var i = 0; i < 16; i++) {
  4709. if (te[i] !== me[i]) return false;
  4710. }
  4711. return true;
  4712. },
  4713. fromArray: function (array, offset) {
  4714. if (offset === undefined) offset = 0;
  4715. for (var i = 0; i < 16; i++) {
  4716. this.elements[i] = array[i + offset];
  4717. }
  4718. return this;
  4719. },
  4720. toArray: function (array, offset) {
  4721. if (array === undefined) array = [];
  4722. if (offset === undefined) offset = 0;
  4723. var te = this.elements;
  4724. array[offset] = te[0];
  4725. array[offset + 1] = te[1];
  4726. array[offset + 2] = te[2];
  4727. array[offset + 3] = te[3];
  4728. array[offset + 4] = te[4];
  4729. array[offset + 5] = te[5];
  4730. array[offset + 6] = te[6];
  4731. array[offset + 7] = te[7];
  4732. array[offset + 8] = te[8];
  4733. array[offset + 9] = te[9];
  4734. array[offset + 10] = te[10];
  4735. array[offset + 11] = te[11];
  4736. array[offset + 12] = te[12];
  4737. array[offset + 13] = te[13];
  4738. array[offset + 14] = te[14];
  4739. array[offset + 15] = te[15];
  4740. return array;
  4741. }
  4742. });
  4743. /**
  4744. * @author mrdoob / http://mrdoob.com/
  4745. * @author WestLangley / http://github.com/WestLangley
  4746. * @author bhouston / http://clara.io
  4747. */
  4748. var _matrix = new Matrix4();
  4749. var _quaternion$1 = new Quaternion();
  4750. function Euler(x, y, z, order) {
  4751. this._x = x || 0;
  4752. this._y = y || 0;
  4753. this._z = z || 0;
  4754. this._order = order || Euler.DefaultOrder;
  4755. }
  4756. Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  4757. Euler.DefaultOrder = 'XYZ';
  4758. Object.defineProperties(Euler.prototype, {
  4759. x: {
  4760. get: function () {
  4761. return this._x;
  4762. },
  4763. set: function (value) {
  4764. this._x = value;
  4765. this._onChangeCallback();
  4766. }
  4767. },
  4768. y: {
  4769. get: function () {
  4770. return this._y;
  4771. },
  4772. set: function (value) {
  4773. this._y = value;
  4774. this._onChangeCallback();
  4775. }
  4776. },
  4777. z: {
  4778. get: function () {
  4779. return this._z;
  4780. },
  4781. set: function (value) {
  4782. this._z = value;
  4783. this._onChangeCallback();
  4784. }
  4785. },
  4786. order: {
  4787. get: function () {
  4788. return this._order;
  4789. },
  4790. set: function (value) {
  4791. this._order = value;
  4792. this._onChangeCallback();
  4793. }
  4794. }
  4795. });
  4796. Object.assign(Euler.prototype, {
  4797. isEuler: true,
  4798. set: function (x, y, z, order) {
  4799. this._x = x;
  4800. this._y = y;
  4801. this._z = z;
  4802. this._order = order || this._order;
  4803. this._onChangeCallback();
  4804. return this;
  4805. },
  4806. clone: function () {
  4807. return new this.constructor(this._x, this._y, this._z, this._order);
  4808. },
  4809. copy: function (euler) {
  4810. this._x = euler._x;
  4811. this._y = euler._y;
  4812. this._z = euler._z;
  4813. this._order = euler._order;
  4814. this._onChangeCallback();
  4815. return this;
  4816. },
  4817. setFromRotationMatrix: function (m, order, update) {
  4818. var clamp = _Math.clamp; // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4819. var te = m.elements;
  4820. var m11 = te[0],
  4821. m12 = te[4],
  4822. m13 = te[8];
  4823. var m21 = te[1],
  4824. m22 = te[5],
  4825. m23 = te[9];
  4826. var m31 = te[2],
  4827. m32 = te[6],
  4828. m33 = te[10];
  4829. order = order || this._order;
  4830. if (order === 'XYZ') {
  4831. this._y = Math.asin(clamp(m13, -1, 1));
  4832. if (Math.abs(m13) < 0.9999999) {
  4833. this._x = Math.atan2(-m23, m33);
  4834. this._z = Math.atan2(-m12, m11);
  4835. } else {
  4836. this._x = Math.atan2(m32, m22);
  4837. this._z = 0;
  4838. }
  4839. } else if (order === 'YXZ') {
  4840. this._x = Math.asin(-clamp(m23, -1, 1));
  4841. if (Math.abs(m23) < 0.9999999) {
  4842. this._y = Math.atan2(m13, m33);
  4843. this._z = Math.atan2(m21, m22);
  4844. } else {
  4845. this._y = Math.atan2(-m31, m11);
  4846. this._z = 0;
  4847. }
  4848. } else if (order === 'ZXY') {
  4849. this._x = Math.asin(clamp(m32, -1, 1));
  4850. if (Math.abs(m32) < 0.9999999) {
  4851. this._y = Math.atan2(-m31, m33);
  4852. this._z = Math.atan2(-m12, m22);
  4853. } else {
  4854. this._y = 0;
  4855. this._z = Math.atan2(m21, m11);
  4856. }
  4857. } else if (order === 'ZYX') {
  4858. this._y = Math.asin(-clamp(m31, -1, 1));
  4859. if (Math.abs(m31) < 0.9999999) {
  4860. this._x = Math.atan2(m32, m33);
  4861. this._z = Math.atan2(m21, m11);
  4862. } else {
  4863. this._x = 0;
  4864. this._z = Math.atan2(-m12, m22);
  4865. }
  4866. } else if (order === 'YZX') {
  4867. this._z = Math.asin(clamp(m21, -1, 1));
  4868. if (Math.abs(m21) < 0.9999999) {
  4869. this._x = Math.atan2(-m23, m22);
  4870. this._y = Math.atan2(-m31, m11);
  4871. } else {
  4872. this._x = 0;
  4873. this._y = Math.atan2(m13, m33);
  4874. }
  4875. } else if (order === 'XZY') {
  4876. this._z = Math.asin(-clamp(m12, -1, 1));
  4877. if (Math.abs(m12) < 0.9999999) {
  4878. this._x = Math.atan2(m32, m22);
  4879. this._y = Math.atan2(m13, m11);
  4880. } else {
  4881. this._x = Math.atan2(-m23, m33);
  4882. this._y = 0;
  4883. }
  4884. } else {
  4885. console.warn('THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order);
  4886. }
  4887. this._order = order;
  4888. if (update !== false) this._onChangeCallback();
  4889. return this;
  4890. },
  4891. setFromQuaternion: function (q, order, update) {
  4892. _matrix.makeRotationFromQuaternion(q);
  4893. return this.setFromRotationMatrix(_matrix, order, update);
  4894. },
  4895. setFromVector3: function (v, order) {
  4896. return this.set(v.x, v.y, v.z, order || this._order);
  4897. },
  4898. reorder: function (newOrder) {
  4899. // WARNING: this discards revolution information -bhouston
  4900. _quaternion$1.setFromEuler(this);
  4901. return this.setFromQuaternion(_quaternion$1, newOrder);
  4902. },
  4903. equals: function (euler) {
  4904. return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  4905. },
  4906. fromArray: function (array) {
  4907. this._x = array[0];
  4908. this._y = array[1];
  4909. this._z = array[2];
  4910. if (array[3] !== undefined) this._order = array[3];
  4911. this._onChangeCallback();
  4912. return this;
  4913. },
  4914. toArray: function (array, offset) {
  4915. if (array === undefined) array = [];
  4916. if (offset === undefined) offset = 0;
  4917. array[offset] = this._x;
  4918. array[offset + 1] = this._y;
  4919. array[offset + 2] = this._z;
  4920. array[offset + 3] = this._order;
  4921. return array;
  4922. },
  4923. toVector3: function (optionalResult) {
  4924. if (optionalResult) {
  4925. return optionalResult.set(this._x, this._y, this._z);
  4926. } else {
  4927. return new Vector3(this._x, this._y, this._z);
  4928. }
  4929. },
  4930. _onChange: function (callback) {
  4931. this._onChangeCallback = callback;
  4932. return this;
  4933. },
  4934. _onChangeCallback: function () {}
  4935. });
  4936. /**
  4937. * @author mrdoob / http://mrdoob.com/
  4938. */
  4939. function Layers() {
  4940. this.mask = 1 | 0;
  4941. }
  4942. Object.assign(Layers.prototype, {
  4943. set: function (channel) {
  4944. this.mask = 1 << channel | 0;
  4945. },
  4946. enable: function (channel) {
  4947. this.mask |= 1 << channel | 0;
  4948. },
  4949. enableAll: function () {
  4950. this.mask = 0xffffffff | 0;
  4951. },
  4952. toggle: function (channel) {
  4953. this.mask ^= 1 << channel | 0;
  4954. },
  4955. disable: function (channel) {
  4956. this.mask &= ~(1 << channel | 0);
  4957. },
  4958. disableAll: function () {
  4959. this.mask = 0;
  4960. },
  4961. test: function (layers) {
  4962. return (this.mask & layers.mask) !== 0;
  4963. }
  4964. });
  4965. var _object3DId = 0;
  4966. var _v1$1 = new Vector3();
  4967. var _q1 = new Quaternion();
  4968. var _m1$1 = new Matrix4();
  4969. var _target = new Vector3();
  4970. var _position = new Vector3();
  4971. var _scale = new Vector3();
  4972. var _quaternion$2 = new Quaternion();
  4973. var _xAxis = new Vector3(1, 0, 0);
  4974. var _yAxis = new Vector3(0, 1, 0);
  4975. var _zAxis = new Vector3(0, 0, 1);
  4976. var _addedEvent = {
  4977. type: 'added'
  4978. };
  4979. var _removedEvent = {
  4980. type: 'removed'
  4981. };
  4982. /**
  4983. * @author mrdoob / http://mrdoob.com/
  4984. * @author mikael emtinger / http://gomo.se/
  4985. * @author alteredq / http://alteredqualia.com/
  4986. * @author WestLangley / http://github.com/WestLangley
  4987. * @author elephantatwork / www.elephantatwork.ch
  4988. */
  4989. function Object3D() {
  4990. Object.defineProperty(this, 'id', {
  4991. value: _object3DId++
  4992. });
  4993. this.uuid = _Math.generateUUID();
  4994. this.name = '';
  4995. this.type = 'Object3D';
  4996. this.parent = null;
  4997. this.children = [];
  4998. this.up = Object3D.DefaultUp.clone();
  4999. var position = new Vector3();
  5000. var rotation = new Euler();
  5001. var quaternion = new Quaternion();
  5002. var scale = new Vector3(1, 1, 1);
  5003. function onRotationChange() {
  5004. quaternion.setFromEuler(rotation, false);
  5005. }
  5006. function onQuaternionChange() {
  5007. rotation.setFromQuaternion(quaternion, undefined, false);
  5008. }
  5009. rotation._onChange(onRotationChange);
  5010. quaternion._onChange(onQuaternionChange);
  5011. Object.defineProperties(this, {
  5012. position: {
  5013. configurable: true,
  5014. enumerable: true,
  5015. value: position
  5016. },
  5017. rotation: {
  5018. configurable: true,
  5019. enumerable: true,
  5020. value: rotation
  5021. },
  5022. quaternion: {
  5023. configurable: true,
  5024. enumerable: true,
  5025. value: quaternion
  5026. },
  5027. scale: {
  5028. configurable: true,
  5029. enumerable: true,
  5030. value: scale
  5031. },
  5032. modelViewMatrix: {
  5033. value: new Matrix4()
  5034. },
  5035. normalMatrix: {
  5036. value: new Matrix3()
  5037. }
  5038. });
  5039. this.matrix = new Matrix4();
  5040. this.matrixWorld = new Matrix4();
  5041. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  5042. this.matrixWorldNeedsUpdate = false;
  5043. this.layers = new Layers();
  5044. this.visible = true;
  5045. this.castShadow = false;
  5046. this.receiveShadow = false;
  5047. this.frustumCulled = true;
  5048. this.renderOrder = 0;
  5049. this.userData = {};
  5050. }
  5051. Object3D.DefaultUp = new Vector3(0, 1, 0);
  5052. Object3D.DefaultMatrixAutoUpdate = true;
  5053. Object3D.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  5054. constructor: Object3D,
  5055. isObject3D: true,
  5056. onBeforeRender: function () {},
  5057. onAfterRender: function () {},
  5058. applyMatrix: function (matrix) {
  5059. if (this.matrixAutoUpdate) this.updateMatrix();
  5060. this.matrix.premultiply(matrix);
  5061. this.matrix.decompose(this.position, this.quaternion, this.scale);
  5062. },
  5063. applyQuaternion: function (q) {
  5064. this.quaternion.premultiply(q);
  5065. return this;
  5066. },
  5067. setRotationFromAxisAngle: function (axis, angle) {
  5068. // assumes axis is normalized
  5069. this.quaternion.setFromAxisAngle(axis, angle);
  5070. },
  5071. setRotationFromEuler: function (euler) {
  5072. this.quaternion.setFromEuler(euler, true);
  5073. },
  5074. setRotationFromMatrix: function (m) {
  5075. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  5076. this.quaternion.setFromRotationMatrix(m);
  5077. },
  5078. setRotationFromQuaternion: function (q) {
  5079. // assumes q is normalized
  5080. this.quaternion.copy(q);
  5081. },
  5082. rotateOnAxis: function (axis, angle) {
  5083. // rotate object on axis in object space
  5084. // axis is assumed to be normalized
  5085. _q1.setFromAxisAngle(axis, angle);
  5086. this.quaternion.multiply(_q1);
  5087. return this;
  5088. },
  5089. rotateOnWorldAxis: function (axis, angle) {
  5090. // rotate object on axis in world space
  5091. // axis is assumed to be normalized
  5092. // method assumes no rotated parent
  5093. _q1.setFromAxisAngle(axis, angle);
  5094. this.quaternion.premultiply(_q1);
  5095. return this;
  5096. },
  5097. rotateX: function (angle) {
  5098. return this.rotateOnAxis(_xAxis, angle);
  5099. },
  5100. rotateY: function (angle) {
  5101. return this.rotateOnAxis(_yAxis, angle);
  5102. },
  5103. rotateZ: function (angle) {
  5104. return this.rotateOnAxis(_zAxis, angle);
  5105. },
  5106. translateOnAxis: function (axis, distance) {
  5107. // translate object by distance along axis in object space
  5108. // axis is assumed to be normalized
  5109. _v1$1.copy(axis).applyQuaternion(this.quaternion);
  5110. this.position.add(_v1$1.multiplyScalar(distance));
  5111. return this;
  5112. },
  5113. translateX: function (distance) {
  5114. return this.translateOnAxis(_xAxis, distance);
  5115. },
  5116. translateY: function (distance) {
  5117. return this.translateOnAxis(_yAxis, distance);
  5118. },
  5119. translateZ: function (distance) {
  5120. return this.translateOnAxis(_zAxis, distance);
  5121. },
  5122. localToWorld: function (vector) {
  5123. return vector.applyMatrix4(this.matrixWorld);
  5124. },
  5125. worldToLocal: function (vector) {
  5126. return vector.applyMatrix4(_m1$1.getInverse(this.matrixWorld));
  5127. },
  5128. lookAt: function (x, y, z) {
  5129. // This method does not support objects having non-uniformly-scaled parent(s)
  5130. if (x.isVector3) {
  5131. _target.copy(x);
  5132. } else {
  5133. _target.set(x, y, z);
  5134. }
  5135. var parent = this.parent;
  5136. this.updateWorldMatrix(true, false);
  5137. _position.setFromMatrixPosition(this.matrixWorld);
  5138. if (this.isCamera || this.isLight) {
  5139. _m1$1.lookAt(_position, _target, this.up);
  5140. } else {
  5141. _m1$1.lookAt(_target, _position, this.up);
  5142. }
  5143. this.quaternion.setFromRotationMatrix(_m1$1);
  5144. if (parent) {
  5145. _m1$1.extractRotation(parent.matrixWorld);
  5146. _q1.setFromRotationMatrix(_m1$1);
  5147. this.quaternion.premultiply(_q1.inverse());
  5148. }
  5149. },
  5150. add: function (object) {
  5151. if (arguments.length > 1) {
  5152. for (var i = 0; i < arguments.length; i++) {
  5153. this.add(arguments[i]);
  5154. }
  5155. return this;
  5156. }
  5157. if (object === this) {
  5158. console.error("THREE.Object3D.add: object can't be added as a child of itself.", object);
  5159. return this;
  5160. }
  5161. if (object && object.isObject3D) {
  5162. if (object.parent !== null) {
  5163. object.parent.remove(object);
  5164. }
  5165. object.parent = this;
  5166. this.children.push(object);
  5167. object.dispatchEvent(_addedEvent);
  5168. } else {
  5169. console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.", object);
  5170. }
  5171. return this;
  5172. },
  5173. remove: function (object) {
  5174. if (arguments.length > 1) {
  5175. for (var i = 0; i < arguments.length; i++) {
  5176. this.remove(arguments[i]);
  5177. }
  5178. return this;
  5179. }
  5180. var index = this.children.indexOf(object);
  5181. if (index !== -1) {
  5182. object.parent = null;
  5183. this.children.splice(index, 1);
  5184. object.dispatchEvent(_removedEvent);
  5185. }
  5186. return this;
  5187. },
  5188. attach: function (object) {
  5189. // adds object as a child of this, while maintaining the object's world transform
  5190. this.updateWorldMatrix(true, false);
  5191. _m1$1.getInverse(this.matrixWorld);
  5192. if (object.parent !== null) {
  5193. object.parent.updateWorldMatrix(true, false);
  5194. _m1$1.multiply(object.parent.matrixWorld);
  5195. }
  5196. object.applyMatrix(_m1$1);
  5197. object.updateWorldMatrix(false, false);
  5198. this.add(object);
  5199. return this;
  5200. },
  5201. getObjectById: function (id) {
  5202. return this.getObjectByProperty('id', id);
  5203. },
  5204. getObjectByName: function (name) {
  5205. return this.getObjectByProperty('name', name);
  5206. },
  5207. getObjectByProperty: function (name, value) {
  5208. if (this[name] === value) return this;
  5209. for (var i = 0, l = this.children.length; i < l; i++) {
  5210. var child = this.children[i];
  5211. var object = child.getObjectByProperty(name, value);
  5212. if (object !== undefined) {
  5213. return object;
  5214. }
  5215. }
  5216. return undefined;
  5217. },
  5218. getWorldPosition: function (target) {
  5219. if (target === undefined) {
  5220. console.warn('THREE.Object3D: .getWorldPosition() target is now required');
  5221. target = new Vector3();
  5222. }
  5223. this.updateMatrixWorld(true);
  5224. return target.setFromMatrixPosition(this.matrixWorld);
  5225. },
  5226. getWorldQuaternion: function (target) {
  5227. if (target === undefined) {
  5228. console.warn('THREE.Object3D: .getWorldQuaternion() target is now required');
  5229. target = new Quaternion();
  5230. }
  5231. this.updateMatrixWorld(true);
  5232. this.matrixWorld.decompose(_position, target, _scale);
  5233. return target;
  5234. },
  5235. getWorldScale: function (target) {
  5236. if (target === undefined) {
  5237. console.warn('THREE.Object3D: .getWorldScale() target is now required');
  5238. target = new Vector3();
  5239. }
  5240. this.updateMatrixWorld(true);
  5241. this.matrixWorld.decompose(_position, _quaternion$2, target);
  5242. return target;
  5243. },
  5244. getWorldDirection: function (target) {
  5245. if (target === undefined) {
  5246. console.warn('THREE.Object3D: .getWorldDirection() target is now required');
  5247. target = new Vector3();
  5248. }
  5249. this.updateMatrixWorld(true);
  5250. var e = this.matrixWorld.elements;
  5251. return target.set(e[8], e[9], e[10]).normalize();
  5252. },
  5253. raycast: function () {},
  5254. traverse: function (callback) {
  5255. callback(this);
  5256. var children = this.children;
  5257. for (var i = 0, l = children.length; i < l; i++) {
  5258. children[i].traverse(callback);
  5259. }
  5260. },
  5261. traverseVisible: function (callback) {
  5262. if (this.visible === false) return;
  5263. callback(this);
  5264. var children = this.children;
  5265. for (var i = 0, l = children.length; i < l; i++) {
  5266. children[i].traverseVisible(callback);
  5267. }
  5268. },
  5269. traverseAncestors: function (callback) {
  5270. var parent = this.parent;
  5271. if (parent !== null) {
  5272. callback(parent);
  5273. parent.traverseAncestors(callback);
  5274. }
  5275. },
  5276. updateMatrix: function () {
  5277. this.matrix.compose(this.position, this.quaternion, this.scale);
  5278. this.matrixWorldNeedsUpdate = true;
  5279. },
  5280. updateMatrixWorld: function (force) {
  5281. if (this.matrixAutoUpdate) this.updateMatrix();
  5282. if (this.matrixWorldNeedsUpdate || force) {
  5283. if (this.parent === null) {
  5284. this.matrixWorld.copy(this.matrix);
  5285. } else {
  5286. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  5287. }
  5288. this.matrixWorldNeedsUpdate = false;
  5289. force = true;
  5290. } // update children
  5291. var children = this.children;
  5292. for (var i = 0, l = children.length; i < l; i++) {
  5293. children[i].updateMatrixWorld(force);
  5294. }
  5295. },
  5296. updateWorldMatrix: function (updateParents, updateChildren) {
  5297. var parent = this.parent;
  5298. if (updateParents === true && parent !== null) {
  5299. parent.updateWorldMatrix(true, false);
  5300. }
  5301. if (this.matrixAutoUpdate) this.updateMatrix();
  5302. if (this.parent === null) {
  5303. this.matrixWorld.copy(this.matrix);
  5304. } else {
  5305. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  5306. } // update children
  5307. if (updateChildren === true) {
  5308. var children = this.children;
  5309. for (var i = 0, l = children.length; i < l; i++) {
  5310. children[i].updateWorldMatrix(false, true);
  5311. }
  5312. }
  5313. },
  5314. toJSON: function (meta) {
  5315. // meta is a string when called from JSON.stringify
  5316. var isRootObject = meta === undefined || typeof meta === 'string';
  5317. var output = {}; // meta is a hash used to collect geometries, materials.
  5318. // not providing it implies that this is the root object
  5319. // being serialized.
  5320. if (isRootObject) {
  5321. // initialize meta obj
  5322. meta = {
  5323. geometries: {},
  5324. materials: {},
  5325. textures: {},
  5326. images: {},
  5327. shapes: {}
  5328. };
  5329. output.metadata = {
  5330. version: 4.5,
  5331. type: 'Object',
  5332. generator: 'Object3D.toJSON'
  5333. };
  5334. } // standard Object3D serialization
  5335. var object = {};
  5336. object.uuid = this.uuid;
  5337. object.type = this.type;
  5338. if (this.name !== '') object.name = this.name;
  5339. if (this.castShadow === true) object.castShadow = true;
  5340. if (this.receiveShadow === true) object.receiveShadow = true;
  5341. if (this.visible === false) object.visible = false;
  5342. if (this.frustumCulled === false) object.frustumCulled = false;
  5343. if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
  5344. if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
  5345. object.layers = this.layers.mask;
  5346. object.matrix = this.matrix.toArray();
  5347. if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific properties
  5348. if (this.isMesh && this.drawMode !== TrianglesDrawMode) object.drawMode = this.drawMode; //
  5349. function serialize(library, element) {
  5350. if (library[element.uuid] === undefined) {
  5351. library[element.uuid] = element.toJSON(meta);
  5352. }
  5353. return element.uuid;
  5354. }
  5355. if (this.isMesh || this.isLine || this.isPoints) {
  5356. object.geometry = serialize(meta.geometries, this.geometry);
  5357. var parameters = this.geometry.parameters;
  5358. if (parameters !== undefined && parameters.shapes !== undefined) {
  5359. var shapes = parameters.shapes;
  5360. if (Array.isArray(shapes)) {
  5361. for (var i = 0, l = shapes.length; i < l; i++) {
  5362. var shape = shapes[i];
  5363. serialize(meta.shapes, shape);
  5364. }
  5365. } else {
  5366. serialize(meta.shapes, shapes);
  5367. }
  5368. }
  5369. }
  5370. if (this.material !== undefined) {
  5371. if (Array.isArray(this.material)) {
  5372. var uuids = [];
  5373. for (var i = 0, l = this.material.length; i < l; i++) {
  5374. uuids.push(serialize(meta.materials, this.material[i]));
  5375. }
  5376. object.material = uuids;
  5377. } else {
  5378. object.material = serialize(meta.materials, this.material);
  5379. }
  5380. } //
  5381. if (this.children.length > 0) {
  5382. object.children = [];
  5383. for (var i = 0; i < this.children.length; i++) {
  5384. object.children.push(this.children[i].toJSON(meta).object);
  5385. }
  5386. }
  5387. if (isRootObject) {
  5388. var geometries = extractFromCache(meta.geometries);
  5389. var materials = extractFromCache(meta.materials);
  5390. var textures = extractFromCache(meta.textures);
  5391. var images = extractFromCache(meta.images);
  5392. var shapes = extractFromCache(meta.shapes);
  5393. if (geometries.length > 0) output.geometries = geometries;
  5394. if (materials.length > 0) output.materials = materials;
  5395. if (textures.length > 0) output.textures = textures;
  5396. if (images.length > 0) output.images = images;
  5397. if (shapes.length > 0) output.shapes = shapes;
  5398. }
  5399. output.object = object;
  5400. return output; // extract data from the cache hash
  5401. // remove metadata on each item
  5402. // and return as array
  5403. function extractFromCache(cache) {
  5404. var values = [];
  5405. for (var key in cache) {
  5406. var data = cache[key];
  5407. delete data.metadata;
  5408. values.push(data);
  5409. }
  5410. return values;
  5411. }
  5412. },
  5413. clone: function (recursive) {
  5414. return new this.constructor().copy(this, recursive);
  5415. },
  5416. copy: function (source, recursive) {
  5417. if (recursive === undefined) recursive = true;
  5418. this.name = source.name;
  5419. this.up.copy(source.up);
  5420. this.position.copy(source.position);
  5421. this.quaternion.copy(source.quaternion);
  5422. this.scale.copy(source.scale);
  5423. this.matrix.copy(source.matrix);
  5424. this.matrixWorld.copy(source.matrixWorld);
  5425. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5426. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  5427. this.layers.mask = source.layers.mask;
  5428. this.visible = source.visible;
  5429. this.castShadow = source.castShadow;
  5430. this.receiveShadow = source.receiveShadow;
  5431. this.frustumCulled = source.frustumCulled;
  5432. this.renderOrder = source.renderOrder;
  5433. this.userData = JSON.parse(JSON.stringify(source.userData));
  5434. if (recursive === true) {
  5435. for (var i = 0; i < source.children.length; i++) {
  5436. var child = source.children[i];
  5437. this.add(child.clone());
  5438. }
  5439. }
  5440. return this;
  5441. }
  5442. });
  5443. /**
  5444. * @author mrdoob / http://mrdoob.com/
  5445. */
  5446. function Scene() {
  5447. Object3D.call(this);
  5448. this.type = 'Scene';
  5449. this.background = null;
  5450. this.fog = null;
  5451. this.overrideMaterial = null;
  5452. this.autoUpdate = true; // checked by the renderer
  5453. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  5454. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  5455. detail: this
  5456. })); // eslint-disable-line no-undef
  5457. }
  5458. }
  5459. Scene.prototype = Object.assign(Object.create(Object3D.prototype), {
  5460. constructor: Scene,
  5461. isScene: true,
  5462. copy: function (source, recursive) {
  5463. Object3D.prototype.copy.call(this, source, recursive);
  5464. if (source.background !== null) this.background = source.background.clone();
  5465. if (source.fog !== null) this.fog = source.fog.clone();
  5466. if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
  5467. this.autoUpdate = source.autoUpdate;
  5468. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5469. return this;
  5470. },
  5471. toJSON: function (meta) {
  5472. var data = Object3D.prototype.toJSON.call(this, meta);
  5473. if (this.background !== null) data.object.background = this.background.toJSON(meta);
  5474. if (this.fog !== null) data.object.fog = this.fog.toJSON();
  5475. return data;
  5476. },
  5477. dispose: function () {
  5478. this.dispatchEvent({
  5479. type: 'dispose'
  5480. });
  5481. }
  5482. });
  5483. var _points = [new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3()];
  5484. var _vector$2 = new Vector3(); // triangle centered vertices
  5485. var _v0 = new Vector3();
  5486. var _v1$2 = new Vector3();
  5487. var _v2 = new Vector3(); // triangle edge vectors
  5488. var _f0 = new Vector3();
  5489. var _f1 = new Vector3();
  5490. var _f2 = new Vector3();
  5491. var _center = new Vector3();
  5492. var _extents = new Vector3();
  5493. var _triangleNormal = new Vector3();
  5494. var _testAxis = new Vector3();
  5495. /**
  5496. * @author bhouston / http://clara.io
  5497. * @author WestLangley / http://github.com/WestLangley
  5498. */
  5499. function Box3(min, max) {
  5500. this.min = min !== undefined ? min : new Vector3(+Infinity, +Infinity, +Infinity);
  5501. this.max = max !== undefined ? max : new Vector3(-Infinity, -Infinity, -Infinity);
  5502. }
  5503. Object.assign(Box3.prototype, {
  5504. isBox3: true,
  5505. set: function (min, max) {
  5506. this.min.copy(min);
  5507. this.max.copy(max);
  5508. return this;
  5509. },
  5510. setFromArray: function (array) {
  5511. var minX = +Infinity;
  5512. var minY = +Infinity;
  5513. var minZ = +Infinity;
  5514. var maxX = -Infinity;
  5515. var maxY = -Infinity;
  5516. var maxZ = -Infinity;
  5517. for (var i = 0, l = array.length; i < l; i += 3) {
  5518. var x = array[i];
  5519. var y = array[i + 1];
  5520. var z = array[i + 2];
  5521. if (x < minX) minX = x;
  5522. if (y < minY) minY = y;
  5523. if (z < minZ) minZ = z;
  5524. if (x > maxX) maxX = x;
  5525. if (y > maxY) maxY = y;
  5526. if (z > maxZ) maxZ = z;
  5527. }
  5528. this.min.set(minX, minY, minZ);
  5529. this.max.set(maxX, maxY, maxZ);
  5530. return this;
  5531. },
  5532. setFromBufferAttribute: function (attribute) {
  5533. var minX = +Infinity;
  5534. var minY = +Infinity;
  5535. var minZ = +Infinity;
  5536. var maxX = -Infinity;
  5537. var maxY = -Infinity;
  5538. var maxZ = -Infinity;
  5539. for (var i = 0, l = attribute.count; i < l; i++) {
  5540. var x = attribute.getX(i);
  5541. var y = attribute.getY(i);
  5542. var z = attribute.getZ(i);
  5543. if (x < minX) minX = x;
  5544. if (y < minY) minY = y;
  5545. if (z < minZ) minZ = z;
  5546. if (x > maxX) maxX = x;
  5547. if (y > maxY) maxY = y;
  5548. if (z > maxZ) maxZ = z;
  5549. }
  5550. this.min.set(minX, minY, minZ);
  5551. this.max.set(maxX, maxY, maxZ);
  5552. return this;
  5553. },
  5554. setFromPoints: function (points) {
  5555. this.makeEmpty();
  5556. for (var i = 0, il = points.length; i < il; i++) {
  5557. this.expandByPoint(points[i]);
  5558. }
  5559. return this;
  5560. },
  5561. setFromCenterAndSize: function (center, size) {
  5562. var halfSize = _vector$2.copy(size).multiplyScalar(0.5);
  5563. this.min.copy(center).sub(halfSize);
  5564. this.max.copy(center).add(halfSize);
  5565. return this;
  5566. },
  5567. setFromObject: function (object) {
  5568. this.makeEmpty();
  5569. return this.expandByObject(object);
  5570. },
  5571. clone: function () {
  5572. return new this.constructor().copy(this);
  5573. },
  5574. copy: function (box) {
  5575. this.min.copy(box.min);
  5576. this.max.copy(box.max);
  5577. return this;
  5578. },
  5579. makeEmpty: function () {
  5580. this.min.x = this.min.y = this.min.z = +Infinity;
  5581. this.max.x = this.max.y = this.max.z = -Infinity;
  5582. return this;
  5583. },
  5584. isEmpty: function () {
  5585. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  5586. return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  5587. },
  5588. getCenter: function (target) {
  5589. if (target === undefined) {
  5590. console.warn('THREE.Box3: .getCenter() target is now required');
  5591. target = new Vector3();
  5592. }
  5593. return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  5594. },
  5595. getSize: function (target) {
  5596. if (target === undefined) {
  5597. console.warn('THREE.Box3: .getSize() target is now required');
  5598. target = new Vector3();
  5599. }
  5600. return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  5601. },
  5602. expandByPoint: function (point) {
  5603. this.min.min(point);
  5604. this.max.max(point);
  5605. return this;
  5606. },
  5607. expandByVector: function (vector) {
  5608. this.min.sub(vector);
  5609. this.max.add(vector);
  5610. return this;
  5611. },
  5612. expandByScalar: function (scalar) {
  5613. this.min.addScalar(-scalar);
  5614. this.max.addScalar(scalar);
  5615. return this;
  5616. },
  5617. expandByObject: function (object) {
  5618. var i, l; // Computes the world-axis-aligned bounding box of an object (including its children),
  5619. // accounting for both the object's, and children's, world transforms
  5620. object.updateWorldMatrix(false, false);
  5621. var geometry = object.geometry;
  5622. if (geometry !== undefined) {
  5623. if (geometry.isGeometry) {
  5624. var vertices = geometry.vertices;
  5625. for (i = 0, l = vertices.length; i < l; i++) {
  5626. _vector$2.copy(vertices[i]);
  5627. _vector$2.applyMatrix4(object.matrixWorld);
  5628. this.expandByPoint(_vector$2);
  5629. }
  5630. } else if (geometry.isBufferGeometry) {
  5631. var attribute = geometry.attributes.position;
  5632. if (attribute !== undefined) {
  5633. for (i = 0, l = attribute.count; i < l; i++) {
  5634. _vector$2.fromBufferAttribute(attribute, i).applyMatrix4(object.matrixWorld);
  5635. this.expandByPoint(_vector$2);
  5636. }
  5637. }
  5638. }
  5639. } //
  5640. var children = object.children;
  5641. for (i = 0, l = children.length; i < l; i++) {
  5642. this.expandByObject(children[i]);
  5643. }
  5644. return this;
  5645. },
  5646. containsPoint: function (point) {
  5647. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y || point.z < this.min.z || point.z > this.max.z ? false : true;
  5648. },
  5649. containsBox: function (box) {
  5650. return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y && this.min.z <= box.min.z && box.max.z <= this.max.z;
  5651. },
  5652. getParameter: function (point, target) {
  5653. // This can potentially have a divide by zero if the box
  5654. // has a size dimension of 0.
  5655. if (target === undefined) {
  5656. console.warn('THREE.Box3: .getParameter() target is now required');
  5657. target = new Vector3();
  5658. }
  5659. return target.set((point.x - this.min.x) / (this.max.x - this.min.x), (point.y - this.min.y) / (this.max.y - this.min.y), (point.z - this.min.z) / (this.max.z - this.min.z));
  5660. },
  5661. intersectsBox: function (box) {
  5662. // using 6 splitting planes to rule out intersections.
  5663. return box.max.x < this.min.x || box.min.x > this.max.x || box.max.y < this.min.y || box.min.y > this.max.y || box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  5664. },
  5665. intersectsSphere: function (sphere) {
  5666. // Find the point on the AABB closest to the sphere center.
  5667. this.clampPoint(sphere.center, _vector$2); // If that point is inside the sphere, the AABB and sphere intersect.
  5668. return _vector$2.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  5669. },
  5670. intersectsPlane: function (plane) {
  5671. // We compute the minimum and maximum dot product values. If those values
  5672. // are on the same side (back or front) of the plane, then there is no intersection.
  5673. var min, max;
  5674. if (plane.normal.x > 0) {
  5675. min = plane.normal.x * this.min.x;
  5676. max = plane.normal.x * this.max.x;
  5677. } else {
  5678. min = plane.normal.x * this.max.x;
  5679. max = plane.normal.x * this.min.x;
  5680. }
  5681. if (plane.normal.y > 0) {
  5682. min += plane.normal.y * this.min.y;
  5683. max += plane.normal.y * this.max.y;
  5684. } else {
  5685. min += plane.normal.y * this.max.y;
  5686. max += plane.normal.y * this.min.y;
  5687. }
  5688. if (plane.normal.z > 0) {
  5689. min += plane.normal.z * this.min.z;
  5690. max += plane.normal.z * this.max.z;
  5691. } else {
  5692. min += plane.normal.z * this.max.z;
  5693. max += plane.normal.z * this.min.z;
  5694. }
  5695. return min <= -plane.constant && max >= -plane.constant;
  5696. },
  5697. intersectsTriangle: function (triangle) {
  5698. if (this.isEmpty()) {
  5699. return false;
  5700. } // compute box center and extents
  5701. this.getCenter(_center);
  5702. _extents.subVectors(this.max, _center); // translate triangle to aabb origin
  5703. _v0.subVectors(triangle.a, _center);
  5704. _v1$2.subVectors(triangle.b, _center);
  5705. _v2.subVectors(triangle.c, _center); // compute edge vectors for triangle
  5706. _f0.subVectors(_v1$2, _v0);
  5707. _f1.subVectors(_v2, _v1$2);
  5708. _f2.subVectors(_v0, _v2); // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  5709. // make an axis testing of each of the 3 sides of the aabb against each of the 3 sides of the triangle = 9 axis of separation
  5710. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  5711. var axes = [0, -_f0.z, _f0.y, 0, -_f1.z, _f1.y, 0, -_f2.z, _f2.y, _f0.z, 0, -_f0.x, _f1.z, 0, -_f1.x, _f2.z, 0, -_f2.x, -_f0.y, _f0.x, 0, -_f1.y, _f1.x, 0, -_f2.y, _f2.x, 0];
  5712. if (!satForAxes(axes, _v0, _v1$2, _v2, _extents)) {
  5713. return false;
  5714. } // test 3 face normals from the aabb
  5715. axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  5716. if (!satForAxes(axes, _v0, _v1$2, _v2, _extents)) {
  5717. return false;
  5718. } // finally testing the face normal of the triangle
  5719. // use already existing triangle edge vectors here
  5720. _triangleNormal.crossVectors(_f0, _f1);
  5721. axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
  5722. return satForAxes(axes, _v0, _v1$2, _v2, _extents);
  5723. },
  5724. clampPoint: function (point, target) {
  5725. if (target === undefined) {
  5726. console.warn('THREE.Box3: .clampPoint() target is now required');
  5727. target = new Vector3();
  5728. }
  5729. return target.copy(point).clamp(this.min, this.max);
  5730. },
  5731. distanceToPoint: function (point) {
  5732. var clampedPoint = _vector$2.copy(point).clamp(this.min, this.max);
  5733. return clampedPoint.sub(point).length();
  5734. },
  5735. getBoundingSphere: function (target) {
  5736. if (target === undefined) {
  5737. console.error('THREE.Box3: .getBoundingSphere() target is now required'); //target = new Sphere(); // removed to avoid cyclic dependency
  5738. }
  5739. this.getCenter(target.center);
  5740. target.radius = this.getSize(_vector$2).length() * 0.5;
  5741. return target;
  5742. },
  5743. intersect: function (box) {
  5744. this.min.max(box.min);
  5745. this.max.min(box.max); // 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.
  5746. if (this.isEmpty()) this.makeEmpty();
  5747. return this;
  5748. },
  5749. union: function (box) {
  5750. this.min.min(box.min);
  5751. this.max.max(box.max);
  5752. return this;
  5753. },
  5754. applyMatrix4: function (matrix) {
  5755. // transform of empty box is an empty box.
  5756. if (this.isEmpty()) return this; // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  5757. _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
  5758. _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
  5759. _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
  5760. _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
  5761. _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
  5762. _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
  5763. _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
  5764. _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
  5765. this.setFromPoints(_points);
  5766. return this;
  5767. },
  5768. translate: function (offset) {
  5769. this.min.add(offset);
  5770. this.max.add(offset);
  5771. return this;
  5772. },
  5773. equals: function (box) {
  5774. return box.min.equals(this.min) && box.max.equals(this.max);
  5775. }
  5776. });
  5777. function satForAxes(axes, v0, v1, v2, extents) {
  5778. var i, j;
  5779. for (i = 0, j = axes.length - 3; i <= j; i += 3) {
  5780. _testAxis.fromArray(axes, i); // project the aabb onto the seperating axis
  5781. var r = extents.x * Math.abs(_testAxis.x) + extents.y * Math.abs(_testAxis.y) + extents.z * Math.abs(_testAxis.z); // project all 3 vertices of the triangle onto the seperating axis
  5782. var p0 = v0.dot(_testAxis);
  5783. var p1 = v1.dot(_testAxis);
  5784. var p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects r
  5785. if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
  5786. // points of the projected triangle are outside the projected half-length of the aabb
  5787. // the axis is seperating and we can exit
  5788. return false;
  5789. }
  5790. }
  5791. return true;
  5792. }
  5793. var _box = new Box3();
  5794. /**
  5795. * @author bhouston / http://clara.io
  5796. * @author mrdoob / http://mrdoob.com/
  5797. */
  5798. function Sphere(center, radius) {
  5799. this.center = center !== undefined ? center : new Vector3();
  5800. this.radius = radius !== undefined ? radius : 0;
  5801. }
  5802. Object.assign(Sphere.prototype, {
  5803. set: function (center, radius) {
  5804. this.center.copy(center);
  5805. this.radius = radius;
  5806. return this;
  5807. },
  5808. setFromPoints: function (points, optionalCenter) {
  5809. var center = this.center;
  5810. if (optionalCenter !== undefined) {
  5811. center.copy(optionalCenter);
  5812. } else {
  5813. _box.setFromPoints(points).getCenter(center);
  5814. }
  5815. var maxRadiusSq = 0;
  5816. for (var i = 0, il = points.length; i < il; i++) {
  5817. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
  5818. }
  5819. this.radius = Math.sqrt(maxRadiusSq);
  5820. return this;
  5821. },
  5822. clone: function () {
  5823. return new this.constructor().copy(this);
  5824. },
  5825. copy: function (sphere) {
  5826. this.center.copy(sphere.center);
  5827. this.radius = sphere.radius;
  5828. return this;
  5829. },
  5830. empty: function () {
  5831. return this.radius <= 0;
  5832. },
  5833. containsPoint: function (point) {
  5834. return point.distanceToSquared(this.center) <= this.radius * this.radius;
  5835. },
  5836. distanceToPoint: function (point) {
  5837. return point.distanceTo(this.center) - this.radius;
  5838. },
  5839. intersectsSphere: function (sphere) {
  5840. var radiusSum = this.radius + sphere.radius;
  5841. return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  5842. },
  5843. intersectsBox: function (box) {
  5844. return box.intersectsSphere(this);
  5845. },
  5846. intersectsPlane: function (plane) {
  5847. return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  5848. },
  5849. clampPoint: function (point, target) {
  5850. var deltaLengthSq = this.center.distanceToSquared(point);
  5851. if (target === undefined) {
  5852. console.warn('THREE.Sphere: .clampPoint() target is now required');
  5853. target = new Vector3();
  5854. }
  5855. target.copy(point);
  5856. if (deltaLengthSq > this.radius * this.radius) {
  5857. target.sub(this.center).normalize();
  5858. target.multiplyScalar(this.radius).add(this.center);
  5859. }
  5860. return target;
  5861. },
  5862. getBoundingBox: function (target) {
  5863. if (target === undefined) {
  5864. console.warn('THREE.Sphere: .getBoundingBox() target is now required');
  5865. target = new Box3();
  5866. }
  5867. target.set(this.center, this.center);
  5868. target.expandByScalar(this.radius);
  5869. return target;
  5870. },
  5871. applyMatrix4: function (matrix) {
  5872. this.center.applyMatrix4(matrix);
  5873. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  5874. return this;
  5875. },
  5876. translate: function (offset) {
  5877. this.center.add(offset);
  5878. return this;
  5879. },
  5880. equals: function (sphere) {
  5881. return sphere.center.equals(this.center) && sphere.radius === this.radius;
  5882. }
  5883. });
  5884. var _vector$3 = new Vector3();
  5885. var _segCenter = new Vector3();
  5886. var _segDir = new Vector3();
  5887. var _diff = new Vector3();
  5888. var _edge1 = new Vector3();
  5889. var _edge2 = new Vector3();
  5890. var _normal = new Vector3();
  5891. /**
  5892. * @author bhouston / http://clara.io
  5893. */
  5894. function Ray(origin, direction) {
  5895. this.origin = origin !== undefined ? origin : new Vector3();
  5896. this.direction = direction !== undefined ? direction : new Vector3();
  5897. }
  5898. Object.assign(Ray.prototype, {
  5899. set: function (origin, direction) {
  5900. this.origin.copy(origin);
  5901. this.direction.copy(direction);
  5902. return this;
  5903. },
  5904. clone: function () {
  5905. return new this.constructor().copy(this);
  5906. },
  5907. copy: function (ray) {
  5908. this.origin.copy(ray.origin);
  5909. this.direction.copy(ray.direction);
  5910. return this;
  5911. },
  5912. at: function (t, target) {
  5913. if (target === undefined) {
  5914. console.warn('THREE.Ray: .at() target is now required');
  5915. target = new Vector3();
  5916. }
  5917. return target.copy(this.direction).multiplyScalar(t).add(this.origin);
  5918. },
  5919. lookAt: function (v) {
  5920. this.direction.copy(v).sub(this.origin).normalize();
  5921. return this;
  5922. },
  5923. recast: function (t) {
  5924. this.origin.copy(this.at(t, _vector$3));
  5925. return this;
  5926. },
  5927. closestPointToPoint: function (point, target) {
  5928. if (target === undefined) {
  5929. console.warn('THREE.Ray: .closestPointToPoint() target is now required');
  5930. target = new Vector3();
  5931. }
  5932. target.subVectors(point, this.origin);
  5933. var directionDistance = target.dot(this.direction);
  5934. if (directionDistance < 0) {
  5935. return target.copy(this.origin);
  5936. }
  5937. return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  5938. },
  5939. distanceToPoint: function (point) {
  5940. return Math.sqrt(this.distanceSqToPoint(point));
  5941. },
  5942. distanceSqToPoint: function (point) {
  5943. var directionDistance = _vector$3.subVectors(point, this.origin).dot(this.direction); // point behind the ray
  5944. if (directionDistance < 0) {
  5945. return this.origin.distanceToSquared(point);
  5946. }
  5947. _vector$3.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  5948. return _vector$3.distanceToSquared(point);
  5949. },
  5950. distanceSqToSegment: function (v0, v1, optionalPointOnRay, optionalPointOnSegment) {
  5951. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  5952. // It returns the min distance between the ray and the segment
  5953. // defined by v0 and v1
  5954. // It can also set two optional targets :
  5955. // - The closest point on the ray
  5956. // - The closest point on the segment
  5957. _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
  5958. _segDir.copy(v1).sub(v0).normalize();
  5959. _diff.copy(this.origin).sub(_segCenter);
  5960. var segExtent = v0.distanceTo(v1) * 0.5;
  5961. var a01 = -this.direction.dot(_segDir);
  5962. var b0 = _diff.dot(this.direction);
  5963. var b1 = -_diff.dot(_segDir);
  5964. var c = _diff.lengthSq();
  5965. var det = Math.abs(1 - a01 * a01);
  5966. var s0, s1, sqrDist, extDet;
  5967. if (det > 0) {
  5968. // The ray and segment are not parallel.
  5969. s0 = a01 * b1 - b0;
  5970. s1 = a01 * b0 - b1;
  5971. extDet = segExtent * det;
  5972. if (s0 >= 0) {
  5973. if (s1 >= -extDet) {
  5974. if (s1 <= extDet) {
  5975. // region 0
  5976. // Minimum at interior points of ray and segment.
  5977. var invDet = 1 / det;
  5978. s0 *= invDet;
  5979. s1 *= invDet;
  5980. sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
  5981. } else {
  5982. // region 1
  5983. s1 = segExtent;
  5984. s0 = Math.max(0, -(a01 * s1 + b0));
  5985. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  5986. }
  5987. } else {
  5988. // region 5
  5989. s1 = -segExtent;
  5990. s0 = Math.max(0, -(a01 * s1 + b0));
  5991. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  5992. }
  5993. } else {
  5994. if (s1 <= -extDet) {
  5995. // region 4
  5996. s0 = Math.max(0, -(-a01 * segExtent + b0));
  5997. s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  5998. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  5999. } else if (s1 <= extDet) {
  6000. // region 3
  6001. s0 = 0;
  6002. s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
  6003. sqrDist = s1 * (s1 + 2 * b1) + c;
  6004. } else {
  6005. // region 2
  6006. s0 = Math.max(0, -(a01 * segExtent + b0));
  6007. s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  6008. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  6009. }
  6010. }
  6011. } else {
  6012. // Ray and segment are parallel.
  6013. s1 = a01 > 0 ? -segExtent : segExtent;
  6014. s0 = Math.max(0, -(a01 * s1 + b0));
  6015. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  6016. }
  6017. if (optionalPointOnRay) {
  6018. optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
  6019. }
  6020. if (optionalPointOnSegment) {
  6021. optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
  6022. }
  6023. return sqrDist;
  6024. },
  6025. intersectSphere: function (sphere, target) {
  6026. _vector$3.subVectors(sphere.center, this.origin);
  6027. var tca = _vector$3.dot(this.direction);
  6028. var d2 = _vector$3.dot(_vector$3) - tca * tca;
  6029. var radius2 = sphere.radius * sphere.radius;
  6030. if (d2 > radius2) return null;
  6031. var thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of sphere
  6032. var t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere
  6033. var t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null
  6034. if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:
  6035. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  6036. // in order to always return an intersect point that is in front of the ray.
  6037. if (t0 < 0) return this.at(t1, target); // else t0 is in front of the ray, so return the first collision point scaled by t0
  6038. return this.at(t0, target);
  6039. },
  6040. intersectsSphere: function (sphere) {
  6041. return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  6042. },
  6043. distanceToPlane: function (plane) {
  6044. var denominator = plane.normal.dot(this.direction);
  6045. if (denominator === 0) {
  6046. // line is coplanar, return origin
  6047. if (plane.distanceToPoint(this.origin) === 0) {
  6048. return 0;
  6049. } // Null is preferable to undefined since undefined means.... it is undefined
  6050. return null;
  6051. }
  6052. var t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the plane
  6053. return t >= 0 ? t : null;
  6054. },
  6055. intersectPlane: function (plane, target) {
  6056. var t = this.distanceToPlane(plane);
  6057. if (t === null) {
  6058. return null;
  6059. }
  6060. return this.at(t, target);
  6061. },
  6062. intersectsPlane: function (plane) {
  6063. // check if the ray lies on the plane first
  6064. var distToPoint = plane.distanceToPoint(this.origin);
  6065. if (distToPoint === 0) {
  6066. return true;
  6067. }
  6068. var denominator = plane.normal.dot(this.direction);
  6069. if (denominator * distToPoint < 0) {
  6070. return true;
  6071. } // ray origin is behind the plane (and is pointing behind it)
  6072. return false;
  6073. },
  6074. intersectBox: function (box, target) {
  6075. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  6076. var invdirx = 1 / this.direction.x,
  6077. invdiry = 1 / this.direction.y,
  6078. invdirz = 1 / this.direction.z;
  6079. var origin = this.origin;
  6080. if (invdirx >= 0) {
  6081. tmin = (box.min.x - origin.x) * invdirx;
  6082. tmax = (box.max.x - origin.x) * invdirx;
  6083. } else {
  6084. tmin = (box.max.x - origin.x) * invdirx;
  6085. tmax = (box.min.x - origin.x) * invdirx;
  6086. }
  6087. if (invdiry >= 0) {
  6088. tymin = (box.min.y - origin.y) * invdiry;
  6089. tymax = (box.max.y - origin.y) * invdiry;
  6090. } else {
  6091. tymin = (box.max.y - origin.y) * invdiry;
  6092. tymax = (box.min.y - origin.y) * invdiry;
  6093. }
  6094. if (tmin > tymax || tymin > tmax) return null; // These lines also handle the case where tmin or tmax is NaN
  6095. // (result of 0 * Infinity). x !== x returns true if x is NaN
  6096. if (tymin > tmin || tmin !== tmin) tmin = tymin;
  6097. if (tymax < tmax || tmax !== tmax) tmax = tymax;
  6098. if (invdirz >= 0) {
  6099. tzmin = (box.min.z - origin.z) * invdirz;
  6100. tzmax = (box.max.z - origin.z) * invdirz;
  6101. } else {
  6102. tzmin = (box.max.z - origin.z) * invdirz;
  6103. tzmax = (box.min.z - origin.z) * invdirz;
  6104. }
  6105. if (tmin > tzmax || tzmin > tmax) return null;
  6106. if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
  6107. if (tzmax < tmax || tmax !== tmax) tmax = tzmax; //return point closest to the ray (positive side)
  6108. if (tmax < 0) return null;
  6109. return this.at(tmin >= 0 ? tmin : tmax, target);
  6110. },
  6111. intersectsBox: function (box) {
  6112. return this.intersectBox(box, _vector$3) !== null;
  6113. },
  6114. intersectTriangle: function (a, b, c, backfaceCulling, target) {
  6115. // Compute the offset origin, edges, and normal.
  6116. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  6117. _edge1.subVectors(b, a);
  6118. _edge2.subVectors(c, a);
  6119. _normal.crossVectors(_edge1, _edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  6120. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  6121. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  6122. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  6123. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  6124. var DdN = this.direction.dot(_normal);
  6125. var sign;
  6126. if (DdN > 0) {
  6127. if (backfaceCulling) return null;
  6128. sign = 1;
  6129. } else if (DdN < 0) {
  6130. sign = -1;
  6131. DdN = -DdN;
  6132. } else {
  6133. return null;
  6134. }
  6135. _diff.subVectors(this.origin, a);
  6136. var DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersection
  6137. if (DdQxE2 < 0) {
  6138. return null;
  6139. }
  6140. var DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); // b2 < 0, no intersection
  6141. if (DdE1xQ < 0) {
  6142. return null;
  6143. } // b1+b2 > 1, no intersection
  6144. if (DdQxE2 + DdE1xQ > DdN) {
  6145. return null;
  6146. } // Line intersects triangle, check if ray does.
  6147. var QdN = -sign * _diff.dot(_normal); // t < 0, no intersection
  6148. if (QdN < 0) {
  6149. return null;
  6150. } // Ray intersects triangle.
  6151. return this.at(QdN / DdN, target);
  6152. },
  6153. applyMatrix4: function (matrix4) {
  6154. this.origin.applyMatrix4(matrix4);
  6155. this.direction.transformDirection(matrix4);
  6156. return this;
  6157. },
  6158. equals: function (ray) {
  6159. return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  6160. }
  6161. });
  6162. /**
  6163. * @author bhouston / http://clara.io
  6164. * @author mrdoob / http://mrdoob.com/
  6165. */
  6166. var _v0$1 = new Vector3();
  6167. var _v1$3 = new Vector3();
  6168. var _v2$1 = new Vector3();
  6169. var _v3 = new Vector3();
  6170. var _vab = new Vector3();
  6171. var _vac = new Vector3();
  6172. var _vbc = new Vector3();
  6173. var _vap = new Vector3();
  6174. var _vbp = new Vector3();
  6175. var _vcp = new Vector3();
  6176. function Triangle(a, b, c) {
  6177. this.a = a !== undefined ? a : new Vector3();
  6178. this.b = b !== undefined ? b : new Vector3();
  6179. this.c = c !== undefined ? c : new Vector3();
  6180. }
  6181. Object.assign(Triangle, {
  6182. getNormal: function (a, b, c, target) {
  6183. if (target === undefined) {
  6184. console.warn('THREE.Triangle: .getNormal() target is now required');
  6185. target = new Vector3();
  6186. }
  6187. target.subVectors(c, b);
  6188. _v0$1.subVectors(a, b);
  6189. target.cross(_v0$1);
  6190. var targetLengthSq = target.lengthSq();
  6191. if (targetLengthSq > 0) {
  6192. return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
  6193. }
  6194. return target.set(0, 0, 0);
  6195. },
  6196. // static/instance method to calculate barycentric coordinates
  6197. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  6198. getBarycoord: function (point, a, b, c, target) {
  6199. _v0$1.subVectors(c, a);
  6200. _v1$3.subVectors(b, a);
  6201. _v2$1.subVectors(point, a);
  6202. var dot00 = _v0$1.dot(_v0$1);
  6203. var dot01 = _v0$1.dot(_v1$3);
  6204. var dot02 = _v0$1.dot(_v2$1);
  6205. var dot11 = _v1$3.dot(_v1$3);
  6206. var dot12 = _v1$3.dot(_v2$1);
  6207. var denom = dot00 * dot11 - dot01 * dot01;
  6208. if (target === undefined) {
  6209. console.warn('THREE.Triangle: .getBarycoord() target is now required');
  6210. target = new Vector3();
  6211. } // collinear or singular triangle
  6212. if (denom === 0) {
  6213. // arbitrary location outside of triangle?
  6214. // not sure if this is the best idea, maybe should be returning undefined
  6215. return target.set(-2, -1, -1);
  6216. }
  6217. var invDenom = 1 / denom;
  6218. var u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  6219. var v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1
  6220. return target.set(1 - u - v, v, u);
  6221. },
  6222. containsPoint: function (point, a, b, c) {
  6223. Triangle.getBarycoord(point, a, b, c, _v3);
  6224. return _v3.x >= 0 && _v3.y >= 0 && _v3.x + _v3.y <= 1;
  6225. },
  6226. getUV: function (point, p1, p2, p3, uv1, uv2, uv3, target) {
  6227. this.getBarycoord(point, p1, p2, p3, _v3);
  6228. target.set(0, 0);
  6229. target.addScaledVector(uv1, _v3.x);
  6230. target.addScaledVector(uv2, _v3.y);
  6231. target.addScaledVector(uv3, _v3.z);
  6232. return target;
  6233. },
  6234. isFrontFacing: function (a, b, c, direction) {
  6235. _v0$1.subVectors(c, b);
  6236. _v1$3.subVectors(a, b); // strictly front facing
  6237. return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  6238. }
  6239. });
  6240. Object.assign(Triangle.prototype, {
  6241. set: function (a, b, c) {
  6242. this.a.copy(a);
  6243. this.b.copy(b);
  6244. this.c.copy(c);
  6245. return this;
  6246. },
  6247. setFromPointsAndIndices: function (points, i0, i1, i2) {
  6248. this.a.copy(points[i0]);
  6249. this.b.copy(points[i1]);
  6250. this.c.copy(points[i2]);
  6251. return this;
  6252. },
  6253. clone: function () {
  6254. return new this.constructor().copy(this);
  6255. },
  6256. copy: function (triangle) {
  6257. this.a.copy(triangle.a);
  6258. this.b.copy(triangle.b);
  6259. this.c.copy(triangle.c);
  6260. return this;
  6261. },
  6262. getArea: function () {
  6263. _v0$1.subVectors(this.c, this.b);
  6264. _v1$3.subVectors(this.a, this.b);
  6265. return _v0$1.cross(_v1$3).length() * 0.5;
  6266. },
  6267. getMidpoint: function (target) {
  6268. if (target === undefined) {
  6269. console.warn('THREE.Triangle: .getMidpoint() target is now required');
  6270. target = new Vector3();
  6271. }
  6272. return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  6273. },
  6274. getNormal: function (target) {
  6275. return Triangle.getNormal(this.a, this.b, this.c, target);
  6276. },
  6277. getPlane: function (target) {
  6278. if (target === undefined) {
  6279. console.warn('THREE.Triangle: .getPlane() target is now required');
  6280. target = new Vector3();
  6281. }
  6282. return target.setFromCoplanarPoints(this.a, this.b, this.c);
  6283. },
  6284. getBarycoord: function (point, target) {
  6285. return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
  6286. },
  6287. getUV: function (point, uv1, uv2, uv3, target) {
  6288. return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
  6289. },
  6290. containsPoint: function (point) {
  6291. return Triangle.containsPoint(point, this.a, this.b, this.c);
  6292. },
  6293. isFrontFacing: function (direction) {
  6294. return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  6295. },
  6296. intersectsBox: function (box) {
  6297. return box.intersectsTriangle(this);
  6298. },
  6299. closestPointToPoint: function (p, target) {
  6300. if (target === undefined) {
  6301. console.warn('THREE.Triangle: .closestPointToPoint() target is now required');
  6302. target = new Vector3();
  6303. }
  6304. var a = this.a,
  6305. b = this.b,
  6306. c = this.c;
  6307. var v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  6308. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  6309. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  6310. // basically, we're distinguishing which of the voronoi regions of the triangle
  6311. // the point lies in with the minimum amount of redundant computation.
  6312. _vab.subVectors(b, a);
  6313. _vac.subVectors(c, a);
  6314. _vap.subVectors(p, a);
  6315. var d1 = _vab.dot(_vap);
  6316. var d2 = _vac.dot(_vap);
  6317. if (d1 <= 0 && d2 <= 0) {
  6318. // vertex region of A; barycentric coords (1, 0, 0)
  6319. return target.copy(a);
  6320. }
  6321. _vbp.subVectors(p, b);
  6322. var d3 = _vab.dot(_vbp);
  6323. var d4 = _vac.dot(_vbp);
  6324. if (d3 >= 0 && d4 <= d3) {
  6325. // vertex region of B; barycentric coords (0, 1, 0)
  6326. return target.copy(b);
  6327. }
  6328. var vc = d1 * d4 - d3 * d2;
  6329. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  6330. v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)
  6331. return target.copy(a).addScaledVector(_vab, v);
  6332. }
  6333. _vcp.subVectors(p, c);
  6334. var d5 = _vab.dot(_vcp);
  6335. var d6 = _vac.dot(_vcp);
  6336. if (d6 >= 0 && d5 <= d6) {
  6337. // vertex region of C; barycentric coords (0, 0, 1)
  6338. return target.copy(c);
  6339. }
  6340. var vb = d5 * d2 - d1 * d6;
  6341. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  6342. w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)
  6343. return target.copy(a).addScaledVector(_vac, w);
  6344. }
  6345. var va = d3 * d6 - d5 * d4;
  6346. if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
  6347. _vbc.subVectors(c, b);
  6348. w = (d4 - d3) / (d4 - d3 + (d5 - d6)); // edge region of BC; barycentric coords (0, 1-w, w)
  6349. return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
  6350. } // face region
  6351. var denom = 1 / (va + vb + vc); // u = va * denom
  6352. v = vb * denom;
  6353. w = vc * denom;
  6354. return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
  6355. },
  6356. equals: function (triangle) {
  6357. return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  6358. }
  6359. });
  6360. /**
  6361. * @author mrdoob / http://mrdoob.com/
  6362. */
  6363. var _colorKeywords = {
  6364. 'aliceblue': 0xF0F8FF,
  6365. 'antiquewhite': 0xFAEBD7,
  6366. 'aqua': 0x00FFFF,
  6367. 'aquamarine': 0x7FFFD4,
  6368. 'azure': 0xF0FFFF,
  6369. 'beige': 0xF5F5DC,
  6370. 'bisque': 0xFFE4C4,
  6371. 'black': 0x000000,
  6372. 'blanchedalmond': 0xFFEBCD,
  6373. 'blue': 0x0000FF,
  6374. 'blueviolet': 0x8A2BE2,
  6375. 'brown': 0xA52A2A,
  6376. 'burlywood': 0xDEB887,
  6377. 'cadetblue': 0x5F9EA0,
  6378. 'chartreuse': 0x7FFF00,
  6379. 'chocolate': 0xD2691E,
  6380. 'coral': 0xFF7F50,
  6381. 'cornflowerblue': 0x6495ED,
  6382. 'cornsilk': 0xFFF8DC,
  6383. 'crimson': 0xDC143C,
  6384. 'cyan': 0x00FFFF,
  6385. 'darkblue': 0x00008B,
  6386. 'darkcyan': 0x008B8B,
  6387. 'darkgoldenrod': 0xB8860B,
  6388. 'darkgray': 0xA9A9A9,
  6389. 'darkgreen': 0x006400,
  6390. 'darkgrey': 0xA9A9A9,
  6391. 'darkkhaki': 0xBDB76B,
  6392. 'darkmagenta': 0x8B008B,
  6393. 'darkolivegreen': 0x556B2F,
  6394. 'darkorange': 0xFF8C00,
  6395. 'darkorchid': 0x9932CC,
  6396. 'darkred': 0x8B0000,
  6397. 'darksalmon': 0xE9967A,
  6398. 'darkseagreen': 0x8FBC8F,
  6399. 'darkslateblue': 0x483D8B,
  6400. 'darkslategray': 0x2F4F4F,
  6401. 'darkslategrey': 0x2F4F4F,
  6402. 'darkturquoise': 0x00CED1,
  6403. 'darkviolet': 0x9400D3,
  6404. 'deeppink': 0xFF1493,
  6405. 'deepskyblue': 0x00BFFF,
  6406. 'dimgray': 0x696969,
  6407. 'dimgrey': 0x696969,
  6408. 'dodgerblue': 0x1E90FF,
  6409. 'firebrick': 0xB22222,
  6410. 'floralwhite': 0xFFFAF0,
  6411. 'forestgreen': 0x228B22,
  6412. 'fuchsia': 0xFF00FF,
  6413. 'gainsboro': 0xDCDCDC,
  6414. 'ghostwhite': 0xF8F8FF,
  6415. 'gold': 0xFFD700,
  6416. 'goldenrod': 0xDAA520,
  6417. 'gray': 0x808080,
  6418. 'green': 0x008000,
  6419. 'greenyellow': 0xADFF2F,
  6420. 'grey': 0x808080,
  6421. 'honeydew': 0xF0FFF0,
  6422. 'hotpink': 0xFF69B4,
  6423. 'indianred': 0xCD5C5C,
  6424. 'indigo': 0x4B0082,
  6425. 'ivory': 0xFFFFF0,
  6426. 'khaki': 0xF0E68C,
  6427. 'lavender': 0xE6E6FA,
  6428. 'lavenderblush': 0xFFF0F5,
  6429. 'lawngreen': 0x7CFC00,
  6430. 'lemonchiffon': 0xFFFACD,
  6431. 'lightblue': 0xADD8E6,
  6432. 'lightcoral': 0xF08080,
  6433. 'lightcyan': 0xE0FFFF,
  6434. 'lightgoldenrodyellow': 0xFAFAD2,
  6435. 'lightgray': 0xD3D3D3,
  6436. 'lightgreen': 0x90EE90,
  6437. 'lightgrey': 0xD3D3D3,
  6438. 'lightpink': 0xFFB6C1,
  6439. 'lightsalmon': 0xFFA07A,
  6440. 'lightseagreen': 0x20B2AA,
  6441. 'lightskyblue': 0x87CEFA,
  6442. 'lightslategray': 0x778899,
  6443. 'lightslategrey': 0x778899,
  6444. 'lightsteelblue': 0xB0C4DE,
  6445. 'lightyellow': 0xFFFFE0,
  6446. 'lime': 0x00FF00,
  6447. 'limegreen': 0x32CD32,
  6448. 'linen': 0xFAF0E6,
  6449. 'magenta': 0xFF00FF,
  6450. 'maroon': 0x800000,
  6451. 'mediumaquamarine': 0x66CDAA,
  6452. 'mediumblue': 0x0000CD,
  6453. 'mediumorchid': 0xBA55D3,
  6454. 'mediumpurple': 0x9370DB,
  6455. 'mediumseagreen': 0x3CB371,
  6456. 'mediumslateblue': 0x7B68EE,
  6457. 'mediumspringgreen': 0x00FA9A,
  6458. 'mediumturquoise': 0x48D1CC,
  6459. 'mediumvioletred': 0xC71585,
  6460. 'midnightblue': 0x191970,
  6461. 'mintcream': 0xF5FFFA,
  6462. 'mistyrose': 0xFFE4E1,
  6463. 'moccasin': 0xFFE4B5,
  6464. 'navajowhite': 0xFFDEAD,
  6465. 'navy': 0x000080,
  6466. 'oldlace': 0xFDF5E6,
  6467. 'olive': 0x808000,
  6468. 'olivedrab': 0x6B8E23,
  6469. 'orange': 0xFFA500,
  6470. 'orangered': 0xFF4500,
  6471. 'orchid': 0xDA70D6,
  6472. 'palegoldenrod': 0xEEE8AA,
  6473. 'palegreen': 0x98FB98,
  6474. 'paleturquoise': 0xAFEEEE,
  6475. 'palevioletred': 0xDB7093,
  6476. 'papayawhip': 0xFFEFD5,
  6477. 'peachpuff': 0xFFDAB9,
  6478. 'peru': 0xCD853F,
  6479. 'pink': 0xFFC0CB,
  6480. 'plum': 0xDDA0DD,
  6481. 'powderblue': 0xB0E0E6,
  6482. 'purple': 0x800080,
  6483. 'rebeccapurple': 0x663399,
  6484. 'red': 0xFF0000,
  6485. 'rosybrown': 0xBC8F8F,
  6486. 'royalblue': 0x4169E1,
  6487. 'saddlebrown': 0x8B4513,
  6488. 'salmon': 0xFA8072,
  6489. 'sandybrown': 0xF4A460,
  6490. 'seagreen': 0x2E8B57,
  6491. 'seashell': 0xFFF5EE,
  6492. 'sienna': 0xA0522D,
  6493. 'silver': 0xC0C0C0,
  6494. 'skyblue': 0x87CEEB,
  6495. 'slateblue': 0x6A5ACD,
  6496. 'slategray': 0x708090,
  6497. 'slategrey': 0x708090,
  6498. 'snow': 0xFFFAFA,
  6499. 'springgreen': 0x00FF7F,
  6500. 'steelblue': 0x4682B4,
  6501. 'tan': 0xD2B48C,
  6502. 'teal': 0x008080,
  6503. 'thistle': 0xD8BFD8,
  6504. 'tomato': 0xFF6347,
  6505. 'turquoise': 0x40E0D0,
  6506. 'violet': 0xEE82EE,
  6507. 'wheat': 0xF5DEB3,
  6508. 'white': 0xFFFFFF,
  6509. 'whitesmoke': 0xF5F5F5,
  6510. 'yellow': 0xFFFF00,
  6511. 'yellowgreen': 0x9ACD32
  6512. };
  6513. var _hslA = {
  6514. h: 0,
  6515. s: 0,
  6516. l: 0
  6517. };
  6518. var _hslB = {
  6519. h: 0,
  6520. s: 0,
  6521. l: 0
  6522. };
  6523. function Color(r, g, b) {
  6524. if (g === undefined && b === undefined) {
  6525. // r is THREE.Color, hex or string
  6526. return this.set(r);
  6527. }
  6528. return this.setRGB(r, g, b);
  6529. }
  6530. function hue2rgb(p, q, t) {
  6531. if (t < 0) t += 1;
  6532. if (t > 1) t -= 1;
  6533. if (t < 1 / 6) return p + (q - p) * 6 * t;
  6534. if (t < 1 / 2) return q;
  6535. if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);
  6536. return p;
  6537. }
  6538. function SRGBToLinear(c) {
  6539. return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
  6540. }
  6541. function LinearToSRGB(c) {
  6542. return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
  6543. }
  6544. Object.assign(Color.prototype, {
  6545. isColor: true,
  6546. r: 1,
  6547. g: 1,
  6548. b: 1,
  6549. set: function (value) {
  6550. if (value && value.isColor) {
  6551. this.copy(value);
  6552. } else if (typeof value === 'number') {
  6553. this.setHex(value);
  6554. } else if (typeof value === 'string') {
  6555. this.setStyle(value);
  6556. }
  6557. return this;
  6558. },
  6559. setScalar: function (scalar) {
  6560. this.r = scalar;
  6561. this.g = scalar;
  6562. this.b = scalar;
  6563. return this;
  6564. },
  6565. setHex: function (hex) {
  6566. hex = Math.floor(hex);
  6567. this.r = (hex >> 16 & 255) / 255;
  6568. this.g = (hex >> 8 & 255) / 255;
  6569. this.b = (hex & 255) / 255;
  6570. return this;
  6571. },
  6572. setRGB: function (r, g, b) {
  6573. this.r = r;
  6574. this.g = g;
  6575. this.b = b;
  6576. return this;
  6577. },
  6578. setHSL: function (h, s, l) {
  6579. // h,s,l ranges are in 0.0 - 1.0
  6580. h = _Math.euclideanModulo(h, 1);
  6581. s = _Math.clamp(s, 0, 1);
  6582. l = _Math.clamp(l, 0, 1);
  6583. if (s === 0) {
  6584. this.r = this.g = this.b = l;
  6585. } else {
  6586. var p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
  6587. var q = 2 * l - p;
  6588. this.r = hue2rgb(q, p, h + 1 / 3);
  6589. this.g = hue2rgb(q, p, h);
  6590. this.b = hue2rgb(q, p, h - 1 / 3);
  6591. }
  6592. return this;
  6593. },
  6594. setStyle: function (style) {
  6595. function handleAlpha(string) {
  6596. if (string === undefined) return;
  6597. if (parseFloat(string) < 1) {
  6598. console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
  6599. }
  6600. }
  6601. var m;
  6602. if (m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(style)) {
  6603. // rgb / hsl
  6604. var color;
  6605. var name = m[1];
  6606. var components = m[2];
  6607. switch (name) {
  6608. case 'rgb':
  6609. case 'rgba':
  6610. if (color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  6611. // rgb(255,0,0) rgba(255,0,0,0.5)
  6612. this.r = Math.min(255, parseInt(color[1], 10)) / 255;
  6613. this.g = Math.min(255, parseInt(color[2], 10)) / 255;
  6614. this.b = Math.min(255, parseInt(color[3], 10)) / 255;
  6615. handleAlpha(color[5]);
  6616. return this;
  6617. }
  6618. if (color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  6619. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  6620. this.r = Math.min(100, parseInt(color[1], 10)) / 100;
  6621. this.g = Math.min(100, parseInt(color[2], 10)) / 100;
  6622. this.b = Math.min(100, parseInt(color[3], 10)) / 100;
  6623. handleAlpha(color[5]);
  6624. return this;
  6625. }
  6626. break;
  6627. case 'hsl':
  6628. case 'hsla':
  6629. if (color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  6630. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  6631. var h = parseFloat(color[1]) / 360;
  6632. var s = parseInt(color[2], 10) / 100;
  6633. var l = parseInt(color[3], 10) / 100;
  6634. handleAlpha(color[5]);
  6635. return this.setHSL(h, s, l);
  6636. }
  6637. break;
  6638. }
  6639. } else if (m = /^\#([A-Fa-f0-9]+)$/.exec(style)) {
  6640. // hex color
  6641. var hex = m[1];
  6642. var size = hex.length;
  6643. if (size === 3) {
  6644. // #ff0
  6645. this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
  6646. this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
  6647. this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
  6648. return this;
  6649. } else if (size === 6) {
  6650. // #ff0000
  6651. this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
  6652. this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
  6653. this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
  6654. return this;
  6655. }
  6656. }
  6657. if (style && style.length > 0) {
  6658. // color keywords
  6659. var hex = _colorKeywords[style];
  6660. if (hex !== undefined) {
  6661. // red
  6662. this.setHex(hex);
  6663. } else {
  6664. // unknown color
  6665. console.warn('THREE.Color: Unknown color ' + style);
  6666. }
  6667. }
  6668. return this;
  6669. },
  6670. clone: function () {
  6671. return new this.constructor(this.r, this.g, this.b);
  6672. },
  6673. copy: function (color) {
  6674. this.r = color.r;
  6675. this.g = color.g;
  6676. this.b = color.b;
  6677. return this;
  6678. },
  6679. copyGammaToLinear: function (color, gammaFactor) {
  6680. if (gammaFactor === undefined) gammaFactor = 2.0;
  6681. this.r = Math.pow(color.r, gammaFactor);
  6682. this.g = Math.pow(color.g, gammaFactor);
  6683. this.b = Math.pow(color.b, gammaFactor);
  6684. return this;
  6685. },
  6686. copyLinearToGamma: function (color, gammaFactor) {
  6687. if (gammaFactor === undefined) gammaFactor = 2.0;
  6688. var safeInverse = gammaFactor > 0 ? 1.0 / gammaFactor : 1.0;
  6689. this.r = Math.pow(color.r, safeInverse);
  6690. this.g = Math.pow(color.g, safeInverse);
  6691. this.b = Math.pow(color.b, safeInverse);
  6692. return this;
  6693. },
  6694. convertGammaToLinear: function (gammaFactor) {
  6695. this.copyGammaToLinear(this, gammaFactor);
  6696. return this;
  6697. },
  6698. convertLinearToGamma: function (gammaFactor) {
  6699. this.copyLinearToGamma(this, gammaFactor);
  6700. return this;
  6701. },
  6702. copySRGBToLinear: function (color) {
  6703. this.r = SRGBToLinear(color.r);
  6704. this.g = SRGBToLinear(color.g);
  6705. this.b = SRGBToLinear(color.b);
  6706. return this;
  6707. },
  6708. copyLinearToSRGB: function (color) {
  6709. this.r = LinearToSRGB(color.r);
  6710. this.g = LinearToSRGB(color.g);
  6711. this.b = LinearToSRGB(color.b);
  6712. return this;
  6713. },
  6714. convertSRGBToLinear: function () {
  6715. this.copySRGBToLinear(this);
  6716. return this;
  6717. },
  6718. convertLinearToSRGB: function () {
  6719. this.copyLinearToSRGB(this);
  6720. return this;
  6721. },
  6722. getHex: function () {
  6723. return this.r * 255 << 16 ^ this.g * 255 << 8 ^ this.b * 255 << 0;
  6724. },
  6725. getHexString: function () {
  6726. return ('000000' + this.getHex().toString(16)).slice(-6);
  6727. },
  6728. getHSL: function (target) {
  6729. // h,s,l ranges are in 0.0 - 1.0
  6730. if (target === undefined) {
  6731. console.warn('THREE.Color: .getHSL() target is now required');
  6732. target = {
  6733. h: 0,
  6734. s: 0,
  6735. l: 0
  6736. };
  6737. }
  6738. var r = this.r,
  6739. g = this.g,
  6740. b = this.b;
  6741. var max = Math.max(r, g, b);
  6742. var min = Math.min(r, g, b);
  6743. var hue, saturation;
  6744. var lightness = (min + max) / 2.0;
  6745. if (min === max) {
  6746. hue = 0;
  6747. saturation = 0;
  6748. } else {
  6749. var delta = max - min;
  6750. saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
  6751. switch (max) {
  6752. case r:
  6753. hue = (g - b) / delta + (g < b ? 6 : 0);
  6754. break;
  6755. case g:
  6756. hue = (b - r) / delta + 2;
  6757. break;
  6758. case b:
  6759. hue = (r - g) / delta + 4;
  6760. break;
  6761. }
  6762. hue /= 6;
  6763. }
  6764. target.h = hue;
  6765. target.s = saturation;
  6766. target.l = lightness;
  6767. return target;
  6768. },
  6769. getStyle: function () {
  6770. return 'rgb(' + (this.r * 255 | 0) + ',' + (this.g * 255 | 0) + ',' + (this.b * 255 | 0) + ')';
  6771. },
  6772. offsetHSL: function (h, s, l) {
  6773. this.getHSL(_hslA);
  6774. _hslA.h += h;
  6775. _hslA.s += s;
  6776. _hslA.l += l;
  6777. this.setHSL(_hslA.h, _hslA.s, _hslA.l);
  6778. return this;
  6779. },
  6780. add: function (color) {
  6781. this.r += color.r;
  6782. this.g += color.g;
  6783. this.b += color.b;
  6784. return this;
  6785. },
  6786. addColors: function (color1, color2) {
  6787. this.r = color1.r + color2.r;
  6788. this.g = color1.g + color2.g;
  6789. this.b = color1.b + color2.b;
  6790. return this;
  6791. },
  6792. addScalar: function (s) {
  6793. this.r += s;
  6794. this.g += s;
  6795. this.b += s;
  6796. return this;
  6797. },
  6798. sub: function (color) {
  6799. this.r = Math.max(0, this.r - color.r);
  6800. this.g = Math.max(0, this.g - color.g);
  6801. this.b = Math.max(0, this.b - color.b);
  6802. return this;
  6803. },
  6804. multiply: function (color) {
  6805. this.r *= color.r;
  6806. this.g *= color.g;
  6807. this.b *= color.b;
  6808. return this;
  6809. },
  6810. multiplyScalar: function (s) {
  6811. this.r *= s;
  6812. this.g *= s;
  6813. this.b *= s;
  6814. return this;
  6815. },
  6816. lerp: function (color, alpha) {
  6817. this.r += (color.r - this.r) * alpha;
  6818. this.g += (color.g - this.g) * alpha;
  6819. this.b += (color.b - this.b) * alpha;
  6820. return this;
  6821. },
  6822. lerpHSL: function (color, alpha) {
  6823. this.getHSL(_hslA);
  6824. color.getHSL(_hslB);
  6825. var h = _Math.lerp(_hslA.h, _hslB.h, alpha);
  6826. var s = _Math.lerp(_hslA.s, _hslB.s, alpha);
  6827. var l = _Math.lerp(_hslA.l, _hslB.l, alpha);
  6828. this.setHSL(h, s, l);
  6829. return this;
  6830. },
  6831. equals: function (c) {
  6832. return c.r === this.r && c.g === this.g && c.b === this.b;
  6833. },
  6834. fromArray: function (array, offset) {
  6835. if (offset === undefined) offset = 0;
  6836. this.r = array[offset];
  6837. this.g = array[offset + 1];
  6838. this.b = array[offset + 2];
  6839. return this;
  6840. },
  6841. toArray: function (array, offset) {
  6842. if (array === undefined) array = [];
  6843. if (offset === undefined) offset = 0;
  6844. array[offset] = this.r;
  6845. array[offset + 1] = this.g;
  6846. array[offset + 2] = this.b;
  6847. return array;
  6848. },
  6849. toJSON: function () {
  6850. return this.getHex();
  6851. }
  6852. });
  6853. /**
  6854. * @author mrdoob / http://mrdoob.com/
  6855. * @author alteredq / http://alteredqualia.com/
  6856. */
  6857. function Face3(a, b, c, normal, color, materialIndex) {
  6858. this.a = a;
  6859. this.b = b;
  6860. this.c = c;
  6861. this.normal = normal && normal.isVector3 ? normal : new Vector3();
  6862. this.vertexNormals = Array.isArray(normal) ? normal : [];
  6863. this.color = color && color.isColor ? color : new Color();
  6864. this.vertexColors = Array.isArray(color) ? color : [];
  6865. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  6866. }
  6867. Object.assign(Face3.prototype, {
  6868. clone: function () {
  6869. return new this.constructor().copy(this);
  6870. },
  6871. copy: function (source) {
  6872. this.a = source.a;
  6873. this.b = source.b;
  6874. this.c = source.c;
  6875. this.normal.copy(source.normal);
  6876. this.color.copy(source.color);
  6877. this.materialIndex = source.materialIndex;
  6878. for (var i = 0, il = source.vertexNormals.length; i < il; i++) {
  6879. this.vertexNormals[i] = source.vertexNormals[i].clone();
  6880. }
  6881. for (var i = 0, il = source.vertexColors.length; i < il; i++) {
  6882. this.vertexColors[i] = source.vertexColors[i].clone();
  6883. }
  6884. return this;
  6885. }
  6886. });
  6887. /**
  6888. * @author mrdoob / http://mrdoob.com/
  6889. * @author alteredq / http://alteredqualia.com/
  6890. */
  6891. var materialId = 0;
  6892. function Material() {
  6893. Object.defineProperty(this, 'id', {
  6894. value: materialId++
  6895. });
  6896. this.uuid = _Math.generateUUID();
  6897. this.name = '';
  6898. this.type = 'Material';
  6899. this.fog = true;
  6900. this.blending = NormalBlending;
  6901. this.side = FrontSide;
  6902. this.flatShading = false;
  6903. this.vertexTangents = false;
  6904. this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors
  6905. this.opacity = 1;
  6906. this.transparent = false;
  6907. this.blendSrc = SrcAlphaFactor;
  6908. this.blendDst = OneMinusSrcAlphaFactor;
  6909. this.blendEquation = AddEquation;
  6910. this.blendSrcAlpha = null;
  6911. this.blendDstAlpha = null;
  6912. this.blendEquationAlpha = null;
  6913. this.depthFunc = LessEqualDepth;
  6914. this.depthTest = true;
  6915. this.depthWrite = true;
  6916. this.stencilWriteMask = 0xff;
  6917. this.stencilFunc = AlwaysStencilFunc;
  6918. this.stencilRef = 0;
  6919. this.stencilFuncMask = 0xff;
  6920. this.stencilFail = KeepStencilOp;
  6921. this.stencilZFail = KeepStencilOp;
  6922. this.stencilZPass = KeepStencilOp;
  6923. this.stencilWrite = false;
  6924. this.clippingPlanes = null;
  6925. this.clipIntersection = false;
  6926. this.clipShadows = false;
  6927. this.shadowSide = null;
  6928. this.colorWrite = true;
  6929. this.precision = null; // override the renderer's default precision for this material
  6930. this.polygonOffset = false;
  6931. this.polygonOffsetFactor = 0;
  6932. this.polygonOffsetUnits = 0;
  6933. this.dithering = false;
  6934. this.alphaTest = 0;
  6935. this.premultipliedAlpha = false;
  6936. this.visible = true;
  6937. this.toneMapped = true;
  6938. this.userData = {};
  6939. this.needsUpdate = true;
  6940. }
  6941. Material.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  6942. constructor: Material,
  6943. isMaterial: true,
  6944. onBeforeCompile: function () {},
  6945. setValues: function (values) {
  6946. if (values === undefined) return;
  6947. for (var key in values) {
  6948. var newValue = values[key];
  6949. if (newValue === undefined) {
  6950. console.warn("THREE.Material: '" + key + "' parameter is undefined.");
  6951. continue;
  6952. } // for backward compatability if shading is set in the constructor
  6953. if (key === 'shading') {
  6954. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  6955. this.flatShading = newValue === FlatShading ? true : false;
  6956. continue;
  6957. }
  6958. var currentValue = this[key];
  6959. if (currentValue === undefined) {
  6960. console.warn("THREE." + this.type + ": '" + key + "' is not a property of this material.");
  6961. continue;
  6962. }
  6963. if (currentValue && currentValue.isColor) {
  6964. currentValue.set(newValue);
  6965. } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
  6966. currentValue.copy(newValue);
  6967. } else {
  6968. this[key] = newValue;
  6969. }
  6970. }
  6971. },
  6972. toJSON: function (meta) {
  6973. var isRoot = meta === undefined || typeof meta === 'string';
  6974. if (isRoot) {
  6975. meta = {
  6976. textures: {},
  6977. images: {}
  6978. };
  6979. }
  6980. var data = {
  6981. metadata: {
  6982. version: 4.5,
  6983. type: 'Material',
  6984. generator: 'Material.toJSON'
  6985. }
  6986. }; // standard Material serialization
  6987. data.uuid = this.uuid;
  6988. data.type = this.type;
  6989. if (this.name !== '') data.name = this.name;
  6990. if (this.color && this.color.isColor) data.color = this.color.getHex();
  6991. if (this.roughness !== undefined) data.roughness = this.roughness;
  6992. if (this.metalness !== undefined) data.metalness = this.metalness;
  6993. if (this.sheen && this.sheen.isColor) data.sheen = this.sheen.getHex();
  6994. if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
  6995. if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
  6996. if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
  6997. if (this.shininess !== undefined) data.shininess = this.shininess;
  6998. if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
  6999. if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;
  7000. if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
  7001. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
  7002. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  7003. }
  7004. if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;
  7005. if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;
  7006. if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;
  7007. if (this.lightMap && this.lightMap.isTexture) data.lightMap = this.lightMap.toJSON(meta).uuid;
  7008. if (this.aoMap && this.aoMap.isTexture) {
  7009. data.aoMap = this.aoMap.toJSON(meta).uuid;
  7010. data.aoMapIntensity = this.aoMapIntensity;
  7011. }
  7012. if (this.bumpMap && this.bumpMap.isTexture) {
  7013. data.bumpMap = this.bumpMap.toJSON(meta).uuid;
  7014. data.bumpScale = this.bumpScale;
  7015. }
  7016. if (this.normalMap && this.normalMap.isTexture) {
  7017. data.normalMap = this.normalMap.toJSON(meta).uuid;
  7018. data.normalMapType = this.normalMapType;
  7019. data.normalScale = this.normalScale.toArray();
  7020. }
  7021. if (this.displacementMap && this.displacementMap.isTexture) {
  7022. data.displacementMap = this.displacementMap.toJSON(meta).uuid;
  7023. data.displacementScale = this.displacementScale;
  7024. data.displacementBias = this.displacementBias;
  7025. }
  7026. if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
  7027. if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
  7028. if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
  7029. if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;
  7030. if (this.envMap && this.envMap.isTexture) {
  7031. data.envMap = this.envMap.toJSON(meta).uuid;
  7032. data.reflectivity = this.reflectivity; // Scale behind envMap
  7033. data.refractionRatio = this.refractionRatio;
  7034. if (this.combine !== undefined) data.combine = this.combine;
  7035. if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
  7036. }
  7037. if (this.gradientMap && this.gradientMap.isTexture) {
  7038. data.gradientMap = this.gradientMap.toJSON(meta).uuid;
  7039. }
  7040. if (this.size !== undefined) data.size = this.size;
  7041. if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
  7042. if (this.blending !== NormalBlending) data.blending = this.blending;
  7043. if (this.flatShading === true) data.flatShading = this.flatShading;
  7044. if (this.side !== FrontSide) data.side = this.side;
  7045. if (this.vertexColors !== NoColors) data.vertexColors = this.vertexColors;
  7046. if (this.opacity < 1) data.opacity = this.opacity;
  7047. if (this.transparent === true) data.transparent = this.transparent;
  7048. data.depthFunc = this.depthFunc;
  7049. data.depthTest = this.depthTest;
  7050. data.depthWrite = this.depthWrite;
  7051. data.stencilWrite = this.stencilWrite;
  7052. data.stencilWriteMask = this.stencilWriteMask;
  7053. data.stencilFunc = this.stencilFunc;
  7054. data.stencilRef = this.stencilRef;
  7055. data.stencilFuncMask = this.stencilFuncMask;
  7056. data.stencilFail = this.stencilFail;
  7057. data.stencilZFail = this.stencilZFail;
  7058. data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)
  7059. if (this.rotation && this.rotation !== 0) data.rotation = this.rotation;
  7060. if (this.polygonOffset === true) data.polygonOffset = true;
  7061. if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
  7062. if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
  7063. if (this.linewidth && this.linewidth !== 1) data.linewidth = this.linewidth;
  7064. if (this.dashSize !== undefined) data.dashSize = this.dashSize;
  7065. if (this.gapSize !== undefined) data.gapSize = this.gapSize;
  7066. if (this.scale !== undefined) data.scale = this.scale;
  7067. if (this.dithering === true) data.dithering = true;
  7068. if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
  7069. if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
  7070. if (this.wireframe === true) data.wireframe = this.wireframe;
  7071. if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
  7072. if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
  7073. if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
  7074. if (this.morphTargets === true) data.morphTargets = true;
  7075. if (this.morphNormals === true) data.morphNormals = true;
  7076. if (this.skinning === true) data.skinning = true;
  7077. if (this.visible === false) data.visible = false;
  7078. if (this.toneMapped === false) data.toneMapped = false;
  7079. if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; // TODO: Copied from Object3D.toJSON
  7080. function extractFromCache(cache) {
  7081. var values = [];
  7082. for (var key in cache) {
  7083. var data = cache[key];
  7084. delete data.metadata;
  7085. values.push(data);
  7086. }
  7087. return values;
  7088. }
  7089. if (isRoot) {
  7090. var textures = extractFromCache(meta.textures);
  7091. var images = extractFromCache(meta.images);
  7092. if (textures.length > 0) data.textures = textures;
  7093. if (images.length > 0) data.images = images;
  7094. }
  7095. return data;
  7096. },
  7097. clone: function () {
  7098. return new this.constructor().copy(this);
  7099. },
  7100. copy: function (source) {
  7101. this.name = source.name;
  7102. this.fog = source.fog;
  7103. this.blending = source.blending;
  7104. this.side = source.side;
  7105. this.flatShading = source.flatShading;
  7106. this.vertexColors = source.vertexColors;
  7107. this.opacity = source.opacity;
  7108. this.transparent = source.transparent;
  7109. this.blendSrc = source.blendSrc;
  7110. this.blendDst = source.blendDst;
  7111. this.blendEquation = source.blendEquation;
  7112. this.blendSrcAlpha = source.blendSrcAlpha;
  7113. this.blendDstAlpha = source.blendDstAlpha;
  7114. this.blendEquationAlpha = source.blendEquationAlpha;
  7115. this.depthFunc = source.depthFunc;
  7116. this.depthTest = source.depthTest;
  7117. this.depthWrite = source.depthWrite;
  7118. this.stencilWrite = source.stencilWrite;
  7119. this.stencilWriteMask = source.stencilWriteMask;
  7120. this.stencilFunc = source.stencilFunc;
  7121. this.stencilRef = source.stencilRef;
  7122. this.stencilFuncMask = source.stencilFuncMask;
  7123. this.stencilFail = source.stencilFail;
  7124. this.stencilZFail = source.stencilZFail;
  7125. this.stencilZPass = source.stencilZPass;
  7126. this.colorWrite = source.colorWrite;
  7127. this.precision = source.precision;
  7128. this.polygonOffset = source.polygonOffset;
  7129. this.polygonOffsetFactor = source.polygonOffsetFactor;
  7130. this.polygonOffsetUnits = source.polygonOffsetUnits;
  7131. this.dithering = source.dithering;
  7132. this.alphaTest = source.alphaTest;
  7133. this.premultipliedAlpha = source.premultipliedAlpha;
  7134. this.visible = source.visible;
  7135. this.toneMapped = source.toneMapped;
  7136. this.userData = JSON.parse(JSON.stringify(source.userData));
  7137. this.clipShadows = source.clipShadows;
  7138. this.clipIntersection = source.clipIntersection;
  7139. var srcPlanes = source.clippingPlanes,
  7140. dstPlanes = null;
  7141. if (srcPlanes !== null) {
  7142. var n = srcPlanes.length;
  7143. dstPlanes = new Array(n);
  7144. for (var i = 0; i !== n; ++i) dstPlanes[i] = srcPlanes[i].clone();
  7145. }
  7146. this.clippingPlanes = dstPlanes;
  7147. this.shadowSide = source.shadowSide;
  7148. return this;
  7149. },
  7150. dispose: function () {
  7151. this.dispatchEvent({
  7152. type: 'dispose'
  7153. });
  7154. }
  7155. });
  7156. /**
  7157. * @author mrdoob / http://mrdoob.com/
  7158. * @author alteredq / http://alteredqualia.com/
  7159. *
  7160. * parameters = {
  7161. * color: <hex>,
  7162. * opacity: <float>,
  7163. * map: new THREE.Texture( <Image> ),
  7164. *
  7165. * lightMap: new THREE.Texture( <Image> ),
  7166. * lightMapIntensity: <float>
  7167. *
  7168. * aoMap: new THREE.Texture( <Image> ),
  7169. * aoMapIntensity: <float>
  7170. *
  7171. * specularMap: new THREE.Texture( <Image> ),
  7172. *
  7173. * alphaMap: new THREE.Texture( <Image> ),
  7174. *
  7175. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  7176. * combine: THREE.Multiply,
  7177. * reflectivity: <float>,
  7178. * refractionRatio: <float>,
  7179. *
  7180. * depthTest: <bool>,
  7181. * depthWrite: <bool>,
  7182. *
  7183. * wireframe: <boolean>,
  7184. * wireframeLinewidth: <float>,
  7185. *
  7186. * skinning: <bool>,
  7187. * morphTargets: <bool>
  7188. * }
  7189. */
  7190. function MeshBasicMaterial(parameters) {
  7191. Material.call(this);
  7192. this.type = 'MeshBasicMaterial';
  7193. this.color = new Color(0xffffff); // emissive
  7194. this.map = null;
  7195. this.lightMap = null;
  7196. this.lightMapIntensity = 1.0;
  7197. this.aoMap = null;
  7198. this.aoMapIntensity = 1.0;
  7199. this.specularMap = null;
  7200. this.alphaMap = null;
  7201. this.envMap = null;
  7202. this.combine = MultiplyOperation;
  7203. this.reflectivity = 1;
  7204. this.refractionRatio = 0.98;
  7205. this.wireframe = false;
  7206. this.wireframeLinewidth = 1;
  7207. this.wireframeLinecap = 'round';
  7208. this.wireframeLinejoin = 'round';
  7209. this.skinning = false;
  7210. this.morphTargets = false;
  7211. this.setValues(parameters);
  7212. }
  7213. MeshBasicMaterial.prototype = Object.create(Material.prototype);
  7214. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  7215. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  7216. MeshBasicMaterial.prototype.copy = function (source) {
  7217. Material.prototype.copy.call(this, source);
  7218. this.color.copy(source.color);
  7219. this.map = source.map;
  7220. this.lightMap = source.lightMap;
  7221. this.lightMapIntensity = source.lightMapIntensity;
  7222. this.aoMap = source.aoMap;
  7223. this.aoMapIntensity = source.aoMapIntensity;
  7224. this.specularMap = source.specularMap;
  7225. this.alphaMap = source.alphaMap;
  7226. this.envMap = source.envMap;
  7227. this.combine = source.combine;
  7228. this.reflectivity = source.reflectivity;
  7229. this.refractionRatio = source.refractionRatio;
  7230. this.wireframe = source.wireframe;
  7231. this.wireframeLinewidth = source.wireframeLinewidth;
  7232. this.wireframeLinecap = source.wireframeLinecap;
  7233. this.wireframeLinejoin = source.wireframeLinejoin;
  7234. this.skinning = source.skinning;
  7235. this.morphTargets = source.morphTargets;
  7236. return this;
  7237. };
  7238. /**
  7239. * @author mrdoob / http://mrdoob.com/
  7240. */
  7241. function BufferAttribute(array, itemSize, normalized) {
  7242. if (Array.isArray(array)) {
  7243. throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
  7244. }
  7245. this.name = '';
  7246. this.array = array;
  7247. this.itemSize = itemSize;
  7248. this.count = array !== undefined ? array.length / itemSize : 0;
  7249. this.normalized = normalized === true;
  7250. this.dynamic = false;
  7251. this.updateRange = {
  7252. offset: 0,
  7253. count: -1
  7254. };
  7255. this.version = 0;
  7256. }
  7257. Object.defineProperty(BufferAttribute.prototype, 'needsUpdate', {
  7258. set: function (value) {
  7259. if (value === true) this.version++;
  7260. }
  7261. });
  7262. Object.assign(BufferAttribute.prototype, {
  7263. isBufferAttribute: true,
  7264. onUploadCallback: function () {},
  7265. setDynamic: function (value) {
  7266. this.dynamic = value;
  7267. return this;
  7268. },
  7269. copy: function (source) {
  7270. this.name = source.name;
  7271. this.array = new source.array.constructor(source.array);
  7272. this.itemSize = source.itemSize;
  7273. this.count = source.count;
  7274. this.normalized = source.normalized;
  7275. this.dynamic = source.dynamic;
  7276. return this;
  7277. },
  7278. copyAt: function (index1, attribute, index2) {
  7279. index1 *= this.itemSize;
  7280. index2 *= attribute.itemSize;
  7281. for (var i = 0, l = this.itemSize; i < l; i++) {
  7282. this.array[index1 + i] = attribute.array[index2 + i];
  7283. }
  7284. return this;
  7285. },
  7286. copyArray: function (array) {
  7287. this.array.set(array);
  7288. return this;
  7289. },
  7290. copyColorsArray: function (colors) {
  7291. var array = this.array,
  7292. offset = 0;
  7293. for (var i = 0, l = colors.length; i < l; i++) {
  7294. var color = colors[i];
  7295. if (color === undefined) {
  7296. console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);
  7297. color = new Color();
  7298. }
  7299. array[offset++] = color.r;
  7300. array[offset++] = color.g;
  7301. array[offset++] = color.b;
  7302. }
  7303. return this;
  7304. },
  7305. copyVector2sArray: function (vectors) {
  7306. var array = this.array,
  7307. offset = 0;
  7308. for (var i = 0, l = vectors.length; i < l; i++) {
  7309. var vector = vectors[i];
  7310. if (vector === undefined) {
  7311. console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i);
  7312. vector = new Vector2();
  7313. }
  7314. array[offset++] = vector.x;
  7315. array[offset++] = vector.y;
  7316. }
  7317. return this;
  7318. },
  7319. copyVector3sArray: function (vectors) {
  7320. var array = this.array,
  7321. offset = 0;
  7322. for (var i = 0, l = vectors.length; i < l; i++) {
  7323. var vector = vectors[i];
  7324. if (vector === undefined) {
  7325. console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i);
  7326. vector = new Vector3();
  7327. }
  7328. array[offset++] = vector.x;
  7329. array[offset++] = vector.y;
  7330. array[offset++] = vector.z;
  7331. }
  7332. return this;
  7333. },
  7334. copyVector4sArray: function (vectors) {
  7335. var array = this.array,
  7336. offset = 0;
  7337. for (var i = 0, l = vectors.length; i < l; i++) {
  7338. var vector = vectors[i];
  7339. if (vector === undefined) {
  7340. console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i);
  7341. vector = new Vector4();
  7342. }
  7343. array[offset++] = vector.x;
  7344. array[offset++] = vector.y;
  7345. array[offset++] = vector.z;
  7346. array[offset++] = vector.w;
  7347. }
  7348. return this;
  7349. },
  7350. set: function (value, offset) {
  7351. if (offset === undefined) offset = 0;
  7352. this.array.set(value, offset);
  7353. return this;
  7354. },
  7355. getX: function (index) {
  7356. return this.array[index * this.itemSize];
  7357. },
  7358. setX: function (index, x) {
  7359. this.array[index * this.itemSize] = x;
  7360. return this;
  7361. },
  7362. getY: function (index) {
  7363. return this.array[index * this.itemSize + 1];
  7364. },
  7365. setY: function (index, y) {
  7366. this.array[index * this.itemSize + 1] = y;
  7367. return this;
  7368. },
  7369. getZ: function (index) {
  7370. return this.array[index * this.itemSize + 2];
  7371. },
  7372. setZ: function (index, z) {
  7373. this.array[index * this.itemSize + 2] = z;
  7374. return this;
  7375. },
  7376. getW: function (index) {
  7377. return this.array[index * this.itemSize + 3];
  7378. },
  7379. setW: function (index, w) {
  7380. this.array[index * this.itemSize + 3] = w;
  7381. return this;
  7382. },
  7383. setXY: function (index, x, y) {
  7384. index *= this.itemSize;
  7385. this.array[index + 0] = x;
  7386. this.array[index + 1] = y;
  7387. return this;
  7388. },
  7389. setXYZ: function (index, x, y, z) {
  7390. index *= this.itemSize;
  7391. this.array[index + 0] = x;
  7392. this.array[index + 1] = y;
  7393. this.array[index + 2] = z;
  7394. return this;
  7395. },
  7396. setXYZW: function (index, x, y, z, w) {
  7397. index *= this.itemSize;
  7398. this.array[index + 0] = x;
  7399. this.array[index + 1] = y;
  7400. this.array[index + 2] = z;
  7401. this.array[index + 3] = w;
  7402. return this;
  7403. },
  7404. onUpload: function (callback) {
  7405. this.onUploadCallback = callback;
  7406. return this;
  7407. },
  7408. clone: function () {
  7409. return new this.constructor(this.array, this.itemSize).copy(this);
  7410. },
  7411. toJSON: function () {
  7412. return {
  7413. itemSize: this.itemSize,
  7414. type: this.array.constructor.name,
  7415. array: Array.prototype.slice.call(this.array),
  7416. normalized: this.normalized
  7417. };
  7418. }
  7419. }); //
  7420. function Int8BufferAttribute(array, itemSize, normalized) {
  7421. BufferAttribute.call(this, new Int8Array(array), itemSize, normalized);
  7422. }
  7423. Int8BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7424. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  7425. function Uint8BufferAttribute(array, itemSize, normalized) {
  7426. BufferAttribute.call(this, new Uint8Array(array), itemSize, normalized);
  7427. }
  7428. Uint8BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7429. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  7430. function Uint8ClampedBufferAttribute(array, itemSize, normalized) {
  7431. BufferAttribute.call(this, new Uint8ClampedArray(array), itemSize, normalized);
  7432. }
  7433. Uint8ClampedBufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7434. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  7435. function Int16BufferAttribute(array, itemSize, normalized) {
  7436. BufferAttribute.call(this, new Int16Array(array), itemSize, normalized);
  7437. }
  7438. Int16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7439. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  7440. function Uint16BufferAttribute(array, itemSize, normalized) {
  7441. BufferAttribute.call(this, new Uint16Array(array), itemSize, normalized);
  7442. }
  7443. Uint16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7444. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  7445. function Int32BufferAttribute(array, itemSize, normalized) {
  7446. BufferAttribute.call(this, new Int32Array(array), itemSize, normalized);
  7447. }
  7448. Int32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7449. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  7450. function Uint32BufferAttribute(array, itemSize, normalized) {
  7451. BufferAttribute.call(this, new Uint32Array(array), itemSize, normalized);
  7452. }
  7453. Uint32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7454. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  7455. function Float32BufferAttribute(array, itemSize, normalized) {
  7456. BufferAttribute.call(this, new Float32Array(array), itemSize, normalized);
  7457. }
  7458. Float32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7459. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  7460. function Float64BufferAttribute(array, itemSize, normalized) {
  7461. BufferAttribute.call(this, new Float64Array(array), itemSize, normalized);
  7462. }
  7463. Float64BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7464. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  7465. /**
  7466. * @author mrdoob / http://mrdoob.com/
  7467. */
  7468. function DirectGeometry() {
  7469. this.vertices = [];
  7470. this.normals = [];
  7471. this.colors = [];
  7472. this.uvs = [];
  7473. this.uvs2 = [];
  7474. this.groups = [];
  7475. this.morphTargets = {};
  7476. this.skinWeights = [];
  7477. this.skinIndices = []; // this.lineDistances = [];
  7478. this.boundingBox = null;
  7479. this.boundingSphere = null; // update flags
  7480. this.verticesNeedUpdate = false;
  7481. this.normalsNeedUpdate = false;
  7482. this.colorsNeedUpdate = false;
  7483. this.uvsNeedUpdate = false;
  7484. this.groupsNeedUpdate = false;
  7485. }
  7486. Object.assign(DirectGeometry.prototype, {
  7487. computeGroups: function (geometry) {
  7488. var group;
  7489. var groups = [];
  7490. var materialIndex = undefined;
  7491. var faces = geometry.faces;
  7492. for (var i = 0; i < faces.length; i++) {
  7493. var face = faces[i]; // materials
  7494. if (face.materialIndex !== materialIndex) {
  7495. materialIndex = face.materialIndex;
  7496. if (group !== undefined) {
  7497. group.count = i * 3 - group.start;
  7498. groups.push(group);
  7499. }
  7500. group = {
  7501. start: i * 3,
  7502. materialIndex: materialIndex
  7503. };
  7504. }
  7505. }
  7506. if (group !== undefined) {
  7507. group.count = i * 3 - group.start;
  7508. groups.push(group);
  7509. }
  7510. this.groups = groups;
  7511. },
  7512. fromGeometry: function (geometry) {
  7513. var faces = geometry.faces;
  7514. var vertices = geometry.vertices;
  7515. var faceVertexUvs = geometry.faceVertexUvs;
  7516. var hasFaceVertexUv = faceVertexUvs[0] && faceVertexUvs[0].length > 0;
  7517. var hasFaceVertexUv2 = faceVertexUvs[1] && faceVertexUvs[1].length > 0; // morphs
  7518. var morphTargets = geometry.morphTargets;
  7519. var morphTargetsLength = morphTargets.length;
  7520. var morphTargetsPosition;
  7521. if (morphTargetsLength > 0) {
  7522. morphTargetsPosition = [];
  7523. for (var i = 0; i < morphTargetsLength; i++) {
  7524. morphTargetsPosition[i] = {
  7525. name: morphTargets[i].name,
  7526. data: []
  7527. };
  7528. }
  7529. this.morphTargets.position = morphTargetsPosition;
  7530. }
  7531. var morphNormals = geometry.morphNormals;
  7532. var morphNormalsLength = morphNormals.length;
  7533. var morphTargetsNormal;
  7534. if (morphNormalsLength > 0) {
  7535. morphTargetsNormal = [];
  7536. for (var i = 0; i < morphNormalsLength; i++) {
  7537. morphTargetsNormal[i] = {
  7538. name: morphNormals[i].name,
  7539. data: []
  7540. };
  7541. }
  7542. this.morphTargets.normal = morphTargetsNormal;
  7543. } // skins
  7544. var skinIndices = geometry.skinIndices;
  7545. var skinWeights = geometry.skinWeights;
  7546. var hasSkinIndices = skinIndices.length === vertices.length;
  7547. var hasSkinWeights = skinWeights.length === vertices.length; //
  7548. if (vertices.length > 0 && faces.length === 0) {
  7549. console.error('THREE.DirectGeometry: Faceless geometries are not supported.');
  7550. }
  7551. for (var i = 0; i < faces.length; i++) {
  7552. var face = faces[i];
  7553. this.vertices.push(vertices[face.a], vertices[face.b], vertices[face.c]);
  7554. var vertexNormals = face.vertexNormals;
  7555. if (vertexNormals.length === 3) {
  7556. this.normals.push(vertexNormals[0], vertexNormals[1], vertexNormals[2]);
  7557. } else {
  7558. var normal = face.normal;
  7559. this.normals.push(normal, normal, normal);
  7560. }
  7561. var vertexColors = face.vertexColors;
  7562. if (vertexColors.length === 3) {
  7563. this.colors.push(vertexColors[0], vertexColors[1], vertexColors[2]);
  7564. } else {
  7565. var color = face.color;
  7566. this.colors.push(color, color, color);
  7567. }
  7568. if (hasFaceVertexUv === true) {
  7569. var vertexUvs = faceVertexUvs[0][i];
  7570. if (vertexUvs !== undefined) {
  7571. this.uvs.push(vertexUvs[0], vertexUvs[1], vertexUvs[2]);
  7572. } else {
  7573. console.warn('THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i);
  7574. this.uvs.push(new Vector2(), new Vector2(), new Vector2());
  7575. }
  7576. }
  7577. if (hasFaceVertexUv2 === true) {
  7578. var vertexUvs = faceVertexUvs[1][i];
  7579. if (vertexUvs !== undefined) {
  7580. this.uvs2.push(vertexUvs[0], vertexUvs[1], vertexUvs[2]);
  7581. } else {
  7582. console.warn('THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i);
  7583. this.uvs2.push(new Vector2(), new Vector2(), new Vector2());
  7584. }
  7585. } // morphs
  7586. for (var j = 0; j < morphTargetsLength; j++) {
  7587. var morphTarget = morphTargets[j].vertices;
  7588. morphTargetsPosition[j].data.push(morphTarget[face.a], morphTarget[face.b], morphTarget[face.c]);
  7589. }
  7590. for (var j = 0; j < morphNormalsLength; j++) {
  7591. var morphNormal = morphNormals[j].vertexNormals[i];
  7592. morphTargetsNormal[j].data.push(morphNormal.a, morphNormal.b, morphNormal.c);
  7593. } // skins
  7594. if (hasSkinIndices) {
  7595. this.skinIndices.push(skinIndices[face.a], skinIndices[face.b], skinIndices[face.c]);
  7596. }
  7597. if (hasSkinWeights) {
  7598. this.skinWeights.push(skinWeights[face.a], skinWeights[face.b], skinWeights[face.c]);
  7599. }
  7600. }
  7601. this.computeGroups(geometry);
  7602. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  7603. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  7604. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  7605. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  7606. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  7607. if (geometry.boundingSphere !== null) {
  7608. this.boundingSphere = geometry.boundingSphere.clone();
  7609. }
  7610. if (geometry.boundingBox !== null) {
  7611. this.boundingBox = geometry.boundingBox.clone();
  7612. }
  7613. return this;
  7614. }
  7615. });
  7616. /**
  7617. * @author mrdoob / http://mrdoob.com/
  7618. */
  7619. function arrayMax(array) {
  7620. if (array.length === 0) return -Infinity;
  7621. var max = array[0];
  7622. for (var i = 1, l = array.length; i < l; ++i) {
  7623. if (array[i] > max) max = array[i];
  7624. }
  7625. return max;
  7626. }
  7627. /**
  7628. * @author alteredq / http://alteredqualia.com/
  7629. * @author mrdoob / http://mrdoob.com/
  7630. */
  7631. var _bufferGeometryId = 1; // BufferGeometry uses odd numbers as Id
  7632. var _m1$2 = new Matrix4();
  7633. var _obj = new Object3D();
  7634. var _offset = new Vector3();
  7635. var _box$1 = new Box3();
  7636. var _boxMorphTargets = new Box3();
  7637. var _vector$4 = new Vector3();
  7638. function BufferGeometry() {
  7639. Object.defineProperty(this, 'id', {
  7640. value: _bufferGeometryId += 2
  7641. });
  7642. this.uuid = _Math.generateUUID();
  7643. this.name = '';
  7644. this.type = 'BufferGeometry';
  7645. this.index = null;
  7646. this.attributes = {};
  7647. this.morphAttributes = {};
  7648. this.groups = [];
  7649. this.boundingBox = null;
  7650. this.boundingSphere = null;
  7651. this.drawRange = {
  7652. start: 0,
  7653. count: Infinity
  7654. };
  7655. this.userData = {};
  7656. }
  7657. BufferGeometry.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  7658. constructor: BufferGeometry,
  7659. isBufferGeometry: true,
  7660. getIndex: function () {
  7661. return this.index;
  7662. },
  7663. setIndex: function (index) {
  7664. if (Array.isArray(index)) {
  7665. this.index = new (arrayMax(index) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
  7666. } else {
  7667. this.index = index;
  7668. }
  7669. },
  7670. addAttribute: function (name, attribute) {
  7671. if (!(attribute && attribute.isBufferAttribute) && !(attribute && attribute.isInterleavedBufferAttribute)) {
  7672. console.warn('THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).');
  7673. return this.addAttribute(name, new BufferAttribute(arguments[1], arguments[2]));
  7674. }
  7675. if (name === 'index') {
  7676. console.warn('THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.');
  7677. this.setIndex(attribute);
  7678. return this;
  7679. }
  7680. return this.setAttribute(name, attribute);
  7681. },
  7682. getAttribute: function (name) {
  7683. return this.attributes[name];
  7684. },
  7685. setAttribute: function (name, attribute) {
  7686. this.attributes[name] = attribute;
  7687. return this;
  7688. },
  7689. removeAttribute: function (name) {
  7690. delete this.attributes[name];
  7691. return this;
  7692. },
  7693. addGroup: function (start, count, materialIndex) {
  7694. this.groups.push({
  7695. start: start,
  7696. count: count,
  7697. materialIndex: materialIndex !== undefined ? materialIndex : 0
  7698. });
  7699. },
  7700. clearGroups: function () {
  7701. this.groups = [];
  7702. },
  7703. setDrawRange: function (start, count) {
  7704. this.drawRange.start = start;
  7705. this.drawRange.count = count;
  7706. },
  7707. applyMatrix: function (matrix) {
  7708. var position = this.attributes.position;
  7709. if (position !== undefined) {
  7710. matrix.applyToBufferAttribute(position);
  7711. position.needsUpdate = true;
  7712. }
  7713. var normal = this.attributes.normal;
  7714. if (normal !== undefined) {
  7715. var normalMatrix = new Matrix3().getNormalMatrix(matrix);
  7716. normalMatrix.applyToBufferAttribute(normal);
  7717. normal.needsUpdate = true;
  7718. }
  7719. var tangent = this.attributes.tangent;
  7720. if (tangent !== undefined) {
  7721. var normalMatrix = new Matrix3().getNormalMatrix(matrix); // Tangent is vec4, but the '.w' component is a sign value (+1/-1).
  7722. normalMatrix.applyToBufferAttribute(tangent);
  7723. tangent.needsUpdate = true;
  7724. }
  7725. if (this.boundingBox !== null) {
  7726. this.computeBoundingBox();
  7727. }
  7728. if (this.boundingSphere !== null) {
  7729. this.computeBoundingSphere();
  7730. }
  7731. return this;
  7732. },
  7733. rotateX: function (angle) {
  7734. // rotate geometry around world x-axis
  7735. _m1$2.makeRotationX(angle);
  7736. this.applyMatrix(_m1$2);
  7737. return this;
  7738. },
  7739. rotateY: function (angle) {
  7740. // rotate geometry around world y-axis
  7741. _m1$2.makeRotationY(angle);
  7742. this.applyMatrix(_m1$2);
  7743. return this;
  7744. },
  7745. rotateZ: function (angle) {
  7746. // rotate geometry around world z-axis
  7747. _m1$2.makeRotationZ(angle);
  7748. this.applyMatrix(_m1$2);
  7749. return this;
  7750. },
  7751. translate: function (x, y, z) {
  7752. // translate geometry
  7753. _m1$2.makeTranslation(x, y, z);
  7754. this.applyMatrix(_m1$2);
  7755. return this;
  7756. },
  7757. scale: function (x, y, z) {
  7758. // scale geometry
  7759. _m1$2.makeScale(x, y, z);
  7760. this.applyMatrix(_m1$2);
  7761. return this;
  7762. },
  7763. lookAt: function (vector) {
  7764. _obj.lookAt(vector);
  7765. _obj.updateMatrix();
  7766. this.applyMatrix(_obj.matrix);
  7767. return this;
  7768. },
  7769. center: function () {
  7770. this.computeBoundingBox();
  7771. this.boundingBox.getCenter(_offset).negate();
  7772. this.translate(_offset.x, _offset.y, _offset.z);
  7773. return this;
  7774. },
  7775. setFromObject: function (object) {
  7776. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  7777. var geometry = object.geometry;
  7778. if (object.isPoints || object.isLine) {
  7779. var positions = new Float32BufferAttribute(geometry.vertices.length * 3, 3);
  7780. var colors = new Float32BufferAttribute(geometry.colors.length * 3, 3);
  7781. this.addAttribute('position', positions.copyVector3sArray(geometry.vertices));
  7782. this.addAttribute('color', colors.copyColorsArray(geometry.colors));
  7783. if (geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length) {
  7784. var lineDistances = new Float32BufferAttribute(geometry.lineDistances.length, 1);
  7785. this.addAttribute('lineDistance', lineDistances.copyArray(geometry.lineDistances));
  7786. }
  7787. if (geometry.boundingSphere !== null) {
  7788. this.boundingSphere = geometry.boundingSphere.clone();
  7789. }
  7790. if (geometry.boundingBox !== null) {
  7791. this.boundingBox = geometry.boundingBox.clone();
  7792. }
  7793. } else if (object.isMesh) {
  7794. if (geometry && geometry.isGeometry) {
  7795. this.fromGeometry(geometry);
  7796. }
  7797. }
  7798. return this;
  7799. },
  7800. setFromPoints: function (points) {
  7801. var position = [];
  7802. for (var i = 0, l = points.length; i < l; i++) {
  7803. var point = points[i];
  7804. position.push(point.x, point.y, point.z || 0);
  7805. }
  7806. this.addAttribute('position', new Float32BufferAttribute(position, 3));
  7807. return this;
  7808. },
  7809. updateFromObject: function (object) {
  7810. var geometry = object.geometry;
  7811. if (object.isMesh) {
  7812. var direct = geometry.__directGeometry;
  7813. if (geometry.elementsNeedUpdate === true) {
  7814. direct = undefined;
  7815. geometry.elementsNeedUpdate = false;
  7816. }
  7817. if (direct === undefined) {
  7818. return this.fromGeometry(geometry);
  7819. }
  7820. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  7821. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  7822. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  7823. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  7824. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  7825. geometry.verticesNeedUpdate = false;
  7826. geometry.normalsNeedUpdate = false;
  7827. geometry.colorsNeedUpdate = false;
  7828. geometry.uvsNeedUpdate = false;
  7829. geometry.groupsNeedUpdate = false;
  7830. geometry = direct;
  7831. }
  7832. var attribute;
  7833. if (geometry.verticesNeedUpdate === true) {
  7834. attribute = this.attributes.position;
  7835. if (attribute !== undefined) {
  7836. attribute.copyVector3sArray(geometry.vertices);
  7837. attribute.needsUpdate = true;
  7838. }
  7839. geometry.verticesNeedUpdate = false;
  7840. }
  7841. if (geometry.normalsNeedUpdate === true) {
  7842. attribute = this.attributes.normal;
  7843. if (attribute !== undefined) {
  7844. attribute.copyVector3sArray(geometry.normals);
  7845. attribute.needsUpdate = true;
  7846. }
  7847. geometry.normalsNeedUpdate = false;
  7848. }
  7849. if (geometry.colorsNeedUpdate === true) {
  7850. attribute = this.attributes.color;
  7851. if (attribute !== undefined) {
  7852. attribute.copyColorsArray(geometry.colors);
  7853. attribute.needsUpdate = true;
  7854. }
  7855. geometry.colorsNeedUpdate = false;
  7856. }
  7857. if (geometry.uvsNeedUpdate) {
  7858. attribute = this.attributes.uv;
  7859. if (attribute !== undefined) {
  7860. attribute.copyVector2sArray(geometry.uvs);
  7861. attribute.needsUpdate = true;
  7862. }
  7863. geometry.uvsNeedUpdate = false;
  7864. }
  7865. if (geometry.lineDistancesNeedUpdate) {
  7866. attribute = this.attributes.lineDistance;
  7867. if (attribute !== undefined) {
  7868. attribute.copyArray(geometry.lineDistances);
  7869. attribute.needsUpdate = true;
  7870. }
  7871. geometry.lineDistancesNeedUpdate = false;
  7872. }
  7873. if (geometry.groupsNeedUpdate) {
  7874. geometry.computeGroups(object.geometry);
  7875. this.groups = geometry.groups;
  7876. geometry.groupsNeedUpdate = false;
  7877. }
  7878. return this;
  7879. },
  7880. fromGeometry: function (geometry) {
  7881. geometry.__directGeometry = new DirectGeometry().fromGeometry(geometry);
  7882. return this.fromDirectGeometry(geometry.__directGeometry);
  7883. },
  7884. fromDirectGeometry: function (geometry) {
  7885. var positions = new Float32Array(geometry.vertices.length * 3);
  7886. this.addAttribute('position', new BufferAttribute(positions, 3).copyVector3sArray(geometry.vertices));
  7887. if (geometry.normals.length > 0) {
  7888. var normals = new Float32Array(geometry.normals.length * 3);
  7889. this.addAttribute('normal', new BufferAttribute(normals, 3).copyVector3sArray(geometry.normals));
  7890. }
  7891. if (geometry.colors.length > 0) {
  7892. var colors = new Float32Array(geometry.colors.length * 3);
  7893. this.addAttribute('color', new BufferAttribute(colors, 3).copyColorsArray(geometry.colors));
  7894. }
  7895. if (geometry.uvs.length > 0) {
  7896. var uvs = new Float32Array(geometry.uvs.length * 2);
  7897. this.addAttribute('uv', new BufferAttribute(uvs, 2).copyVector2sArray(geometry.uvs));
  7898. }
  7899. if (geometry.uvs2.length > 0) {
  7900. var uvs2 = new Float32Array(geometry.uvs2.length * 2);
  7901. this.addAttribute('uv2', new BufferAttribute(uvs2, 2).copyVector2sArray(geometry.uvs2));
  7902. } // groups
  7903. this.groups = geometry.groups; // morphs
  7904. for (var name in geometry.morphTargets) {
  7905. var array = [];
  7906. var morphTargets = geometry.morphTargets[name];
  7907. for (var i = 0, l = morphTargets.length; i < l; i++) {
  7908. var morphTarget = morphTargets[i];
  7909. var attribute = new Float32BufferAttribute(morphTarget.data.length * 3, 3);
  7910. attribute.name = morphTarget.name;
  7911. array.push(attribute.copyVector3sArray(morphTarget.data));
  7912. }
  7913. this.morphAttributes[name] = array;
  7914. } // skinning
  7915. if (geometry.skinIndices.length > 0) {
  7916. var skinIndices = new Float32BufferAttribute(geometry.skinIndices.length * 4, 4);
  7917. this.addAttribute('skinIndex', skinIndices.copyVector4sArray(geometry.skinIndices));
  7918. }
  7919. if (geometry.skinWeights.length > 0) {
  7920. var skinWeights = new Float32BufferAttribute(geometry.skinWeights.length * 4, 4);
  7921. this.addAttribute('skinWeight', skinWeights.copyVector4sArray(geometry.skinWeights));
  7922. } //
  7923. if (geometry.boundingSphere !== null) {
  7924. this.boundingSphere = geometry.boundingSphere.clone();
  7925. }
  7926. if (geometry.boundingBox !== null) {
  7927. this.boundingBox = geometry.boundingBox.clone();
  7928. }
  7929. return this;
  7930. },
  7931. computeBoundingBox: function () {
  7932. if (this.boundingBox === null) {
  7933. this.boundingBox = new Box3();
  7934. }
  7935. var position = this.attributes.position;
  7936. var morphAttributesPosition = this.morphAttributes.position;
  7937. if (position !== undefined) {
  7938. this.boundingBox.setFromBufferAttribute(position); // process morph attributes if present
  7939. if (morphAttributesPosition) {
  7940. for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
  7941. var morphAttribute = morphAttributesPosition[i];
  7942. _box$1.setFromBufferAttribute(morphAttribute);
  7943. this.boundingBox.expandByPoint(_box$1.min);
  7944. this.boundingBox.expandByPoint(_box$1.max);
  7945. }
  7946. }
  7947. } else {
  7948. this.boundingBox.makeEmpty();
  7949. }
  7950. if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
  7951. console.error('THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  7952. }
  7953. },
  7954. computeBoundingSphere: function () {
  7955. if (this.boundingSphere === null) {
  7956. this.boundingSphere = new Sphere();
  7957. }
  7958. var position = this.attributes.position;
  7959. var morphAttributesPosition = this.morphAttributes.position;
  7960. if (position) {
  7961. // first, find the center of the bounding sphere
  7962. var center = this.boundingSphere.center;
  7963. _box$1.setFromBufferAttribute(position); // process morph attributes if present
  7964. if (morphAttributesPosition) {
  7965. for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
  7966. var morphAttribute = morphAttributesPosition[i];
  7967. _boxMorphTargets.setFromBufferAttribute(morphAttribute);
  7968. _box$1.expandByPoint(_boxMorphTargets.min);
  7969. _box$1.expandByPoint(_boxMorphTargets.max);
  7970. }
  7971. }
  7972. _box$1.getCenter(center); // second, try to find a boundingSphere with a radius smaller than the
  7973. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  7974. var maxRadiusSq = 0;
  7975. for (var i = 0, il = position.count; i < il; i++) {
  7976. _vector$4.fromBufferAttribute(position, i);
  7977. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$4));
  7978. } // process morph attributes if present
  7979. if (morphAttributesPosition) {
  7980. for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
  7981. var morphAttribute = morphAttributesPosition[i];
  7982. for (var j = 0, jl = morphAttribute.count; j < jl; j++) {
  7983. _vector$4.fromBufferAttribute(morphAttribute, j);
  7984. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$4));
  7985. }
  7986. }
  7987. }
  7988. this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
  7989. if (isNaN(this.boundingSphere.radius)) {
  7990. console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
  7991. }
  7992. }
  7993. },
  7994. computeFaceNormals: function () {// backwards compatibility
  7995. },
  7996. computeVertexNormals: function () {
  7997. var index = this.index;
  7998. var attributes = this.attributes;
  7999. if (attributes.position) {
  8000. var positions = attributes.position.array;
  8001. if (attributes.normal === undefined) {
  8002. this.addAttribute('normal', new BufferAttribute(new Float32Array(positions.length), 3));
  8003. } else {
  8004. // reset existing normals to zero
  8005. var array = attributes.normal.array;
  8006. for (var i = 0, il = array.length; i < il; i++) {
  8007. array[i] = 0;
  8008. }
  8009. }
  8010. var normals = attributes.normal.array;
  8011. var vA, vB, vC;
  8012. var pA = new Vector3(),
  8013. pB = new Vector3(),
  8014. pC = new Vector3();
  8015. var cb = new Vector3(),
  8016. ab = new Vector3(); // indexed elements
  8017. if (index) {
  8018. var indices = index.array;
  8019. for (var i = 0, il = index.count; i < il; i += 3) {
  8020. vA = indices[i + 0] * 3;
  8021. vB = indices[i + 1] * 3;
  8022. vC = indices[i + 2] * 3;
  8023. pA.fromArray(positions, vA);
  8024. pB.fromArray(positions, vB);
  8025. pC.fromArray(positions, vC);
  8026. cb.subVectors(pC, pB);
  8027. ab.subVectors(pA, pB);
  8028. cb.cross(ab);
  8029. normals[vA] += cb.x;
  8030. normals[vA + 1] += cb.y;
  8031. normals[vA + 2] += cb.z;
  8032. normals[vB] += cb.x;
  8033. normals[vB + 1] += cb.y;
  8034. normals[vB + 2] += cb.z;
  8035. normals[vC] += cb.x;
  8036. normals[vC + 1] += cb.y;
  8037. normals[vC + 2] += cb.z;
  8038. }
  8039. } else {
  8040. // non-indexed elements (unconnected triangle soup)
  8041. for (var i = 0, il = positions.length; i < il; i += 9) {
  8042. pA.fromArray(positions, i);
  8043. pB.fromArray(positions, i + 3);
  8044. pC.fromArray(positions, i + 6);
  8045. cb.subVectors(pC, pB);
  8046. ab.subVectors(pA, pB);
  8047. cb.cross(ab);
  8048. normals[i] = cb.x;
  8049. normals[i + 1] = cb.y;
  8050. normals[i + 2] = cb.z;
  8051. normals[i + 3] = cb.x;
  8052. normals[i + 4] = cb.y;
  8053. normals[i + 5] = cb.z;
  8054. normals[i + 6] = cb.x;
  8055. normals[i + 7] = cb.y;
  8056. normals[i + 8] = cb.z;
  8057. }
  8058. }
  8059. this.normalizeNormals();
  8060. attributes.normal.needsUpdate = true;
  8061. }
  8062. },
  8063. merge: function (geometry, offset) {
  8064. if (!(geometry && geometry.isBufferGeometry)) {
  8065. console.error('THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry);
  8066. return;
  8067. }
  8068. if (offset === undefined) {
  8069. offset = 0;
  8070. console.warn('THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.');
  8071. }
  8072. var attributes = this.attributes;
  8073. for (var key in attributes) {
  8074. if (geometry.attributes[key] === undefined) continue;
  8075. var attribute1 = attributes[key];
  8076. var attributeArray1 = attribute1.array;
  8077. var attribute2 = geometry.attributes[key];
  8078. var attributeArray2 = attribute2.array;
  8079. var attributeOffset = attribute2.itemSize * offset;
  8080. var length = Math.min(attributeArray2.length, attributeArray1.length - attributeOffset);
  8081. for (var i = 0, j = attributeOffset; i < length; i++, j++) {
  8082. attributeArray1[j] = attributeArray2[i];
  8083. }
  8084. }
  8085. return this;
  8086. },
  8087. normalizeNormals: function () {
  8088. var normals = this.attributes.normal;
  8089. for (var i = 0, il = normals.count; i < il; i++) {
  8090. _vector$4.x = normals.getX(i);
  8091. _vector$4.y = normals.getY(i);
  8092. _vector$4.z = normals.getZ(i);
  8093. _vector$4.normalize();
  8094. normals.setXYZ(i, _vector$4.x, _vector$4.y, _vector$4.z);
  8095. }
  8096. },
  8097. toNonIndexed: function () {
  8098. function convertBufferAttribute(attribute, indices) {
  8099. var array = attribute.array;
  8100. var itemSize = attribute.itemSize;
  8101. var array2 = new array.constructor(indices.length * itemSize);
  8102. var index = 0,
  8103. index2 = 0;
  8104. for (var i = 0, l = indices.length; i < l; i++) {
  8105. index = indices[i] * itemSize;
  8106. for (var j = 0; j < itemSize; j++) {
  8107. array2[index2++] = array[index++];
  8108. }
  8109. }
  8110. return new BufferAttribute(array2, itemSize);
  8111. } //
  8112. if (this.index === null) {
  8113. console.warn('THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.');
  8114. return this;
  8115. }
  8116. var geometry2 = new BufferGeometry();
  8117. var indices = this.index.array;
  8118. var attributes = this.attributes; // attributes
  8119. for (var name in attributes) {
  8120. var attribute = attributes[name];
  8121. var newAttribute = convertBufferAttribute(attribute, indices);
  8122. geometry2.addAttribute(name, newAttribute);
  8123. } // morph attributes
  8124. var morphAttributes = this.morphAttributes;
  8125. for (name in morphAttributes) {
  8126. var morphArray = [];
  8127. var morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  8128. for (var i = 0, il = morphAttribute.length; i < il; i++) {
  8129. var attribute = morphAttribute[i];
  8130. var newAttribute = convertBufferAttribute(attribute, indices);
  8131. morphArray.push(newAttribute);
  8132. }
  8133. geometry2.morphAttributes[name] = morphArray;
  8134. } // groups
  8135. var groups = this.groups;
  8136. for (var i = 0, l = groups.length; i < l; i++) {
  8137. var group = groups[i];
  8138. geometry2.addGroup(group.start, group.count, group.materialIndex);
  8139. }
  8140. return geometry2;
  8141. },
  8142. toJSON: function () {
  8143. var data = {
  8144. metadata: {
  8145. version: 4.5,
  8146. type: 'BufferGeometry',
  8147. generator: 'BufferGeometry.toJSON'
  8148. }
  8149. }; // standard BufferGeometry serialization
  8150. data.uuid = this.uuid;
  8151. data.type = this.type;
  8152. if (this.name !== '') data.name = this.name;
  8153. if (Object.keys(this.userData).length > 0) data.userData = this.userData;
  8154. if (this.parameters !== undefined) {
  8155. var parameters = this.parameters;
  8156. for (var key in parameters) {
  8157. if (parameters[key] !== undefined) data[key] = parameters[key];
  8158. }
  8159. return data;
  8160. }
  8161. data.data = {
  8162. attributes: {}
  8163. };
  8164. var index = this.index;
  8165. if (index !== null) {
  8166. data.data.index = {
  8167. type: index.array.constructor.name,
  8168. array: Array.prototype.slice.call(index.array)
  8169. };
  8170. }
  8171. var attributes = this.attributes;
  8172. for (var key in attributes) {
  8173. var attribute = attributes[key];
  8174. var attributeData = attribute.toJSON();
  8175. if (attribute.name !== '') attributeData.name = attribute.name;
  8176. data.data.attributes[key] = attributeData;
  8177. }
  8178. var morphAttributes = {};
  8179. var hasMorphAttributes = false;
  8180. for (var key in this.morphAttributes) {
  8181. var attributeArray = this.morphAttributes[key];
  8182. var array = [];
  8183. for (var i = 0, il = attributeArray.length; i < il; i++) {
  8184. var attribute = attributeArray[i];
  8185. var attributeData = attribute.toJSON();
  8186. if (attribute.name !== '') attributeData.name = attribute.name;
  8187. array.push(attributeData);
  8188. }
  8189. if (array.length > 0) {
  8190. morphAttributes[key] = array;
  8191. hasMorphAttributes = true;
  8192. }
  8193. }
  8194. if (hasMorphAttributes) data.data.morphAttributes = morphAttributes;
  8195. var groups = this.groups;
  8196. if (groups.length > 0) {
  8197. data.data.groups = JSON.parse(JSON.stringify(groups));
  8198. }
  8199. var boundingSphere = this.boundingSphere;
  8200. if (boundingSphere !== null) {
  8201. data.data.boundingSphere = {
  8202. center: boundingSphere.center.toArray(),
  8203. radius: boundingSphere.radius
  8204. };
  8205. }
  8206. return data;
  8207. },
  8208. clone: function () {
  8209. /*
  8210. // Handle primitives
  8211. var parameters = this.parameters;
  8212. if ( parameters !== undefined ) {
  8213. var values = [];
  8214. for ( var key in parameters ) {
  8215. values.push( parameters[ key ] );
  8216. }
  8217. var geometry = Object.create( this.constructor.prototype );
  8218. this.constructor.apply( geometry, values );
  8219. return geometry;
  8220. }
  8221. return new this.constructor().copy( this );
  8222. */
  8223. return new BufferGeometry().copy(this);
  8224. },
  8225. copy: function (source) {
  8226. var name, i, l; // reset
  8227. this.index = null;
  8228. this.attributes = {};
  8229. this.morphAttributes = {};
  8230. this.groups = [];
  8231. this.boundingBox = null;
  8232. this.boundingSphere = null; // name
  8233. this.name = source.name; // index
  8234. var index = source.index;
  8235. if (index !== null) {
  8236. this.setIndex(index.clone());
  8237. } // attributes
  8238. var attributes = source.attributes;
  8239. for (name in attributes) {
  8240. var attribute = attributes[name];
  8241. this.addAttribute(name, attribute.clone());
  8242. } // morph attributes
  8243. var morphAttributes = source.morphAttributes;
  8244. for (name in morphAttributes) {
  8245. var array = [];
  8246. var morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  8247. for (i = 0, l = morphAttribute.length; i < l; i++) {
  8248. array.push(morphAttribute[i].clone());
  8249. }
  8250. this.morphAttributes[name] = array;
  8251. } // groups
  8252. var groups = source.groups;
  8253. for (i = 0, l = groups.length; i < l; i++) {
  8254. var group = groups[i];
  8255. this.addGroup(group.start, group.count, group.materialIndex);
  8256. } // bounding box
  8257. var boundingBox = source.boundingBox;
  8258. if (boundingBox !== null) {
  8259. this.boundingBox = boundingBox.clone();
  8260. } // bounding sphere
  8261. var boundingSphere = source.boundingSphere;
  8262. if (boundingSphere !== null) {
  8263. this.boundingSphere = boundingSphere.clone();
  8264. } // draw range
  8265. this.drawRange.start = source.drawRange.start;
  8266. this.drawRange.count = source.drawRange.count; // user data
  8267. this.userData = source.userData;
  8268. return this;
  8269. },
  8270. dispose: function () {
  8271. this.dispatchEvent({
  8272. type: 'dispose'
  8273. });
  8274. }
  8275. });
  8276. /**
  8277. * @author mrdoob / http://mrdoob.com/
  8278. * @author alteredq / http://alteredqualia.com/
  8279. * @author mikael emtinger / http://gomo.se/
  8280. * @author jonobr1 / http://jonobr1.com/
  8281. */
  8282. var _inverseMatrix = new Matrix4();
  8283. var _ray = new Ray();
  8284. var _sphere = new Sphere();
  8285. var _vA = new Vector3();
  8286. var _vB = new Vector3();
  8287. var _vC = new Vector3();
  8288. var _tempA = new Vector3();
  8289. var _tempB = new Vector3();
  8290. var _tempC = new Vector3();
  8291. var _morphA = new Vector3();
  8292. var _morphB = new Vector3();
  8293. var _morphC = new Vector3();
  8294. var _uvA = new Vector2();
  8295. var _uvB = new Vector2();
  8296. var _uvC = new Vector2();
  8297. var _intersectionPoint = new Vector3();
  8298. var _intersectionPointWorld = new Vector3();
  8299. function Mesh(geometry, material) {
  8300. Object3D.call(this);
  8301. this.type = 'Mesh';
  8302. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  8303. this.material = material !== undefined ? material : new MeshBasicMaterial({
  8304. color: Math.random() * 0xffffff
  8305. });
  8306. this.drawMode = TrianglesDrawMode;
  8307. this.updateMorphTargets();
  8308. }
  8309. Mesh.prototype = Object.assign(Object.create(Object3D.prototype), {
  8310. constructor: Mesh,
  8311. isMesh: true,
  8312. setDrawMode: function (value) {
  8313. this.drawMode = value;
  8314. },
  8315. copy: function (source) {
  8316. Object3D.prototype.copy.call(this, source);
  8317. this.drawMode = source.drawMode;
  8318. if (source.morphTargetInfluences !== undefined) {
  8319. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  8320. }
  8321. if (source.morphTargetDictionary !== undefined) {
  8322. this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
  8323. }
  8324. return this;
  8325. },
  8326. updateMorphTargets: function () {
  8327. var geometry = this.geometry;
  8328. var m, ml, name;
  8329. if (geometry.isBufferGeometry) {
  8330. var morphAttributes = geometry.morphAttributes;
  8331. var keys = Object.keys(morphAttributes);
  8332. if (keys.length > 0) {
  8333. var morphAttribute = morphAttributes[keys[0]];
  8334. if (morphAttribute !== undefined) {
  8335. this.morphTargetInfluences = [];
  8336. this.morphTargetDictionary = {};
  8337. for (m = 0, ml = morphAttribute.length; m < ml; m++) {
  8338. name = morphAttribute[m].name || String(m);
  8339. this.morphTargetInfluences.push(0);
  8340. this.morphTargetDictionary[name] = m;
  8341. }
  8342. }
  8343. }
  8344. } else {
  8345. var morphTargets = geometry.morphTargets;
  8346. if (morphTargets !== undefined && morphTargets.length > 0) {
  8347. console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  8348. }
  8349. }
  8350. },
  8351. raycast: function (raycaster, intersects) {
  8352. var geometry = this.geometry;
  8353. var material = this.material;
  8354. var matrixWorld = this.matrixWorld;
  8355. if (material === undefined) return; // Checking boundingSphere distance to ray
  8356. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  8357. _sphere.copy(geometry.boundingSphere);
  8358. _sphere.applyMatrix4(matrixWorld);
  8359. if (raycaster.ray.intersectsSphere(_sphere) === false) return; //
  8360. _inverseMatrix.getInverse(matrixWorld);
  8361. _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix); // Check boundingBox before continuing
  8362. if (geometry.boundingBox !== null) {
  8363. if (_ray.intersectsBox(geometry.boundingBox) === false) return;
  8364. }
  8365. var intersection;
  8366. if (geometry.isBufferGeometry) {
  8367. var a, b, c;
  8368. var index = geometry.index;
  8369. var position = geometry.attributes.position;
  8370. var morphPosition = geometry.morphAttributes.position;
  8371. var uv = geometry.attributes.uv;
  8372. var uv2 = geometry.attributes.uv2;
  8373. var groups = geometry.groups;
  8374. var drawRange = geometry.drawRange;
  8375. var i, j, il, jl;
  8376. var group, groupMaterial;
  8377. var start, end;
  8378. if (index !== null) {
  8379. // indexed buffer geometry
  8380. if (Array.isArray(material)) {
  8381. for (i = 0, il = groups.length; i < il; i++) {
  8382. group = groups[i];
  8383. groupMaterial = material[group.materialIndex];
  8384. start = Math.max(group.start, drawRange.start);
  8385. end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  8386. for (j = start, jl = end; j < jl; j += 3) {
  8387. a = index.getX(j);
  8388. b = index.getX(j + 1);
  8389. c = index.getX(j + 2);
  8390. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray, position, morphPosition, uv, uv2, a, b, c);
  8391. if (intersection) {
  8392. intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
  8393. intersection.face.materialIndex = group.materialIndex;
  8394. intersects.push(intersection);
  8395. }
  8396. }
  8397. }
  8398. } else {
  8399. start = Math.max(0, drawRange.start);
  8400. end = Math.min(index.count, drawRange.start + drawRange.count);
  8401. for (i = start, il = end; i < il; i += 3) {
  8402. a = index.getX(i);
  8403. b = index.getX(i + 1);
  8404. c = index.getX(i + 2);
  8405. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray, position, morphPosition, uv, uv2, a, b, c);
  8406. if (intersection) {
  8407. intersection.faceIndex = Math.floor(i / 3); // triangle number in indexed buffer semantics
  8408. intersects.push(intersection);
  8409. }
  8410. }
  8411. }
  8412. } else if (position !== undefined) {
  8413. // non-indexed buffer geometry
  8414. if (Array.isArray(material)) {
  8415. for (i = 0, il = groups.length; i < il; i++) {
  8416. group = groups[i];
  8417. groupMaterial = material[group.materialIndex];
  8418. start = Math.max(group.start, drawRange.start);
  8419. end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  8420. for (j = start, jl = end; j < jl; j += 3) {
  8421. a = j;
  8422. b = j + 1;
  8423. c = j + 2;
  8424. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray, position, morphPosition, uv, uv2, a, b, c);
  8425. if (intersection) {
  8426. intersection.faceIndex = Math.floor(j / 3); // triangle number in non-indexed buffer semantics
  8427. intersection.face.materialIndex = group.materialIndex;
  8428. intersects.push(intersection);
  8429. }
  8430. }
  8431. }
  8432. } else {
  8433. start = Math.max(0, drawRange.start);
  8434. end = Math.min(position.count, drawRange.start + drawRange.count);
  8435. for (i = start, il = end; i < il; i += 3) {
  8436. a = i;
  8437. b = i + 1;
  8438. c = i + 2;
  8439. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray, position, morphPosition, uv, uv2, a, b, c);
  8440. if (intersection) {
  8441. intersection.faceIndex = Math.floor(i / 3); // triangle number in non-indexed buffer semantics
  8442. intersects.push(intersection);
  8443. }
  8444. }
  8445. }
  8446. }
  8447. } else if (geometry.isGeometry) {
  8448. var fvA, fvB, fvC;
  8449. var isMultiMaterial = Array.isArray(material);
  8450. var vertices = geometry.vertices;
  8451. var faces = geometry.faces;
  8452. var uvs;
  8453. var faceVertexUvs = geometry.faceVertexUvs[0];
  8454. if (faceVertexUvs.length > 0) uvs = faceVertexUvs;
  8455. for (var f = 0, fl = faces.length; f < fl; f++) {
  8456. var face = faces[f];
  8457. var faceMaterial = isMultiMaterial ? material[face.materialIndex] : material;
  8458. if (faceMaterial === undefined) continue;
  8459. fvA = vertices[face.a];
  8460. fvB = vertices[face.b];
  8461. fvC = vertices[face.c];
  8462. intersection = checkIntersection(this, faceMaterial, raycaster, _ray, fvA, fvB, fvC, _intersectionPoint);
  8463. if (intersection) {
  8464. if (uvs && uvs[f]) {
  8465. var uvs_f = uvs[f];
  8466. _uvA.copy(uvs_f[0]);
  8467. _uvB.copy(uvs_f[1]);
  8468. _uvC.copy(uvs_f[2]);
  8469. intersection.uv = Triangle.getUV(_intersectionPoint, fvA, fvB, fvC, _uvA, _uvB, _uvC, new Vector2());
  8470. }
  8471. intersection.face = face;
  8472. intersection.faceIndex = f;
  8473. intersects.push(intersection);
  8474. }
  8475. }
  8476. }
  8477. },
  8478. clone: function () {
  8479. return new this.constructor(this.geometry, this.material).copy(this);
  8480. }
  8481. });
  8482. function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
  8483. var intersect;
  8484. if (material.side === BackSide) {
  8485. intersect = ray.intersectTriangle(pC, pB, pA, true, point);
  8486. } else {
  8487. intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
  8488. }
  8489. if (intersect === null) return null;
  8490. _intersectionPointWorld.copy(point);
  8491. _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  8492. var distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  8493. if (distance < raycaster.near || distance > raycaster.far) return null;
  8494. return {
  8495. distance: distance,
  8496. point: _intersectionPointWorld.clone(),
  8497. object: object
  8498. };
  8499. }
  8500. function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, uv, uv2, a, b, c) {
  8501. _vA.fromBufferAttribute(position, a);
  8502. _vB.fromBufferAttribute(position, b);
  8503. _vC.fromBufferAttribute(position, c);
  8504. var morphInfluences = object.morphTargetInfluences;
  8505. if (material.morphTargets && morphPosition && morphInfluences) {
  8506. _morphA.set(0, 0, 0);
  8507. _morphB.set(0, 0, 0);
  8508. _morphC.set(0, 0, 0);
  8509. for (var i = 0, il = morphPosition.length; i < il; i++) {
  8510. var influence = morphInfluences[i];
  8511. var morphAttribute = morphPosition[i];
  8512. if (influence === 0) continue;
  8513. _tempA.fromBufferAttribute(morphAttribute, a);
  8514. _tempB.fromBufferAttribute(morphAttribute, b);
  8515. _tempC.fromBufferAttribute(morphAttribute, c);
  8516. _morphA.addScaledVector(_tempA.sub(_vA), influence);
  8517. _morphB.addScaledVector(_tempB.sub(_vB), influence);
  8518. _morphC.addScaledVector(_tempC.sub(_vC), influence);
  8519. }
  8520. _vA.add(_morphA);
  8521. _vB.add(_morphB);
  8522. _vC.add(_morphC);
  8523. }
  8524. var intersection = checkIntersection(object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint);
  8525. if (intersection) {
  8526. if (uv) {
  8527. _uvA.fromBufferAttribute(uv, a);
  8528. _uvB.fromBufferAttribute(uv, b);
  8529. _uvC.fromBufferAttribute(uv, c);
  8530. intersection.uv = Triangle.getUV(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2());
  8531. }
  8532. if (uv2) {
  8533. _uvA.fromBufferAttribute(uv2, a);
  8534. _uvB.fromBufferAttribute(uv2, b);
  8535. _uvC.fromBufferAttribute(uv2, c);
  8536. intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2());
  8537. }
  8538. var face = new Face3(a, b, c);
  8539. Triangle.getNormal(_vA, _vB, _vC, face.normal);
  8540. intersection.face = face;
  8541. }
  8542. return intersection;
  8543. }
  8544. /**
  8545. * @author mrdoob / http://mrdoob.com/
  8546. * @author kile / http://kile.stravaganza.org/
  8547. * @author alteredq / http://alteredqualia.com/
  8548. * @author mikael emtinger / http://gomo.se/
  8549. * @author zz85 / http://www.lab4games.net/zz85/blog
  8550. * @author bhouston / http://clara.io
  8551. */
  8552. var _geometryId = 0; // Geometry uses even numbers as Id
  8553. var _m1$3 = new Matrix4();
  8554. var _obj$1 = new Object3D();
  8555. var _offset$1 = new Vector3();
  8556. function Geometry() {
  8557. Object.defineProperty(this, 'id', {
  8558. value: _geometryId += 2
  8559. });
  8560. this.uuid = _Math.generateUUID();
  8561. this.name = '';
  8562. this.type = 'Geometry';
  8563. this.vertices = [];
  8564. this.colors = [];
  8565. this.faces = [];
  8566. this.faceVertexUvs = [[]];
  8567. this.morphTargets = [];
  8568. this.morphNormals = [];
  8569. this.skinWeights = [];
  8570. this.skinIndices = [];
  8571. this.lineDistances = [];
  8572. this.boundingBox = null;
  8573. this.boundingSphere = null; // update flags
  8574. this.elementsNeedUpdate = false;
  8575. this.verticesNeedUpdate = false;
  8576. this.uvsNeedUpdate = false;
  8577. this.normalsNeedUpdate = false;
  8578. this.colorsNeedUpdate = false;
  8579. this.lineDistancesNeedUpdate = false;
  8580. this.groupsNeedUpdate = false;
  8581. }
  8582. Geometry.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  8583. constructor: Geometry,
  8584. isGeometry: true,
  8585. applyMatrix: function (matrix) {
  8586. var normalMatrix = new Matrix3().getNormalMatrix(matrix);
  8587. for (var i = 0, il = this.vertices.length; i < il; i++) {
  8588. var vertex = this.vertices[i];
  8589. vertex.applyMatrix4(matrix);
  8590. }
  8591. for (var i = 0, il = this.faces.length; i < il; i++) {
  8592. var face = this.faces[i];
  8593. face.normal.applyMatrix3(normalMatrix).normalize();
  8594. for (var j = 0, jl = face.vertexNormals.length; j < jl; j++) {
  8595. face.vertexNormals[j].applyMatrix3(normalMatrix).normalize();
  8596. }
  8597. }
  8598. if (this.boundingBox !== null) {
  8599. this.computeBoundingBox();
  8600. }
  8601. if (this.boundingSphere !== null) {
  8602. this.computeBoundingSphere();
  8603. }
  8604. this.verticesNeedUpdate = true;
  8605. this.normalsNeedUpdate = true;
  8606. return this;
  8607. },
  8608. rotateX: function (angle) {
  8609. // rotate geometry around world x-axis
  8610. _m1$3.makeRotationX(angle);
  8611. this.applyMatrix(_m1$3);
  8612. return this;
  8613. },
  8614. rotateY: function (angle) {
  8615. // rotate geometry around world y-axis
  8616. _m1$3.makeRotationY(angle);
  8617. this.applyMatrix(_m1$3);
  8618. return this;
  8619. },
  8620. rotateZ: function (angle) {
  8621. // rotate geometry around world z-axis
  8622. _m1$3.makeRotationZ(angle);
  8623. this.applyMatrix(_m1$3);
  8624. return this;
  8625. },
  8626. translate: function (x, y, z) {
  8627. // translate geometry
  8628. _m1$3.makeTranslation(x, y, z);
  8629. this.applyMatrix(_m1$3);
  8630. return this;
  8631. },
  8632. scale: function (x, y, z) {
  8633. // scale geometry
  8634. _m1$3.makeScale(x, y, z);
  8635. this.applyMatrix(_m1$3);
  8636. return this;
  8637. },
  8638. lookAt: function (vector) {
  8639. _obj$1.lookAt(vector);
  8640. _obj$1.updateMatrix();
  8641. this.applyMatrix(_obj$1.matrix);
  8642. return this;
  8643. },
  8644. fromBufferGeometry: function (geometry) {
  8645. var scope = this;
  8646. var indices = geometry.index !== null ? geometry.index.array : undefined;
  8647. var attributes = geometry.attributes;
  8648. if (attributes.position === undefined) {
  8649. console.error('THREE.Geometry.fromBufferGeometry(): Position attribute required for conversion.');
  8650. return this;
  8651. }
  8652. var positions = attributes.position.array;
  8653. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  8654. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  8655. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  8656. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  8657. if (uvs2 !== undefined) this.faceVertexUvs[1] = [];
  8658. for (var i = 0; i < positions.length; i += 3) {
  8659. scope.vertices.push(new Vector3().fromArray(positions, i));
  8660. if (colors !== undefined) {
  8661. scope.colors.push(new Color().fromArray(colors, i));
  8662. }
  8663. }
  8664. function addFace(a, b, c, materialIndex) {
  8665. var vertexColors = colors === undefined ? [] : [scope.colors[a].clone(), scope.colors[b].clone(), scope.colors[c].clone()];
  8666. var vertexNormals = normals === undefined ? [] : [new Vector3().fromArray(normals, a * 3), new Vector3().fromArray(normals, b * 3), new Vector3().fromArray(normals, c * 3)];
  8667. var face = new Face3(a, b, c, vertexNormals, vertexColors, materialIndex);
  8668. scope.faces.push(face);
  8669. if (uvs !== undefined) {
  8670. scope.faceVertexUvs[0].push([new Vector2().fromArray(uvs, a * 2), new Vector2().fromArray(uvs, b * 2), new Vector2().fromArray(uvs, c * 2)]);
  8671. }
  8672. if (uvs2 !== undefined) {
  8673. scope.faceVertexUvs[1].push([new Vector2().fromArray(uvs2, a * 2), new Vector2().fromArray(uvs2, b * 2), new Vector2().fromArray(uvs2, c * 2)]);
  8674. }
  8675. }
  8676. var groups = geometry.groups;
  8677. if (groups.length > 0) {
  8678. for (var i = 0; i < groups.length; i++) {
  8679. var group = groups[i];
  8680. var start = group.start;
  8681. var count = group.count;
  8682. for (var j = start, jl = start + count; j < jl; j += 3) {
  8683. if (indices !== undefined) {
  8684. addFace(indices[j], indices[j + 1], indices[j + 2], group.materialIndex);
  8685. } else {
  8686. addFace(j, j + 1, j + 2, group.materialIndex);
  8687. }
  8688. }
  8689. }
  8690. } else {
  8691. if (indices !== undefined) {
  8692. for (var i = 0; i < indices.length; i += 3) {
  8693. addFace(indices[i], indices[i + 1], indices[i + 2]);
  8694. }
  8695. } else {
  8696. for (var i = 0; i < positions.length / 3; i += 3) {
  8697. addFace(i, i + 1, i + 2);
  8698. }
  8699. }
  8700. }
  8701. this.computeFaceNormals();
  8702. if (geometry.boundingBox !== null) {
  8703. this.boundingBox = geometry.boundingBox.clone();
  8704. }
  8705. if (geometry.boundingSphere !== null) {
  8706. this.boundingSphere = geometry.boundingSphere.clone();
  8707. }
  8708. return this;
  8709. },
  8710. center: function () {
  8711. this.computeBoundingBox();
  8712. this.boundingBox.getCenter(_offset$1).negate();
  8713. this.translate(_offset$1.x, _offset$1.y, _offset$1.z);
  8714. return this;
  8715. },
  8716. normalize: function () {
  8717. this.computeBoundingSphere();
  8718. var center = this.boundingSphere.center;
  8719. var radius = this.boundingSphere.radius;
  8720. var s = radius === 0 ? 1 : 1.0 / radius;
  8721. var matrix = new Matrix4();
  8722. matrix.set(s, 0, 0, -s * center.x, 0, s, 0, -s * center.y, 0, 0, s, -s * center.z, 0, 0, 0, 1);
  8723. this.applyMatrix(matrix);
  8724. return this;
  8725. },
  8726. computeFaceNormals: function () {
  8727. var cb = new Vector3(),
  8728. ab = new Vector3();
  8729. for (var f = 0, fl = this.faces.length; f < fl; f++) {
  8730. var face = this.faces[f];
  8731. var vA = this.vertices[face.a];
  8732. var vB = this.vertices[face.b];
  8733. var vC = this.vertices[face.c];
  8734. cb.subVectors(vC, vB);
  8735. ab.subVectors(vA, vB);
  8736. cb.cross(ab);
  8737. cb.normalize();
  8738. face.normal.copy(cb);
  8739. }
  8740. },
  8741. computeVertexNormals: function (areaWeighted) {
  8742. if (areaWeighted === undefined) areaWeighted = true;
  8743. var v, vl, f, fl, face, vertices;
  8744. vertices = new Array(this.vertices.length);
  8745. for (v = 0, vl = this.vertices.length; v < vl; v++) {
  8746. vertices[v] = new Vector3();
  8747. }
  8748. if (areaWeighted) {
  8749. // vertex normals weighted by triangle areas
  8750. // http://www.iquilezles.org/www/articles/normals/normals.htm
  8751. var vA, vB, vC;
  8752. var cb = new Vector3(),
  8753. ab = new Vector3();
  8754. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8755. face = this.faces[f];
  8756. vA = this.vertices[face.a];
  8757. vB = this.vertices[face.b];
  8758. vC = this.vertices[face.c];
  8759. cb.subVectors(vC, vB);
  8760. ab.subVectors(vA, vB);
  8761. cb.cross(ab);
  8762. vertices[face.a].add(cb);
  8763. vertices[face.b].add(cb);
  8764. vertices[face.c].add(cb);
  8765. }
  8766. } else {
  8767. this.computeFaceNormals();
  8768. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8769. face = this.faces[f];
  8770. vertices[face.a].add(face.normal);
  8771. vertices[face.b].add(face.normal);
  8772. vertices[face.c].add(face.normal);
  8773. }
  8774. }
  8775. for (v = 0, vl = this.vertices.length; v < vl; v++) {
  8776. vertices[v].normalize();
  8777. }
  8778. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8779. face = this.faces[f];
  8780. var vertexNormals = face.vertexNormals;
  8781. if (vertexNormals.length === 3) {
  8782. vertexNormals[0].copy(vertices[face.a]);
  8783. vertexNormals[1].copy(vertices[face.b]);
  8784. vertexNormals[2].copy(vertices[face.c]);
  8785. } else {
  8786. vertexNormals[0] = vertices[face.a].clone();
  8787. vertexNormals[1] = vertices[face.b].clone();
  8788. vertexNormals[2] = vertices[face.c].clone();
  8789. }
  8790. }
  8791. if (this.faces.length > 0) {
  8792. this.normalsNeedUpdate = true;
  8793. }
  8794. },
  8795. computeFlatVertexNormals: function () {
  8796. var f, fl, face;
  8797. this.computeFaceNormals();
  8798. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8799. face = this.faces[f];
  8800. var vertexNormals = face.vertexNormals;
  8801. if (vertexNormals.length === 3) {
  8802. vertexNormals[0].copy(face.normal);
  8803. vertexNormals[1].copy(face.normal);
  8804. vertexNormals[2].copy(face.normal);
  8805. } else {
  8806. vertexNormals[0] = face.normal.clone();
  8807. vertexNormals[1] = face.normal.clone();
  8808. vertexNormals[2] = face.normal.clone();
  8809. }
  8810. }
  8811. if (this.faces.length > 0) {
  8812. this.normalsNeedUpdate = true;
  8813. }
  8814. },
  8815. computeMorphNormals: function () {
  8816. var i, il, f, fl, face; // save original normals
  8817. // - create temp variables on first access
  8818. // otherwise just copy (for faster repeated calls)
  8819. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8820. face = this.faces[f];
  8821. if (!face.__originalFaceNormal) {
  8822. face.__originalFaceNormal = face.normal.clone();
  8823. } else {
  8824. face.__originalFaceNormal.copy(face.normal);
  8825. }
  8826. if (!face.__originalVertexNormals) face.__originalVertexNormals = [];
  8827. for (i = 0, il = face.vertexNormals.length; i < il; i++) {
  8828. if (!face.__originalVertexNormals[i]) {
  8829. face.__originalVertexNormals[i] = face.vertexNormals[i].clone();
  8830. } else {
  8831. face.__originalVertexNormals[i].copy(face.vertexNormals[i]);
  8832. }
  8833. }
  8834. } // use temp geometry to compute face and vertex normals for each morph
  8835. var tmpGeo = new Geometry();
  8836. tmpGeo.faces = this.faces;
  8837. for (i = 0, il = this.morphTargets.length; i < il; i++) {
  8838. // create on first access
  8839. if (!this.morphNormals[i]) {
  8840. this.morphNormals[i] = {};
  8841. this.morphNormals[i].faceNormals = [];
  8842. this.morphNormals[i].vertexNormals = [];
  8843. var dstNormalsFace = this.morphNormals[i].faceNormals;
  8844. var dstNormalsVertex = this.morphNormals[i].vertexNormals;
  8845. var faceNormal, vertexNormals;
  8846. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8847. faceNormal = new Vector3();
  8848. vertexNormals = {
  8849. a: new Vector3(),
  8850. b: new Vector3(),
  8851. c: new Vector3()
  8852. };
  8853. dstNormalsFace.push(faceNormal);
  8854. dstNormalsVertex.push(vertexNormals);
  8855. }
  8856. }
  8857. var morphNormals = this.morphNormals[i]; // set vertices to morph target
  8858. tmpGeo.vertices = this.morphTargets[i].vertices; // compute morph normals
  8859. tmpGeo.computeFaceNormals();
  8860. tmpGeo.computeVertexNormals(); // store morph normals
  8861. var faceNormal, vertexNormals;
  8862. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8863. face = this.faces[f];
  8864. faceNormal = morphNormals.faceNormals[f];
  8865. vertexNormals = morphNormals.vertexNormals[f];
  8866. faceNormal.copy(face.normal);
  8867. vertexNormals.a.copy(face.vertexNormals[0]);
  8868. vertexNormals.b.copy(face.vertexNormals[1]);
  8869. vertexNormals.c.copy(face.vertexNormals[2]);
  8870. }
  8871. } // restore original normals
  8872. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8873. face = this.faces[f];
  8874. face.normal = face.__originalFaceNormal;
  8875. face.vertexNormals = face.__originalVertexNormals;
  8876. }
  8877. },
  8878. computeBoundingBox: function () {
  8879. if (this.boundingBox === null) {
  8880. this.boundingBox = new Box3();
  8881. }
  8882. this.boundingBox.setFromPoints(this.vertices);
  8883. },
  8884. computeBoundingSphere: function () {
  8885. if (this.boundingSphere === null) {
  8886. this.boundingSphere = new Sphere();
  8887. }
  8888. this.boundingSphere.setFromPoints(this.vertices);
  8889. },
  8890. merge: function (geometry, matrix, materialIndexOffset) {
  8891. if (!(geometry && geometry.isGeometry)) {
  8892. console.error('THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry);
  8893. return;
  8894. }
  8895. var normalMatrix,
  8896. vertexOffset = this.vertices.length,
  8897. vertices1 = this.vertices,
  8898. vertices2 = geometry.vertices,
  8899. faces1 = this.faces,
  8900. faces2 = geometry.faces,
  8901. colors1 = this.colors,
  8902. colors2 = geometry.colors;
  8903. if (materialIndexOffset === undefined) materialIndexOffset = 0;
  8904. if (matrix !== undefined) {
  8905. normalMatrix = new Matrix3().getNormalMatrix(matrix);
  8906. } // vertices
  8907. for (var i = 0, il = vertices2.length; i < il; i++) {
  8908. var vertex = vertices2[i];
  8909. var vertexCopy = vertex.clone();
  8910. if (matrix !== undefined) vertexCopy.applyMatrix4(matrix);
  8911. vertices1.push(vertexCopy);
  8912. } // colors
  8913. for (var i = 0, il = colors2.length; i < il; i++) {
  8914. colors1.push(colors2[i].clone());
  8915. } // faces
  8916. for (i = 0, il = faces2.length; i < il; i++) {
  8917. var face = faces2[i],
  8918. faceCopy,
  8919. normal,
  8920. color,
  8921. faceVertexNormals = face.vertexNormals,
  8922. faceVertexColors = face.vertexColors;
  8923. faceCopy = new Face3(face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset);
  8924. faceCopy.normal.copy(face.normal);
  8925. if (normalMatrix !== undefined) {
  8926. faceCopy.normal.applyMatrix3(normalMatrix).normalize();
  8927. }
  8928. for (var j = 0, jl = faceVertexNormals.length; j < jl; j++) {
  8929. normal = faceVertexNormals[j].clone();
  8930. if (normalMatrix !== undefined) {
  8931. normal.applyMatrix3(normalMatrix).normalize();
  8932. }
  8933. faceCopy.vertexNormals.push(normal);
  8934. }
  8935. faceCopy.color.copy(face.color);
  8936. for (var j = 0, jl = faceVertexColors.length; j < jl; j++) {
  8937. color = faceVertexColors[j];
  8938. faceCopy.vertexColors.push(color.clone());
  8939. }
  8940. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  8941. faces1.push(faceCopy);
  8942. } // uvs
  8943. for (var i = 0, il = geometry.faceVertexUvs.length; i < il; i++) {
  8944. var faceVertexUvs2 = geometry.faceVertexUvs[i];
  8945. if (this.faceVertexUvs[i] === undefined) this.faceVertexUvs[i] = [];
  8946. for (var j = 0, jl = faceVertexUvs2.length; j < jl; j++) {
  8947. var uvs2 = faceVertexUvs2[j],
  8948. uvsCopy = [];
  8949. for (var k = 0, kl = uvs2.length; k < kl; k++) {
  8950. uvsCopy.push(uvs2[k].clone());
  8951. }
  8952. this.faceVertexUvs[i].push(uvsCopy);
  8953. }
  8954. }
  8955. },
  8956. mergeMesh: function (mesh) {
  8957. if (!(mesh && mesh.isMesh)) {
  8958. console.error('THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh);
  8959. return;
  8960. }
  8961. if (mesh.matrixAutoUpdate) mesh.updateMatrix();
  8962. this.merge(mesh.geometry, mesh.matrix);
  8963. },
  8964. /*
  8965. * Checks for duplicate vertices with hashmap.
  8966. * Duplicated vertices are removed
  8967. * and faces' vertices are updated.
  8968. */
  8969. mergeVertices: function () {
  8970. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  8971. var unique = [],
  8972. changes = [];
  8973. var v, key;
  8974. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  8975. var precision = Math.pow(10, precisionPoints);
  8976. var i, il, face;
  8977. var indices, j, jl;
  8978. for (i = 0, il = this.vertices.length; i < il; i++) {
  8979. v = this.vertices[i];
  8980. key = Math.round(v.x * precision) + '_' + Math.round(v.y * precision) + '_' + Math.round(v.z * precision);
  8981. if (verticesMap[key] === undefined) {
  8982. verticesMap[key] = i;
  8983. unique.push(this.vertices[i]);
  8984. changes[i] = unique.length - 1;
  8985. } else {
  8986. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  8987. changes[i] = changes[verticesMap[key]];
  8988. }
  8989. } // if faces are completely degenerate after merging vertices, we
  8990. // have to remove them from the geometry.
  8991. var faceIndicesToRemove = [];
  8992. for (i = 0, il = this.faces.length; i < il; i++) {
  8993. face = this.faces[i];
  8994. face.a = changes[face.a];
  8995. face.b = changes[face.b];
  8996. face.c = changes[face.c];
  8997. indices = [face.a, face.b, face.c]; // if any duplicate vertices are found in a Face3
  8998. // we have to remove the face as nothing can be saved
  8999. for (var n = 0; n < 3; n++) {
  9000. if (indices[n] === indices[(n + 1) % 3]) {
  9001. faceIndicesToRemove.push(i);
  9002. break;
  9003. }
  9004. }
  9005. }
  9006. for (i = faceIndicesToRemove.length - 1; i >= 0; i--) {
  9007. var idx = faceIndicesToRemove[i];
  9008. this.faces.splice(idx, 1);
  9009. for (j = 0, jl = this.faceVertexUvs.length; j < jl; j++) {
  9010. this.faceVertexUvs[j].splice(idx, 1);
  9011. }
  9012. } // Use unique set of vertices
  9013. var diff = this.vertices.length - unique.length;
  9014. this.vertices = unique;
  9015. return diff;
  9016. },
  9017. setFromPoints: function (points) {
  9018. this.vertices = [];
  9019. for (var i = 0, l = points.length; i < l; i++) {
  9020. var point = points[i];
  9021. this.vertices.push(new Vector3(point.x, point.y, point.z || 0));
  9022. }
  9023. return this;
  9024. },
  9025. sortFacesByMaterialIndex: function () {
  9026. var faces = this.faces;
  9027. var length = faces.length; // tag faces
  9028. for (var i = 0; i < length; i++) {
  9029. faces[i]._id = i;
  9030. } // sort faces
  9031. function materialIndexSort(a, b) {
  9032. return a.materialIndex - b.materialIndex;
  9033. }
  9034. faces.sort(materialIndexSort); // sort uvs
  9035. var uvs1 = this.faceVertexUvs[0];
  9036. var uvs2 = this.faceVertexUvs[1];
  9037. var newUvs1, newUvs2;
  9038. if (uvs1 && uvs1.length === length) newUvs1 = [];
  9039. if (uvs2 && uvs2.length === length) newUvs2 = [];
  9040. for (var i = 0; i < length; i++) {
  9041. var id = faces[i]._id;
  9042. if (newUvs1) newUvs1.push(uvs1[id]);
  9043. if (newUvs2) newUvs2.push(uvs2[id]);
  9044. }
  9045. if (newUvs1) this.faceVertexUvs[0] = newUvs1;
  9046. if (newUvs2) this.faceVertexUvs[1] = newUvs2;
  9047. },
  9048. toJSON: function () {
  9049. var data = {
  9050. metadata: {
  9051. version: 4.5,
  9052. type: 'Geometry',
  9053. generator: 'Geometry.toJSON'
  9054. }
  9055. }; // standard Geometry serialization
  9056. data.uuid = this.uuid;
  9057. data.type = this.type;
  9058. if (this.name !== '') data.name = this.name;
  9059. if (this.parameters !== undefined) {
  9060. var parameters = this.parameters;
  9061. for (var key in parameters) {
  9062. if (parameters[key] !== undefined) data[key] = parameters[key];
  9063. }
  9064. return data;
  9065. }
  9066. var vertices = [];
  9067. for (var i = 0; i < this.vertices.length; i++) {
  9068. var vertex = this.vertices[i];
  9069. vertices.push(vertex.x, vertex.y, vertex.z);
  9070. }
  9071. var faces = [];
  9072. var normals = [];
  9073. var normalsHash = {};
  9074. var colors = [];
  9075. var colorsHash = {};
  9076. var uvs = [];
  9077. var uvsHash = {};
  9078. for (var i = 0; i < this.faces.length; i++) {
  9079. var face = this.faces[i];
  9080. var hasMaterial = true;
  9081. var hasFaceUv = false; // deprecated
  9082. var hasFaceVertexUv = this.faceVertexUvs[0][i] !== undefined;
  9083. var hasFaceNormal = face.normal.length() > 0;
  9084. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  9085. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  9086. var hasFaceVertexColor = face.vertexColors.length > 0;
  9087. var faceType = 0;
  9088. faceType = setBit(faceType, 0, 0); // isQuad
  9089. faceType = setBit(faceType, 1, hasMaterial);
  9090. faceType = setBit(faceType, 2, hasFaceUv);
  9091. faceType = setBit(faceType, 3, hasFaceVertexUv);
  9092. faceType = setBit(faceType, 4, hasFaceNormal);
  9093. faceType = setBit(faceType, 5, hasFaceVertexNormal);
  9094. faceType = setBit(faceType, 6, hasFaceColor);
  9095. faceType = setBit(faceType, 7, hasFaceVertexColor);
  9096. faces.push(faceType);
  9097. faces.push(face.a, face.b, face.c);
  9098. faces.push(face.materialIndex);
  9099. if (hasFaceVertexUv) {
  9100. var faceVertexUvs = this.faceVertexUvs[0][i];
  9101. faces.push(getUvIndex(faceVertexUvs[0]), getUvIndex(faceVertexUvs[1]), getUvIndex(faceVertexUvs[2]));
  9102. }
  9103. if (hasFaceNormal) {
  9104. faces.push(getNormalIndex(face.normal));
  9105. }
  9106. if (hasFaceVertexNormal) {
  9107. var vertexNormals = face.vertexNormals;
  9108. faces.push(getNormalIndex(vertexNormals[0]), getNormalIndex(vertexNormals[1]), getNormalIndex(vertexNormals[2]));
  9109. }
  9110. if (hasFaceColor) {
  9111. faces.push(getColorIndex(face.color));
  9112. }
  9113. if (hasFaceVertexColor) {
  9114. var vertexColors = face.vertexColors;
  9115. faces.push(getColorIndex(vertexColors[0]), getColorIndex(vertexColors[1]), getColorIndex(vertexColors[2]));
  9116. }
  9117. }
  9118. function setBit(value, position, enabled) {
  9119. return enabled ? value | 1 << position : value & ~(1 << position);
  9120. }
  9121. function getNormalIndex(normal) {
  9122. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  9123. if (normalsHash[hash] !== undefined) {
  9124. return normalsHash[hash];
  9125. }
  9126. normalsHash[hash] = normals.length / 3;
  9127. normals.push(normal.x, normal.y, normal.z);
  9128. return normalsHash[hash];
  9129. }
  9130. function getColorIndex(color) {
  9131. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  9132. if (colorsHash[hash] !== undefined) {
  9133. return colorsHash[hash];
  9134. }
  9135. colorsHash[hash] = colors.length;
  9136. colors.push(color.getHex());
  9137. return colorsHash[hash];
  9138. }
  9139. function getUvIndex(uv) {
  9140. var hash = uv.x.toString() + uv.y.toString();
  9141. if (uvsHash[hash] !== undefined) {
  9142. return uvsHash[hash];
  9143. }
  9144. uvsHash[hash] = uvs.length / 2;
  9145. uvs.push(uv.x, uv.y);
  9146. return uvsHash[hash];
  9147. }
  9148. data.data = {};
  9149. data.data.vertices = vertices;
  9150. data.data.normals = normals;
  9151. if (colors.length > 0) data.data.colors = colors;
  9152. if (uvs.length > 0) data.data.uvs = [uvs]; // temporal backward compatibility
  9153. data.data.faces = faces;
  9154. return data;
  9155. },
  9156. clone: function () {
  9157. /*
  9158. // Handle primitives
  9159. var parameters = this.parameters;
  9160. if ( parameters !== undefined ) {
  9161. var values = [];
  9162. for ( var key in parameters ) {
  9163. values.push( parameters[ key ] );
  9164. }
  9165. var geometry = Object.create( this.constructor.prototype );
  9166. this.constructor.apply( geometry, values );
  9167. return geometry;
  9168. }
  9169. return new this.constructor().copy( this );
  9170. */
  9171. return new Geometry().copy(this);
  9172. },
  9173. copy: function (source) {
  9174. var i, il, j, jl, k, kl; // reset
  9175. this.vertices = [];
  9176. this.colors = [];
  9177. this.faces = [];
  9178. this.faceVertexUvs = [[]];
  9179. this.morphTargets = [];
  9180. this.morphNormals = [];
  9181. this.skinWeights = [];
  9182. this.skinIndices = [];
  9183. this.lineDistances = [];
  9184. this.boundingBox = null;
  9185. this.boundingSphere = null; // name
  9186. this.name = source.name; // vertices
  9187. var vertices = source.vertices;
  9188. for (i = 0, il = vertices.length; i < il; i++) {
  9189. this.vertices.push(vertices[i].clone());
  9190. } // colors
  9191. var colors = source.colors;
  9192. for (i = 0, il = colors.length; i < il; i++) {
  9193. this.colors.push(colors[i].clone());
  9194. } // faces
  9195. var faces = source.faces;
  9196. for (i = 0, il = faces.length; i < il; i++) {
  9197. this.faces.push(faces[i].clone());
  9198. } // face vertex uvs
  9199. for (i = 0, il = source.faceVertexUvs.length; i < il; i++) {
  9200. var faceVertexUvs = source.faceVertexUvs[i];
  9201. if (this.faceVertexUvs[i] === undefined) {
  9202. this.faceVertexUvs[i] = [];
  9203. }
  9204. for (j = 0, jl = faceVertexUvs.length; j < jl; j++) {
  9205. var uvs = faceVertexUvs[j],
  9206. uvsCopy = [];
  9207. for (k = 0, kl = uvs.length; k < kl; k++) {
  9208. var uv = uvs[k];
  9209. uvsCopy.push(uv.clone());
  9210. }
  9211. this.faceVertexUvs[i].push(uvsCopy);
  9212. }
  9213. } // morph targets
  9214. var morphTargets = source.morphTargets;
  9215. for (i = 0, il = morphTargets.length; i < il; i++) {
  9216. var morphTarget = {};
  9217. morphTarget.name = morphTargets[i].name; // vertices
  9218. if (morphTargets[i].vertices !== undefined) {
  9219. morphTarget.vertices = [];
  9220. for (j = 0, jl = morphTargets[i].vertices.length; j < jl; j++) {
  9221. morphTarget.vertices.push(morphTargets[i].vertices[j].clone());
  9222. }
  9223. } // normals
  9224. if (morphTargets[i].normals !== undefined) {
  9225. morphTarget.normals = [];
  9226. for (j = 0, jl = morphTargets[i].normals.length; j < jl; j++) {
  9227. morphTarget.normals.push(morphTargets[i].normals[j].clone());
  9228. }
  9229. }
  9230. this.morphTargets.push(morphTarget);
  9231. } // morph normals
  9232. var morphNormals = source.morphNormals;
  9233. for (i = 0, il = morphNormals.length; i < il; i++) {
  9234. var morphNormal = {}; // vertex normals
  9235. if (morphNormals[i].vertexNormals !== undefined) {
  9236. morphNormal.vertexNormals = [];
  9237. for (j = 0, jl = morphNormals[i].vertexNormals.length; j < jl; j++) {
  9238. var srcVertexNormal = morphNormals[i].vertexNormals[j];
  9239. var destVertexNormal = {};
  9240. destVertexNormal.a = srcVertexNormal.a.clone();
  9241. destVertexNormal.b = srcVertexNormal.b.clone();
  9242. destVertexNormal.c = srcVertexNormal.c.clone();
  9243. morphNormal.vertexNormals.push(destVertexNormal);
  9244. }
  9245. } // face normals
  9246. if (morphNormals[i].faceNormals !== undefined) {
  9247. morphNormal.faceNormals = [];
  9248. for (j = 0, jl = morphNormals[i].faceNormals.length; j < jl; j++) {
  9249. morphNormal.faceNormals.push(morphNormals[i].faceNormals[j].clone());
  9250. }
  9251. }
  9252. this.morphNormals.push(morphNormal);
  9253. } // skin weights
  9254. var skinWeights = source.skinWeights;
  9255. for (i = 0, il = skinWeights.length; i < il; i++) {
  9256. this.skinWeights.push(skinWeights[i].clone());
  9257. } // skin indices
  9258. var skinIndices = source.skinIndices;
  9259. for (i = 0, il = skinIndices.length; i < il; i++) {
  9260. this.skinIndices.push(skinIndices[i].clone());
  9261. } // line distances
  9262. var lineDistances = source.lineDistances;
  9263. for (i = 0, il = lineDistances.length; i < il; i++) {
  9264. this.lineDistances.push(lineDistances[i]);
  9265. } // bounding box
  9266. var boundingBox = source.boundingBox;
  9267. if (boundingBox !== null) {
  9268. this.boundingBox = boundingBox.clone();
  9269. } // bounding sphere
  9270. var boundingSphere = source.boundingSphere;
  9271. if (boundingSphere !== null) {
  9272. this.boundingSphere = boundingSphere.clone();
  9273. } // update flags
  9274. this.elementsNeedUpdate = source.elementsNeedUpdate;
  9275. this.verticesNeedUpdate = source.verticesNeedUpdate;
  9276. this.uvsNeedUpdate = source.uvsNeedUpdate;
  9277. this.normalsNeedUpdate = source.normalsNeedUpdate;
  9278. this.colorsNeedUpdate = source.colorsNeedUpdate;
  9279. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  9280. this.groupsNeedUpdate = source.groupsNeedUpdate;
  9281. return this;
  9282. },
  9283. dispose: function () {
  9284. this.dispatchEvent({
  9285. type: 'dispose'
  9286. });
  9287. }
  9288. });
  9289. /**
  9290. * @author mrdoob / http://mrdoob.com/
  9291. * @author Mugen87 / https://github.com/Mugen87
  9292. */
  9293. // BoxGeometry
  9294. class BoxGeometry extends Geometry {
  9295. constructor(width, height, depth, widthSegments, heightSegments, depthSegments) {
  9296. super();
  9297. this.type = 'BoxGeometry';
  9298. this.parameters = {
  9299. width: width,
  9300. height: height,
  9301. depth: depth,
  9302. widthSegments: widthSegments,
  9303. heightSegments: heightSegments,
  9304. depthSegments: depthSegments
  9305. };
  9306. this.fromBufferGeometry(new BoxBufferGeometry(width, height, depth, widthSegments, heightSegments, depthSegments));
  9307. this.mergeVertices();
  9308. }
  9309. } // BoxBufferGeometry
  9310. exports.CubeGeometry = exports.BoxGeometry = BoxGeometry;
  9311. class BoxBufferGeometry extends BufferGeometry {
  9312. constructor(width, height, depth, widthSegments, heightSegments, depthSegments) {
  9313. super();
  9314. this.type = 'BoxBufferGeometry';
  9315. this.parameters = {
  9316. width: width,
  9317. height: height,
  9318. depth: depth,
  9319. widthSegments: widthSegments,
  9320. heightSegments: heightSegments,
  9321. depthSegments: depthSegments
  9322. };
  9323. var scope = this;
  9324. width = width || 1;
  9325. height = height || 1;
  9326. depth = depth || 1; // segments
  9327. widthSegments = Math.floor(widthSegments) || 1;
  9328. heightSegments = Math.floor(heightSegments) || 1;
  9329. depthSegments = Math.floor(depthSegments) || 1; // buffers
  9330. var indices = [];
  9331. var vertices = [];
  9332. var normals = [];
  9333. var uvs = []; // helper variables
  9334. var numberOfVertices = 0;
  9335. var groupStart = 0; // build each side of the box geometry
  9336. buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
  9337. buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
  9338. buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
  9339. buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
  9340. buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
  9341. buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
  9342. // build geometry
  9343. this.setIndex(indices);
  9344. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  9345. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  9346. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  9347. function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
  9348. var segmentWidth = width / gridX;
  9349. var segmentHeight = height / gridY;
  9350. var widthHalf = width / 2;
  9351. var heightHalf = height / 2;
  9352. var depthHalf = depth / 2;
  9353. var gridX1 = gridX + 1;
  9354. var gridY1 = gridY + 1;
  9355. var vertexCounter = 0;
  9356. var groupCount = 0;
  9357. var ix, iy;
  9358. var vector = new Vector3(); // generate vertices, normals and uvs
  9359. for (iy = 0; iy < gridY1; iy++) {
  9360. var y = iy * segmentHeight - heightHalf;
  9361. for (ix = 0; ix < gridX1; ix++) {
  9362. var x = ix * segmentWidth - widthHalf; // set values to correct vector component
  9363. vector[u] = x * udir;
  9364. vector[v] = y * vdir;
  9365. vector[w] = depthHalf; // now apply vector to vertex buffer
  9366. vertices.push(vector.x, vector.y, vector.z); // set values to correct vector component
  9367. vector[u] = 0;
  9368. vector[v] = 0;
  9369. vector[w] = depth > 0 ? 1 : -1; // now apply vector to normal buffer
  9370. normals.push(vector.x, vector.y, vector.z); // uvs
  9371. uvs.push(ix / gridX);
  9372. uvs.push(1 - iy / gridY); // counters
  9373. vertexCounter += 1;
  9374. }
  9375. } // indices
  9376. // 1. you need three indices to draw a single face
  9377. // 2. a single segment consists of two faces
  9378. // 3. so we need to generate six (2*3) indices per segment
  9379. for (iy = 0; iy < gridY; iy++) {
  9380. for (ix = 0; ix < gridX; ix++) {
  9381. var a = numberOfVertices + ix + gridX1 * iy;
  9382. var b = numberOfVertices + ix + gridX1 * (iy + 1);
  9383. var c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
  9384. var d = numberOfVertices + (ix + 1) + gridX1 * iy; // faces
  9385. indices.push(a, b, d);
  9386. indices.push(b, c, d); // increase counter
  9387. groupCount += 6;
  9388. }
  9389. } // add a group to the geometry. this will ensure multi material support
  9390. scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groups
  9391. groupStart += groupCount; // update total number of vertices
  9392. numberOfVertices += vertexCounter;
  9393. }
  9394. }
  9395. }
  9396. /**
  9397. * Uniform Utilities
  9398. */
  9399. exports.BoxBufferGeometry = BoxBufferGeometry;
  9400. function cloneUniforms(src) {
  9401. var dst = {};
  9402. for (var u in src) {
  9403. dst[u] = {};
  9404. for (var p in src[u]) {
  9405. var property = src[u][p];
  9406. if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture)) {
  9407. dst[u][p] = property.clone();
  9408. } else if (Array.isArray(property)) {
  9409. dst[u][p] = property.slice();
  9410. } else {
  9411. dst[u][p] = property;
  9412. }
  9413. }
  9414. }
  9415. return dst;
  9416. }
  9417. function mergeUniforms(uniforms) {
  9418. var merged = {};
  9419. for (var u = 0; u < uniforms.length; u++) {
  9420. var tmp = cloneUniforms(uniforms[u]);
  9421. for (var p in tmp) {
  9422. merged[p] = tmp[p];
  9423. }
  9424. }
  9425. return merged;
  9426. } // Legacy
  9427. var UniformsUtils = {
  9428. clone: cloneUniforms,
  9429. merge: mergeUniforms
  9430. };
  9431. exports.UniformsUtils = UniformsUtils;
  9432. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  9433. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  9434. /**
  9435. * @author alteredq / http://alteredqualia.com/
  9436. *
  9437. * parameters = {
  9438. * defines: { "label" : "value" },
  9439. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  9440. *
  9441. * fragmentShader: <string>,
  9442. * vertexShader: <string>,
  9443. *
  9444. * wireframe: <boolean>,
  9445. * wireframeLinewidth: <float>,
  9446. *
  9447. * lights: <bool>,
  9448. *
  9449. * skinning: <bool>,
  9450. * morphTargets: <bool>,
  9451. * morphNormals: <bool>
  9452. * }
  9453. */
  9454. function ShaderMaterial(parameters) {
  9455. Material.call(this);
  9456. this.type = 'ShaderMaterial';
  9457. this.defines = {};
  9458. this.uniforms = {};
  9459. this.vertexShader = default_vertex;
  9460. this.fragmentShader = default_fragment;
  9461. this.linewidth = 1;
  9462. this.wireframe = false;
  9463. this.wireframeLinewidth = 1;
  9464. this.fog = false; // set to use scene fog
  9465. this.lights = false; // set to use scene lights
  9466. this.clipping = false; // set to use user-defined clipping planes
  9467. this.skinning = false; // set to use skinning attribute streams
  9468. this.morphTargets = false; // set to use morph targets
  9469. this.morphNormals = false; // set to use morph normals
  9470. this.extensions = {
  9471. derivatives: false,
  9472. // set to use derivatives
  9473. fragDepth: false,
  9474. // set to use fragment depth values
  9475. drawBuffers: false,
  9476. // set to use draw buffers
  9477. shaderTextureLOD: false // set to use shader texture LOD
  9478. }; // When rendered geometry doesn't include these attributes but the material does,
  9479. // use these default values in WebGL. This avoids errors when buffer data is missing.
  9480. this.defaultAttributeValues = {
  9481. 'color': [1, 1, 1],
  9482. 'uv': [0, 0],
  9483. 'uv2': [0, 0]
  9484. };
  9485. this.index0AttributeName = undefined;
  9486. this.uniformsNeedUpdate = false;
  9487. if (parameters !== undefined) {
  9488. if (parameters.attributes !== undefined) {
  9489. console.error('THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.');
  9490. }
  9491. this.setValues(parameters);
  9492. }
  9493. }
  9494. ShaderMaterial.prototype = Object.create(Material.prototype);
  9495. ShaderMaterial.prototype.constructor = ShaderMaterial;
  9496. ShaderMaterial.prototype.isShaderMaterial = true;
  9497. ShaderMaterial.prototype.copy = function (source) {
  9498. Material.prototype.copy.call(this, source);
  9499. this.fragmentShader = source.fragmentShader;
  9500. this.vertexShader = source.vertexShader;
  9501. this.uniforms = cloneUniforms(source.uniforms);
  9502. this.defines = Object.assign({}, source.defines);
  9503. this.wireframe = source.wireframe;
  9504. this.wireframeLinewidth = source.wireframeLinewidth;
  9505. this.lights = source.lights;
  9506. this.clipping = source.clipping;
  9507. this.skinning = source.skinning;
  9508. this.morphTargets = source.morphTargets;
  9509. this.morphNormals = source.morphNormals;
  9510. this.extensions = source.extensions;
  9511. return this;
  9512. };
  9513. ShaderMaterial.prototype.toJSON = function (meta) {
  9514. var data = Material.prototype.toJSON.call(this, meta);
  9515. data.uniforms = {};
  9516. for (var name in this.uniforms) {
  9517. var uniform = this.uniforms[name];
  9518. var value = uniform.value;
  9519. if (value && value.isTexture) {
  9520. data.uniforms[name] = {
  9521. type: 't',
  9522. value: value.toJSON(meta).uuid
  9523. };
  9524. } else if (value && value.isColor) {
  9525. data.uniforms[name] = {
  9526. type: 'c',
  9527. value: value.getHex()
  9528. };
  9529. } else if (value && value.isVector2) {
  9530. data.uniforms[name] = {
  9531. type: 'v2',
  9532. value: value.toArray()
  9533. };
  9534. } else if (value && value.isVector3) {
  9535. data.uniforms[name] = {
  9536. type: 'v3',
  9537. value: value.toArray()
  9538. };
  9539. } else if (value && value.isVector4) {
  9540. data.uniforms[name] = {
  9541. type: 'v4',
  9542. value: value.toArray()
  9543. };
  9544. } else if (value && value.isMatrix3) {
  9545. data.uniforms[name] = {
  9546. type: 'm3',
  9547. value: value.toArray()
  9548. };
  9549. } else if (value && value.isMatrix4) {
  9550. data.uniforms[name] = {
  9551. type: 'm4',
  9552. value: value.toArray()
  9553. };
  9554. } else {
  9555. data.uniforms[name] = {
  9556. value: value
  9557. }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  9558. }
  9559. }
  9560. if (Object.keys(this.defines).length > 0) data.defines = this.defines;
  9561. data.vertexShader = this.vertexShader;
  9562. data.fragmentShader = this.fragmentShader;
  9563. var extensions = {};
  9564. for (var key in this.extensions) {
  9565. if (this.extensions[key] === true) extensions[key] = true;
  9566. }
  9567. if (Object.keys(extensions).length > 0) data.extensions = extensions;
  9568. return data;
  9569. };
  9570. /**
  9571. * @author mrdoob / http://mrdoob.com/
  9572. * @author mikael emtinger / http://gomo.se/
  9573. * @author WestLangley / http://github.com/WestLangley
  9574. */
  9575. function Camera() {
  9576. Object3D.call(this);
  9577. this.type = 'Camera';
  9578. this.matrixWorldInverse = new Matrix4();
  9579. this.projectionMatrix = new Matrix4();
  9580. this.projectionMatrixInverse = new Matrix4();
  9581. }
  9582. Camera.prototype = Object.assign(Object.create(Object3D.prototype), {
  9583. constructor: Camera,
  9584. isCamera: true,
  9585. copy: function (source, recursive) {
  9586. Object3D.prototype.copy.call(this, source, recursive);
  9587. this.matrixWorldInverse.copy(source.matrixWorldInverse);
  9588. this.projectionMatrix.copy(source.projectionMatrix);
  9589. this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
  9590. return this;
  9591. },
  9592. getWorldDirection: function (target) {
  9593. if (target === undefined) {
  9594. console.warn('THREE.Camera: .getWorldDirection() target is now required');
  9595. target = new Vector3();
  9596. }
  9597. this.updateMatrixWorld(true);
  9598. var e = this.matrixWorld.elements;
  9599. return target.set(-e[8], -e[9], -e[10]).normalize();
  9600. },
  9601. updateMatrixWorld: function (force) {
  9602. Object3D.prototype.updateMatrixWorld.call(this, force);
  9603. this.matrixWorldInverse.getInverse(this.matrixWorld);
  9604. },
  9605. clone: function () {
  9606. return new this.constructor().copy(this);
  9607. }
  9608. });
  9609. /**
  9610. * @author mrdoob / http://mrdoob.com/
  9611. * @author greggman / http://games.greggman.com/
  9612. * @author zz85 / http://www.lab4games.net/zz85/blog
  9613. * @author tschw
  9614. */
  9615. function PerspectiveCamera(fov, aspect, near, far) {
  9616. Camera.call(this);
  9617. this.type = 'PerspectiveCamera';
  9618. this.fov = fov !== undefined ? fov : 50;
  9619. this.zoom = 1;
  9620. this.near = near !== undefined ? near : 0.1;
  9621. this.far = far !== undefined ? far : 2000;
  9622. this.focus = 10;
  9623. this.aspect = aspect !== undefined ? aspect : 1;
  9624. this.view = null;
  9625. this.filmGauge = 35; // width of the film (default in millimeters)
  9626. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  9627. this.updateProjectionMatrix();
  9628. }
  9629. PerspectiveCamera.prototype = Object.assign(Object.create(Camera.prototype), {
  9630. constructor: PerspectiveCamera,
  9631. isPerspectiveCamera: true,
  9632. copy: function (source, recursive) {
  9633. Camera.prototype.copy.call(this, source, recursive);
  9634. this.fov = source.fov;
  9635. this.zoom = source.zoom;
  9636. this.near = source.near;
  9637. this.far = source.far;
  9638. this.focus = source.focus;
  9639. this.aspect = source.aspect;
  9640. this.view = source.view === null ? null : Object.assign({}, source.view);
  9641. this.filmGauge = source.filmGauge;
  9642. this.filmOffset = source.filmOffset;
  9643. return this;
  9644. },
  9645. /**
  9646. * Sets the FOV by focal length in respect to the current .filmGauge.
  9647. *
  9648. * The default film gauge is 35, so that the focal length can be specified for
  9649. * a 35mm (full frame) camera.
  9650. *
  9651. * Values for focal length and film gauge must have the same unit.
  9652. */
  9653. setFocalLength: function (focalLength) {
  9654. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  9655. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  9656. this.fov = _Math.RAD2DEG * 2 * Math.atan(vExtentSlope);
  9657. this.updateProjectionMatrix();
  9658. },
  9659. /**
  9660. * Calculates the focal length from the current .fov and .filmGauge.
  9661. */
  9662. getFocalLength: function () {
  9663. var vExtentSlope = Math.tan(_Math.DEG2RAD * 0.5 * this.fov);
  9664. return 0.5 * this.getFilmHeight() / vExtentSlope;
  9665. },
  9666. getEffectiveFOV: function () {
  9667. return _Math.RAD2DEG * 2 * Math.atan(Math.tan(_Math.DEG2RAD * 0.5 * this.fov) / this.zoom);
  9668. },
  9669. getFilmWidth: function () {
  9670. // film not completely covered in portrait format (aspect < 1)
  9671. return this.filmGauge * Math.min(this.aspect, 1);
  9672. },
  9673. getFilmHeight: function () {
  9674. // film not completely covered in landscape format (aspect > 1)
  9675. return this.filmGauge / Math.max(this.aspect, 1);
  9676. },
  9677. /**
  9678. * Sets an offset in a larger frustum. This is useful for multi-window or
  9679. * multi-monitor/multi-machine setups.
  9680. *
  9681. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  9682. * the monitors are in grid like this
  9683. *
  9684. * +---+---+---+
  9685. * | A | B | C |
  9686. * +---+---+---+
  9687. * | D | E | F |
  9688. * +---+---+---+
  9689. *
  9690. * then for each monitor you would call it like this
  9691. *
  9692. * var w = 1920;
  9693. * var h = 1080;
  9694. * var fullWidth = w * 3;
  9695. * var fullHeight = h * 2;
  9696. *
  9697. * --A--
  9698. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  9699. * --B--
  9700. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  9701. * --C--
  9702. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  9703. * --D--
  9704. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  9705. * --E--
  9706. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  9707. * --F--
  9708. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  9709. *
  9710. * Note there is no reason monitors have to be the same size or in a grid.
  9711. */
  9712. setViewOffset: function (fullWidth, fullHeight, x, y, width, height) {
  9713. this.aspect = fullWidth / fullHeight;
  9714. if (this.view === null) {
  9715. this.view = {
  9716. enabled: true,
  9717. fullWidth: 1,
  9718. fullHeight: 1,
  9719. offsetX: 0,
  9720. offsetY: 0,
  9721. width: 1,
  9722. height: 1
  9723. };
  9724. }
  9725. this.view.enabled = true;
  9726. this.view.fullWidth = fullWidth;
  9727. this.view.fullHeight = fullHeight;
  9728. this.view.offsetX = x;
  9729. this.view.offsetY = y;
  9730. this.view.width = width;
  9731. this.view.height = height;
  9732. this.updateProjectionMatrix();
  9733. },
  9734. clearViewOffset: function () {
  9735. if (this.view !== null) {
  9736. this.view.enabled = false;
  9737. }
  9738. this.updateProjectionMatrix();
  9739. },
  9740. updateProjectionMatrix: function () {
  9741. var near = this.near,
  9742. top = near * Math.tan(_Math.DEG2RAD * 0.5 * this.fov) / this.zoom,
  9743. height = 2 * top,
  9744. width = this.aspect * height,
  9745. left = -0.5 * width,
  9746. view = this.view;
  9747. if (this.view !== null && this.view.enabled) {
  9748. var fullWidth = view.fullWidth,
  9749. fullHeight = view.fullHeight;
  9750. left += view.offsetX * width / fullWidth;
  9751. top -= view.offsetY * height / fullHeight;
  9752. width *= view.width / fullWidth;
  9753. height *= view.height / fullHeight;
  9754. }
  9755. var skew = this.filmOffset;
  9756. if (skew !== 0) left += near * skew / this.getFilmWidth();
  9757. this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
  9758. this.projectionMatrixInverse.getInverse(this.projectionMatrix);
  9759. },
  9760. toJSON: function (meta) {
  9761. var data = Object3D.prototype.toJSON.call(this, meta);
  9762. data.object.fov = this.fov;
  9763. data.object.zoom = this.zoom;
  9764. data.object.near = this.near;
  9765. data.object.far = this.far;
  9766. data.object.focus = this.focus;
  9767. data.object.aspect = this.aspect;
  9768. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  9769. data.object.filmGauge = this.filmGauge;
  9770. data.object.filmOffset = this.filmOffset;
  9771. return data;
  9772. }
  9773. });
  9774. /**
  9775. * Camera for rendering cube maps
  9776. * - renders scene into axis-aligned cube
  9777. *
  9778. * @author alteredq / http://alteredqualia.com/
  9779. */
  9780. var fov = 90,
  9781. aspect = 1;
  9782. function CubeCamera(near, far, cubeResolution, options) {
  9783. Object3D.call(this);
  9784. this.type = 'CubeCamera';
  9785. var cameraPX = new PerspectiveCamera(fov, aspect, near, far);
  9786. cameraPX.up.set(0, -1, 0);
  9787. cameraPX.lookAt(new Vector3(1, 0, 0));
  9788. this.add(cameraPX);
  9789. var cameraNX = new PerspectiveCamera(fov, aspect, near, far);
  9790. cameraNX.up.set(0, -1, 0);
  9791. cameraNX.lookAt(new Vector3(-1, 0, 0));
  9792. this.add(cameraNX);
  9793. var cameraPY = new PerspectiveCamera(fov, aspect, near, far);
  9794. cameraPY.up.set(0, 0, 1);
  9795. cameraPY.lookAt(new Vector3(0, 1, 0));
  9796. this.add(cameraPY);
  9797. var cameraNY = new PerspectiveCamera(fov, aspect, near, far);
  9798. cameraNY.up.set(0, 0, -1);
  9799. cameraNY.lookAt(new Vector3(0, -1, 0));
  9800. this.add(cameraNY);
  9801. var cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
  9802. cameraPZ.up.set(0, -1, 0);
  9803. cameraPZ.lookAt(new Vector3(0, 0, 1));
  9804. this.add(cameraPZ);
  9805. var cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
  9806. cameraNZ.up.set(0, -1, 0);
  9807. cameraNZ.lookAt(new Vector3(0, 0, -1));
  9808. this.add(cameraNZ);
  9809. options = options || {
  9810. format: RGBFormat,
  9811. magFilter: LinearFilter,
  9812. minFilter: LinearFilter
  9813. };
  9814. this.renderTarget = new WebGLRenderTargetCube(cubeResolution, cubeResolution, options);
  9815. this.renderTarget.texture.name = "CubeCamera";
  9816. this.update = function (renderer, scene) {
  9817. if (this.parent === null) this.updateMatrixWorld();
  9818. var currentRenderTarget = renderer.getRenderTarget();
  9819. var renderTarget = this.renderTarget;
  9820. var generateMipmaps = renderTarget.texture.generateMipmaps;
  9821. renderTarget.texture.generateMipmaps = false;
  9822. renderer.setRenderTarget(renderTarget, 0);
  9823. renderer.render(scene, cameraPX);
  9824. renderer.setRenderTarget(renderTarget, 1);
  9825. renderer.render(scene, cameraNX);
  9826. renderer.setRenderTarget(renderTarget, 2);
  9827. renderer.render(scene, cameraPY);
  9828. renderer.setRenderTarget(renderTarget, 3);
  9829. renderer.render(scene, cameraNY);
  9830. renderer.setRenderTarget(renderTarget, 4);
  9831. renderer.render(scene, cameraPZ);
  9832. renderTarget.texture.generateMipmaps = generateMipmaps;
  9833. renderer.setRenderTarget(renderTarget, 5);
  9834. renderer.render(scene, cameraNZ);
  9835. renderer.setRenderTarget(currentRenderTarget);
  9836. };
  9837. this.clear = function (renderer, color, depth, stencil) {
  9838. var currentRenderTarget = renderer.getRenderTarget();
  9839. var renderTarget = this.renderTarget;
  9840. for (var i = 0; i < 6; i++) {
  9841. renderer.setRenderTarget(renderTarget, i);
  9842. renderer.clear(color, depth, stencil);
  9843. }
  9844. renderer.setRenderTarget(currentRenderTarget);
  9845. };
  9846. }
  9847. CubeCamera.prototype = Object.create(Object3D.prototype);
  9848. CubeCamera.prototype.constructor = CubeCamera;
  9849. /**
  9850. * @author alteredq / http://alteredqualia.com
  9851. * @author WestLangley / http://github.com/WestLangley
  9852. */
  9853. function WebGLRenderTargetCube(width, height, options) {
  9854. WebGLRenderTarget.call(this, width, height, options);
  9855. }
  9856. WebGLRenderTargetCube.prototype = Object.create(WebGLRenderTarget.prototype);
  9857. WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube;
  9858. WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true;
  9859. WebGLRenderTargetCube.prototype.fromEquirectangularTexture = function (renderer, texture) {
  9860. this.texture.type = texture.type;
  9861. this.texture.format = texture.format;
  9862. this.texture.encoding = texture.encoding;
  9863. var scene = new Scene();
  9864. var shader = {
  9865. uniforms: {
  9866. tEquirect: {
  9867. value: null
  9868. }
  9869. },
  9870. vertexShader: ["varying vec3 vWorldDirection;", "vec3 transformDirection( in vec3 dir, in mat4 matrix ) {", " return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );", "}", "void main() {", " vWorldDirection = transformDirection( position, modelMatrix );", " #include <begin_vertex>", " #include <project_vertex>", "}"].join('\n'),
  9871. fragmentShader: ["uniform sampler2D tEquirect;", "varying vec3 vWorldDirection;", "#define RECIPROCAL_PI 0.31830988618", "#define RECIPROCAL_PI2 0.15915494", "void main() {", " vec3 direction = normalize( vWorldDirection );", " vec2 sampleUV;", " sampleUV.y = asin( clamp( direction.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;", " sampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;", " gl_FragColor = texture2D( tEquirect, sampleUV );", "}"].join('\n')
  9872. };
  9873. var material = new ShaderMaterial({
  9874. type: 'CubemapFromEquirect',
  9875. uniforms: cloneUniforms(shader.uniforms),
  9876. vertexShader: shader.vertexShader,
  9877. fragmentShader: shader.fragmentShader,
  9878. side: BackSide,
  9879. blending: NoBlending
  9880. });
  9881. material.uniforms.tEquirect.value = texture;
  9882. var mesh = new Mesh(new BoxBufferGeometry(5, 5, 5), material);
  9883. scene.add(mesh);
  9884. var camera = new CubeCamera(1, 10, 1);
  9885. camera.renderTarget = this;
  9886. camera.renderTarget.texture.name = 'CubeCameraTexture';
  9887. camera.update(renderer, scene);
  9888. mesh.geometry.dispose();
  9889. mesh.material.dispose();
  9890. return this;
  9891. };
  9892. /**
  9893. * @author alteredq / http://alteredqualia.com/
  9894. */
  9895. function DataTexture(data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  9896. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  9897. this.image = {
  9898. data: data || null,
  9899. width: width || 1,
  9900. height: height || 1
  9901. };
  9902. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  9903. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  9904. this.generateMipmaps = false;
  9905. this.flipY = false;
  9906. this.unpackAlignment = 1;
  9907. this.needsUpdate = true;
  9908. }
  9909. DataTexture.prototype = Object.create(Texture.prototype);
  9910. DataTexture.prototype.constructor = DataTexture;
  9911. DataTexture.prototype.isDataTexture = true;
  9912. /**
  9913. * @author bhouston / http://clara.io
  9914. */
  9915. var _vector1 = new Vector3();
  9916. var _vector2 = new Vector3();
  9917. var _normalMatrix = new Matrix3();
  9918. function Plane(normal, constant) {
  9919. // normal is assumed to be normalized
  9920. this.normal = normal !== undefined ? normal : new Vector3(1, 0, 0);
  9921. this.constant = constant !== undefined ? constant : 0;
  9922. }
  9923. Object.assign(Plane.prototype, {
  9924. isPlane: true,
  9925. set: function (normal, constant) {
  9926. this.normal.copy(normal);
  9927. this.constant = constant;
  9928. return this;
  9929. },
  9930. setComponents: function (x, y, z, w) {
  9931. this.normal.set(x, y, z);
  9932. this.constant = w;
  9933. return this;
  9934. },
  9935. setFromNormalAndCoplanarPoint: function (normal, point) {
  9936. this.normal.copy(normal);
  9937. this.constant = -point.dot(this.normal);
  9938. return this;
  9939. },
  9940. setFromCoplanarPoints: function (a, b, c) {
  9941. var normal = _vector1.subVectors(c, b).cross(_vector2.subVectors(a, b)).normalize(); // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  9942. this.setFromNormalAndCoplanarPoint(normal, a);
  9943. return this;
  9944. },
  9945. clone: function () {
  9946. return new this.constructor().copy(this);
  9947. },
  9948. copy: function (plane) {
  9949. this.normal.copy(plane.normal);
  9950. this.constant = plane.constant;
  9951. return this;
  9952. },
  9953. normalize: function () {
  9954. // Note: will lead to a divide by zero if the plane is invalid.
  9955. var inverseNormalLength = 1.0 / this.normal.length();
  9956. this.normal.multiplyScalar(inverseNormalLength);
  9957. this.constant *= inverseNormalLength;
  9958. return this;
  9959. },
  9960. negate: function () {
  9961. this.constant *= -1;
  9962. this.normal.negate();
  9963. return this;
  9964. },
  9965. distanceToPoint: function (point) {
  9966. return this.normal.dot(point) + this.constant;
  9967. },
  9968. distanceToSphere: function (sphere) {
  9969. return this.distanceToPoint(sphere.center) - sphere.radius;
  9970. },
  9971. projectPoint: function (point, target) {
  9972. if (target === undefined) {
  9973. console.warn('THREE.Plane: .projectPoint() target is now required');
  9974. target = new Vector3();
  9975. }
  9976. return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
  9977. },
  9978. intersectLine: function (line, target) {
  9979. if (target === undefined) {
  9980. console.warn('THREE.Plane: .intersectLine() target is now required');
  9981. target = new Vector3();
  9982. }
  9983. var direction = line.delta(_vector1);
  9984. var denominator = this.normal.dot(direction);
  9985. if (denominator === 0) {
  9986. // line is coplanar, return origin
  9987. if (this.distanceToPoint(line.start) === 0) {
  9988. return target.copy(line.start);
  9989. } // Unsure if this is the correct method to handle this case.
  9990. return undefined;
  9991. }
  9992. var t = -(line.start.dot(this.normal) + this.constant) / denominator;
  9993. if (t < 0 || t > 1) {
  9994. return undefined;
  9995. }
  9996. return target.copy(direction).multiplyScalar(t).add(line.start);
  9997. },
  9998. intersectsLine: function (line) {
  9999. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  10000. var startSign = this.distanceToPoint(line.start);
  10001. var endSign = this.distanceToPoint(line.end);
  10002. return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
  10003. },
  10004. intersectsBox: function (box) {
  10005. return box.intersectsPlane(this);
  10006. },
  10007. intersectsSphere: function (sphere) {
  10008. return sphere.intersectsPlane(this);
  10009. },
  10010. coplanarPoint: function (target) {
  10011. if (target === undefined) {
  10012. console.warn('THREE.Plane: .coplanarPoint() target is now required');
  10013. target = new Vector3();
  10014. }
  10015. return target.copy(this.normal).multiplyScalar(-this.constant);
  10016. },
  10017. applyMatrix4: function (matrix, optionalNormalMatrix) {
  10018. var normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
  10019. var referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
  10020. var normal = this.normal.applyMatrix3(normalMatrix).normalize();
  10021. this.constant = -referencePoint.dot(normal);
  10022. return this;
  10023. },
  10024. translate: function (offset) {
  10025. this.constant -= offset.dot(this.normal);
  10026. return this;
  10027. },
  10028. equals: function (plane) {
  10029. return plane.normal.equals(this.normal) && plane.constant === this.constant;
  10030. }
  10031. });
  10032. /**
  10033. * @author mrdoob / http://mrdoob.com/
  10034. * @author alteredq / http://alteredqualia.com/
  10035. * @author bhouston / http://clara.io
  10036. */
  10037. var _sphere$1 = new Sphere();
  10038. var _vector$5 = new Vector3();
  10039. function Frustum(p0, p1, p2, p3, p4, p5) {
  10040. this.planes = [p0 !== undefined ? p0 : new Plane(), p1 !== undefined ? p1 : new Plane(), p2 !== undefined ? p2 : new Plane(), p3 !== undefined ? p3 : new Plane(), p4 !== undefined ? p4 : new Plane(), p5 !== undefined ? p5 : new Plane()];
  10041. }
  10042. Object.assign(Frustum.prototype, {
  10043. set: function (p0, p1, p2, p3, p4, p5) {
  10044. var planes = this.planes;
  10045. planes[0].copy(p0);
  10046. planes[1].copy(p1);
  10047. planes[2].copy(p2);
  10048. planes[3].copy(p3);
  10049. planes[4].copy(p4);
  10050. planes[5].copy(p5);
  10051. return this;
  10052. },
  10053. clone: function () {
  10054. return new this.constructor().copy(this);
  10055. },
  10056. copy: function (frustum) {
  10057. var planes = this.planes;
  10058. for (var i = 0; i < 6; i++) {
  10059. planes[i].copy(frustum.planes[i]);
  10060. }
  10061. return this;
  10062. },
  10063. setFromMatrix: function (m) {
  10064. var planes = this.planes;
  10065. var me = m.elements;
  10066. var me0 = me[0],
  10067. me1 = me[1],
  10068. me2 = me[2],
  10069. me3 = me[3];
  10070. var me4 = me[4],
  10071. me5 = me[5],
  10072. me6 = me[6],
  10073. me7 = me[7];
  10074. var me8 = me[8],
  10075. me9 = me[9],
  10076. me10 = me[10],
  10077. me11 = me[11];
  10078. var me12 = me[12],
  10079. me13 = me[13],
  10080. me14 = me[14],
  10081. me15 = me[15];
  10082. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  10083. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  10084. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  10085. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  10086. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  10087. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  10088. return this;
  10089. },
  10090. intersectsObject: function (object) {
  10091. var geometry = object.geometry;
  10092. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  10093. _sphere$1.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
  10094. return this.intersectsSphere(_sphere$1);
  10095. },
  10096. intersectsSprite: function (sprite) {
  10097. _sphere$1.center.set(0, 0, 0);
  10098. _sphere$1.radius = 0.7071067811865476;
  10099. _sphere$1.applyMatrix4(sprite.matrixWorld);
  10100. return this.intersectsSphere(_sphere$1);
  10101. },
  10102. intersectsSphere: function (sphere) {
  10103. var planes = this.planes;
  10104. var center = sphere.center;
  10105. var negRadius = -sphere.radius;
  10106. for (var i = 0; i < 6; i++) {
  10107. var distance = planes[i].distanceToPoint(center);
  10108. if (distance < negRadius) {
  10109. return false;
  10110. }
  10111. }
  10112. return true;
  10113. },
  10114. intersectsBox: function (box) {
  10115. var planes = this.planes;
  10116. for (var i = 0; i < 6; i++) {
  10117. var plane = planes[i]; // corner at max distance
  10118. _vector$5.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  10119. _vector$5.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  10120. _vector$5.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  10121. if (plane.distanceToPoint(_vector$5) < 0) {
  10122. return false;
  10123. }
  10124. }
  10125. return true;
  10126. },
  10127. containsPoint: function (point) {
  10128. var planes = this.planes;
  10129. for (var i = 0; i < 6; i++) {
  10130. if (planes[i].distanceToPoint(point) < 0) {
  10131. return false;
  10132. }
  10133. }
  10134. return true;
  10135. }
  10136. });
  10137. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  10138. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  10139. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";
  10140. var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif";
  10141. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  10142. var begin_vertex = "vec3 transformed = vec3( position );";
  10143. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  10144. var bsdfs = "vec2 integrateSpecularBRDF( const in float dotNV, const in float roughness ) {\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\treturn vec2( -1.04, 1.04 ) * a004 + r.zw;\n}\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n#else\n\tif( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t}\n\treturn 1.0;\n#endif\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nvec3 F_Schlick_RoughnessDependent( const in vec3 F0, const in float dotNV, const in float roughness ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotNV - 6.98316 ) * dotNV );\n\tvec3 Fr = max( vec3( 1.0 - roughness ), F0 ) - F0;\n\treturn Fr * fresnel + F0;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + viewDir );\n\tfloat dotNL = saturate( dot( normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nvec3 BRDF_Specular_GGX_Environment( const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\treturn specularColor * brdf.x + brdf.y;\n}\nvoid BRDF_Specular_Multiscattering_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tvec3 F = F_Schlick_RoughnessDependent( specularColor, dotNV, roughness );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\tvec3 FssEss = F * brdf.x + brdf.y;\n\tfloat Ess = brdf.x + brdf.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie(float roughness, float NoH) {\n\tfloat invAlpha = 1.0 / roughness;\n\tfloat cos2h = NoH * NoH;\n\tfloat sin2h = max(1.0 - cos2h, 0.0078125);\treturn (2.0 + invAlpha) * pow(sin2h, invAlpha * 0.5) / (2.0 * PI);\n}\nfloat V_Neubelt(float NoV, float NoL) {\n\treturn saturate(1.0 / (4.0 * (NoL + NoV - NoL * NoV)));\n}\nvec3 BRDF_Specular_Sheen( const in float roughness, const in vec3 L, const in GeometricContext geometry, vec3 specularColor ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 H = normalize( V + L );\n\tfloat dotNH = saturate( dot( N, H ) );\n\treturn specularColor * D_Charlie( roughness, dotNH ) * V_Neubelt( dot(N, V), dot(N, L) );\n}\n#endif";
  10145. var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\t\tfDet *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif";
  10146. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vViewPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\tif ( clipped ) discard;\n\t#endif\n#endif";
  10147. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\t#if ! defined( STANDARD ) && ! defined( PHONG ) && ! defined( MATCAP )\n\t\tvarying vec3 vViewPosition;\n\t#endif\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  10148. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( STANDARD ) && ! defined( PHONG ) && ! defined( MATCAP )\n\tvarying vec3 vViewPosition;\n#endif";
  10149. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( STANDARD ) && ! defined( PHONG ) && ! defined( MATCAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif";
  10150. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  10151. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  10152. var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  10153. var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";
  10154. 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#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat max3( vec3 v ) { return max( max( v.x, v.y ), v.z ); }\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n return m[ 2 ][ 3 ] == - 1.0;\n}";
  10155. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n#define cubeUV_textureSize (1024.0)\nint getFaceFromDirection(vec3 direction) {\n\tvec3 absDirection = abs(direction);\n\tint face = -1;\n\tif( absDirection.x > absDirection.z ) {\n\t\tif(absDirection.x > absDirection.y )\n\t\t\tface = direction.x > 0.0 ? 0 : 3;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\telse {\n\t\tif(absDirection.z > absDirection.y )\n\t\t\tface = direction.z > 0.0 ? 2 : 5;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\treturn face;\n}\n#define cubeUV_maxLods1 (log2(cubeUV_textureSize*0.25) - 1.0)\n#define cubeUV_rangeClamp (exp2((6.0 - 1.0) * 2.0))\nvec2 MipLevelInfo( vec3 vec, float roughnessLevel, float roughness ) {\n\tfloat scale = exp2(cubeUV_maxLods1 - roughnessLevel);\n\tfloat dxRoughness = dFdx(roughness);\n\tfloat dyRoughness = dFdy(roughness);\n\tvec3 dx = dFdx( vec * scale * dxRoughness );\n\tvec3 dy = dFdy( vec * scale * dyRoughness );\n\tfloat d = max( dot( dx, dx ), dot( dy, dy ) );\n\td = clamp(d, 1.0, cubeUV_rangeClamp);\n\tfloat mipLevel = 0.5 * log2(d);\n\treturn vec2(floor(mipLevel), fract(mipLevel));\n}\n#define cubeUV_maxLods2 (log2(cubeUV_textureSize*0.25) - 2.0)\n#define cubeUV_rcpTextureSize (1.0 / cubeUV_textureSize)\nvec2 getCubeUV(vec3 direction, float roughnessLevel, float mipLevel) {\n\tmipLevel = roughnessLevel > cubeUV_maxLods2 - 3.0 ? 0.0 : mipLevel;\n\tfloat a = 16.0 * cubeUV_rcpTextureSize;\n\tvec2 exp2_packed = exp2( vec2( roughnessLevel, mipLevel ) );\n\tvec2 rcp_exp2_packed = vec2( 1.0 ) / exp2_packed;\n\tfloat powScale = exp2_packed.x * exp2_packed.y;\n\tfloat scale = rcp_exp2_packed.x * rcp_exp2_packed.y * 0.25;\n\tfloat mipOffset = 0.75*(1.0 - rcp_exp2_packed.y) * rcp_exp2_packed.x;\n\tbool bRes = mipLevel == 0.0;\n\tscale = bRes && (scale < a) ? a : scale;\n\tvec3 r;\n\tvec2 offset;\n\tint face = getFaceFromDirection(direction);\n\tfloat rcpPowScale = 1.0 / powScale;\n\tif( face == 0) {\n\t\tr = vec3(direction.x, -direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 1) {\n\t\tr = vec3(direction.y, direction.x, direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 2) {\n\t\tr = vec3(direction.z, direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 3) {\n\t\tr = vec3(direction.x, direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse if( face == 4) {\n\t\tr = vec3(direction.y, direction.x, -direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse {\n\t\tr = vec3(direction.z, -direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\tr = normalize(r);\n\tfloat texelOffset = 0.5 * cubeUV_rcpTextureSize;\n\tvec2 s = ( r.yz / abs( r.x ) + vec2( 1.0 ) ) * 0.5;\n\tvec2 base = offset + vec2( texelOffset );\n\treturn base + s * ( scale - 2.0 * texelOffset );\n}\n#define cubeUV_maxLods3 (log2(cubeUV_textureSize*0.25) - 3.0)\nvec4 textureCubeUV( sampler2D envMap, vec3 reflectedDirection, float roughness ) {\n\tfloat roughnessVal = roughness* cubeUV_maxLods3;\n\tfloat r1 = floor(roughnessVal);\n\tfloat r2 = r1 + 1.0;\n\tfloat t = fract(roughnessVal);\n\tvec2 mipInfo = MipLevelInfo(reflectedDirection, r1, roughness);\n\tfloat s = mipInfo.y;\n\tfloat level0 = mipInfo.x;\n\tfloat level1 = level0 + 1.0;\n\tlevel1 = level1 > 5.0 ? 5.0 : level1;\n\tlevel0 += min( floor( s + 0.5 ), 5.0 );\n\tvec2 uv_10 = getCubeUV(reflectedDirection, r1, level0);\n\tvec4 color10 = envMapTexelToLinear(texture2D(envMap, uv_10));\n\tvec2 uv_20 = getCubeUV(reflectedDirection, r2, level0);\n\tvec4 color20 = envMapTexelToLinear(texture2D(envMap, uv_20));\n\tvec4 result = mix(color10, color20, t);\n\treturn vec4(result.rgb, 1.0);\n}\n#endif";
  10156. var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\ttransformedNormal = mat3( instanceMatrix ) * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = normalMatrix * objectTangent;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif";
  10157. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  10158. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  10159. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  10160. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  10161. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  10162. var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( gammaFactor ) ), value.a );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( 1.0 / gammaFactor ) ), value.a );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * value.a * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\tD = min( floor( D ) / 255.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n\tvec3 Xp_Y_XYZp = cLogLuvM * value.rgb;\n\tXp_Y_XYZp = max( Xp_Y_XYZp, vec3( 1e-6, 1e-6, 1e-6 ) );\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract( Le );\n\tvResult.z = ( Le - ( floor( vResult.w * 255.0 ) ) / 255.0 ) / 255.0;\n\treturn vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2( ( Le - 127.0 ) / 2.0 );\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = cLogLuvInverseM * Xp_Y_XYZp.rgb;\n\treturn vec4( max( vRGB, 0.0 ), 1.0 );\n}";
  10163. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\treflectVec = normalize( reflectVec );\n\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\treflectVec = normalize( reflectVec );\n\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\tenvColor = envMapTexelToLinear( envColor );\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";
  10164. var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform int maxMipLevel;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif";
  10165. var envmap_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif";
  10166. var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) ||defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif";
  10167. var envmap_vertex = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif";
  10168. var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = -mvPosition.z;\n#endif";
  10169. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";
  10170. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * fogDepth * fogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif";
  10171. 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";
  10172. 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";
  10173. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif";
  10174. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  10175. var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\nvIndirectFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n\tvIndirectBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n#endif";
  10176. var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in GeometricContext geometry ) {\n\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t\tfloat shadowCameraNear;\n\t\tfloat shadowCameraFar;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif";
  10177. var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, queryVec, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float roughness, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat sigma = PI * roughness * roughness / ( 1.0 + roughness );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + log2( sigma );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t vec3 reflectVec = reflect( -viewDir, normal );\n\t\t reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t#else\n\t\t vec3 reflectVec = refract( -viewDir, normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( roughness, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, queryReflectVec, roughness );\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif";
  10178. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  10179. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifdef TOON\n\t\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#else\n\t\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\t\tvec3 irradiance = dotNL * directLight.color;\n\t#endif\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)";
  10180. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 );\n#ifdef REFLECTIVITY\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#endif\n#ifdef CLEARCOAT\n\tmaterial.clearcoat = saturate( clearcoat );\tmaterial.clearcoatRoughness = clamp( clearcoatRoughness, 0.04, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheen;\n#endif";
  10181. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n#ifdef CLEARCOAT\n\tfloat clearcoat;\n\tfloat clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tvec3 sheenColor;\n#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearcoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNL = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = ccDotNL * directLight.color;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tccIrradiance *= PI;\n\t\t#endif\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t\treflectedLight.directSpecular += ccIrradiance * material.clearcoat * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_Sheen(\n\t\t\tmaterial.specularRoughness,\n\t\t\tdirectLight.direction,\n\t\t\tgeometry,\n\t\t\tmaterial.sheenColor\n\t\t);\n\t#else\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.normal, material.specularColor, material.specularRoughness);\n\t#endif\n\treflectedLight.directDiffuse += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNV = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular += clearcoatRadiance * material.clearcoat * BRDF_Specular_GGX_Environment( geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t\tfloat ccDotNL = ccDotNV;\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\tfloat clearcoatInv = 1.0 - clearcoatDHR;\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tBRDF_Specular_Multiscattering_Environment( geometry, material.specularColor, material.specularRoughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += clearcoatInv * radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}";
  10182. var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\n#ifdef CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tdirectLight.color *= all( bvec3( pointLight.shadow, directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tdirectLight.color *= all( bvec3( spotLight.shadow, directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectLight.color *= all( bvec3( directionalLight.shadow, directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";
  10183. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getLightProbeIndirectIrradiance( geometry, maxMipLevel );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.normal, material.specularRoughness, maxMipLevel );\n\t#ifdef CLEARCOAT\n\t\tclearcoatRadiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness, maxMipLevel );\n\t#endif\n#endif";
  10184. var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n#endif";
  10185. var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 1.0 ? log2( vFragDepth ) * logDepthBufFC * 0.5 : gl_FragCoord.z;\n#endif";
  10186. var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  10187. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif";
  10188. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif";
  10189. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  10190. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  10191. var map_particle_fragment = "#ifdef USE_MAP\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif";
  10192. var map_particle_pars_fragment = "#ifdef USE_MAP\n\tuniform mat3 uvTransform;\n\tuniform sampler2D map;\n#endif";
  10193. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  10194. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  10195. 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";
  10196. 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";
  10197. 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";
  10198. var normal_fragment_begin = "#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t\tbitangent = bitangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;";
  10199. var normal_fragment_maps = "#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\t#ifdef USE_TANGENT\n\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = normalScale * mapN.xy;\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( -vViewPosition, normal, normalScale, normalMap );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif";
  10200. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 normalScale, in sampler2D normalMap ) {\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tfloat scale = sign( st1.t * st0.s - st0.t * st1.s );\n\t\tvec3 S = normalize( ( q0 * st1.t - q1 * st0.t ) * scale );\n\t\tvec3 T = normalize( ( - q0 * st1.s + q1 * st0.s ) * scale );\n\t\tvec3 N = normalize( surf_norm );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy *= normalScale;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tbool frontFacing = dot( cross( S, T ), N ) > 0.0;\n\t\t\tmapN.xy *= ( float( frontFacing ) * 2.0 - 1.0 );\n\t\t#else\n\t\t\tmapN.xy *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t#endif\n\t\tmat3 tsn = mat3( S, T, N );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif";
  10201. var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  10202. var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\t#ifdef USE_TANGENT\n\t\tmat3 vTBN = mat3( tangent, bitangent, clearcoatNormal );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = clearcoatNormalScale * mapN.xy;\n\t\tclearcoatNormal = normalize( vTBN * mapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatNormalScale, clearcoatNormalMap );\n\t#endif\n#endif";
  10203. var clearcoat_normalmap_pars_fragment = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif";
  10204. var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec4 encodeHalfRGBA ( vec2 v ) {\n\tvec4 encoded = vec4( 0.0 );\n\tconst vec2 offset = vec2( 1.0 / 255.0, 0.0 );\n\tencoded.xy = vec2( v.x, fract( v.x * 255.0 ) );\n\tencoded.xy = encoded.xy - ( encoded.yy * offset );\n\tencoded.zw = vec2( v.y, fract( v.y * 255.0 ) );\n\tencoded.zw = encoded.zw - ( encoded.ww * offset );\n\treturn encoded;\n}\nvec2 decodeHalfRGBA( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}";
  10205. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  10206. var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;";
  10207. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  10208. var dithering_pars_fragment = "#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif";
  10209. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  10210. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  10211. var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn decodeHalfRGBA( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = ( floor( uv * size - 0.5 ) + 0.5 ) * texelSize;\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\t\tvec2 f = fract( uv * size + 0.5 );\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\t\treturn c;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tshadow = (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif";
  10212. var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif";
  10213. var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n#endif";
  10214. var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLight directionalLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= all( bvec2( directionalLight.shadow, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLight spotLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= all( bvec2( spotLight.shadow, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLight pointLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= all( bvec2( pointLight.shadow, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#endif\n\t#endif\n\treturn shadow;\n}";
  10215. 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";
  10216. var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform highp sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif";
  10217. var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif";
  10218. var skinnormal_vertex = "#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif";
  10219. 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";
  10220. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  10221. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  10222. var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( ( color * ( 2.51 * color + 0.03 ) ) / ( color * ( 2.43 * color + 0.59 ) + 0.14 ) );\n}";
  10223. var uv_pars_fragment = "#ifdef USE_UV\n\tvarying vec2 vUv;\n#endif";
  10224. var uv_pars_vertex = "#ifdef USE_UV\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif";
  10225. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  10226. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  10227. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif";
  10228. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif";
  10229. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif";
  10230. var background_frag = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  10231. var background_vert = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}";
  10232. var cube_frag = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  10233. var cube_vert = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}";
  10234. var depth_frag = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - gl_FragCoord.z ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n\t#endif\n}";
  10235. var depth_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n}";
  10236. var distanceRGBA_frag = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}";
  10237. var distanceRGBA_vert = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}";
  10238. var equirect_frag = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV;\n\tsampleUV.y = asin( clamp( direction.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tvec4 texColor = texture2D( tEquirect, sampleUV );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  10239. var equirect_vert = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}";
  10240. 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}";
  10241. 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}";
  10242. var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\treflectedLight.indirectDiffuse += texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  10243. 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}";
  10244. var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;\n\t#else\n\t\treflectedLight.indirectDiffuse += vIndirectFront;\n\t#endif\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  10245. var meshlambert_vert = "#define LAMBERT\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  10246. var meshmatcap_frag = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t\tmatcapColor = matcapTexelToLinear( matcapColor );\n\t#else\n\t\tvec4 matcapColor = vec4( 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  10247. var meshmatcap_vert = "#define MATCAP\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#ifndef FLAT_SHADED\n\t\tvNormal = normalize( transformedNormal );\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";
  10248. var meshphong_frag = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  10249. var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  10250. var meshphysical_frag = "#define STANDARD\n#ifdef PHYSICAL\n\t#define REFLECTIVITY\n\t#define CLEARCOAT\n\t#define TRANSPARENCY\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef TRANSPARENCY\n\tuniform float transparency;\n#endif\n#ifdef REFLECTIVITY\n\tuniform float reflectivity;\n#endif\n#ifdef CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheen;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <lights_physical_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_normalmap_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#ifdef TRANSPARENCY\n\t\tdiffuseColor.a *= saturate( 1. - transparency + linearToRelativeLuminance( reflectedLight.directSpecular + reflectedLight.indirectSpecular ) );\n\t#endif\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  10251. var meshphysical_vert = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  10252. var normal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}";
  10253. var normal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  10254. var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  10255. var points_vert = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}";
  10256. var shadow_frag = "uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <fog_fragment>\n}";
  10257. var shadow_vert = "#include <fog_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  10258. var sprite_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  10259. var sprite_vert = "uniform float rotation;\nuniform vec2 center;\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  10260. var ShaderChunk = {
  10261. alphamap_fragment: alphamap_fragment,
  10262. alphamap_pars_fragment: alphamap_pars_fragment,
  10263. alphatest_fragment: alphatest_fragment,
  10264. aomap_fragment: aomap_fragment,
  10265. aomap_pars_fragment: aomap_pars_fragment,
  10266. begin_vertex: begin_vertex,
  10267. beginnormal_vertex: beginnormal_vertex,
  10268. bsdfs: bsdfs,
  10269. bumpmap_pars_fragment: bumpmap_pars_fragment,
  10270. clipping_planes_fragment: clipping_planes_fragment,
  10271. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  10272. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  10273. clipping_planes_vertex: clipping_planes_vertex,
  10274. color_fragment: color_fragment,
  10275. color_pars_fragment: color_pars_fragment,
  10276. color_pars_vertex: color_pars_vertex,
  10277. color_vertex: color_vertex,
  10278. common: common,
  10279. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  10280. defaultnormal_vertex: defaultnormal_vertex,
  10281. displacementmap_pars_vertex: displacementmap_pars_vertex,
  10282. displacementmap_vertex: displacementmap_vertex,
  10283. emissivemap_fragment: emissivemap_fragment,
  10284. emissivemap_pars_fragment: emissivemap_pars_fragment,
  10285. encodings_fragment: encodings_fragment,
  10286. encodings_pars_fragment: encodings_pars_fragment,
  10287. envmap_fragment: envmap_fragment,
  10288. envmap_common_pars_fragment: envmap_common_pars_fragment,
  10289. envmap_pars_fragment: envmap_pars_fragment,
  10290. envmap_pars_vertex: envmap_pars_vertex,
  10291. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  10292. envmap_vertex: envmap_vertex,
  10293. fog_vertex: fog_vertex,
  10294. fog_pars_vertex: fog_pars_vertex,
  10295. fog_fragment: fog_fragment,
  10296. fog_pars_fragment: fog_pars_fragment,
  10297. gradientmap_pars_fragment: gradientmap_pars_fragment,
  10298. lightmap_fragment: lightmap_fragment,
  10299. lightmap_pars_fragment: lightmap_pars_fragment,
  10300. lights_lambert_vertex: lights_lambert_vertex,
  10301. lights_pars_begin: lights_pars_begin,
  10302. lights_phong_fragment: lights_phong_fragment,
  10303. lights_phong_pars_fragment: lights_phong_pars_fragment,
  10304. lights_physical_fragment: lights_physical_fragment,
  10305. lights_physical_pars_fragment: lights_physical_pars_fragment,
  10306. lights_fragment_begin: lights_fragment_begin,
  10307. lights_fragment_maps: lights_fragment_maps,
  10308. lights_fragment_end: lights_fragment_end,
  10309. logdepthbuf_fragment: logdepthbuf_fragment,
  10310. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  10311. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  10312. logdepthbuf_vertex: logdepthbuf_vertex,
  10313. map_fragment: map_fragment,
  10314. map_pars_fragment: map_pars_fragment,
  10315. map_particle_fragment: map_particle_fragment,
  10316. map_particle_pars_fragment: map_particle_pars_fragment,
  10317. metalnessmap_fragment: metalnessmap_fragment,
  10318. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  10319. morphnormal_vertex: morphnormal_vertex,
  10320. morphtarget_pars_vertex: morphtarget_pars_vertex,
  10321. morphtarget_vertex: morphtarget_vertex,
  10322. normal_fragment_begin: normal_fragment_begin,
  10323. normal_fragment_maps: normal_fragment_maps,
  10324. normalmap_pars_fragment: normalmap_pars_fragment,
  10325. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  10326. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  10327. clearcoat_normalmap_pars_fragment: clearcoat_normalmap_pars_fragment,
  10328. packing: packing,
  10329. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  10330. project_vertex: project_vertex,
  10331. dithering_fragment: dithering_fragment,
  10332. dithering_pars_fragment: dithering_pars_fragment,
  10333. roughnessmap_fragment: roughnessmap_fragment,
  10334. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  10335. shadowmap_pars_fragment: shadowmap_pars_fragment,
  10336. shadowmap_pars_vertex: shadowmap_pars_vertex,
  10337. shadowmap_vertex: shadowmap_vertex,
  10338. shadowmask_pars_fragment: shadowmask_pars_fragment,
  10339. skinbase_vertex: skinbase_vertex,
  10340. skinning_pars_vertex: skinning_pars_vertex,
  10341. skinning_vertex: skinning_vertex,
  10342. skinnormal_vertex: skinnormal_vertex,
  10343. specularmap_fragment: specularmap_fragment,
  10344. specularmap_pars_fragment: specularmap_pars_fragment,
  10345. tonemapping_fragment: tonemapping_fragment,
  10346. tonemapping_pars_fragment: tonemapping_pars_fragment,
  10347. uv_pars_fragment: uv_pars_fragment,
  10348. uv_pars_vertex: uv_pars_vertex,
  10349. uv_vertex: uv_vertex,
  10350. uv2_pars_fragment: uv2_pars_fragment,
  10351. uv2_pars_vertex: uv2_pars_vertex,
  10352. uv2_vertex: uv2_vertex,
  10353. worldpos_vertex: worldpos_vertex,
  10354. background_frag: background_frag,
  10355. background_vert: background_vert,
  10356. cube_frag: cube_frag,
  10357. cube_vert: cube_vert,
  10358. depth_frag: depth_frag,
  10359. depth_vert: depth_vert,
  10360. distanceRGBA_frag: distanceRGBA_frag,
  10361. distanceRGBA_vert: distanceRGBA_vert,
  10362. equirect_frag: equirect_frag,
  10363. equirect_vert: equirect_vert,
  10364. linedashed_frag: linedashed_frag,
  10365. linedashed_vert: linedashed_vert,
  10366. meshbasic_frag: meshbasic_frag,
  10367. meshbasic_vert: meshbasic_vert,
  10368. meshlambert_frag: meshlambert_frag,
  10369. meshlambert_vert: meshlambert_vert,
  10370. meshmatcap_frag: meshmatcap_frag,
  10371. meshmatcap_vert: meshmatcap_vert,
  10372. meshphong_frag: meshphong_frag,
  10373. meshphong_vert: meshphong_vert,
  10374. meshphysical_frag: meshphysical_frag,
  10375. meshphysical_vert: meshphysical_vert,
  10376. normal_frag: normal_frag,
  10377. normal_vert: normal_vert,
  10378. points_frag: points_frag,
  10379. points_vert: points_vert,
  10380. shadow_frag: shadow_frag,
  10381. shadow_vert: shadow_vert,
  10382. sprite_frag: sprite_frag,
  10383. sprite_vert: sprite_vert
  10384. };
  10385. /**
  10386. * Uniforms library for shared webgl shaders
  10387. */
  10388. exports.ShaderChunk = ShaderChunk;
  10389. var UniformsLib = {
  10390. common: {
  10391. diffuse: {
  10392. value: new Color(0xeeeeee)
  10393. },
  10394. opacity: {
  10395. value: 1.0
  10396. },
  10397. map: {
  10398. value: null
  10399. },
  10400. uvTransform: {
  10401. value: new Matrix3()
  10402. },
  10403. alphaMap: {
  10404. value: null
  10405. }
  10406. },
  10407. specularmap: {
  10408. specularMap: {
  10409. value: null
  10410. }
  10411. },
  10412. envmap: {
  10413. envMap: {
  10414. value: null
  10415. },
  10416. flipEnvMap: {
  10417. value: -1
  10418. },
  10419. reflectivity: {
  10420. value: 1.0
  10421. },
  10422. refractionRatio: {
  10423. value: 0.98
  10424. },
  10425. maxMipLevel: {
  10426. value: 0
  10427. }
  10428. },
  10429. aomap: {
  10430. aoMap: {
  10431. value: null
  10432. },
  10433. aoMapIntensity: {
  10434. value: 1
  10435. }
  10436. },
  10437. lightmap: {
  10438. lightMap: {
  10439. value: null
  10440. },
  10441. lightMapIntensity: {
  10442. value: 1
  10443. }
  10444. },
  10445. emissivemap: {
  10446. emissiveMap: {
  10447. value: null
  10448. }
  10449. },
  10450. bumpmap: {
  10451. bumpMap: {
  10452. value: null
  10453. },
  10454. bumpScale: {
  10455. value: 1
  10456. }
  10457. },
  10458. normalmap: {
  10459. normalMap: {
  10460. value: null
  10461. },
  10462. normalScale: {
  10463. value: new Vector2(1, 1)
  10464. }
  10465. },
  10466. displacementmap: {
  10467. displacementMap: {
  10468. value: null
  10469. },
  10470. displacementScale: {
  10471. value: 1
  10472. },
  10473. displacementBias: {
  10474. value: 0
  10475. }
  10476. },
  10477. roughnessmap: {
  10478. roughnessMap: {
  10479. value: null
  10480. }
  10481. },
  10482. metalnessmap: {
  10483. metalnessMap: {
  10484. value: null
  10485. }
  10486. },
  10487. gradientmap: {
  10488. gradientMap: {
  10489. value: null
  10490. }
  10491. },
  10492. fog: {
  10493. fogDensity: {
  10494. value: 0.00025
  10495. },
  10496. fogNear: {
  10497. value: 1
  10498. },
  10499. fogFar: {
  10500. value: 2000
  10501. },
  10502. fogColor: {
  10503. value: new Color(0xffffff)
  10504. }
  10505. },
  10506. lights: {
  10507. ambientLightColor: {
  10508. value: []
  10509. },
  10510. lightProbe: {
  10511. value: []
  10512. },
  10513. directionalLights: {
  10514. value: [],
  10515. properties: {
  10516. direction: {},
  10517. color: {},
  10518. shadow: {},
  10519. shadowBias: {},
  10520. shadowRadius: {},
  10521. shadowMapSize: {}
  10522. }
  10523. },
  10524. directionalShadowMap: {
  10525. value: []
  10526. },
  10527. directionalShadowMatrix: {
  10528. value: []
  10529. },
  10530. spotLights: {
  10531. value: [],
  10532. properties: {
  10533. color: {},
  10534. position: {},
  10535. direction: {},
  10536. distance: {},
  10537. coneCos: {},
  10538. penumbraCos: {},
  10539. decay: {},
  10540. shadow: {},
  10541. shadowBias: {},
  10542. shadowRadius: {},
  10543. shadowMapSize: {}
  10544. }
  10545. },
  10546. spotShadowMap: {
  10547. value: []
  10548. },
  10549. spotShadowMatrix: {
  10550. value: []
  10551. },
  10552. pointLights: {
  10553. value: [],
  10554. properties: {
  10555. color: {},
  10556. position: {},
  10557. decay: {},
  10558. distance: {},
  10559. shadow: {},
  10560. shadowBias: {},
  10561. shadowRadius: {},
  10562. shadowMapSize: {},
  10563. shadowCameraNear: {},
  10564. shadowCameraFar: {}
  10565. }
  10566. },
  10567. pointShadowMap: {
  10568. value: []
  10569. },
  10570. pointShadowMatrix: {
  10571. value: []
  10572. },
  10573. hemisphereLights: {
  10574. value: [],
  10575. properties: {
  10576. direction: {},
  10577. skyColor: {},
  10578. groundColor: {}
  10579. }
  10580. },
  10581. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  10582. rectAreaLights: {
  10583. value: [],
  10584. properties: {
  10585. color: {},
  10586. position: {},
  10587. width: {},
  10588. height: {}
  10589. }
  10590. }
  10591. },
  10592. points: {
  10593. diffuse: {
  10594. value: new Color(0xeeeeee)
  10595. },
  10596. opacity: {
  10597. value: 1.0
  10598. },
  10599. size: {
  10600. value: 1.0
  10601. },
  10602. scale: {
  10603. value: 1.0
  10604. },
  10605. map: {
  10606. value: null
  10607. },
  10608. uvTransform: {
  10609. value: new Matrix3()
  10610. }
  10611. },
  10612. sprite: {
  10613. diffuse: {
  10614. value: new Color(0xeeeeee)
  10615. },
  10616. opacity: {
  10617. value: 1.0
  10618. },
  10619. center: {
  10620. value: new Vector2(0.5, 0.5)
  10621. },
  10622. rotation: {
  10623. value: 0.0
  10624. },
  10625. map: {
  10626. value: null
  10627. },
  10628. uvTransform: {
  10629. value: new Matrix3()
  10630. }
  10631. }
  10632. };
  10633. /**
  10634. * @author alteredq / http://alteredqualia.com/
  10635. * @author mrdoob / http://mrdoob.com/
  10636. * @author mikael emtinger / http://gomo.se/
  10637. */
  10638. exports.UniformsLib = UniformsLib;
  10639. var ShaderLib = {
  10640. basic: {
  10641. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
  10642. vertexShader: ShaderChunk.meshbasic_vert,
  10643. fragmentShader: ShaderChunk.meshbasic_frag
  10644. },
  10645. lambert: {
  10646. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.fog, UniformsLib.lights, {
  10647. emissive: {
  10648. value: new Color(0x000000)
  10649. }
  10650. }]),
  10651. vertexShader: ShaderChunk.meshlambert_vert,
  10652. fragmentShader: ShaderChunk.meshlambert_frag
  10653. },
  10654. phong: {
  10655. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, {
  10656. emissive: {
  10657. value: new Color(0x000000)
  10658. },
  10659. specular: {
  10660. value: new Color(0x111111)
  10661. },
  10662. shininess: {
  10663. value: 30
  10664. }
  10665. }]),
  10666. vertexShader: ShaderChunk.meshphong_vert,
  10667. fragmentShader: ShaderChunk.meshphong_frag
  10668. },
  10669. standard: {
  10670. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.roughnessmap, UniformsLib.metalnessmap, UniformsLib.fog, UniformsLib.lights, {
  10671. emissive: {
  10672. value: new Color(0x000000)
  10673. },
  10674. roughness: {
  10675. value: 0.5
  10676. },
  10677. metalness: {
  10678. value: 0.5
  10679. },
  10680. envMapIntensity: {
  10681. value: 1
  10682. } // temporary
  10683. }]),
  10684. vertexShader: ShaderChunk.meshphysical_vert,
  10685. fragmentShader: ShaderChunk.meshphysical_frag
  10686. },
  10687. matcap: {
  10688. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
  10689. matcap: {
  10690. value: null
  10691. }
  10692. }]),
  10693. vertexShader: ShaderChunk.meshmatcap_vert,
  10694. fragmentShader: ShaderChunk.meshmatcap_frag
  10695. },
  10696. points: {
  10697. uniforms: mergeUniforms([UniformsLib.points, UniformsLib.fog]),
  10698. vertexShader: ShaderChunk.points_vert,
  10699. fragmentShader: ShaderChunk.points_frag
  10700. },
  10701. dashed: {
  10702. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.fog, {
  10703. scale: {
  10704. value: 1
  10705. },
  10706. dashSize: {
  10707. value: 1
  10708. },
  10709. totalSize: {
  10710. value: 2
  10711. }
  10712. }]),
  10713. vertexShader: ShaderChunk.linedashed_vert,
  10714. fragmentShader: ShaderChunk.linedashed_frag
  10715. },
  10716. depth: {
  10717. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
  10718. vertexShader: ShaderChunk.depth_vert,
  10719. fragmentShader: ShaderChunk.depth_frag
  10720. },
  10721. normal: {
  10722. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
  10723. opacity: {
  10724. value: 1.0
  10725. }
  10726. }]),
  10727. vertexShader: ShaderChunk.normal_vert,
  10728. fragmentShader: ShaderChunk.normal_frag
  10729. },
  10730. sprite: {
  10731. uniforms: mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
  10732. vertexShader: ShaderChunk.sprite_vert,
  10733. fragmentShader: ShaderChunk.sprite_frag
  10734. },
  10735. background: {
  10736. uniforms: {
  10737. uvTransform: {
  10738. value: new Matrix3()
  10739. },
  10740. t2D: {
  10741. value: null
  10742. }
  10743. },
  10744. vertexShader: ShaderChunk.background_vert,
  10745. fragmentShader: ShaderChunk.background_frag
  10746. },
  10747. /* -------------------------------------------------------------------------
  10748. // Cube map shader
  10749. ------------------------------------------------------------------------- */
  10750. cube: {
  10751. uniforms: {
  10752. tCube: {
  10753. value: null
  10754. },
  10755. tFlip: {
  10756. value: -1
  10757. },
  10758. opacity: {
  10759. value: 1.0
  10760. }
  10761. },
  10762. vertexShader: ShaderChunk.cube_vert,
  10763. fragmentShader: ShaderChunk.cube_frag
  10764. },
  10765. equirect: {
  10766. uniforms: {
  10767. tEquirect: {
  10768. value: null
  10769. }
  10770. },
  10771. vertexShader: ShaderChunk.equirect_vert,
  10772. fragmentShader: ShaderChunk.equirect_frag
  10773. },
  10774. distanceRGBA: {
  10775. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
  10776. referencePosition: {
  10777. value: new Vector3()
  10778. },
  10779. nearDistance: {
  10780. value: 1
  10781. },
  10782. farDistance: {
  10783. value: 1000
  10784. }
  10785. }]),
  10786. vertexShader: ShaderChunk.distanceRGBA_vert,
  10787. fragmentShader: ShaderChunk.distanceRGBA_frag
  10788. },
  10789. shadow: {
  10790. uniforms: mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
  10791. color: {
  10792. value: new Color(0x00000)
  10793. },
  10794. opacity: {
  10795. value: 1.0
  10796. }
  10797. }]),
  10798. vertexShader: ShaderChunk.shadow_vert,
  10799. fragmentShader: ShaderChunk.shadow_frag
  10800. }
  10801. };
  10802. exports.ShaderLib = ShaderLib;
  10803. ShaderLib.physical = {
  10804. uniforms: mergeUniforms([ShaderLib.standard.uniforms, {
  10805. transparency: {
  10806. value: 0
  10807. },
  10808. clearcoat: {
  10809. value: 0
  10810. },
  10811. clearcoatRoughness: {
  10812. value: 0
  10813. },
  10814. sheen: {
  10815. value: new Color(0x000000)
  10816. },
  10817. clearcoatNormalScale: {
  10818. value: new Vector2(1, 1)
  10819. },
  10820. clearcoatNormalMap: {
  10821. value: null
  10822. }
  10823. }]),
  10824. vertexShader: ShaderChunk.meshphysical_vert,
  10825. fragmentShader: ShaderChunk.meshphysical_frag
  10826. };
  10827. /**
  10828. * @author mrdoob / http://mrdoob.com/
  10829. */
  10830. function WebGLAnimation() {
  10831. var context = null;
  10832. var isAnimating = false;
  10833. var animationLoop = null;
  10834. function onAnimationFrame(time, frame) {
  10835. if (isAnimating === false) return;
  10836. animationLoop(time, frame);
  10837. context.requestAnimationFrame(onAnimationFrame);
  10838. }
  10839. return {
  10840. start: function () {
  10841. if (isAnimating === true) return;
  10842. if (animationLoop === null) return;
  10843. context.requestAnimationFrame(onAnimationFrame);
  10844. isAnimating = true;
  10845. },
  10846. stop: function () {
  10847. isAnimating = false;
  10848. },
  10849. setAnimationLoop: function (callback) {
  10850. animationLoop = callback;
  10851. },
  10852. setContext: function (value) {
  10853. context = value;
  10854. }
  10855. };
  10856. }
  10857. /**
  10858. * @author mrdoob / http://mrdoob.com/
  10859. */
  10860. function WebGLAttributes(gl) {
  10861. var buffers = new WeakMap();
  10862. function createBuffer(attribute, bufferType) {
  10863. var array = attribute.array;
  10864. var usage = attribute.dynamic ? 35048 : 35044;
  10865. var buffer = gl.createBuffer();
  10866. gl.bindBuffer(bufferType, buffer);
  10867. gl.bufferData(bufferType, array, usage);
  10868. attribute.onUploadCallback();
  10869. var type = 5126;
  10870. if (array instanceof Float32Array) {
  10871. type = 5126;
  10872. } else if (array instanceof Float64Array) {
  10873. console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');
  10874. } else if (array instanceof Uint16Array) {
  10875. type = 5123;
  10876. } else if (array instanceof Int16Array) {
  10877. type = 5122;
  10878. } else if (array instanceof Uint32Array) {
  10879. type = 5125;
  10880. } else if (array instanceof Int32Array) {
  10881. type = 5124;
  10882. } else if (array instanceof Int8Array) {
  10883. type = 5120;
  10884. } else if (array instanceof Uint8Array) {
  10885. type = 5121;
  10886. }
  10887. return {
  10888. buffer: buffer,
  10889. type: type,
  10890. bytesPerElement: array.BYTES_PER_ELEMENT,
  10891. version: attribute.version
  10892. };
  10893. }
  10894. function updateBuffer(buffer, attribute, bufferType) {
  10895. var array = attribute.array;
  10896. var updateRange = attribute.updateRange;
  10897. gl.bindBuffer(bufferType, buffer);
  10898. if (attribute.dynamic === false) {
  10899. gl.bufferData(bufferType, array, 35044);
  10900. } else if (updateRange.count === -1) {
  10901. // Not using update ranges
  10902. gl.bufferSubData(bufferType, 0, array);
  10903. } else if (updateRange.count === 0) {
  10904. 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.');
  10905. } else {
  10906. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
  10907. updateRange.count = -1; // reset range
  10908. }
  10909. } //
  10910. function get(attribute) {
  10911. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  10912. return buffers.get(attribute);
  10913. }
  10914. function remove(attribute) {
  10915. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  10916. var data = buffers.get(attribute);
  10917. if (data) {
  10918. gl.deleteBuffer(data.buffer);
  10919. buffers.delete(attribute);
  10920. }
  10921. }
  10922. function update(attribute, bufferType) {
  10923. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  10924. var data = buffers.get(attribute);
  10925. if (data === undefined) {
  10926. buffers.set(attribute, createBuffer(attribute, bufferType));
  10927. } else if (data.version < attribute.version) {
  10928. updateBuffer(data.buffer, attribute, bufferType);
  10929. data.version = attribute.version;
  10930. }
  10931. }
  10932. return {
  10933. get: get,
  10934. remove: remove,
  10935. update: update
  10936. };
  10937. }
  10938. /**
  10939. * @author mrdoob / http://mrdoob.com/
  10940. * @author Mugen87 / https://github.com/Mugen87
  10941. */
  10942. // PlaneGeometry
  10943. function PlaneGeometry(width, height, widthSegments, heightSegments) {
  10944. Geometry.call(this);
  10945. this.type = 'PlaneGeometry';
  10946. this.parameters = {
  10947. width: width,
  10948. height: height,
  10949. widthSegments: widthSegments,
  10950. heightSegments: heightSegments
  10951. };
  10952. this.fromBufferGeometry(new PlaneBufferGeometry(width, height, widthSegments, heightSegments));
  10953. this.mergeVertices();
  10954. }
  10955. PlaneGeometry.prototype = Object.create(Geometry.prototype);
  10956. PlaneGeometry.prototype.constructor = PlaneGeometry; // PlaneBufferGeometry
  10957. function PlaneBufferGeometry(width, height, widthSegments, heightSegments) {
  10958. BufferGeometry.call(this);
  10959. this.type = 'PlaneBufferGeometry';
  10960. this.parameters = {
  10961. width: width,
  10962. height: height,
  10963. widthSegments: widthSegments,
  10964. heightSegments: heightSegments
  10965. };
  10966. width = width || 1;
  10967. height = height || 1;
  10968. var width_half = width / 2;
  10969. var height_half = height / 2;
  10970. var gridX = Math.floor(widthSegments) || 1;
  10971. var gridY = Math.floor(heightSegments) || 1;
  10972. var gridX1 = gridX + 1;
  10973. var gridY1 = gridY + 1;
  10974. var segment_width = width / gridX;
  10975. var segment_height = height / gridY;
  10976. var ix, iy; // buffers
  10977. var indices = [];
  10978. var vertices = [];
  10979. var normals = [];
  10980. var uvs = []; // generate vertices, normals and uvs
  10981. for (iy = 0; iy < gridY1; iy++) {
  10982. var y = iy * segment_height - height_half;
  10983. for (ix = 0; ix < gridX1; ix++) {
  10984. var x = ix * segment_width - width_half;
  10985. vertices.push(x, -y, 0);
  10986. normals.push(0, 0, 1);
  10987. uvs.push(ix / gridX);
  10988. uvs.push(1 - iy / gridY);
  10989. }
  10990. } // indices
  10991. for (iy = 0; iy < gridY; iy++) {
  10992. for (ix = 0; ix < gridX; ix++) {
  10993. var a = ix + gridX1 * iy;
  10994. var b = ix + gridX1 * (iy + 1);
  10995. var c = ix + 1 + gridX1 * (iy + 1);
  10996. var d = ix + 1 + gridX1 * iy; // faces
  10997. indices.push(a, b, d);
  10998. indices.push(b, c, d);
  10999. }
  11000. } // build geometry
  11001. this.setIndex(indices);
  11002. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  11003. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  11004. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  11005. }
  11006. PlaneBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  11007. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  11008. /**
  11009. * @author mrdoob / http://mrdoob.com/
  11010. */
  11011. function WebGLBackground(renderer, state, objects, premultipliedAlpha) {
  11012. var clearColor = new Color(0x000000);
  11013. var clearAlpha = 0;
  11014. var planeMesh;
  11015. var boxMesh; // Store the current background texture and its `version`
  11016. // so we can recompile the material accordingly.
  11017. var currentBackground = null;
  11018. var currentBackgroundVersion = 0;
  11019. function render(renderList, scene, camera, forceClear) {
  11020. var background = scene.background; // Ignore background in AR
  11021. // TODO: Reconsider this.
  11022. var vr = renderer.vr;
  11023. var session = vr.getSession && vr.getSession();
  11024. if (session && session.environmentBlendMode === 'additive') {
  11025. background = null;
  11026. }
  11027. if (background === null) {
  11028. setClear(clearColor, clearAlpha);
  11029. currentBackground = null;
  11030. currentBackgroundVersion = 0;
  11031. } else if (background && background.isColor) {
  11032. setClear(background, 1);
  11033. forceClear = true;
  11034. currentBackground = null;
  11035. currentBackgroundVersion = 0;
  11036. }
  11037. if (renderer.autoClear || forceClear) {
  11038. renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
  11039. }
  11040. if (background && (background.isCubeTexture || background.isWebGLRenderTargetCube)) {
  11041. if (boxMesh === undefined) {
  11042. boxMesh = new Mesh(new BoxBufferGeometry(1, 1, 1), new ShaderMaterial({
  11043. type: 'BackgroundCubeMaterial',
  11044. uniforms: cloneUniforms(ShaderLib.cube.uniforms),
  11045. vertexShader: ShaderLib.cube.vertexShader,
  11046. fragmentShader: ShaderLib.cube.fragmentShader,
  11047. side: BackSide,
  11048. depthTest: false,
  11049. depthWrite: false,
  11050. fog: false
  11051. }));
  11052. boxMesh.geometry.removeAttribute('normal');
  11053. boxMesh.geometry.removeAttribute('uv');
  11054. boxMesh.onBeforeRender = function (renderer, scene, camera) {
  11055. this.matrixWorld.copyPosition(camera.matrixWorld);
  11056. }; // enable code injection for non-built-in material
  11057. Object.defineProperty(boxMesh.material, 'map', {
  11058. get: function () {
  11059. return this.uniforms.tCube.value;
  11060. }
  11061. });
  11062. objects.update(boxMesh);
  11063. }
  11064. var texture = background.isWebGLRenderTargetCube ? background.texture : background;
  11065. boxMesh.material.uniforms.tCube.value = texture;
  11066. boxMesh.material.uniforms.tFlip.value = background.isWebGLRenderTargetCube ? 1 : -1;
  11067. if (currentBackground !== background || currentBackgroundVersion !== texture.version) {
  11068. boxMesh.material.needsUpdate = true;
  11069. currentBackground = background;
  11070. currentBackgroundVersion = texture.version;
  11071. } // push to the pre-sorted opaque render list
  11072. renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
  11073. } else if (background && background.isTexture) {
  11074. if (planeMesh === undefined) {
  11075. planeMesh = new Mesh(new PlaneBufferGeometry(2, 2), new ShaderMaterial({
  11076. type: 'BackgroundMaterial',
  11077. uniforms: cloneUniforms(ShaderLib.background.uniforms),
  11078. vertexShader: ShaderLib.background.vertexShader,
  11079. fragmentShader: ShaderLib.background.fragmentShader,
  11080. side: FrontSide,
  11081. depthTest: false,
  11082. depthWrite: false,
  11083. fog: false
  11084. }));
  11085. planeMesh.geometry.removeAttribute('normal'); // enable code injection for non-built-in material
  11086. Object.defineProperty(planeMesh.material, 'map', {
  11087. get: function () {
  11088. return this.uniforms.t2D.value;
  11089. }
  11090. });
  11091. objects.update(planeMesh);
  11092. }
  11093. planeMesh.material.uniforms.t2D.value = background;
  11094. if (background.matrixAutoUpdate === true) {
  11095. background.updateMatrix();
  11096. }
  11097. planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
  11098. if (currentBackground !== background || currentBackgroundVersion !== background.version) {
  11099. planeMesh.material.needsUpdate = true;
  11100. currentBackground = background;
  11101. currentBackgroundVersion = background.version;
  11102. } // push to the pre-sorted opaque render list
  11103. renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
  11104. }
  11105. }
  11106. function setClear(color, alpha) {
  11107. state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);
  11108. }
  11109. return {
  11110. getClearColor: function () {
  11111. return clearColor;
  11112. },
  11113. setClearColor: function (color, alpha) {
  11114. clearColor.set(color);
  11115. clearAlpha = alpha !== undefined ? alpha : 1;
  11116. setClear(clearColor, clearAlpha);
  11117. },
  11118. getClearAlpha: function () {
  11119. return clearAlpha;
  11120. },
  11121. setClearAlpha: function (alpha) {
  11122. clearAlpha = alpha;
  11123. setClear(clearColor, clearAlpha);
  11124. },
  11125. render: render
  11126. };
  11127. }
  11128. /**
  11129. * @author mrdoob / http://mrdoob.com/
  11130. */
  11131. function WebGLBufferRenderer(gl, extensions, info, capabilities) {
  11132. var mode;
  11133. function setMode(value) {
  11134. mode = value;
  11135. }
  11136. function render(start, count) {
  11137. gl.drawArrays(mode, start, count);
  11138. info.update(count, mode);
  11139. }
  11140. function renderInstances(geometry, start, count, primcount) {
  11141. if (primcount === 0) return;
  11142. var extension, methodName;
  11143. if (capabilities.isWebGL2) {
  11144. extension = gl;
  11145. methodName = 'drawArraysInstanced';
  11146. } else {
  11147. extension = extensions.get('ANGLE_instanced_arrays');
  11148. methodName = 'drawArraysInstancedANGLE';
  11149. if (extension === null) {
  11150. console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  11151. return;
  11152. }
  11153. }
  11154. extension[methodName](mode, start, count, primcount);
  11155. info.update(count, mode, primcount);
  11156. } //
  11157. this.setMode = setMode;
  11158. this.render = render;
  11159. this.renderInstances = renderInstances;
  11160. }
  11161. /**
  11162. * @author mrdoob / http://mrdoob.com/
  11163. */
  11164. function WebGLCapabilities(gl, extensions, parameters) {
  11165. var maxAnisotropy;
  11166. function getMaxAnisotropy() {
  11167. if (maxAnisotropy !== undefined) return maxAnisotropy;
  11168. var extension = extensions.get('EXT_texture_filter_anisotropic');
  11169. if (extension !== null) {
  11170. maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  11171. } else {
  11172. maxAnisotropy = 0;
  11173. }
  11174. return maxAnisotropy;
  11175. }
  11176. function getMaxPrecision(precision) {
  11177. if (precision === 'highp') {
  11178. if (gl.getShaderPrecisionFormat(35633, 36338).precision > 0 && gl.getShaderPrecisionFormat(35632, 36338).precision > 0) {
  11179. return 'highp';
  11180. }
  11181. precision = 'mediump';
  11182. }
  11183. if (precision === 'mediump') {
  11184. if (gl.getShaderPrecisionFormat(35633, 36337).precision > 0 && gl.getShaderPrecisionFormat(35632, 36337).precision > 0) {
  11185. return 'mediump';
  11186. }
  11187. }
  11188. return 'lowp';
  11189. }
  11190. var isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext;
  11191. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  11192. var maxPrecision = getMaxPrecision(precision);
  11193. if (maxPrecision !== precision) {
  11194. console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
  11195. precision = maxPrecision;
  11196. }
  11197. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  11198. var maxTextures = gl.getParameter(34930);
  11199. var maxVertexTextures = gl.getParameter(35660);
  11200. var maxTextureSize = gl.getParameter(3379);
  11201. var maxCubemapSize = gl.getParameter(34076);
  11202. var maxAttributes = gl.getParameter(34921);
  11203. var maxVertexUniforms = gl.getParameter(36347);
  11204. var maxVaryings = gl.getParameter(36348);
  11205. var maxFragmentUniforms = gl.getParameter(36349);
  11206. var vertexTextures = maxVertexTextures > 0;
  11207. var floatFragmentTextures = isWebGL2 || !!extensions.get('OES_texture_float');
  11208. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  11209. var maxSamples = isWebGL2 ? gl.getParameter(36183) : 0;
  11210. return {
  11211. isWebGL2: isWebGL2,
  11212. getMaxAnisotropy: getMaxAnisotropy,
  11213. getMaxPrecision: getMaxPrecision,
  11214. precision: precision,
  11215. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11216. maxTextures: maxTextures,
  11217. maxVertexTextures: maxVertexTextures,
  11218. maxTextureSize: maxTextureSize,
  11219. maxCubemapSize: maxCubemapSize,
  11220. maxAttributes: maxAttributes,
  11221. maxVertexUniforms: maxVertexUniforms,
  11222. maxVaryings: maxVaryings,
  11223. maxFragmentUniforms: maxFragmentUniforms,
  11224. vertexTextures: vertexTextures,
  11225. floatFragmentTextures: floatFragmentTextures,
  11226. floatVertexTextures: floatVertexTextures,
  11227. maxSamples: maxSamples
  11228. };
  11229. }
  11230. /**
  11231. * @author tschw
  11232. */
  11233. function WebGLClipping() {
  11234. var scope = this,
  11235. globalState = null,
  11236. numGlobalPlanes = 0,
  11237. localClippingEnabled = false,
  11238. renderingShadows = false,
  11239. plane = new Plane(),
  11240. viewNormalMatrix = new Matrix3(),
  11241. uniform = {
  11242. value: null,
  11243. needsUpdate: false
  11244. };
  11245. this.uniform = uniform;
  11246. this.numPlanes = 0;
  11247. this.numIntersection = 0;
  11248. this.init = function (planes, enableLocalClipping, camera) {
  11249. var enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
  11250. // run another frame in order to reset the state:
  11251. numGlobalPlanes !== 0 || localClippingEnabled;
  11252. localClippingEnabled = enableLocalClipping;
  11253. globalState = projectPlanes(planes, camera, 0);
  11254. numGlobalPlanes = planes.length;
  11255. return enabled;
  11256. };
  11257. this.beginShadows = function () {
  11258. renderingShadows = true;
  11259. projectPlanes(null);
  11260. };
  11261. this.endShadows = function () {
  11262. renderingShadows = false;
  11263. resetGlobalState();
  11264. };
  11265. this.setState = function (planes, clipIntersection, clipShadows, camera, cache, fromCache) {
  11266. if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
  11267. // there's no local clipping
  11268. if (renderingShadows) {
  11269. // there's no global clipping
  11270. projectPlanes(null);
  11271. } else {
  11272. resetGlobalState();
  11273. }
  11274. } else {
  11275. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  11276. lGlobal = nGlobal * 4,
  11277. dstArray = cache.clippingState || null;
  11278. uniform.value = dstArray; // ensure unique state
  11279. dstArray = projectPlanes(planes, camera, lGlobal, fromCache);
  11280. for (var i = 0; i !== lGlobal; ++i) {
  11281. dstArray[i] = globalState[i];
  11282. }
  11283. cache.clippingState = dstArray;
  11284. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  11285. this.numPlanes += nGlobal;
  11286. }
  11287. };
  11288. function resetGlobalState() {
  11289. if (uniform.value !== globalState) {
  11290. uniform.value = globalState;
  11291. uniform.needsUpdate = numGlobalPlanes > 0;
  11292. }
  11293. scope.numPlanes = numGlobalPlanes;
  11294. scope.numIntersection = 0;
  11295. }
  11296. function projectPlanes(planes, camera, dstOffset, skipTransform) {
  11297. var nPlanes = planes !== null ? planes.length : 0,
  11298. dstArray = null;
  11299. if (nPlanes !== 0) {
  11300. dstArray = uniform.value;
  11301. if (skipTransform !== true || dstArray === null) {
  11302. var flatSize = dstOffset + nPlanes * 4,
  11303. viewMatrix = camera.matrixWorldInverse;
  11304. viewNormalMatrix.getNormalMatrix(viewMatrix);
  11305. if (dstArray === null || dstArray.length < flatSize) {
  11306. dstArray = new Float32Array(flatSize);
  11307. }
  11308. for (var i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
  11309. plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
  11310. plane.normal.toArray(dstArray, i4);
  11311. dstArray[i4 + 3] = plane.constant;
  11312. }
  11313. }
  11314. uniform.value = dstArray;
  11315. uniform.needsUpdate = true;
  11316. }
  11317. scope.numPlanes = nPlanes;
  11318. return dstArray;
  11319. }
  11320. }
  11321. /**
  11322. * @author mrdoob / http://mrdoob.com/
  11323. */
  11324. function WebGLExtensions(gl) {
  11325. var extensions = {};
  11326. return {
  11327. get: function (name) {
  11328. if (extensions[name] !== undefined) {
  11329. return extensions[name];
  11330. }
  11331. var extension;
  11332. switch (name) {
  11333. case 'WEBGL_depth_texture':
  11334. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  11335. break;
  11336. case 'EXT_texture_filter_anisotropic':
  11337. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  11338. break;
  11339. case 'WEBGL_compressed_texture_s3tc':
  11340. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11341. break;
  11342. case 'WEBGL_compressed_texture_pvrtc':
  11343. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11344. break;
  11345. default:
  11346. extension = gl.getExtension(name);
  11347. }
  11348. if (extension === null) {
  11349. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  11350. }
  11351. extensions[name] = extension;
  11352. return extension;
  11353. }
  11354. };
  11355. }
  11356. /**
  11357. * @author mrdoob / http://mrdoob.com/
  11358. */
  11359. function WebGLGeometries(gl, attributes, info) {
  11360. var geometries = new WeakMap();
  11361. var wireframeAttributes = new WeakMap();
  11362. function onGeometryDispose(event) {
  11363. var geometry = event.target;
  11364. var buffergeometry = geometries.get(geometry);
  11365. if (buffergeometry.index !== null) {
  11366. attributes.remove(buffergeometry.index);
  11367. }
  11368. for (var name in buffergeometry.attributes) {
  11369. attributes.remove(buffergeometry.attributes[name]);
  11370. }
  11371. geometry.removeEventListener('dispose', onGeometryDispose);
  11372. geometries.delete(geometry);
  11373. var attribute = wireframeAttributes.get(buffergeometry);
  11374. if (attribute) {
  11375. attributes.remove(attribute);
  11376. wireframeAttributes.delete(buffergeometry);
  11377. } //
  11378. info.memory.geometries--;
  11379. }
  11380. function get(object, geometry) {
  11381. var buffergeometry = geometries.get(geometry);
  11382. if (buffergeometry) return buffergeometry;
  11383. geometry.addEventListener('dispose', onGeometryDispose);
  11384. if (geometry.isBufferGeometry) {
  11385. buffergeometry = geometry;
  11386. } else if (geometry.isGeometry) {
  11387. if (geometry._bufferGeometry === undefined) {
  11388. geometry._bufferGeometry = new BufferGeometry().setFromObject(object);
  11389. }
  11390. buffergeometry = geometry._bufferGeometry;
  11391. }
  11392. geometries.set(geometry, buffergeometry);
  11393. info.memory.geometries++;
  11394. return buffergeometry;
  11395. }
  11396. function update(geometry) {
  11397. var index = geometry.index;
  11398. var geometryAttributes = geometry.attributes;
  11399. if (index !== null) {
  11400. attributes.update(index, 34963);
  11401. }
  11402. for (var name in geometryAttributes) {
  11403. attributes.update(geometryAttributes[name], 34962);
  11404. } // morph targets
  11405. var morphAttributes = geometry.morphAttributes;
  11406. for (var name in morphAttributes) {
  11407. var array = morphAttributes[name];
  11408. for (var i = 0, l = array.length; i < l; i++) {
  11409. attributes.update(array[i], 34962);
  11410. }
  11411. }
  11412. }
  11413. function updateWireframeAttribute(geometry) {
  11414. var indices = [];
  11415. var geometryIndex = geometry.index;
  11416. var geometryPosition = geometry.attributes.position;
  11417. var version = 0;
  11418. if (geometryIndex !== null) {
  11419. var array = geometryIndex.array;
  11420. version = geometryIndex.version;
  11421. for (var i = 0, l = array.length; i < l; i += 3) {
  11422. var a = array[i + 0];
  11423. var b = array[i + 1];
  11424. var c = array[i + 2];
  11425. indices.push(a, b, b, c, c, a);
  11426. }
  11427. } else {
  11428. var array = geometryPosition.array;
  11429. version = geometryPosition.version;
  11430. for (var i = 0, l = array.length / 3 - 1; i < l; i += 3) {
  11431. var a = i + 0;
  11432. var b = i + 1;
  11433. var c = i + 2;
  11434. indices.push(a, b, b, c, c, a);
  11435. }
  11436. }
  11437. var attribute = new (arrayMax(indices) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
  11438. attribute.version = version;
  11439. attributes.update(attribute, 34963); //
  11440. var previousAttribute = wireframeAttributes.get(geometry);
  11441. if (previousAttribute) attributes.remove(previousAttribute); //
  11442. wireframeAttributes.set(geometry, attribute);
  11443. }
  11444. function getWireframeAttribute(geometry) {
  11445. var currentAttribute = wireframeAttributes.get(geometry);
  11446. if (currentAttribute) {
  11447. var geometryIndex = geometry.index;
  11448. if (geometryIndex !== null) {
  11449. // if the attribute is obsolete, create a new one
  11450. if (currentAttribute.version < geometryIndex.version) {
  11451. updateWireframeAttribute(geometry);
  11452. }
  11453. }
  11454. } else {
  11455. updateWireframeAttribute(geometry);
  11456. }
  11457. return wireframeAttributes.get(geometry);
  11458. }
  11459. return {
  11460. get: get,
  11461. update: update,
  11462. getWireframeAttribute: getWireframeAttribute
  11463. };
  11464. }
  11465. /**
  11466. * @author mrdoob / http://mrdoob.com/
  11467. */
  11468. function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
  11469. var mode;
  11470. function setMode(value) {
  11471. mode = value;
  11472. }
  11473. var type, bytesPerElement;
  11474. function setIndex(value) {
  11475. type = value.type;
  11476. bytesPerElement = value.bytesPerElement;
  11477. }
  11478. function render(start, count) {
  11479. gl.drawElements(mode, count, type, start * bytesPerElement);
  11480. info.update(count, mode);
  11481. }
  11482. function renderInstances(geometry, start, count, primcount) {
  11483. if (primcount === 0) return;
  11484. var extension, methodName;
  11485. if (capabilities.isWebGL2) {
  11486. extension = gl;
  11487. methodName = 'drawElementsInstanced';
  11488. } else {
  11489. extension = extensions.get('ANGLE_instanced_arrays');
  11490. methodName = 'drawElementsInstancedANGLE';
  11491. if (extension === null) {
  11492. console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  11493. return;
  11494. }
  11495. }
  11496. extension[methodName](mode, count, type, start * bytesPerElement, primcount);
  11497. info.update(count, mode, primcount);
  11498. } //
  11499. this.setMode = setMode;
  11500. this.setIndex = setIndex;
  11501. this.render = render;
  11502. this.renderInstances = renderInstances;
  11503. }
  11504. /**
  11505. * @author Mugen87 / https://github.com/Mugen87
  11506. */
  11507. function WebGLInfo(gl) {
  11508. var memory = {
  11509. geometries: 0,
  11510. textures: 0
  11511. };
  11512. var render = {
  11513. frame: 0,
  11514. calls: 0,
  11515. triangles: 0,
  11516. points: 0,
  11517. lines: 0
  11518. };
  11519. function update(count, mode, instanceCount) {
  11520. instanceCount = instanceCount || 1;
  11521. render.calls++;
  11522. switch (mode) {
  11523. case 4:
  11524. render.triangles += instanceCount * (count / 3);
  11525. break;
  11526. case 5:
  11527. case 6:
  11528. render.triangles += instanceCount * (count - 2);
  11529. break;
  11530. case 1:
  11531. render.lines += instanceCount * (count / 2);
  11532. break;
  11533. case 3:
  11534. render.lines += instanceCount * (count - 1);
  11535. break;
  11536. case 2:
  11537. render.lines += instanceCount * count;
  11538. break;
  11539. case 0:
  11540. render.points += instanceCount * count;
  11541. break;
  11542. default:
  11543. console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
  11544. break;
  11545. }
  11546. }
  11547. function reset() {
  11548. render.frame++;
  11549. render.calls = 0;
  11550. render.triangles = 0;
  11551. render.points = 0;
  11552. render.lines = 0;
  11553. }
  11554. return {
  11555. memory: memory,
  11556. render: render,
  11557. programs: null,
  11558. autoReset: true,
  11559. reset: reset,
  11560. update: update
  11561. };
  11562. }
  11563. /**
  11564. * @author mrdoob / http://mrdoob.com/
  11565. */
  11566. function absNumericalSort(a, b) {
  11567. return Math.abs(b[1]) - Math.abs(a[1]);
  11568. }
  11569. function WebGLMorphtargets(gl) {
  11570. var influencesList = {};
  11571. var morphInfluences = new Float32Array(8);
  11572. function update(object, geometry, material, program) {
  11573. var objectInfluences = object.morphTargetInfluences;
  11574. var length = objectInfluences.length;
  11575. var influences = influencesList[geometry.id];
  11576. if (influences === undefined) {
  11577. // initialise list
  11578. influences = [];
  11579. for (var i = 0; i < length; i++) {
  11580. influences[i] = [i, 0];
  11581. }
  11582. influencesList[geometry.id] = influences;
  11583. }
  11584. var morphTargets = material.morphTargets && geometry.morphAttributes.position;
  11585. var morphNormals = material.morphNormals && geometry.morphAttributes.normal; // Remove current morphAttributes
  11586. for (var i = 0; i < length; i++) {
  11587. var influence = influences[i];
  11588. if (influence[1] !== 0) {
  11589. if (morphTargets) geometry.removeAttribute('morphTarget' + i);
  11590. if (morphNormals) geometry.removeAttribute('morphNormal' + i);
  11591. }
  11592. } // Collect influences
  11593. for (var i = 0; i < length; i++) {
  11594. var influence = influences[i];
  11595. influence[0] = i;
  11596. influence[1] = objectInfluences[i];
  11597. }
  11598. influences.sort(absNumericalSort); // Add morphAttributes
  11599. for (var i = 0; i < 8; i++) {
  11600. var influence = influences[i];
  11601. if (influence) {
  11602. var index = influence[0];
  11603. var value = influence[1];
  11604. if (value) {
  11605. if (morphTargets) geometry.addAttribute('morphTarget' + i, morphTargets[index]);
  11606. if (morphNormals) geometry.addAttribute('morphNormal' + i, morphNormals[index]);
  11607. morphInfluences[i] = value;
  11608. continue;
  11609. }
  11610. }
  11611. morphInfluences[i] = 0;
  11612. }
  11613. program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
  11614. }
  11615. return {
  11616. update: update
  11617. };
  11618. }
  11619. /**
  11620. * @author mrdoob / http://mrdoob.com/
  11621. */
  11622. function WebGLObjects(gl, geometries, attributes, info) {
  11623. var updateList = {};
  11624. function update(object) {
  11625. var frame = info.render.frame;
  11626. var geometry = object.geometry;
  11627. var buffergeometry = geometries.get(object, geometry); // Update once per frame
  11628. if (updateList[buffergeometry.id] !== frame) {
  11629. if (geometry.isGeometry) {
  11630. buffergeometry.updateFromObject(object);
  11631. }
  11632. geometries.update(buffergeometry);
  11633. updateList[buffergeometry.id] = frame;
  11634. }
  11635. if (object.isInstancedMesh) {
  11636. attributes.update(object.instanceMatrix, 34962);
  11637. }
  11638. return buffergeometry;
  11639. }
  11640. function dispose() {
  11641. updateList = {};
  11642. }
  11643. return {
  11644. update: update,
  11645. dispose: dispose
  11646. };
  11647. }
  11648. /**
  11649. * @author mrdoob / http://mrdoob.com/
  11650. */
  11651. function CubeTexture(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  11652. images = images !== undefined ? images : [];
  11653. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  11654. format = format !== undefined ? format : RGBFormat;
  11655. Texture.call(this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  11656. this.flipY = false;
  11657. }
  11658. CubeTexture.prototype = Object.create(Texture.prototype);
  11659. CubeTexture.prototype.constructor = CubeTexture;
  11660. CubeTexture.prototype.isCubeTexture = true;
  11661. Object.defineProperty(CubeTexture.prototype, 'images', {
  11662. get: function () {
  11663. return this.image;
  11664. },
  11665. set: function (value) {
  11666. this.image = value;
  11667. }
  11668. });
  11669. /**
  11670. * @author Takahiro https://github.com/takahirox
  11671. */
  11672. function DataTexture2DArray(data, width, height, depth) {
  11673. Texture.call(this, null);
  11674. this.image = {
  11675. data: data || null,
  11676. width: width || 1,
  11677. height: height || 1,
  11678. depth: depth || 1
  11679. };
  11680. this.magFilter = NearestFilter;
  11681. this.minFilter = NearestFilter;
  11682. this.wrapR = ClampToEdgeWrapping;
  11683. this.generateMipmaps = false;
  11684. this.flipY = false;
  11685. this.needsUpdate = true;
  11686. }
  11687. DataTexture2DArray.prototype = Object.create(Texture.prototype);
  11688. DataTexture2DArray.prototype.constructor = DataTexture2DArray;
  11689. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  11690. /**
  11691. * @author Artur Trzesiok
  11692. */
  11693. function DataTexture3D(data, width, height, depth) {
  11694. // We're going to add .setXXX() methods for setting properties later.
  11695. // Users can still set in DataTexture3D directly.
  11696. //
  11697. // var texture = new THREE.DataTexture3D( data, width, height, depth );
  11698. // texture.anisotropy = 16;
  11699. //
  11700. // See #14839
  11701. Texture.call(this, null);
  11702. this.image = {
  11703. data: data || null,
  11704. width: width || 1,
  11705. height: height || 1,
  11706. depth: depth || 1
  11707. };
  11708. this.magFilter = NearestFilter;
  11709. this.minFilter = NearestFilter;
  11710. this.wrapR = ClampToEdgeWrapping;
  11711. this.generateMipmaps = false;
  11712. this.flipY = false;
  11713. this.needsUpdate = true;
  11714. }
  11715. DataTexture3D.prototype = Object.create(Texture.prototype);
  11716. DataTexture3D.prototype.constructor = DataTexture3D;
  11717. DataTexture3D.prototype.isDataTexture3D = true;
  11718. /**
  11719. * @author tschw
  11720. * @author Mugen87 / https://github.com/Mugen87
  11721. * @author mrdoob / http://mrdoob.com/
  11722. *
  11723. * Uniforms of a program.
  11724. * Those form a tree structure with a special top-level container for the root,
  11725. * which you get by calling 'new WebGLUniforms( gl, program )'.
  11726. *
  11727. *
  11728. * Properties of inner nodes including the top-level container:
  11729. *
  11730. * .seq - array of nested uniforms
  11731. * .map - nested uniforms by name
  11732. *
  11733. *
  11734. * Methods of all nodes except the top-level container:
  11735. *
  11736. * .setValue( gl, value, [textures] )
  11737. *
  11738. * uploads a uniform value(s)
  11739. * the 'textures' parameter is needed for sampler uniforms
  11740. *
  11741. *
  11742. * Static methods of the top-level container (textures factorizations):
  11743. *
  11744. * .upload( gl, seq, values, textures )
  11745. *
  11746. * sets uniforms in 'seq' to 'values[id].value'
  11747. *
  11748. * .seqWithValue( seq, values ) : filteredSeq
  11749. *
  11750. * filters 'seq' entries with corresponding entry in values
  11751. *
  11752. *
  11753. * Methods of the top-level container (textures factorizations):
  11754. *
  11755. * .setValue( gl, name, value, textures )
  11756. *
  11757. * sets uniform with name 'name' to 'value'
  11758. *
  11759. * .setOptional( gl, obj, prop )
  11760. *
  11761. * like .set for an optional property of the object
  11762. *
  11763. */
  11764. var emptyTexture = new Texture();
  11765. var emptyTexture2dArray = new DataTexture2DArray();
  11766. var emptyTexture3d = new DataTexture3D();
  11767. var emptyCubeTexture = new CubeTexture(); // --- Utilities ---
  11768. // Array Caches (provide typed arrays for temporary by size)
  11769. var arrayCacheF32 = [];
  11770. var arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
  11771. var mat4array = new Float32Array(16);
  11772. var mat3array = new Float32Array(9);
  11773. var mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
  11774. function flatten(array, nBlocks, blockSize) {
  11775. var firstElem = array[0];
  11776. if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
  11777. // see http://jacksondunstan.com/articles/983
  11778. var n = nBlocks * blockSize,
  11779. r = arrayCacheF32[n];
  11780. if (r === undefined) {
  11781. r = new Float32Array(n);
  11782. arrayCacheF32[n] = r;
  11783. }
  11784. if (nBlocks !== 0) {
  11785. firstElem.toArray(r, 0);
  11786. for (var i = 1, offset = 0; i !== nBlocks; ++i) {
  11787. offset += blockSize;
  11788. array[i].toArray(r, offset);
  11789. }
  11790. }
  11791. return r;
  11792. }
  11793. function arraysEqual(a, b) {
  11794. if (a.length !== b.length) return false;
  11795. for (var i = 0, l = a.length; i < l; i++) {
  11796. if (a[i] !== b[i]) return false;
  11797. }
  11798. return true;
  11799. }
  11800. function copyArray(a, b) {
  11801. for (var i = 0, l = b.length; i < l; i++) {
  11802. a[i] = b[i];
  11803. }
  11804. } // Texture unit allocation
  11805. function allocTexUnits(textures, n) {
  11806. var r = arrayCacheI32[n];
  11807. if (r === undefined) {
  11808. r = new Int32Array(n);
  11809. arrayCacheI32[n] = r;
  11810. }
  11811. for (var i = 0; i !== n; ++i) r[i] = textures.allocateTextureUnit();
  11812. return r;
  11813. } // --- Setters ---
  11814. // Note: Defining these methods externally, because they come in a bunch
  11815. // and this way their names minify.
  11816. // Single scalar
  11817. function setValueV1f(gl, v) {
  11818. var cache = this.cache;
  11819. if (cache[0] === v) return;
  11820. gl.uniform1f(this.addr, v);
  11821. cache[0] = v;
  11822. } // Single float vector (from flat array or THREE.VectorN)
  11823. function setValueV2f(gl, v) {
  11824. var cache = this.cache;
  11825. if (v.x !== undefined) {
  11826. if (cache[0] !== v.x || cache[1] !== v.y) {
  11827. gl.uniform2f(this.addr, v.x, v.y);
  11828. cache[0] = v.x;
  11829. cache[1] = v.y;
  11830. }
  11831. } else {
  11832. if (arraysEqual(cache, v)) return;
  11833. gl.uniform2fv(this.addr, v);
  11834. copyArray(cache, v);
  11835. }
  11836. }
  11837. function setValueV3f(gl, v) {
  11838. var cache = this.cache;
  11839. if (v.x !== undefined) {
  11840. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  11841. gl.uniform3f(this.addr, v.x, v.y, v.z);
  11842. cache[0] = v.x;
  11843. cache[1] = v.y;
  11844. cache[2] = v.z;
  11845. }
  11846. } else if (v.r !== undefined) {
  11847. if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
  11848. gl.uniform3f(this.addr, v.r, v.g, v.b);
  11849. cache[0] = v.r;
  11850. cache[1] = v.g;
  11851. cache[2] = v.b;
  11852. }
  11853. } else {
  11854. if (arraysEqual(cache, v)) return;
  11855. gl.uniform3fv(this.addr, v);
  11856. copyArray(cache, v);
  11857. }
  11858. }
  11859. function setValueV4f(gl, v) {
  11860. var cache = this.cache;
  11861. if (v.x !== undefined) {
  11862. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  11863. gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
  11864. cache[0] = v.x;
  11865. cache[1] = v.y;
  11866. cache[2] = v.z;
  11867. cache[3] = v.w;
  11868. }
  11869. } else {
  11870. if (arraysEqual(cache, v)) return;
  11871. gl.uniform4fv(this.addr, v);
  11872. copyArray(cache, v);
  11873. }
  11874. } // Single matrix (from flat array or MatrixN)
  11875. function setValueM2(gl, v) {
  11876. var cache = this.cache;
  11877. var elements = v.elements;
  11878. if (elements === undefined) {
  11879. if (arraysEqual(cache, v)) return;
  11880. gl.uniformMatrix2fv(this.addr, false, v);
  11881. copyArray(cache, v);
  11882. } else {
  11883. if (arraysEqual(cache, elements)) return;
  11884. mat2array.set(elements);
  11885. gl.uniformMatrix2fv(this.addr, false, mat2array);
  11886. copyArray(cache, elements);
  11887. }
  11888. }
  11889. function setValueM3(gl, v) {
  11890. var cache = this.cache;
  11891. var elements = v.elements;
  11892. if (elements === undefined) {
  11893. if (arraysEqual(cache, v)) return;
  11894. gl.uniformMatrix3fv(this.addr, false, v);
  11895. copyArray(cache, v);
  11896. } else {
  11897. if (arraysEqual(cache, elements)) return;
  11898. mat3array.set(elements);
  11899. gl.uniformMatrix3fv(this.addr, false, mat3array);
  11900. copyArray(cache, elements);
  11901. }
  11902. }
  11903. function setValueM4(gl, v) {
  11904. var cache = this.cache;
  11905. var elements = v.elements;
  11906. if (elements === undefined) {
  11907. if (arraysEqual(cache, v)) return;
  11908. gl.uniformMatrix4fv(this.addr, false, v);
  11909. copyArray(cache, v);
  11910. } else {
  11911. if (arraysEqual(cache, elements)) return;
  11912. mat4array.set(elements);
  11913. gl.uniformMatrix4fv(this.addr, false, mat4array);
  11914. copyArray(cache, elements);
  11915. }
  11916. } // Single texture (2D / Cube)
  11917. function setValueT1(gl, v, textures) {
  11918. var cache = this.cache;
  11919. var unit = textures.allocateTextureUnit();
  11920. if (cache[0] !== unit) {
  11921. gl.uniform1i(this.addr, unit);
  11922. cache[0] = unit;
  11923. }
  11924. textures.safeSetTexture2D(v || emptyTexture, unit);
  11925. }
  11926. function setValueT2DArray1(gl, v, textures) {
  11927. var cache = this.cache;
  11928. var unit = textures.allocateTextureUnit();
  11929. if (cache[0] !== unit) {
  11930. gl.uniform1i(this.addr, unit);
  11931. cache[0] = unit;
  11932. }
  11933. textures.setTexture2DArray(v || emptyTexture2dArray, unit);
  11934. }
  11935. function setValueT3D1(gl, v, textures) {
  11936. var cache = this.cache;
  11937. var unit = textures.allocateTextureUnit();
  11938. if (cache[0] !== unit) {
  11939. gl.uniform1i(this.addr, unit);
  11940. cache[0] = unit;
  11941. }
  11942. textures.setTexture3D(v || emptyTexture3d, unit);
  11943. }
  11944. function setValueT6(gl, v, textures) {
  11945. var cache = this.cache;
  11946. var unit = textures.allocateTextureUnit();
  11947. if (cache[0] !== unit) {
  11948. gl.uniform1i(this.addr, unit);
  11949. cache[0] = unit;
  11950. }
  11951. textures.safeSetTextureCube(v || emptyCubeTexture, unit);
  11952. } // Integer / Boolean vectors or arrays thereof (always flat arrays)
  11953. function setValueV1i(gl, v) {
  11954. var cache = this.cache;
  11955. if (cache[0] === v) return;
  11956. gl.uniform1i(this.addr, v);
  11957. cache[0] = v;
  11958. }
  11959. function setValueV2i(gl, v) {
  11960. var cache = this.cache;
  11961. if (arraysEqual(cache, v)) return;
  11962. gl.uniform2iv(this.addr, v);
  11963. copyArray(cache, v);
  11964. }
  11965. function setValueV3i(gl, v) {
  11966. var cache = this.cache;
  11967. if (arraysEqual(cache, v)) return;
  11968. gl.uniform3iv(this.addr, v);
  11969. copyArray(cache, v);
  11970. }
  11971. function setValueV4i(gl, v) {
  11972. var cache = this.cache;
  11973. if (arraysEqual(cache, v)) return;
  11974. gl.uniform4iv(this.addr, v);
  11975. copyArray(cache, v);
  11976. } // Helper to pick the right setter for the singular case
  11977. function getSingularSetter(type) {
  11978. switch (type) {
  11979. case 0x1406:
  11980. return setValueV1f;
  11981. // FLOAT
  11982. case 0x8b50:
  11983. return setValueV2f;
  11984. // _VEC2
  11985. case 0x8b51:
  11986. return setValueV3f;
  11987. // _VEC3
  11988. case 0x8b52:
  11989. return setValueV4f;
  11990. // _VEC4
  11991. case 0x8b5a:
  11992. return setValueM2;
  11993. // _MAT2
  11994. case 0x8b5b:
  11995. return setValueM3;
  11996. // _MAT3
  11997. case 0x8b5c:
  11998. return setValueM4;
  11999. // _MAT4
  12000. case 0x8b5e:
  12001. case 0x8d66:
  12002. return setValueT1;
  12003. // SAMPLER_2D, SAMPLER_EXTERNAL_OES
  12004. case 0x8b5f:
  12005. return setValueT3D1;
  12006. // SAMPLER_3D
  12007. case 0x8b60:
  12008. return setValueT6;
  12009. // SAMPLER_CUBE
  12010. case 0x8DC1:
  12011. return setValueT2DArray1;
  12012. // SAMPLER_2D_ARRAY
  12013. case 0x1404:
  12014. case 0x8b56:
  12015. return setValueV1i;
  12016. // INT, BOOL
  12017. case 0x8b53:
  12018. case 0x8b57:
  12019. return setValueV2i;
  12020. // _VEC2
  12021. case 0x8b54:
  12022. case 0x8b58:
  12023. return setValueV3i;
  12024. // _VEC3
  12025. case 0x8b55:
  12026. case 0x8b59:
  12027. return setValueV4i;
  12028. // _VEC4
  12029. }
  12030. } // Array of scalars
  12031. function setValueV1fArray(gl, v) {
  12032. gl.uniform1fv(this.addr, v);
  12033. } // Integer / Boolean vectors or arrays thereof (always flat arrays)
  12034. function setValueV1iArray(gl, v) {
  12035. gl.uniform1iv(this.addr, v);
  12036. }
  12037. function setValueV2iArray(gl, v) {
  12038. gl.uniform2iv(this.addr, v);
  12039. }
  12040. function setValueV3iArray(gl, v) {
  12041. gl.uniform3iv(this.addr, v);
  12042. }
  12043. function setValueV4iArray(gl, v) {
  12044. gl.uniform4iv(this.addr, v);
  12045. } // Array of vectors (flat or from THREE classes)
  12046. function setValueV2fArray(gl, v) {
  12047. var data = flatten(v, this.size, 2);
  12048. gl.uniform2fv(this.addr, data);
  12049. }
  12050. function setValueV3fArray(gl, v) {
  12051. var data = flatten(v, this.size, 3);
  12052. gl.uniform3fv(this.addr, data);
  12053. }
  12054. function setValueV4fArray(gl, v) {
  12055. var data = flatten(v, this.size, 4);
  12056. gl.uniform4fv(this.addr, data);
  12057. } // Array of matrices (flat or from THREE clases)
  12058. function setValueM2Array(gl, v) {
  12059. var data = flatten(v, this.size, 4);
  12060. gl.uniformMatrix2fv(this.addr, false, data);
  12061. }
  12062. function setValueM3Array(gl, v) {
  12063. var data = flatten(v, this.size, 9);
  12064. gl.uniformMatrix3fv(this.addr, false, data);
  12065. }
  12066. function setValueM4Array(gl, v) {
  12067. var data = flatten(v, this.size, 16);
  12068. gl.uniformMatrix4fv(this.addr, false, data);
  12069. } // Array of textures (2D / Cube)
  12070. function setValueT1Array(gl, v, textures) {
  12071. var n = v.length;
  12072. var units = allocTexUnits(textures, n);
  12073. gl.uniform1iv(this.addr, units);
  12074. for (var i = 0; i !== n; ++i) {
  12075. textures.safeSetTexture2D(v[i] || emptyTexture, units[i]);
  12076. }
  12077. }
  12078. function setValueT6Array(gl, v, textures) {
  12079. var n = v.length;
  12080. var units = allocTexUnits(textures, n);
  12081. gl.uniform1iv(this.addr, units);
  12082. for (var i = 0; i !== n; ++i) {
  12083. textures.safeSetTextureCube(v[i] || emptyCubeTexture, units[i]);
  12084. }
  12085. } // Helper to pick the right setter for a pure (bottom-level) array
  12086. function getPureArraySetter(type) {
  12087. switch (type) {
  12088. case 0x1406:
  12089. return setValueV1fArray;
  12090. // FLOAT
  12091. case 0x8b50:
  12092. return setValueV2fArray;
  12093. // _VEC2
  12094. case 0x8b51:
  12095. return setValueV3fArray;
  12096. // _VEC3
  12097. case 0x8b52:
  12098. return setValueV4fArray;
  12099. // _VEC4
  12100. case 0x8b5a:
  12101. return setValueM2Array;
  12102. // _MAT2
  12103. case 0x8b5b:
  12104. return setValueM3Array;
  12105. // _MAT3
  12106. case 0x8b5c:
  12107. return setValueM4Array;
  12108. // _MAT4
  12109. case 0x8b5e:
  12110. return setValueT1Array;
  12111. // SAMPLER_2D
  12112. case 0x8b60:
  12113. return setValueT6Array;
  12114. // SAMPLER_CUBE
  12115. case 0x1404:
  12116. case 0x8b56:
  12117. return setValueV1iArray;
  12118. // INT, BOOL
  12119. case 0x8b53:
  12120. case 0x8b57:
  12121. return setValueV2iArray;
  12122. // _VEC2
  12123. case 0x8b54:
  12124. case 0x8b58:
  12125. return setValueV3iArray;
  12126. // _VEC3
  12127. case 0x8b55:
  12128. case 0x8b59:
  12129. return setValueV4iArray;
  12130. // _VEC4
  12131. }
  12132. } // --- Uniform Classes ---
  12133. function SingleUniform(id, activeInfo, addr) {
  12134. this.id = id;
  12135. this.addr = addr;
  12136. this.cache = [];
  12137. this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  12138. }
  12139. function PureArrayUniform(id, activeInfo, addr) {
  12140. this.id = id;
  12141. this.addr = addr;
  12142. this.cache = [];
  12143. this.size = activeInfo.size;
  12144. this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  12145. }
  12146. PureArrayUniform.prototype.updateCache = function (data) {
  12147. var cache = this.cache;
  12148. if (data instanceof Float32Array && cache.length !== data.length) {
  12149. this.cache = new Float32Array(data.length);
  12150. }
  12151. copyArray(cache, data);
  12152. };
  12153. function StructuredUniform(id) {
  12154. this.id = id;
  12155. this.seq = [];
  12156. this.map = {};
  12157. }
  12158. StructuredUniform.prototype.setValue = function (gl, value, textures) {
  12159. var seq = this.seq;
  12160. for (var i = 0, n = seq.length; i !== n; ++i) {
  12161. var u = seq[i];
  12162. u.setValue(gl, value[u.id], textures);
  12163. }
  12164. }; // --- Top-level ---
  12165. // Parser - builds up the property tree from the path strings
  12166. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g; // extracts
  12167. // - the identifier (member name or array index)
  12168. // - followed by an optional right bracket (found when array index)
  12169. // - followed by an optional left bracket or dot (type of subscript)
  12170. //
  12171. // Note: These portions can be read in a non-overlapping fashion and
  12172. // allow straightforward parsing of the hierarchy that WebGL encodes
  12173. // in the uniform names.
  12174. function addUniform(container, uniformObject) {
  12175. container.seq.push(uniformObject);
  12176. container.map[uniformObject.id] = uniformObject;
  12177. }
  12178. function parseUniform(activeInfo, addr, container) {
  12179. var path = activeInfo.name,
  12180. pathLength = path.length; // reset RegExp object, because of the early exit of a previous run
  12181. RePathPart.lastIndex = 0;
  12182. while (true) {
  12183. var match = RePathPart.exec(path),
  12184. matchEnd = RePathPart.lastIndex,
  12185. id = match[1],
  12186. idIsIndex = match[2] === ']',
  12187. subscript = match[3];
  12188. if (idIsIndex) id = id | 0; // convert to integer
  12189. if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
  12190. // bare name or "pure" bottom-level array "[0]" suffix
  12191. addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
  12192. break;
  12193. } else {
  12194. // step into inner node / create it in case it doesn't exist
  12195. var map = container.map,
  12196. next = map[id];
  12197. if (next === undefined) {
  12198. next = new StructuredUniform(id);
  12199. addUniform(container, next);
  12200. }
  12201. container = next;
  12202. }
  12203. }
  12204. } // Root Container
  12205. function WebGLUniforms(gl, program) {
  12206. this.seq = [];
  12207. this.map = {};
  12208. var n = gl.getProgramParameter(program, 35718);
  12209. for (var i = 0; i < n; ++i) {
  12210. var info = gl.getActiveUniform(program, i),
  12211. addr = gl.getUniformLocation(program, info.name);
  12212. parseUniform(info, addr, this);
  12213. }
  12214. }
  12215. WebGLUniforms.prototype.setValue = function (gl, name, value, textures) {
  12216. var u = this.map[name];
  12217. if (u !== undefined) u.setValue(gl, value, textures);
  12218. };
  12219. WebGLUniforms.prototype.setOptional = function (gl, object, name) {
  12220. var v = object[name];
  12221. if (v !== undefined) this.setValue(gl, name, v);
  12222. }; // Static interface
  12223. WebGLUniforms.upload = function (gl, seq, values, textures) {
  12224. for (var i = 0, n = seq.length; i !== n; ++i) {
  12225. var u = seq[i],
  12226. v = values[u.id];
  12227. if (v.needsUpdate !== false) {
  12228. // note: always updating when .needsUpdate is undefined
  12229. u.setValue(gl, v.value, textures);
  12230. }
  12231. }
  12232. };
  12233. WebGLUniforms.seqWithValue = function (seq, values) {
  12234. var r = [];
  12235. for (var i = 0, n = seq.length; i !== n; ++i) {
  12236. var u = seq[i];
  12237. if (u.id in values) r.push(u);
  12238. }
  12239. return r;
  12240. };
  12241. /**
  12242. * @author mrdoob / http://mrdoob.com/
  12243. */
  12244. function WebGLShader(gl, type, string) {
  12245. var shader = gl.createShader(type);
  12246. gl.shaderSource(shader, string);
  12247. gl.compileShader(shader);
  12248. return shader;
  12249. }
  12250. /**
  12251. * @author mrdoob / http://mrdoob.com/
  12252. */
  12253. var programIdCount = 0;
  12254. function addLineNumbers(string) {
  12255. var lines = string.split('\n');
  12256. for (var i = 0; i < lines.length; i++) {
  12257. lines[i] = i + 1 + ': ' + lines[i];
  12258. }
  12259. return lines.join('\n');
  12260. }
  12261. function getEncodingComponents(encoding) {
  12262. switch (encoding) {
  12263. case LinearEncoding:
  12264. return ['Linear', '( value )'];
  12265. case sRGBEncoding:
  12266. return ['sRGB', '( value )'];
  12267. case RGBEEncoding:
  12268. return ['RGBE', '( value )'];
  12269. case RGBM7Encoding:
  12270. return ['RGBM', '( value, 7.0 )'];
  12271. case RGBM16Encoding:
  12272. return ['RGBM', '( value, 16.0 )'];
  12273. case RGBDEncoding:
  12274. return ['RGBD', '( value, 256.0 )'];
  12275. case GammaEncoding:
  12276. return ['Gamma', '( value, float( GAMMA_FACTOR ) )'];
  12277. case LogLuvEncoding:
  12278. return ['LogLuv', '( value )'];
  12279. default:
  12280. throw new Error('unsupported encoding: ' + encoding);
  12281. }
  12282. }
  12283. function getShaderErrors(gl, shader, type) {
  12284. var status = gl.getShaderParameter(shader, 35713);
  12285. var log = gl.getShaderInfoLog(shader).trim();
  12286. if (status && log === '') return ''; // --enable-privileged-webgl-extension
  12287. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  12288. var source = gl.getShaderSource(shader);
  12289. return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers(source);
  12290. }
  12291. function getTexelDecodingFunction(functionName, encoding) {
  12292. var components = getEncodingComponents(encoding);
  12293. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[0] + 'ToLinear' + components[1] + '; }';
  12294. }
  12295. function getTexelEncodingFunction(functionName, encoding) {
  12296. var components = getEncodingComponents(encoding);
  12297. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
  12298. }
  12299. function getToneMappingFunction(functionName, toneMapping) {
  12300. var toneMappingName;
  12301. switch (toneMapping) {
  12302. case LinearToneMapping:
  12303. toneMappingName = 'Linear';
  12304. break;
  12305. case ReinhardToneMapping:
  12306. toneMappingName = 'Reinhard';
  12307. break;
  12308. case Uncharted2ToneMapping:
  12309. toneMappingName = 'Uncharted2';
  12310. break;
  12311. case CineonToneMapping:
  12312. toneMappingName = 'OptimizedCineon';
  12313. break;
  12314. case ACESFilmicToneMapping:
  12315. toneMappingName = 'ACESFilmic';
  12316. break;
  12317. default:
  12318. throw new Error('unsupported toneMapping: ' + toneMapping);
  12319. }
  12320. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  12321. }
  12322. function generateExtensions(extensions, parameters, rendererExtensions) {
  12323. extensions = extensions || {};
  12324. var chunks = [extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading ? '#extension GL_OES_standard_derivatives : enable' : '', (extensions.fragDepth || parameters.logarithmicDepthBuffer) && rendererExtensions.get('EXT_frag_depth') ? '#extension GL_EXT_frag_depth : enable' : '', extensions.drawBuffers && rendererExtensions.get('WEBGL_draw_buffers') ? '#extension GL_EXT_draw_buffers : require' : '', (extensions.shaderTextureLOD || parameters.envMap) && rendererExtensions.get('EXT_shader_texture_lod') ? '#extension GL_EXT_shader_texture_lod : enable' : ''];
  12325. return chunks.filter(filterEmptyLine).join('\n');
  12326. }
  12327. function generateDefines(defines) {
  12328. var chunks = [];
  12329. for (var name in defines) {
  12330. var value = defines[name];
  12331. if (value === false) continue;
  12332. chunks.push('#define ' + name + ' ' + value);
  12333. }
  12334. return chunks.join('\n');
  12335. }
  12336. function fetchAttributeLocations(gl, program) {
  12337. var attributes = {};
  12338. var n = gl.getProgramParameter(program, 35721);
  12339. for (var i = 0; i < n; i++) {
  12340. var info = gl.getActiveAttrib(program, i);
  12341. var name = info.name; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  12342. attributes[name] = gl.getAttribLocation(program, name);
  12343. }
  12344. return attributes;
  12345. }
  12346. function filterEmptyLine(string) {
  12347. return string !== '';
  12348. }
  12349. function replaceLightNums(string, parameters) {
  12350. return string.replace(/NUM_DIR_LIGHTS/g, parameters.numDirLights).replace(/NUM_SPOT_LIGHTS/g, parameters.numSpotLights).replace(/NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g, parameters.numPointLights).replace(/NUM_HEMI_LIGHTS/g, parameters.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows);
  12351. }
  12352. function replaceClippingPlaneNums(string, parameters) {
  12353. return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
  12354. } // Resolve Includes
  12355. var includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  12356. function resolveIncludes(string) {
  12357. return string.replace(includePattern, includeReplacer);
  12358. }
  12359. function includeReplacer(match, include) {
  12360. var string = ShaderChunk[include];
  12361. if (string === undefined) {
  12362. throw new Error('Can not resolve #include <' + include + '>');
  12363. }
  12364. return resolveIncludes(string);
  12365. } // Unroll Loops
  12366. var loopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  12367. function unrollLoops(string) {
  12368. return string.replace(loopPattern, loopReplacer);
  12369. }
  12370. function loopReplacer(match, start, end, snippet) {
  12371. var string = '';
  12372. for (var i = parseInt(start); i < parseInt(end); i++) {
  12373. string += snippet.replace(/\[ i \]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
  12374. }
  12375. return string;
  12376. } //
  12377. function generatePrecision(parameters) {
  12378. var precisionstring = "precision " + parameters.precision + " float;\nprecision " + parameters.precision + " int;";
  12379. if (parameters.precision === "highp") {
  12380. precisionstring += "\n#define HIGH_PRECISION";
  12381. } else if (parameters.precision === "mediump") {
  12382. precisionstring += "\n#define MEDIUM_PRECISION";
  12383. } else if (parameters.precision === "lowp") {
  12384. precisionstring += "\n#define LOW_PRECISION";
  12385. }
  12386. return precisionstring;
  12387. }
  12388. function generateShadowMapTypeDefine(parameters) {
  12389. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  12390. if (parameters.shadowMapType === PCFShadowMap) {
  12391. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  12392. } else if (parameters.shadowMapType === PCFSoftShadowMap) {
  12393. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  12394. } else if (parameters.shadowMapType === VSMShadowMap) {
  12395. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  12396. }
  12397. return shadowMapTypeDefine;
  12398. }
  12399. function generateEnvMapTypeDefine(parameters, material) {
  12400. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  12401. if (parameters.envMap) {
  12402. switch (material.envMap.mapping) {
  12403. case CubeReflectionMapping:
  12404. case CubeRefractionMapping:
  12405. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  12406. break;
  12407. case CubeUVReflectionMapping:
  12408. case CubeUVRefractionMapping:
  12409. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  12410. break;
  12411. case EquirectangularReflectionMapping:
  12412. case EquirectangularRefractionMapping:
  12413. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  12414. break;
  12415. case SphericalReflectionMapping:
  12416. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  12417. break;
  12418. }
  12419. }
  12420. return envMapTypeDefine;
  12421. }
  12422. function generateEnvMapModeDefine(parameters, material) {
  12423. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  12424. if (parameters.envMap) {
  12425. switch (material.envMap.mapping) {
  12426. case CubeRefractionMapping:
  12427. case EquirectangularRefractionMapping:
  12428. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  12429. break;
  12430. }
  12431. }
  12432. return envMapModeDefine;
  12433. }
  12434. function generateEnvMapBlendingDefine(parameters, material) {
  12435. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  12436. if (parameters.envMap) {
  12437. switch (material.combine) {
  12438. case MultiplyOperation:
  12439. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  12440. break;
  12441. case MixOperation:
  12442. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  12443. break;
  12444. case AddOperation:
  12445. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  12446. break;
  12447. }
  12448. }
  12449. return envMapBlendingDefine;
  12450. }
  12451. function WebGLProgram(renderer, extensions, code, material, shader, parameters) {
  12452. var gl = renderer.getContext();
  12453. var defines = material.defines;
  12454. var vertexShader = shader.vertexShader;
  12455. var fragmentShader = shader.fragmentShader;
  12456. var shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
  12457. var envMapTypeDefine = generateEnvMapTypeDefine(parameters, material);
  12458. var envMapModeDefine = generateEnvMapModeDefine(parameters, material);
  12459. var envMapBlendingDefine = generateEnvMapBlendingDefine(parameters, material);
  12460. var gammaFactorDefine = renderer.gammaFactor > 0 ? renderer.gammaFactor : 1.0;
  12461. var customExtensions = parameters.isWebGL2 ? '' : generateExtensions(material.extensions, parameters, extensions);
  12462. var customDefines = generateDefines(defines);
  12463. var program = gl.createProgram();
  12464. var prefixVertex, prefixFragment;
  12465. var renderTarget = renderer.getRenderTarget();
  12466. var numMultiviewViews = renderTarget && renderTarget.isWebGLMultiviewRenderTarget ? renderTarget.numViews : 0;
  12467. if (material.isRawShaderMaterial) {
  12468. prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
  12469. if (prefixVertex.length > 0) {
  12470. prefixVertex += '\n';
  12471. }
  12472. prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
  12473. if (prefixFragment.length > 0) {
  12474. prefixFragment += '\n';
  12475. }
  12476. } else {
  12477. prefixVertex = [generatePrecision(parameters), '#define SHADER_NAME ' + shader.name, customDefines, parameters.instancing ? '#define USE_INSTANCING' : '', parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', '#define GAMMA_FACTOR ' + gammaFactorDefine, '#define MAX_BONES ' + parameters.maxBones, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors ? '#define USE_COLOR' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.skinning ? '#define USE_SKINNING' : '', parameters.useVertexTexture ? '#define BONE_TEXTURE' : '', parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', parameters.doubleSided ? '#define DOUBLE_SIDED' : '', parameters.flipSided ? '#define FLIP_SIDED' : '', parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && (parameters.isWebGL2 || extensions.get('EXT_frag_depth')) ? '#define USE_LOGDEPTHBUF_EXT' : '', 'uniform mat4 modelMatrix;', 'uniform mat4 modelViewMatrix;', 'uniform mat4 projectionMatrix;', 'uniform mat4 viewMatrix;', 'uniform mat3 normalMatrix;', 'uniform vec3 cameraPosition;', '#ifdef USE_INSTANCING', ' attribute mat4 instanceMatrix;', '#endif', 'attribute vec3 position;', 'attribute vec3 normal;', 'attribute vec2 uv;', '#ifdef USE_TANGENT', ' attribute vec4 tangent;', '#endif', '#ifdef USE_COLOR', ' attribute vec3 color;', '#endif', '#ifdef USE_MORPHTARGETS', ' attribute vec3 morphTarget0;', ' attribute vec3 morphTarget1;', ' attribute vec3 morphTarget2;', ' attribute vec3 morphTarget3;', ' #ifdef USE_MORPHNORMALS', ' attribute vec3 morphNormal0;', ' attribute vec3 morphNormal1;', ' attribute vec3 morphNormal2;', ' attribute vec3 morphNormal3;', ' #else', ' attribute vec3 morphTarget4;', ' attribute vec3 morphTarget5;', ' attribute vec3 morphTarget6;', ' attribute vec3 morphTarget7;', ' #endif', '#endif', '#ifdef USE_SKINNING', ' attribute vec4 skinIndex;', ' attribute vec4 skinWeight;', '#endif', '\n'].filter(filterEmptyLine).join('\n');
  12478. prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + shader.name, customDefines, parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + (parameters.alphaTest % 1 ? '' : '.0') : '', // add '.0' if integer
  12479. '#define GAMMA_FACTOR ' + gammaFactorDefine, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.matcap ? '#define USE_MATCAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapTypeDefine : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.envMap ? '#define ' + envMapBlendingDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.sheen ? '#define USE_SHEEN' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors ? '#define USE_COLOR' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.gradientMap ? '#define USE_GRADIENTMAP' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.doubleSided ? '#define DOUBLE_SIDED' : '', parameters.flipSided ? '#define FLIP_SIDED' : '', parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '', parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && (parameters.isWebGL2 || extensions.get('EXT_frag_depth')) ? '#define USE_LOGDEPTHBUF_EXT' : '', ((material.extensions ? material.extensions.shaderTextureLOD : false) || parameters.envMap) && (parameters.isWebGL2 || extensions.get('EXT_shader_texture_lod')) ? '#define TEXTURE_LOD_EXT' : '', 'uniform mat4 viewMatrix;', 'uniform vec3 cameraPosition;', parameters.toneMapping !== NoToneMapping ? '#define TONE_MAPPING' : '', parameters.toneMapping !== NoToneMapping ? ShaderChunk['tonemapping_pars_fragment'] : '', // this code is required here because it is used by the toneMapping() function defined below
  12480. parameters.toneMapping !== NoToneMapping ? getToneMappingFunction('toneMapping', parameters.toneMapping) : '', parameters.dithering ? '#define DITHERING' : '', parameters.outputEncoding || parameters.mapEncoding || parameters.matcapEncoding || 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
  12481. parameters.mapEncoding ? getTexelDecodingFunction('mapTexelToLinear', parameters.mapEncoding) : '', parameters.matcapEncoding ? getTexelDecodingFunction('matcapTexelToLinear', parameters.matcapEncoding) : '', parameters.envMapEncoding ? getTexelDecodingFunction('envMapTexelToLinear', parameters.envMapEncoding) : '', parameters.emissiveMapEncoding ? getTexelDecodingFunction('emissiveMapTexelToLinear', parameters.emissiveMapEncoding) : '', parameters.outputEncoding ? getTexelEncodingFunction('linearToOutputTexel', parameters.outputEncoding) : '', parameters.depthPacking ? '#define DEPTH_PACKING ' + material.depthPacking : '', '\n'].filter(filterEmptyLine).join('\n');
  12482. }
  12483. vertexShader = resolveIncludes(vertexShader);
  12484. vertexShader = replaceLightNums(vertexShader, parameters);
  12485. vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
  12486. fragmentShader = resolveIncludes(fragmentShader);
  12487. fragmentShader = replaceLightNums(fragmentShader, parameters);
  12488. fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
  12489. vertexShader = unrollLoops(vertexShader);
  12490. fragmentShader = unrollLoops(fragmentShader);
  12491. if (parameters.isWebGL2 && !material.isRawShaderMaterial) {
  12492. var isGLSL3ShaderMaterial = false;
  12493. var versionRegex = /^\s*#version\s+300\s+es\s*\n/;
  12494. if (material.isShaderMaterial && vertexShader.match(versionRegex) !== null && fragmentShader.match(versionRegex) !== null) {
  12495. isGLSL3ShaderMaterial = true;
  12496. vertexShader = vertexShader.replace(versionRegex, '');
  12497. fragmentShader = fragmentShader.replace(versionRegex, '');
  12498. } // GLSL 3.0 conversion
  12499. prefixVertex = ['#version 300 es\n', '#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
  12500. prefixFragment = ['#version 300 es\n', '#define varying in', isGLSL3ShaderMaterial ? '' : 'out highp vec4 pc_fragColor;', isGLSL3ShaderMaterial ? '' : '#define gl_FragColor pc_fragColor', '#define gl_FragDepthEXT gl_FragDepth', '#define texture2D texture', '#define textureCube texture', '#define texture2DProj textureProj', '#define texture2DLodEXT textureLod', '#define texture2DProjLodEXT textureProjLod', '#define textureCubeLodEXT textureLod', '#define texture2DGradEXT textureGrad', '#define texture2DProjGradEXT textureProjGrad', '#define textureCubeGradEXT textureGrad'].join('\n') + '\n' + prefixFragment; // Multiview
  12501. if (numMultiviewViews > 0) {
  12502. prefixVertex = prefixVertex.replace('#version 300 es\n', ['#version 300 es\n', '#extension GL_OVR_multiview2 : require', 'layout(num_views = ' + numMultiviewViews + ') in;', '#define VIEW_ID gl_ViewID_OVR'].join('\n'));
  12503. prefixVertex = prefixVertex.replace(['uniform mat4 modelViewMatrix;', 'uniform mat4 projectionMatrix;', 'uniform mat4 viewMatrix;', 'uniform mat3 normalMatrix;'].join('\n'), ['uniform mat4 modelViewMatrices[' + numMultiviewViews + '];', 'uniform mat4 projectionMatrices[' + numMultiviewViews + '];', 'uniform mat4 viewMatrices[' + numMultiviewViews + '];', 'uniform mat3 normalMatrices[' + numMultiviewViews + '];', '#define modelViewMatrix modelViewMatrices[VIEW_ID]', '#define projectionMatrix projectionMatrices[VIEW_ID]', '#define viewMatrix viewMatrices[VIEW_ID]', '#define normalMatrix normalMatrices[VIEW_ID]'].join('\n'));
  12504. prefixFragment = prefixFragment.replace('#version 300 es\n', ['#version 300 es\n', '#extension GL_OVR_multiview2 : require', '#define VIEW_ID gl_ViewID_OVR'].join('\n'));
  12505. prefixFragment = prefixFragment.replace('uniform mat4 viewMatrix;', ['uniform mat4 viewMatrices[' + numMultiviewViews + '];', '#define viewMatrix viewMatrices[VIEW_ID]'].join('\n'));
  12506. }
  12507. }
  12508. var vertexGlsl = prefixVertex + vertexShader;
  12509. var fragmentGlsl = prefixFragment + fragmentShader; // console.log( '*VERTEX*', vertexGlsl );
  12510. // console.log( '*FRAGMENT*', fragmentGlsl );
  12511. var glVertexShader = WebGLShader(gl, 35633, vertexGlsl);
  12512. var glFragmentShader = WebGLShader(gl, 35632, fragmentGlsl);
  12513. gl.attachShader(program, glVertexShader);
  12514. gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.
  12515. if (material.index0AttributeName !== undefined) {
  12516. gl.bindAttribLocation(program, 0, material.index0AttributeName);
  12517. } else if (parameters.morphTargets === true) {
  12518. // programs with morphTargets displace position out of attribute 0
  12519. gl.bindAttribLocation(program, 0, 'position');
  12520. }
  12521. gl.linkProgram(program); // check for link errors
  12522. if (renderer.debug.checkShaderErrors) {
  12523. var programLog = gl.getProgramInfoLog(program).trim();
  12524. var vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
  12525. var fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
  12526. var runnable = true;
  12527. var haveDiagnostics = true;
  12528. if (gl.getProgramParameter(program, 35714) === false) {
  12529. runnable = false;
  12530. var vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
  12531. var fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
  12532. console.error('THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter(program, 35715), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors);
  12533. } else if (programLog !== '') {
  12534. console.warn('THREE.WebGLProgram: gl.getProgramInfoLog()', programLog);
  12535. } else if (vertexLog === '' || fragmentLog === '') {
  12536. haveDiagnostics = false;
  12537. }
  12538. if (haveDiagnostics) {
  12539. this.diagnostics = {
  12540. runnable: runnable,
  12541. material: material,
  12542. programLog: programLog,
  12543. vertexShader: {
  12544. log: vertexLog,
  12545. prefix: prefixVertex
  12546. },
  12547. fragmentShader: {
  12548. log: fragmentLog,
  12549. prefix: prefixFragment
  12550. }
  12551. };
  12552. }
  12553. } // clean up
  12554. gl.deleteShader(glVertexShader);
  12555. gl.deleteShader(glFragmentShader); // set up caching for uniform locations
  12556. var cachedUniforms;
  12557. this.getUniforms = function () {
  12558. if (cachedUniforms === undefined) {
  12559. cachedUniforms = new WebGLUniforms(gl, program);
  12560. }
  12561. return cachedUniforms;
  12562. }; // set up caching for attribute locations
  12563. var cachedAttributes;
  12564. this.getAttributes = function () {
  12565. if (cachedAttributes === undefined) {
  12566. cachedAttributes = fetchAttributeLocations(gl, program);
  12567. }
  12568. return cachedAttributes;
  12569. }; // free resource
  12570. this.destroy = function () {
  12571. gl.deleteProgram(program);
  12572. this.program = undefined;
  12573. }; //
  12574. this.name = shader.name;
  12575. this.id = programIdCount++;
  12576. this.code = code;
  12577. this.usedTimes = 1;
  12578. this.program = program;
  12579. this.vertexShader = glVertexShader;
  12580. this.fragmentShader = glFragmentShader;
  12581. this.numMultiviewViews = numMultiviewViews;
  12582. return this;
  12583. }
  12584. /**
  12585. * @author mrdoob / http://mrdoob.com/
  12586. */
  12587. function WebGLPrograms(renderer, extensions, capabilities) {
  12588. var programs = [];
  12589. var shaderIDs = {
  12590. MeshDepthMaterial: 'depth',
  12591. MeshDistanceMaterial: 'distanceRGBA',
  12592. MeshNormalMaterial: 'normal',
  12593. MeshBasicMaterial: 'basic',
  12594. MeshLambertMaterial: 'lambert',
  12595. MeshPhongMaterial: 'phong',
  12596. MeshToonMaterial: 'phong',
  12597. MeshStandardMaterial: 'physical',
  12598. MeshPhysicalMaterial: 'physical',
  12599. MeshMatcapMaterial: 'matcap',
  12600. LineBasicMaterial: 'basic',
  12601. LineDashedMaterial: 'dashed',
  12602. PointsMaterial: 'points',
  12603. ShadowMaterial: 'shadow',
  12604. SpriteMaterial: 'sprite'
  12605. };
  12606. var parameterNames = ["precision", "supportsVertexTextures", "instancing", "map", "mapEncoding", "matcap", "matcapEncoding", "envMap", "envMapMode", "envMapEncoding", "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "objectSpaceNormalMap", "tangentSpaceNormalMap", "clearcoatNormalMap", "displacementMap", "specularMap", "roughnessMap", "metalnessMap", "gradientMap", "alphaMap", "combine", "vertexColors", "vertexTangents", "fog", "useFog", "fogExp2", "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning", "maxBones", "useVertexTexture", "morphTargets", "morphNormals", "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha", "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights", "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights', "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking", "dithering", "sheen"];
  12607. function allocateBones(object) {
  12608. var skeleton = object.skeleton;
  12609. var bones = skeleton.bones;
  12610. if (capabilities.floatVertexTextures) {
  12611. return 1024;
  12612. } else {
  12613. // default for when object is not specified
  12614. // ( for example when prebuilding shader to be used with multiple objects )
  12615. //
  12616. // - leave some extra space for other uniforms
  12617. // - limit here is ANGLE's 254 max uniform vectors
  12618. // (up to 54 should be safe)
  12619. var nVertexUniforms = capabilities.maxVertexUniforms;
  12620. var nVertexMatrices = Math.floor((nVertexUniforms - 20) / 4);
  12621. var maxBones = Math.min(nVertexMatrices, bones.length);
  12622. if (maxBones < bones.length) {
  12623. console.warn('THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.');
  12624. return 0;
  12625. }
  12626. return maxBones;
  12627. }
  12628. }
  12629. function getTextureEncodingFromMap(map, gammaOverrideLinear) {
  12630. var encoding;
  12631. if (!map) {
  12632. encoding = LinearEncoding;
  12633. } else if (map.isTexture) {
  12634. encoding = map.encoding;
  12635. } else if (map.isWebGLRenderTarget) {
  12636. console.warn("THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead.");
  12637. encoding = map.texture.encoding;
  12638. } // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  12639. if (encoding === LinearEncoding && gammaOverrideLinear) {
  12640. encoding = GammaEncoding;
  12641. }
  12642. return encoding;
  12643. }
  12644. this.getParameters = function (material, lights, shadows, fog, nClipPlanes, nClipIntersection, object) {
  12645. var shaderID = shaderIDs[material.type]; // heuristics to create shader parameters according to lights in the scene
  12646. // (not to blow over maxLights budget)
  12647. var maxBones = object.isSkinnedMesh ? allocateBones(object) : 0;
  12648. var precision = capabilities.precision;
  12649. if (material.precision !== null) {
  12650. precision = capabilities.getMaxPrecision(material.precision);
  12651. if (precision !== material.precision) {
  12652. console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
  12653. }
  12654. }
  12655. var currentRenderTarget = renderer.getRenderTarget();
  12656. var parameters = {
  12657. isWebGL2: capabilities.isWebGL2,
  12658. shaderID: shaderID,
  12659. precision: precision,
  12660. instancing: object.isInstancedMesh === true,
  12661. supportsVertexTextures: capabilities.vertexTextures,
  12662. outputEncoding: getTextureEncodingFromMap(!currentRenderTarget ? null : currentRenderTarget.texture, renderer.gammaOutput),
  12663. map: !!material.map,
  12664. mapEncoding: getTextureEncodingFromMap(material.map, renderer.gammaInput),
  12665. matcap: !!material.matcap,
  12666. matcapEncoding: getTextureEncodingFromMap(material.matcap, renderer.gammaInput),
  12667. envMap: !!material.envMap,
  12668. envMapMode: material.envMap && material.envMap.mapping,
  12669. envMapEncoding: getTextureEncodingFromMap(material.envMap, renderer.gammaInput),
  12670. envMapCubeUV: !!material.envMap && (material.envMap.mapping === CubeUVReflectionMapping || material.envMap.mapping === CubeUVRefractionMapping),
  12671. lightMap: !!material.lightMap,
  12672. aoMap: !!material.aoMap,
  12673. emissiveMap: !!material.emissiveMap,
  12674. emissiveMapEncoding: getTextureEncodingFromMap(material.emissiveMap, renderer.gammaInput),
  12675. bumpMap: !!material.bumpMap,
  12676. normalMap: !!material.normalMap,
  12677. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  12678. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  12679. clearcoatNormalMap: !!material.clearcoatNormalMap,
  12680. displacementMap: !!material.displacementMap,
  12681. roughnessMap: !!material.roughnessMap,
  12682. metalnessMap: !!material.metalnessMap,
  12683. specularMap: !!material.specularMap,
  12684. alphaMap: !!material.alphaMap,
  12685. gradientMap: !!material.gradientMap,
  12686. sheen: !!material.sheen,
  12687. combine: material.combine,
  12688. vertexTangents: material.normalMap && material.vertexTangents,
  12689. vertexColors: material.vertexColors,
  12690. vertexUvs: !!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatNormalMap,
  12691. fog: !!fog,
  12692. useFog: material.fog,
  12693. fogExp2: fog && fog.isFogExp2,
  12694. flatShading: material.flatShading,
  12695. sizeAttenuation: material.sizeAttenuation,
  12696. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  12697. skinning: material.skinning && maxBones > 0,
  12698. maxBones: maxBones,
  12699. useVertexTexture: capabilities.floatVertexTextures,
  12700. morphTargets: material.morphTargets,
  12701. morphNormals: material.morphNormals,
  12702. maxMorphTargets: renderer.maxMorphTargets,
  12703. maxMorphNormals: renderer.maxMorphNormals,
  12704. numDirLights: lights.directional.length,
  12705. numPointLights: lights.point.length,
  12706. numSpotLights: lights.spot.length,
  12707. numRectAreaLights: lights.rectArea.length,
  12708. numHemiLights: lights.hemi.length,
  12709. numDirLightShadows: lights.directionalShadowMap.length,
  12710. numPointLightShadows: lights.pointShadowMap.length,
  12711. numSpotLightShadows: lights.spotShadowMap.length,
  12712. numClippingPlanes: nClipPlanes,
  12713. numClipIntersection: nClipIntersection,
  12714. dithering: material.dithering,
  12715. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  12716. shadowMapType: renderer.shadowMap.type,
  12717. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  12718. physicallyCorrectLights: renderer.physicallyCorrectLights,
  12719. premultipliedAlpha: material.premultipliedAlpha,
  12720. alphaTest: material.alphaTest,
  12721. doubleSided: material.side === DoubleSide,
  12722. flipSided: material.side === BackSide,
  12723. depthPacking: material.depthPacking !== undefined ? material.depthPacking : false
  12724. };
  12725. return parameters;
  12726. };
  12727. this.getProgramCode = function (material, parameters) {
  12728. var array = [];
  12729. if (parameters.shaderID) {
  12730. array.push(parameters.shaderID);
  12731. } else {
  12732. array.push(material.fragmentShader);
  12733. array.push(material.vertexShader);
  12734. }
  12735. if (material.defines !== undefined) {
  12736. for (var name in material.defines) {
  12737. array.push(name);
  12738. array.push(material.defines[name]);
  12739. }
  12740. }
  12741. for (var i = 0; i < parameterNames.length; i++) {
  12742. array.push(parameters[parameterNames[i]]);
  12743. }
  12744. array.push(material.onBeforeCompile.toString());
  12745. array.push(renderer.gammaOutput);
  12746. array.push(renderer.gammaFactor);
  12747. return array.join();
  12748. };
  12749. this.acquireProgram = function (material, shader, parameters, code) {
  12750. var program; // Check if code has been already compiled
  12751. for (var p = 0, pl = programs.length; p < pl; p++) {
  12752. var programInfo = programs[p];
  12753. if (programInfo.code === code) {
  12754. program = programInfo;
  12755. ++program.usedTimes;
  12756. break;
  12757. }
  12758. }
  12759. if (program === undefined) {
  12760. program = new WebGLProgram(renderer, extensions, code, material, shader, parameters);
  12761. programs.push(program);
  12762. }
  12763. return program;
  12764. };
  12765. this.releaseProgram = function (program) {
  12766. if (--program.usedTimes === 0) {
  12767. // Remove from unordered set
  12768. var i = programs.indexOf(program);
  12769. programs[i] = programs[programs.length - 1];
  12770. programs.pop(); // Free WebGL resources
  12771. program.destroy();
  12772. }
  12773. }; // Exposed for resource monitoring & error feedback via renderer.info:
  12774. this.programs = programs;
  12775. }
  12776. /**
  12777. * @author fordacious / fordacious.github.io
  12778. */
  12779. function WebGLProperties() {
  12780. var properties = new WeakMap();
  12781. function get(object) {
  12782. var map = properties.get(object);
  12783. if (map === undefined) {
  12784. map = {};
  12785. properties.set(object, map);
  12786. }
  12787. return map;
  12788. }
  12789. function remove(object) {
  12790. properties.delete(object);
  12791. }
  12792. function update(object, key, value) {
  12793. properties.get(object)[key] = value;
  12794. }
  12795. function dispose() {
  12796. properties = new WeakMap();
  12797. }
  12798. return {
  12799. get: get,
  12800. remove: remove,
  12801. update: update,
  12802. dispose: dispose
  12803. };
  12804. }
  12805. /**
  12806. * @author mrdoob / http://mrdoob.com/
  12807. */
  12808. function painterSortStable(a, b) {
  12809. if (a.groupOrder !== b.groupOrder) {
  12810. return a.groupOrder - b.groupOrder;
  12811. } else if (a.renderOrder !== b.renderOrder) {
  12812. return a.renderOrder - b.renderOrder;
  12813. } else if (a.program !== b.program) {
  12814. return a.program.id - b.program.id;
  12815. } else if (a.material.id !== b.material.id) {
  12816. return a.material.id - b.material.id;
  12817. } else if (a.z !== b.z) {
  12818. return a.z - b.z;
  12819. } else {
  12820. return a.id - b.id;
  12821. }
  12822. }
  12823. function reversePainterSortStable(a, b) {
  12824. if (a.groupOrder !== b.groupOrder) {
  12825. return a.groupOrder - b.groupOrder;
  12826. } else if (a.renderOrder !== b.renderOrder) {
  12827. return a.renderOrder - b.renderOrder;
  12828. } else if (a.z !== b.z) {
  12829. return b.z - a.z;
  12830. } else {
  12831. return a.id - b.id;
  12832. }
  12833. }
  12834. function WebGLRenderList() {
  12835. var renderItems = [];
  12836. var renderItemsIndex = 0;
  12837. var opaque = [];
  12838. var transparent = [];
  12839. var defaultProgram = {
  12840. id: -1
  12841. };
  12842. function init() {
  12843. renderItemsIndex = 0;
  12844. opaque.length = 0;
  12845. transparent.length = 0;
  12846. }
  12847. function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
  12848. var renderItem = renderItems[renderItemsIndex];
  12849. if (renderItem === undefined) {
  12850. renderItem = {
  12851. id: object.id,
  12852. object: object,
  12853. geometry: geometry,
  12854. material: material,
  12855. program: material.program || defaultProgram,
  12856. groupOrder: groupOrder,
  12857. renderOrder: object.renderOrder,
  12858. z: z,
  12859. group: group
  12860. };
  12861. renderItems[renderItemsIndex] = renderItem;
  12862. } else {
  12863. renderItem.id = object.id;
  12864. renderItem.object = object;
  12865. renderItem.geometry = geometry;
  12866. renderItem.material = material;
  12867. renderItem.program = material.program || defaultProgram;
  12868. renderItem.groupOrder = groupOrder;
  12869. renderItem.renderOrder = object.renderOrder;
  12870. renderItem.z = z;
  12871. renderItem.group = group;
  12872. }
  12873. renderItemsIndex++;
  12874. return renderItem;
  12875. }
  12876. function push(object, geometry, material, groupOrder, z, group) {
  12877. var renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  12878. (material.transparent === true ? transparent : opaque).push(renderItem);
  12879. }
  12880. function unshift(object, geometry, material, groupOrder, z, group) {
  12881. var renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  12882. (material.transparent === true ? transparent : opaque).unshift(renderItem);
  12883. }
  12884. function sort() {
  12885. if (opaque.length > 1) opaque.sort(painterSortStable);
  12886. if (transparent.length > 1) transparent.sort(reversePainterSortStable);
  12887. }
  12888. return {
  12889. opaque: opaque,
  12890. transparent: transparent,
  12891. init: init,
  12892. push: push,
  12893. unshift: unshift,
  12894. sort: sort
  12895. };
  12896. }
  12897. function WebGLRenderLists() {
  12898. var lists = new WeakMap();
  12899. function onSceneDispose(event) {
  12900. var scene = event.target;
  12901. scene.removeEventListener('dispose', onSceneDispose);
  12902. lists.delete(scene);
  12903. }
  12904. function get(scene, camera) {
  12905. var cameras = lists.get(scene);
  12906. var list;
  12907. if (cameras === undefined) {
  12908. list = new WebGLRenderList();
  12909. lists.set(scene, new WeakMap());
  12910. lists.get(scene).set(camera, list);
  12911. scene.addEventListener('dispose', onSceneDispose);
  12912. } else {
  12913. list = cameras.get(camera);
  12914. if (list === undefined) {
  12915. list = new WebGLRenderList();
  12916. cameras.set(camera, list);
  12917. }
  12918. }
  12919. return list;
  12920. }
  12921. function dispose() {
  12922. lists = new WeakMap();
  12923. }
  12924. return {
  12925. get: get,
  12926. dispose: dispose
  12927. };
  12928. }
  12929. /**
  12930. * @author mrdoob / http://mrdoob.com/
  12931. */
  12932. function UniformsCache() {
  12933. var lights = {};
  12934. return {
  12935. get: function (light) {
  12936. if (lights[light.id] !== undefined) {
  12937. return lights[light.id];
  12938. }
  12939. var uniforms;
  12940. switch (light.type) {
  12941. case 'DirectionalLight':
  12942. uniforms = {
  12943. direction: new Vector3(),
  12944. color: new Color(),
  12945. shadow: false,
  12946. shadowBias: 0,
  12947. shadowRadius: 1,
  12948. shadowMapSize: new Vector2()
  12949. };
  12950. break;
  12951. case 'SpotLight':
  12952. uniforms = {
  12953. position: new Vector3(),
  12954. direction: new Vector3(),
  12955. color: new Color(),
  12956. distance: 0,
  12957. coneCos: 0,
  12958. penumbraCos: 0,
  12959. decay: 0,
  12960. shadow: false,
  12961. shadowBias: 0,
  12962. shadowRadius: 1,
  12963. shadowMapSize: new Vector2()
  12964. };
  12965. break;
  12966. case 'PointLight':
  12967. uniforms = {
  12968. position: new Vector3(),
  12969. color: new Color(),
  12970. distance: 0,
  12971. decay: 0,
  12972. shadow: false,
  12973. shadowBias: 0,
  12974. shadowRadius: 1,
  12975. shadowMapSize: new Vector2(),
  12976. shadowCameraNear: 1,
  12977. shadowCameraFar: 1000
  12978. };
  12979. break;
  12980. case 'HemisphereLight':
  12981. uniforms = {
  12982. direction: new Vector3(),
  12983. skyColor: new Color(),
  12984. groundColor: new Color()
  12985. };
  12986. break;
  12987. case 'RectAreaLight':
  12988. uniforms = {
  12989. color: new Color(),
  12990. position: new Vector3(),
  12991. halfWidth: new Vector3(),
  12992. halfHeight: new Vector3() // TODO (abelnation): set RectAreaLight shadow uniforms
  12993. };
  12994. break;
  12995. }
  12996. lights[light.id] = uniforms;
  12997. return uniforms;
  12998. }
  12999. };
  13000. }
  13001. var nextVersion = 0;
  13002. function shadowCastingLightsFirst(lightA, lightB) {
  13003. return (lightB.castShadow ? 1 : 0) - (lightA.castShadow ? 1 : 0);
  13004. }
  13005. function WebGLLights() {
  13006. var cache = new UniformsCache();
  13007. var state = {
  13008. version: 0,
  13009. hash: {
  13010. directionalLength: -1,
  13011. pointLength: -1,
  13012. spotLength: -1,
  13013. rectAreaLength: -1,
  13014. hemiLength: -1,
  13015. numDirectionalShadows: -1,
  13016. numPointShadows: -1,
  13017. numSpotShadows: -1
  13018. },
  13019. ambient: [0, 0, 0],
  13020. probe: [],
  13021. directional: [],
  13022. directionalShadowMap: [],
  13023. directionalShadowMatrix: [],
  13024. spot: [],
  13025. spotShadowMap: [],
  13026. spotShadowMatrix: [],
  13027. rectArea: [],
  13028. point: [],
  13029. pointShadowMap: [],
  13030. pointShadowMatrix: [],
  13031. hemi: [],
  13032. numDirectionalShadows: -1,
  13033. numPointShadows: -1,
  13034. numSpotShadows: -1
  13035. };
  13036. for (var i = 0; i < 9; i++) state.probe.push(new Vector3());
  13037. var vector3 = new Vector3();
  13038. var matrix4 = new Matrix4();
  13039. var matrix42 = new Matrix4();
  13040. function setup(lights, shadows, camera) {
  13041. var r = 0,
  13042. g = 0,
  13043. b = 0;
  13044. for (var i = 0; i < 9; i++) state.probe[i].set(0, 0, 0);
  13045. var directionalLength = 0;
  13046. var pointLength = 0;
  13047. var spotLength = 0;
  13048. var rectAreaLength = 0;
  13049. var hemiLength = 0;
  13050. var numDirectionalShadows = 0;
  13051. var numPointShadows = 0;
  13052. var numSpotShadows = 0;
  13053. var viewMatrix = camera.matrixWorldInverse;
  13054. lights.sort(shadowCastingLightsFirst);
  13055. for (var i = 0, l = lights.length; i < l; i++) {
  13056. var light = lights[i];
  13057. var color = light.color;
  13058. var intensity = light.intensity;
  13059. var distance = light.distance;
  13060. var shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
  13061. if (light.isAmbientLight) {
  13062. r += color.r * intensity;
  13063. g += color.g * intensity;
  13064. b += color.b * intensity;
  13065. } else if (light.isLightProbe) {
  13066. for (var j = 0; j < 9; j++) {
  13067. state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
  13068. }
  13069. } else if (light.isDirectionalLight) {
  13070. var uniforms = cache.get(light);
  13071. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  13072. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  13073. vector3.setFromMatrixPosition(light.target.matrixWorld);
  13074. uniforms.direction.sub(vector3);
  13075. uniforms.direction.transformDirection(viewMatrix);
  13076. uniforms.shadow = light.castShadow;
  13077. if (light.castShadow) {
  13078. var shadow = light.shadow;
  13079. uniforms.shadowBias = shadow.bias;
  13080. uniforms.shadowRadius = shadow.radius;
  13081. uniforms.shadowMapSize = shadow.mapSize;
  13082. state.directionalShadowMap[directionalLength] = shadowMap;
  13083. state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
  13084. numDirectionalShadows++;
  13085. }
  13086. state.directional[directionalLength] = uniforms;
  13087. directionalLength++;
  13088. } else if (light.isSpotLight) {
  13089. var uniforms = cache.get(light);
  13090. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  13091. uniforms.position.applyMatrix4(viewMatrix);
  13092. uniforms.color.copy(color).multiplyScalar(intensity);
  13093. uniforms.distance = distance;
  13094. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  13095. vector3.setFromMatrixPosition(light.target.matrixWorld);
  13096. uniforms.direction.sub(vector3);
  13097. uniforms.direction.transformDirection(viewMatrix);
  13098. uniforms.coneCos = Math.cos(light.angle);
  13099. uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
  13100. uniforms.decay = light.decay;
  13101. uniforms.shadow = light.castShadow;
  13102. if (light.castShadow) {
  13103. var shadow = light.shadow;
  13104. uniforms.shadowBias = shadow.bias;
  13105. uniforms.shadowRadius = shadow.radius;
  13106. uniforms.shadowMapSize = shadow.mapSize;
  13107. state.spotShadowMap[spotLength] = shadowMap;
  13108. state.spotShadowMatrix[spotLength] = light.shadow.matrix;
  13109. numSpotShadows++;
  13110. }
  13111. state.spot[spotLength] = uniforms;
  13112. spotLength++;
  13113. } else if (light.isRectAreaLight) {
  13114. var uniforms = cache.get(light); // (a) intensity is the total visible light emitted
  13115. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  13116. // (b) intensity is the brightness of the light
  13117. uniforms.color.copy(color).multiplyScalar(intensity);
  13118. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  13119. uniforms.position.applyMatrix4(viewMatrix); // extract local rotation of light to derive width/height half vectors
  13120. matrix42.identity();
  13121. matrix4.copy(light.matrixWorld);
  13122. matrix4.premultiply(viewMatrix);
  13123. matrix42.extractRotation(matrix4);
  13124. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  13125. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  13126. uniforms.halfWidth.applyMatrix4(matrix42);
  13127. uniforms.halfHeight.applyMatrix4(matrix42); // TODO (abelnation): RectAreaLight distance?
  13128. // uniforms.distance = distance;
  13129. state.rectArea[rectAreaLength] = uniforms;
  13130. rectAreaLength++;
  13131. } else if (light.isPointLight) {
  13132. var uniforms = cache.get(light);
  13133. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  13134. uniforms.position.applyMatrix4(viewMatrix);
  13135. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  13136. uniforms.distance = light.distance;
  13137. uniforms.decay = light.decay;
  13138. uniforms.shadow = light.castShadow;
  13139. if (light.castShadow) {
  13140. var shadow = light.shadow;
  13141. uniforms.shadowBias = shadow.bias;
  13142. uniforms.shadowRadius = shadow.radius;
  13143. uniforms.shadowMapSize = shadow.mapSize;
  13144. uniforms.shadowCameraNear = shadow.camera.near;
  13145. uniforms.shadowCameraFar = shadow.camera.far;
  13146. state.pointShadowMap[pointLength] = shadowMap;
  13147. state.pointShadowMatrix[pointLength] = light.shadow.matrix;
  13148. numPointShadows++;
  13149. }
  13150. state.point[pointLength] = uniforms;
  13151. pointLength++;
  13152. } else if (light.isHemisphereLight) {
  13153. var uniforms = cache.get(light);
  13154. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  13155. uniforms.direction.transformDirection(viewMatrix);
  13156. uniforms.direction.normalize();
  13157. uniforms.skyColor.copy(light.color).multiplyScalar(intensity);
  13158. uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity);
  13159. state.hemi[hemiLength] = uniforms;
  13160. hemiLength++;
  13161. }
  13162. }
  13163. state.ambient[0] = r;
  13164. state.ambient[1] = g;
  13165. state.ambient[2] = b;
  13166. var hash = state.hash;
  13167. if (hash.directionalLength !== directionalLength || hash.pointLength !== pointLength || hash.spotLength !== spotLength || hash.rectAreaLength !== rectAreaLength || hash.hemiLength !== hemiLength || hash.numDirectionalShadows !== numDirectionalShadows || hash.numPointShadows !== numPointShadows || hash.numSpotShadows !== numSpotShadows) {
  13168. state.directional.length = directionalLength;
  13169. state.spot.length = spotLength;
  13170. state.rectArea.length = rectAreaLength;
  13171. state.point.length = pointLength;
  13172. state.hemi.length = hemiLength;
  13173. state.directionalShadowMap.length = numDirectionalShadows;
  13174. state.pointShadowMap.length = numPointShadows;
  13175. state.spotShadowMap.length = numSpotShadows;
  13176. state.directionalShadowMatrix.length = numDirectionalShadows;
  13177. state.pointShadowMatrix.length = numPointShadows;
  13178. state.spotShadowMatrix.length = numSpotShadows;
  13179. hash.directionalLength = directionalLength;
  13180. hash.pointLength = pointLength;
  13181. hash.spotLength = spotLength;
  13182. hash.rectAreaLength = rectAreaLength;
  13183. hash.hemiLength = hemiLength;
  13184. hash.numDirectionalShadows = numDirectionalShadows;
  13185. hash.numPointShadows = numPointShadows;
  13186. hash.numSpotShadows = numSpotShadows;
  13187. state.version = nextVersion++;
  13188. }
  13189. }
  13190. return {
  13191. setup: setup,
  13192. state: state
  13193. };
  13194. }
  13195. /**
  13196. * @author Mugen87 / https://github.com/Mugen87
  13197. */
  13198. function WebGLRenderState() {
  13199. var lights = new WebGLLights();
  13200. var lightsArray = [];
  13201. var shadowsArray = [];
  13202. function init() {
  13203. lightsArray.length = 0;
  13204. shadowsArray.length = 0;
  13205. }
  13206. function pushLight(light) {
  13207. lightsArray.push(light);
  13208. }
  13209. function pushShadow(shadowLight) {
  13210. shadowsArray.push(shadowLight);
  13211. }
  13212. function setupLights(camera) {
  13213. lights.setup(lightsArray, shadowsArray, camera);
  13214. }
  13215. var state = {
  13216. lightsArray: lightsArray,
  13217. shadowsArray: shadowsArray,
  13218. lights: lights
  13219. };
  13220. return {
  13221. init: init,
  13222. state: state,
  13223. setupLights: setupLights,
  13224. pushLight: pushLight,
  13225. pushShadow: pushShadow
  13226. };
  13227. }
  13228. function WebGLRenderStates() {
  13229. var renderStates = new WeakMap();
  13230. function onSceneDispose(event) {
  13231. var scene = event.target;
  13232. scene.removeEventListener('dispose', onSceneDispose);
  13233. renderStates.delete(scene);
  13234. }
  13235. function get(scene, camera) {
  13236. var renderState;
  13237. if (renderStates.has(scene) === false) {
  13238. renderState = new WebGLRenderState();
  13239. renderStates.set(scene, new WeakMap());
  13240. renderStates.get(scene).set(camera, renderState);
  13241. scene.addEventListener('dispose', onSceneDispose);
  13242. } else {
  13243. if (renderStates.get(scene).has(camera) === false) {
  13244. renderState = new WebGLRenderState();
  13245. renderStates.get(scene).set(camera, renderState);
  13246. } else {
  13247. renderState = renderStates.get(scene).get(camera);
  13248. }
  13249. }
  13250. return renderState;
  13251. }
  13252. function dispose() {
  13253. renderStates = new WeakMap();
  13254. }
  13255. return {
  13256. get: get,
  13257. dispose: dispose
  13258. };
  13259. }
  13260. /**
  13261. * @author mrdoob / http://mrdoob.com/
  13262. * @author alteredq / http://alteredqualia.com/
  13263. * @author bhouston / https://clara.io
  13264. * @author WestLangley / http://github.com/WestLangley
  13265. *
  13266. * parameters = {
  13267. *
  13268. * opacity: <float>,
  13269. *
  13270. * map: new THREE.Texture( <Image> ),
  13271. *
  13272. * alphaMap: new THREE.Texture( <Image> ),
  13273. *
  13274. * displacementMap: new THREE.Texture( <Image> ),
  13275. * displacementScale: <float>,
  13276. * displacementBias: <float>,
  13277. *
  13278. * wireframe: <boolean>,
  13279. * wireframeLinewidth: <float>
  13280. * }
  13281. */
  13282. function MeshDepthMaterial(parameters) {
  13283. Material.call(this);
  13284. this.type = 'MeshDepthMaterial';
  13285. this.depthPacking = BasicDepthPacking;
  13286. this.skinning = false;
  13287. this.morphTargets = false;
  13288. this.map = null;
  13289. this.alphaMap = null;
  13290. this.displacementMap = null;
  13291. this.displacementScale = 1;
  13292. this.displacementBias = 0;
  13293. this.wireframe = false;
  13294. this.wireframeLinewidth = 1;
  13295. this.fog = false;
  13296. this.setValues(parameters);
  13297. }
  13298. MeshDepthMaterial.prototype = Object.create(Material.prototype);
  13299. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  13300. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  13301. MeshDepthMaterial.prototype.copy = function (source) {
  13302. Material.prototype.copy.call(this, source);
  13303. this.depthPacking = source.depthPacking;
  13304. this.skinning = source.skinning;
  13305. this.morphTargets = source.morphTargets;
  13306. this.map = source.map;
  13307. this.alphaMap = source.alphaMap;
  13308. this.displacementMap = source.displacementMap;
  13309. this.displacementScale = source.displacementScale;
  13310. this.displacementBias = source.displacementBias;
  13311. this.wireframe = source.wireframe;
  13312. this.wireframeLinewidth = source.wireframeLinewidth;
  13313. return this;
  13314. };
  13315. /**
  13316. * @author WestLangley / http://github.com/WestLangley
  13317. *
  13318. * parameters = {
  13319. *
  13320. * referencePosition: <float>,
  13321. * nearDistance: <float>,
  13322. * farDistance: <float>,
  13323. *
  13324. * skinning: <bool>,
  13325. * morphTargets: <bool>,
  13326. *
  13327. * map: new THREE.Texture( <Image> ),
  13328. *
  13329. * alphaMap: new THREE.Texture( <Image> ),
  13330. *
  13331. * displacementMap: new THREE.Texture( <Image> ),
  13332. * displacementScale: <float>,
  13333. * displacementBias: <float>
  13334. *
  13335. * }
  13336. */
  13337. function MeshDistanceMaterial(parameters) {
  13338. Material.call(this);
  13339. this.type = 'MeshDistanceMaterial';
  13340. this.referencePosition = new Vector3();
  13341. this.nearDistance = 1;
  13342. this.farDistance = 1000;
  13343. this.skinning = false;
  13344. this.morphTargets = false;
  13345. this.map = null;
  13346. this.alphaMap = null;
  13347. this.displacementMap = null;
  13348. this.displacementScale = 1;
  13349. this.displacementBias = 0;
  13350. this.fog = false;
  13351. this.setValues(parameters);
  13352. }
  13353. MeshDistanceMaterial.prototype = Object.create(Material.prototype);
  13354. MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;
  13355. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  13356. MeshDistanceMaterial.prototype.copy = function (source) {
  13357. Material.prototype.copy.call(this, source);
  13358. this.referencePosition.copy(source.referencePosition);
  13359. this.nearDistance = source.nearDistance;
  13360. this.farDistance = source.farDistance;
  13361. this.skinning = source.skinning;
  13362. this.morphTargets = source.morphTargets;
  13363. this.map = source.map;
  13364. this.alphaMap = source.alphaMap;
  13365. this.displacementMap = source.displacementMap;
  13366. this.displacementScale = source.displacementScale;
  13367. this.displacementBias = source.displacementBias;
  13368. return this;
  13369. };
  13370. var vsm_frag = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n float mean = 0.0;\n float squared_mean = 0.0;\n \n\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy ) / resolution ) );\n for ( float i = -1.0; i < 1.0 ; i += SAMPLE_RATE) {\n #ifdef HORIZONAL_PASS\n vec2 distribution = decodeHalfRGBA ( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( i, 0.0 ) * radius ) / resolution ) );\n mean += distribution.x;\n squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n #else\n float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, i ) * radius ) / resolution ) );\n mean += depth;\n squared_mean += depth * depth;\n #endif\n }\n mean = mean * HALF_SAMPLE_RATE;\n squared_mean = squared_mean * HALF_SAMPLE_RATE;\n float std_dev = pow( squared_mean - mean * mean, 0.5 );\n gl_FragColor = encodeHalfRGBA( vec2( mean, std_dev ) );\n}";
  13371. var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  13372. /**
  13373. * @author alteredq / http://alteredqualia.com/
  13374. * @author mrdoob / http://mrdoob.com/
  13375. */
  13376. function WebGLShadowMap(_renderer, _objects, maxTextureSize) {
  13377. var _frustum = new Frustum(),
  13378. _shadowMapSize = new Vector2(),
  13379. _viewportSize = new Vector2(),
  13380. _viewport = new Vector4(),
  13381. _MorphingFlag = 1,
  13382. _SkinningFlag = 2,
  13383. _NumberOfMaterialVariants = (_MorphingFlag | _SkinningFlag) + 1,
  13384. _depthMaterials = new Array(_NumberOfMaterialVariants),
  13385. _distanceMaterials = new Array(_NumberOfMaterialVariants),
  13386. _materialCache = {};
  13387. var shadowSide = {
  13388. 0: BackSide,
  13389. 1: FrontSide,
  13390. 2: DoubleSide
  13391. };
  13392. var shadowMaterialVertical = new ShaderMaterial({
  13393. defines: {
  13394. SAMPLE_RATE: 2.0 / 8.0,
  13395. HALF_SAMPLE_RATE: 1.0 / 8.0
  13396. },
  13397. uniforms: {
  13398. shadow_pass: {
  13399. value: null
  13400. },
  13401. resolution: {
  13402. value: new Vector2()
  13403. },
  13404. radius: {
  13405. value: 4.0
  13406. }
  13407. },
  13408. vertexShader: vsm_vert,
  13409. fragmentShader: vsm_frag
  13410. });
  13411. var shadowMaterialHorizonal = shadowMaterialVertical.clone();
  13412. shadowMaterialHorizonal.defines.HORIZONAL_PASS = 1;
  13413. var fullScreenTri = new BufferGeometry();
  13414. fullScreenTri.addAttribute("position", new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
  13415. var fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical); // init
  13416. for (var i = 0; i !== _NumberOfMaterialVariants; ++i) {
  13417. var useMorphing = (i & _MorphingFlag) !== 0;
  13418. var useSkinning = (i & _SkinningFlag) !== 0;
  13419. var depthMaterial = new MeshDepthMaterial({
  13420. depthPacking: RGBADepthPacking,
  13421. morphTargets: useMorphing,
  13422. skinning: useSkinning
  13423. });
  13424. _depthMaterials[i] = depthMaterial;
  13425. var distanceMaterial = new MeshDistanceMaterial({
  13426. morphTargets: useMorphing,
  13427. skinning: useSkinning
  13428. });
  13429. _distanceMaterials[i] = distanceMaterial;
  13430. }
  13431. var scope = this;
  13432. this.enabled = false;
  13433. this.autoUpdate = true;
  13434. this.needsUpdate = false;
  13435. this.type = PCFShadowMap;
  13436. this.render = function (lights, scene, camera) {
  13437. if (scope.enabled === false) return;
  13438. if (scope.autoUpdate === false && scope.needsUpdate === false) return;
  13439. if (lights.length === 0) return;
  13440. var currentRenderTarget = _renderer.getRenderTarget();
  13441. var activeCubeFace = _renderer.getActiveCubeFace();
  13442. var activeMipmapLevel = _renderer.getActiveMipmapLevel();
  13443. var _state = _renderer.state; // Set GL state for depth map.
  13444. _state.setBlending(NoBlending);
  13445. _state.buffers.color.setClear(1, 1, 1, 1);
  13446. _state.buffers.depth.setTest(true);
  13447. _state.setScissorTest(false); // render depth map
  13448. for (var i = 0, il = lights.length; i < il; i++) {
  13449. var light = lights[i];
  13450. var shadow = light.shadow;
  13451. if (shadow === undefined) {
  13452. console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
  13453. continue;
  13454. }
  13455. _shadowMapSize.copy(shadow.mapSize);
  13456. var shadowFrameExtents = shadow.getFrameExtents();
  13457. _shadowMapSize.multiply(shadowFrameExtents);
  13458. _viewportSize.copy(shadow.mapSize);
  13459. if (_shadowMapSize.x > maxTextureSize || _shadowMapSize.y > maxTextureSize) {
  13460. console.warn('THREE.WebGLShadowMap:', light, 'has shadow exceeding max texture size, reducing');
  13461. if (_shadowMapSize.x > maxTextureSize) {
  13462. _viewportSize.x = Math.floor(maxTextureSize / shadowFrameExtents.x);
  13463. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  13464. shadow.mapSize.x = _viewportSize.x;
  13465. }
  13466. if (_shadowMapSize.y > maxTextureSize) {
  13467. _viewportSize.y = Math.floor(maxTextureSize / shadowFrameExtents.y);
  13468. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  13469. shadow.mapSize.y = _viewportSize.y;
  13470. }
  13471. }
  13472. if (shadow.map === null && !shadow.isPointLightShadow && this.type === VSMShadowMap) {
  13473. var pars = {
  13474. minFilter: LinearFilter,
  13475. magFilter: LinearFilter,
  13476. format: RGBAFormat
  13477. };
  13478. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  13479. shadow.map.texture.name = light.name + ".shadowMap";
  13480. shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  13481. shadow.camera.updateProjectionMatrix();
  13482. }
  13483. if (shadow.map === null) {
  13484. var pars = {
  13485. minFilter: NearestFilter,
  13486. magFilter: NearestFilter,
  13487. format: RGBAFormat
  13488. };
  13489. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  13490. shadow.map.texture.name = light.name + ".shadowMap";
  13491. shadow.camera.updateProjectionMatrix();
  13492. }
  13493. _renderer.setRenderTarget(shadow.map);
  13494. _renderer.clear();
  13495. var viewportCount = shadow.getViewportCount();
  13496. for (var vp = 0; vp < viewportCount; vp++) {
  13497. var viewport = shadow.getViewport(vp);
  13498. _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
  13499. _state.viewport(_viewport);
  13500. shadow.updateMatrices(light, camera, vp);
  13501. _frustum = shadow.getFrustum();
  13502. renderObject(scene, camera, shadow.camera, light, this.type);
  13503. } // do blur pass for VSM
  13504. if (!shadow.isPointLightShadow && this.type === VSMShadowMap) {
  13505. VSMPass(shadow, camera);
  13506. }
  13507. }
  13508. scope.needsUpdate = false;
  13509. _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
  13510. };
  13511. function VSMPass(shadow, camera) {
  13512. var geometry = _objects.update(fullScreenMesh); // vertical pass
  13513. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  13514. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  13515. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  13516. _renderer.setRenderTarget(shadow.mapPass);
  13517. _renderer.clear();
  13518. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); // horizonal pass
  13519. shadowMaterialHorizonal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  13520. shadowMaterialHorizonal.uniforms.resolution.value = shadow.mapSize;
  13521. shadowMaterialHorizonal.uniforms.radius.value = shadow.radius;
  13522. _renderer.setRenderTarget(shadow.map);
  13523. _renderer.clear();
  13524. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizonal, fullScreenMesh, null);
  13525. }
  13526. function getDepthMaterial(object, material, light, shadowCameraNear, shadowCameraFar, type) {
  13527. var geometry = object.geometry;
  13528. var result = null;
  13529. var materialVariants = _depthMaterials;
  13530. var customMaterial = object.customDepthMaterial;
  13531. if (light.isPointLight) {
  13532. materialVariants = _distanceMaterials;
  13533. customMaterial = object.customDistanceMaterial;
  13534. }
  13535. if (!customMaterial) {
  13536. var useMorphing = false;
  13537. if (material.morphTargets) {
  13538. if (geometry && geometry.isBufferGeometry) {
  13539. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  13540. } else if (geometry && geometry.isGeometry) {
  13541. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  13542. }
  13543. }
  13544. if (object.isSkinnedMesh && material.skinning === false) {
  13545. console.warn('THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object);
  13546. }
  13547. var useSkinning = object.isSkinnedMesh && material.skinning;
  13548. var variantIndex = 0;
  13549. if (useMorphing) variantIndex |= _MorphingFlag;
  13550. if (useSkinning) variantIndex |= _SkinningFlag;
  13551. result = materialVariants[variantIndex];
  13552. } else {
  13553. result = customMaterial;
  13554. }
  13555. if (_renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0) {
  13556. // in this case we need a unique material instance reflecting the
  13557. // appropriate state
  13558. var keyA = result.uuid,
  13559. keyB = material.uuid;
  13560. var materialsForVariant = _materialCache[keyA];
  13561. if (materialsForVariant === undefined) {
  13562. materialsForVariant = {};
  13563. _materialCache[keyA] = materialsForVariant;
  13564. }
  13565. var cachedMaterial = materialsForVariant[keyB];
  13566. if (cachedMaterial === undefined) {
  13567. cachedMaterial = result.clone();
  13568. materialsForVariant[keyB] = cachedMaterial;
  13569. }
  13570. result = cachedMaterial;
  13571. }
  13572. result.visible = material.visible;
  13573. result.wireframe = material.wireframe;
  13574. if (type === VSMShadowMap) {
  13575. result.side = material.shadowSide != null ? material.shadowSide : material.side;
  13576. } else {
  13577. result.side = material.shadowSide != null ? material.shadowSide : shadowSide[material.side];
  13578. }
  13579. result.clipShadows = material.clipShadows;
  13580. result.clippingPlanes = material.clippingPlanes;
  13581. result.clipIntersection = material.clipIntersection;
  13582. result.wireframeLinewidth = material.wireframeLinewidth;
  13583. result.linewidth = material.linewidth;
  13584. if (light.isPointLight && result.isMeshDistanceMaterial) {
  13585. result.referencePosition.setFromMatrixPosition(light.matrixWorld);
  13586. result.nearDistance = shadowCameraNear;
  13587. result.farDistance = shadowCameraFar;
  13588. }
  13589. return result;
  13590. }
  13591. function renderObject(object, camera, shadowCamera, light, type) {
  13592. if (object.visible === false) return;
  13593. var visible = object.layers.test(camera.layers);
  13594. if (visible && (object.isMesh || object.isLine || object.isPoints)) {
  13595. if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
  13596. object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
  13597. var geometry = _objects.update(object);
  13598. var material = object.material;
  13599. if (Array.isArray(material)) {
  13600. var groups = geometry.groups;
  13601. for (var k = 0, kl = groups.length; k < kl; k++) {
  13602. var group = groups[k];
  13603. var groupMaterial = material[group.materialIndex];
  13604. if (groupMaterial && groupMaterial.visible) {
  13605. var depthMaterial = getDepthMaterial(object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
  13606. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
  13607. }
  13608. }
  13609. } else if (material.visible) {
  13610. var depthMaterial = getDepthMaterial(object, material, light, shadowCamera.near, shadowCamera.far, type);
  13611. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null);
  13612. }
  13613. }
  13614. }
  13615. var children = object.children;
  13616. for (var i = 0, l = children.length; i < l; i++) {
  13617. renderObject(children[i], camera, shadowCamera, light, type);
  13618. }
  13619. }
  13620. }
  13621. /**
  13622. * @author mrdoob / http://mrdoob.com/
  13623. */
  13624. function WebGLState(gl, extensions, utils, capabilities) {
  13625. function ColorBuffer() {
  13626. var locked = false;
  13627. var color = new Vector4();
  13628. var currentColorMask = null;
  13629. var currentColorClear = new Vector4(0, 0, 0, 0);
  13630. return {
  13631. setMask: function (colorMask) {
  13632. if (currentColorMask !== colorMask && !locked) {
  13633. gl.colorMask(colorMask, colorMask, colorMask, colorMask);
  13634. currentColorMask = colorMask;
  13635. }
  13636. },
  13637. setLocked: function (lock) {
  13638. locked = lock;
  13639. },
  13640. setClear: function (r, g, b, a, premultipliedAlpha) {
  13641. if (premultipliedAlpha === true) {
  13642. r *= a;
  13643. g *= a;
  13644. b *= a;
  13645. }
  13646. color.set(r, g, b, a);
  13647. if (currentColorClear.equals(color) === false) {
  13648. gl.clearColor(r, g, b, a);
  13649. currentColorClear.copy(color);
  13650. }
  13651. },
  13652. reset: function () {
  13653. locked = false;
  13654. currentColorMask = null;
  13655. currentColorClear.set(-1, 0, 0, 0); // set to invalid state
  13656. }
  13657. };
  13658. }
  13659. function DepthBuffer() {
  13660. var locked = false;
  13661. var currentDepthMask = null;
  13662. var currentDepthFunc = null;
  13663. var currentDepthClear = null;
  13664. return {
  13665. setTest: function (depthTest) {
  13666. if (depthTest) {
  13667. enable(2929);
  13668. } else {
  13669. disable(2929);
  13670. }
  13671. },
  13672. setMask: function (depthMask) {
  13673. if (currentDepthMask !== depthMask && !locked) {
  13674. gl.depthMask(depthMask);
  13675. currentDepthMask = depthMask;
  13676. }
  13677. },
  13678. setFunc: function (depthFunc) {
  13679. if (currentDepthFunc !== depthFunc) {
  13680. if (depthFunc) {
  13681. switch (depthFunc) {
  13682. case NeverDepth:
  13683. gl.depthFunc(512);
  13684. break;
  13685. case AlwaysDepth:
  13686. gl.depthFunc(519);
  13687. break;
  13688. case LessDepth:
  13689. gl.depthFunc(513);
  13690. break;
  13691. case LessEqualDepth:
  13692. gl.depthFunc(515);
  13693. break;
  13694. case EqualDepth:
  13695. gl.depthFunc(514);
  13696. break;
  13697. case GreaterEqualDepth:
  13698. gl.depthFunc(518);
  13699. break;
  13700. case GreaterDepth:
  13701. gl.depthFunc(516);
  13702. break;
  13703. case NotEqualDepth:
  13704. gl.depthFunc(517);
  13705. break;
  13706. default:
  13707. gl.depthFunc(515);
  13708. }
  13709. } else {
  13710. gl.depthFunc(515);
  13711. }
  13712. currentDepthFunc = depthFunc;
  13713. }
  13714. },
  13715. setLocked: function (lock) {
  13716. locked = lock;
  13717. },
  13718. setClear: function (depth) {
  13719. if (currentDepthClear !== depth) {
  13720. gl.clearDepth(depth);
  13721. currentDepthClear = depth;
  13722. }
  13723. },
  13724. reset: function () {
  13725. locked = false;
  13726. currentDepthMask = null;
  13727. currentDepthFunc = null;
  13728. currentDepthClear = null;
  13729. }
  13730. };
  13731. }
  13732. function StencilBuffer() {
  13733. var locked = false;
  13734. var currentStencilMask = null;
  13735. var currentStencilFunc = null;
  13736. var currentStencilRef = null;
  13737. var currentStencilFuncMask = null;
  13738. var currentStencilFail = null;
  13739. var currentStencilZFail = null;
  13740. var currentStencilZPass = null;
  13741. var currentStencilClear = null;
  13742. return {
  13743. setTest: function (stencilTest) {
  13744. if (!locked) {
  13745. if (stencilTest) {
  13746. enable(2960);
  13747. } else {
  13748. disable(2960);
  13749. }
  13750. }
  13751. },
  13752. setMask: function (stencilMask) {
  13753. if (currentStencilMask !== stencilMask && !locked) {
  13754. gl.stencilMask(stencilMask);
  13755. currentStencilMask = stencilMask;
  13756. }
  13757. },
  13758. setFunc: function (stencilFunc, stencilRef, stencilMask) {
  13759. if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
  13760. gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
  13761. currentStencilFunc = stencilFunc;
  13762. currentStencilRef = stencilRef;
  13763. currentStencilFuncMask = stencilMask;
  13764. }
  13765. },
  13766. setOp: function (stencilFail, stencilZFail, stencilZPass) {
  13767. if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
  13768. gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
  13769. currentStencilFail = stencilFail;
  13770. currentStencilZFail = stencilZFail;
  13771. currentStencilZPass = stencilZPass;
  13772. }
  13773. },
  13774. setLocked: function (lock) {
  13775. locked = lock;
  13776. },
  13777. setClear: function (stencil) {
  13778. if (currentStencilClear !== stencil) {
  13779. gl.clearStencil(stencil);
  13780. currentStencilClear = stencil;
  13781. }
  13782. },
  13783. reset: function () {
  13784. locked = false;
  13785. currentStencilMask = null;
  13786. currentStencilFunc = null;
  13787. currentStencilRef = null;
  13788. currentStencilFuncMask = null;
  13789. currentStencilFail = null;
  13790. currentStencilZFail = null;
  13791. currentStencilZPass = null;
  13792. currentStencilClear = null;
  13793. }
  13794. };
  13795. } //
  13796. var colorBuffer = new ColorBuffer();
  13797. var depthBuffer = new DepthBuffer();
  13798. var stencilBuffer = new StencilBuffer();
  13799. var maxVertexAttributes = gl.getParameter(34921);
  13800. var newAttributes = new Uint8Array(maxVertexAttributes);
  13801. var enabledAttributes = new Uint8Array(maxVertexAttributes);
  13802. var attributeDivisors = new Uint8Array(maxVertexAttributes);
  13803. var enabledCapabilities = {};
  13804. var compressedTextureFormats = null;
  13805. var currentProgram = null;
  13806. var currentBlendingEnabled = null;
  13807. var currentBlending = null;
  13808. var currentBlendEquation = null;
  13809. var currentBlendSrc = null;
  13810. var currentBlendDst = null;
  13811. var currentBlendEquationAlpha = null;
  13812. var currentBlendSrcAlpha = null;
  13813. var currentBlendDstAlpha = null;
  13814. var currentPremultipledAlpha = false;
  13815. var currentFlipSided = null;
  13816. var currentCullFace = null;
  13817. var currentLineWidth = null;
  13818. var currentPolygonOffsetFactor = null;
  13819. var currentPolygonOffsetUnits = null;
  13820. var maxTextures = gl.getParameter(35661);
  13821. var lineWidthAvailable = false;
  13822. var version = 0;
  13823. var glVersion = gl.getParameter(7938);
  13824. if (glVersion.indexOf('WebGL') !== -1) {
  13825. version = parseFloat(/^WebGL\ ([0-9])/.exec(glVersion)[1]);
  13826. lineWidthAvailable = version >= 1.0;
  13827. } else if (glVersion.indexOf('OpenGL ES') !== -1) {
  13828. version = parseFloat(/^OpenGL\ ES\ ([0-9])/.exec(glVersion)[1]);
  13829. lineWidthAvailable = version >= 2.0;
  13830. }
  13831. var currentTextureSlot = null;
  13832. var currentBoundTextures = {};
  13833. var currentScissor = new Vector4();
  13834. var currentViewport = new Vector4();
  13835. function createTexture(type, target, count) {
  13836. var data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
  13837. var texture = gl.createTexture();
  13838. gl.bindTexture(type, texture);
  13839. gl.texParameteri(type, 10241, 9728);
  13840. gl.texParameteri(type, 10240, 9728);
  13841. for (var i = 0; i < count; i++) {
  13842. gl.texImage2D(target + i, 0, 6408, 1, 1, 0, 6408, 5121, data);
  13843. }
  13844. return texture;
  13845. }
  13846. var emptyTextures = {};
  13847. emptyTextures[3553] = createTexture(3553, 3553, 1);
  13848. emptyTextures[34067] = createTexture(34067, 34069, 6); // init
  13849. colorBuffer.setClear(0, 0, 0, 1);
  13850. depthBuffer.setClear(1);
  13851. stencilBuffer.setClear(0);
  13852. enable(2929);
  13853. depthBuffer.setFunc(LessEqualDepth);
  13854. setFlipSided(false);
  13855. setCullFace(CullFaceBack);
  13856. enable(2884);
  13857. setBlending(NoBlending); //
  13858. function initAttributes() {
  13859. for (var i = 0, l = newAttributes.length; i < l; i++) {
  13860. newAttributes[i] = 0;
  13861. }
  13862. }
  13863. function enableAttribute(attribute) {
  13864. enableAttributeAndDivisor(attribute, 0);
  13865. }
  13866. function enableAttributeAndDivisor(attribute, meshPerAttribute) {
  13867. newAttributes[attribute] = 1;
  13868. if (enabledAttributes[attribute] === 0) {
  13869. gl.enableVertexAttribArray(attribute);
  13870. enabledAttributes[attribute] = 1;
  13871. }
  13872. if (attributeDivisors[attribute] !== meshPerAttribute) {
  13873. var extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
  13874. extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
  13875. attributeDivisors[attribute] = meshPerAttribute;
  13876. }
  13877. }
  13878. function disableUnusedAttributes() {
  13879. for (var i = 0, l = enabledAttributes.length; i !== l; ++i) {
  13880. if (enabledAttributes[i] !== newAttributes[i]) {
  13881. gl.disableVertexAttribArray(i);
  13882. enabledAttributes[i] = 0;
  13883. }
  13884. }
  13885. }
  13886. function enable(id) {
  13887. if (enabledCapabilities[id] !== true) {
  13888. gl.enable(id);
  13889. enabledCapabilities[id] = true;
  13890. }
  13891. }
  13892. function disable(id) {
  13893. if (enabledCapabilities[id] !== false) {
  13894. gl.disable(id);
  13895. enabledCapabilities[id] = false;
  13896. }
  13897. }
  13898. function getCompressedTextureFormats() {
  13899. if (compressedTextureFormats === null) {
  13900. compressedTextureFormats = [];
  13901. if (extensions.get('WEBGL_compressed_texture_pvrtc') || extensions.get('WEBGL_compressed_texture_s3tc') || extensions.get('WEBGL_compressed_texture_etc1') || extensions.get('WEBGL_compressed_texture_astc')) {
  13902. var formats = gl.getParameter(34467);
  13903. for (var i = 0; i < formats.length; i++) {
  13904. compressedTextureFormats.push(formats[i]);
  13905. }
  13906. }
  13907. }
  13908. return compressedTextureFormats;
  13909. }
  13910. function useProgram(program) {
  13911. if (currentProgram !== program) {
  13912. gl.useProgram(program);
  13913. currentProgram = program;
  13914. return true;
  13915. }
  13916. return false;
  13917. }
  13918. function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
  13919. if (blending === NoBlending) {
  13920. if (currentBlendingEnabled) {
  13921. disable(3042);
  13922. currentBlendingEnabled = false;
  13923. }
  13924. return;
  13925. }
  13926. if (!currentBlendingEnabled) {
  13927. enable(3042);
  13928. currentBlendingEnabled = true;
  13929. }
  13930. if (blending !== CustomBlending) {
  13931. if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
  13932. if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
  13933. gl.blendEquation(32774);
  13934. currentBlendEquation = AddEquation;
  13935. currentBlendEquationAlpha = AddEquation;
  13936. }
  13937. if (premultipliedAlpha) {
  13938. switch (blending) {
  13939. case NormalBlending:
  13940. gl.blendFuncSeparate(1, 771, 1, 771);
  13941. break;
  13942. case AdditiveBlending:
  13943. gl.blendFunc(1, 1);
  13944. break;
  13945. case SubtractiveBlending:
  13946. gl.blendFuncSeparate(0, 0, 769, 771);
  13947. break;
  13948. case MultiplyBlending:
  13949. gl.blendFuncSeparate(0, 768, 0, 770);
  13950. break;
  13951. default:
  13952. console.error('THREE.WebGLState: Invalid blending: ', blending);
  13953. break;
  13954. }
  13955. } else {
  13956. switch (blending) {
  13957. case NormalBlending:
  13958. gl.blendFuncSeparate(770, 771, 1, 771);
  13959. break;
  13960. case AdditiveBlending:
  13961. gl.blendFunc(770, 1);
  13962. break;
  13963. case SubtractiveBlending:
  13964. gl.blendFunc(0, 769);
  13965. break;
  13966. case MultiplyBlending:
  13967. gl.blendFunc(0, 768);
  13968. break;
  13969. default:
  13970. console.error('THREE.WebGLState: Invalid blending: ', blending);
  13971. break;
  13972. }
  13973. }
  13974. currentBlendSrc = null;
  13975. currentBlendDst = null;
  13976. currentBlendSrcAlpha = null;
  13977. currentBlendDstAlpha = null;
  13978. currentBlending = blending;
  13979. currentPremultipledAlpha = premultipliedAlpha;
  13980. }
  13981. return;
  13982. } // custom blending
  13983. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13984. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13985. blendDstAlpha = blendDstAlpha || blendDst;
  13986. if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
  13987. gl.blendEquationSeparate(utils.convert(blendEquation), utils.convert(blendEquationAlpha));
  13988. currentBlendEquation = blendEquation;
  13989. currentBlendEquationAlpha = blendEquationAlpha;
  13990. }
  13991. if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
  13992. gl.blendFuncSeparate(utils.convert(blendSrc), utils.convert(blendDst), utils.convert(blendSrcAlpha), utils.convert(blendDstAlpha));
  13993. currentBlendSrc = blendSrc;
  13994. currentBlendDst = blendDst;
  13995. currentBlendSrcAlpha = blendSrcAlpha;
  13996. currentBlendDstAlpha = blendDstAlpha;
  13997. }
  13998. currentBlending = blending;
  13999. currentPremultipledAlpha = null;
  14000. }
  14001. function setMaterial(material, frontFaceCW) {
  14002. material.side === DoubleSide ? disable(2884) : enable(2884);
  14003. var flipSided = material.side === BackSide;
  14004. if (frontFaceCW) flipSided = !flipSided;
  14005. setFlipSided(flipSided);
  14006. material.blending === NormalBlending && material.transparent === false ? setBlending(NoBlending) : setBlending(material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha);
  14007. depthBuffer.setFunc(material.depthFunc);
  14008. depthBuffer.setTest(material.depthTest);
  14009. depthBuffer.setMask(material.depthWrite);
  14010. colorBuffer.setMask(material.colorWrite);
  14011. var stencilWrite = material.stencilWrite;
  14012. stencilBuffer.setTest(stencilWrite);
  14013. if (stencilWrite) {
  14014. stencilBuffer.setMask(material.stencilWriteMask);
  14015. stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
  14016. stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
  14017. }
  14018. setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
  14019. } //
  14020. function setFlipSided(flipSided) {
  14021. if (currentFlipSided !== flipSided) {
  14022. if (flipSided) {
  14023. gl.frontFace(2304);
  14024. } else {
  14025. gl.frontFace(2305);
  14026. }
  14027. currentFlipSided = flipSided;
  14028. }
  14029. }
  14030. function setCullFace(cullFace) {
  14031. if (cullFace !== CullFaceNone) {
  14032. enable(2884);
  14033. if (cullFace !== currentCullFace) {
  14034. if (cullFace === CullFaceBack) {
  14035. gl.cullFace(1029);
  14036. } else if (cullFace === CullFaceFront) {
  14037. gl.cullFace(1028);
  14038. } else {
  14039. gl.cullFace(1032);
  14040. }
  14041. }
  14042. } else {
  14043. disable(2884);
  14044. }
  14045. currentCullFace = cullFace;
  14046. }
  14047. function setLineWidth(width) {
  14048. if (width !== currentLineWidth) {
  14049. if (lineWidthAvailable) gl.lineWidth(width);
  14050. currentLineWidth = width;
  14051. }
  14052. }
  14053. function setPolygonOffset(polygonOffset, factor, units) {
  14054. if (polygonOffset) {
  14055. enable(32823);
  14056. if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
  14057. gl.polygonOffset(factor, units);
  14058. currentPolygonOffsetFactor = factor;
  14059. currentPolygonOffsetUnits = units;
  14060. }
  14061. } else {
  14062. disable(32823);
  14063. }
  14064. }
  14065. function setScissorTest(scissorTest) {
  14066. if (scissorTest) {
  14067. enable(3089);
  14068. } else {
  14069. disable(3089);
  14070. }
  14071. } // texture
  14072. function activeTexture(webglSlot) {
  14073. if (webglSlot === undefined) webglSlot = 33984 + maxTextures - 1;
  14074. if (currentTextureSlot !== webglSlot) {
  14075. gl.activeTexture(webglSlot);
  14076. currentTextureSlot = webglSlot;
  14077. }
  14078. }
  14079. function bindTexture(webglType, webglTexture) {
  14080. if (currentTextureSlot === null) {
  14081. activeTexture();
  14082. }
  14083. var boundTexture = currentBoundTextures[currentTextureSlot];
  14084. if (boundTexture === undefined) {
  14085. boundTexture = {
  14086. type: undefined,
  14087. texture: undefined
  14088. };
  14089. currentBoundTextures[currentTextureSlot] = boundTexture;
  14090. }
  14091. if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
  14092. gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
  14093. boundTexture.type = webglType;
  14094. boundTexture.texture = webglTexture;
  14095. }
  14096. }
  14097. function compressedTexImage2D() {
  14098. try {
  14099. gl.compressedTexImage2D.apply(gl, arguments);
  14100. } catch (error) {
  14101. console.error('THREE.WebGLState:', error);
  14102. }
  14103. }
  14104. function texImage2D() {
  14105. try {
  14106. gl.texImage2D.apply(gl, arguments);
  14107. } catch (error) {
  14108. console.error('THREE.WebGLState:', error);
  14109. }
  14110. }
  14111. function texImage3D() {
  14112. try {
  14113. gl.texImage3D.apply(gl, arguments);
  14114. } catch (error) {
  14115. console.error('THREE.WebGLState:', error);
  14116. }
  14117. } //
  14118. function scissor(scissor) {
  14119. if (currentScissor.equals(scissor) === false) {
  14120. gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
  14121. currentScissor.copy(scissor);
  14122. }
  14123. }
  14124. function viewport(viewport) {
  14125. if (currentViewport.equals(viewport) === false) {
  14126. gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
  14127. currentViewport.copy(viewport);
  14128. }
  14129. } //
  14130. function reset() {
  14131. for (var i = 0; i < enabledAttributes.length; i++) {
  14132. if (enabledAttributes[i] === 1) {
  14133. gl.disableVertexAttribArray(i);
  14134. enabledAttributes[i] = 0;
  14135. }
  14136. }
  14137. enabledCapabilities = {};
  14138. compressedTextureFormats = null;
  14139. currentTextureSlot = null;
  14140. currentBoundTextures = {};
  14141. currentProgram = null;
  14142. currentBlending = null;
  14143. currentFlipSided = null;
  14144. currentCullFace = null;
  14145. colorBuffer.reset();
  14146. depthBuffer.reset();
  14147. stencilBuffer.reset();
  14148. }
  14149. return {
  14150. buffers: {
  14151. color: colorBuffer,
  14152. depth: depthBuffer,
  14153. stencil: stencilBuffer
  14154. },
  14155. initAttributes: initAttributes,
  14156. enableAttribute: enableAttribute,
  14157. enableAttributeAndDivisor: enableAttributeAndDivisor,
  14158. disableUnusedAttributes: disableUnusedAttributes,
  14159. enable: enable,
  14160. disable: disable,
  14161. getCompressedTextureFormats: getCompressedTextureFormats,
  14162. useProgram: useProgram,
  14163. setBlending: setBlending,
  14164. setMaterial: setMaterial,
  14165. setFlipSided: setFlipSided,
  14166. setCullFace: setCullFace,
  14167. setLineWidth: setLineWidth,
  14168. setPolygonOffset: setPolygonOffset,
  14169. setScissorTest: setScissorTest,
  14170. activeTexture: activeTexture,
  14171. bindTexture: bindTexture,
  14172. compressedTexImage2D: compressedTexImage2D,
  14173. texImage2D: texImage2D,
  14174. texImage3D: texImage3D,
  14175. scissor: scissor,
  14176. viewport: viewport,
  14177. reset: reset
  14178. };
  14179. }
  14180. /**
  14181. * @author mrdoob / http://mrdoob.com/
  14182. */
  14183. function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
  14184. var _videoTextures = new WeakMap();
  14185. var _canvas; // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  14186. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  14187. var useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && new OffscreenCanvas(1, 1).getContext("2d") !== null;
  14188. function createCanvas(width, height) {
  14189. // Use OffscreenCanvas when available. Specially needed in web workers
  14190. return useOffscreenCanvas ? new OffscreenCanvas(width, height) : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  14191. }
  14192. function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
  14193. var scale = 1; // handle case if texture exceeds max size
  14194. if (image.width > maxSize || image.height > maxSize) {
  14195. scale = maxSize / Math.max(image.width, image.height);
  14196. } // only perform resize if necessary
  14197. if (scale < 1 || needsPowerOfTwo === true) {
  14198. // only perform resize for certain image types
  14199. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  14200. var floor = needsPowerOfTwo ? _Math.floorPowerOfTwo : Math.floor;
  14201. var width = floor(scale * image.width);
  14202. var height = floor(scale * image.height);
  14203. if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvas
  14204. var canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
  14205. canvas.width = width;
  14206. canvas.height = height;
  14207. var context = canvas.getContext('2d');
  14208. context.drawImage(image, 0, 0, width, height);
  14209. console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
  14210. return canvas;
  14211. } else {
  14212. if ('data' in image) {
  14213. console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
  14214. }
  14215. return image;
  14216. }
  14217. }
  14218. return image;
  14219. }
  14220. function isPowerOfTwo(image) {
  14221. return _Math.isPowerOfTwo(image.width) && _Math.isPowerOfTwo(image.height);
  14222. }
  14223. function textureNeedsPowerOfTwo(texture) {
  14224. if (capabilities.isWebGL2) return false;
  14225. return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  14226. }
  14227. function textureNeedsGenerateMipmaps(texture, supportsMips) {
  14228. return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  14229. }
  14230. function generateMipmap(target, texture, width, height) {
  14231. _gl.generateMipmap(target);
  14232. var textureProperties = properties.get(texture); // Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11
  14233. textureProperties.__maxMipLevel = Math.log(Math.max(width, height)) * Math.LOG2E;
  14234. }
  14235. function getInternalFormat(glFormat, glType) {
  14236. if (!capabilities.isWebGL2) return glFormat;
  14237. var internalFormat = glFormat;
  14238. if (glFormat === 6403) {
  14239. if (glType === 5126) internalFormat = 33326;
  14240. if (glType === 5131) internalFormat = 33325;
  14241. if (glType === 5121) internalFormat = 33321;
  14242. }
  14243. if (glFormat === 6407) {
  14244. if (glType === 5126) internalFormat = 34837;
  14245. if (glType === 5131) internalFormat = 34843;
  14246. if (glType === 5121) internalFormat = 32849;
  14247. }
  14248. if (glFormat === 6408) {
  14249. if (glType === 5126) internalFormat = 34836;
  14250. if (glType === 5131) internalFormat = 34842;
  14251. if (glType === 5121) internalFormat = 32856;
  14252. }
  14253. if (internalFormat === 33325 || internalFormat === 33326 || internalFormat === 34842 || internalFormat === 34836) {
  14254. extensions.get('EXT_color_buffer_float');
  14255. } else if (internalFormat === 34843 || internalFormat === 34837) {
  14256. console.warn('THREE.WebGLRenderer: Floating point textures with RGB format not supported. Please use RGBA instead.');
  14257. }
  14258. return internalFormat;
  14259. } // Fallback filters for non-power-of-2 textures
  14260. function filterFallback(f) {
  14261. if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
  14262. return 9728;
  14263. }
  14264. return 9729;
  14265. } //
  14266. function onTextureDispose(event) {
  14267. var texture = event.target;
  14268. texture.removeEventListener('dispose', onTextureDispose);
  14269. deallocateTexture(texture);
  14270. if (texture.isVideoTexture) {
  14271. _videoTextures.delete(texture);
  14272. }
  14273. info.memory.textures--;
  14274. }
  14275. function onRenderTargetDispose(event) {
  14276. var renderTarget = event.target;
  14277. renderTarget.removeEventListener('dispose', onRenderTargetDispose);
  14278. deallocateRenderTarget(renderTarget);
  14279. info.memory.textures--;
  14280. } //
  14281. function deallocateTexture(texture) {
  14282. var textureProperties = properties.get(texture);
  14283. if (textureProperties.__webglInit === undefined) return;
  14284. _gl.deleteTexture(textureProperties.__webglTexture);
  14285. properties.remove(texture);
  14286. }
  14287. function deallocateRenderTarget(renderTarget) {
  14288. var renderTargetProperties = properties.get(renderTarget);
  14289. var textureProperties = properties.get(renderTarget.texture);
  14290. if (!renderTarget) return;
  14291. if (textureProperties.__webglTexture !== undefined) {
  14292. _gl.deleteTexture(textureProperties.__webglTexture);
  14293. }
  14294. if (renderTarget.depthTexture) {
  14295. renderTarget.depthTexture.dispose();
  14296. }
  14297. if (renderTarget.isWebGLRenderTargetCube) {
  14298. for (var i = 0; i < 6; i++) {
  14299. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
  14300. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
  14301. }
  14302. } else {
  14303. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
  14304. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
  14305. }
  14306. if (renderTarget.isWebGLMultiviewRenderTarget) {
  14307. _gl.deleteTexture(renderTargetProperties.__webglColorTexture);
  14308. _gl.deleteTexture(renderTargetProperties.__webglDepthStencilTexture);
  14309. info.memory.textures -= 2;
  14310. for (var i = 0, il = renderTargetProperties.__webglViewFramebuffers.length; i < il; i++) {
  14311. _gl.deleteFramebuffer(renderTargetProperties.__webglViewFramebuffers[i]);
  14312. }
  14313. }
  14314. properties.remove(renderTarget.texture);
  14315. properties.remove(renderTarget);
  14316. } //
  14317. var textureUnits = 0;
  14318. function resetTextureUnits() {
  14319. textureUnits = 0;
  14320. }
  14321. function allocateTextureUnit() {
  14322. var textureUnit = textureUnits;
  14323. if (textureUnit >= capabilities.maxTextures) {
  14324. console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures);
  14325. }
  14326. textureUnits += 1;
  14327. return textureUnit;
  14328. } //
  14329. function setTexture2D(texture, slot) {
  14330. var textureProperties = properties.get(texture);
  14331. if (texture.isVideoTexture) updateVideoTexture(texture);
  14332. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  14333. var image = texture.image;
  14334. if (image === undefined) {
  14335. console.warn('THREE.WebGLRenderer: Texture marked for update but image is undefined');
  14336. } else if (image.complete === false) {
  14337. console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
  14338. } else {
  14339. uploadTexture(textureProperties, texture, slot);
  14340. return;
  14341. }
  14342. }
  14343. state.activeTexture(33984 + slot);
  14344. state.bindTexture(3553, textureProperties.__webglTexture);
  14345. }
  14346. function setTexture2DArray(texture, slot) {
  14347. var textureProperties = properties.get(texture);
  14348. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  14349. uploadTexture(textureProperties, texture, slot);
  14350. return;
  14351. }
  14352. state.activeTexture(33984 + slot);
  14353. state.bindTexture(35866, textureProperties.__webglTexture);
  14354. }
  14355. function setTexture3D(texture, slot) {
  14356. var textureProperties = properties.get(texture);
  14357. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  14358. uploadTexture(textureProperties, texture, slot);
  14359. return;
  14360. }
  14361. state.activeTexture(33984 + slot);
  14362. state.bindTexture(32879, textureProperties.__webglTexture);
  14363. }
  14364. function setTextureCube(texture, slot) {
  14365. if (texture.image.length !== 6) return;
  14366. var textureProperties = properties.get(texture);
  14367. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  14368. initTexture(textureProperties, texture);
  14369. state.activeTexture(33984 + slot);
  14370. state.bindTexture(34067, textureProperties.__webglTexture);
  14371. _gl.pixelStorei(37440, texture.flipY);
  14372. var isCompressed = texture && texture.isCompressedTexture;
  14373. var isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
  14374. var cubeImage = [];
  14375. for (var i = 0; i < 6; i++) {
  14376. if (!isCompressed && !isDataTexture) {
  14377. cubeImage[i] = resizeImage(texture.image[i], false, true, capabilities.maxCubemapSize);
  14378. } else {
  14379. cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
  14380. }
  14381. }
  14382. var image = cubeImage[0],
  14383. supportsMips = isPowerOfTwo(image) || capabilities.isWebGL2,
  14384. glFormat = utils.convert(texture.format),
  14385. glType = utils.convert(texture.type),
  14386. glInternalFormat = getInternalFormat(glFormat, glType);
  14387. setTextureParameters(34067, texture, supportsMips);
  14388. var mipmaps;
  14389. if (isCompressed) {
  14390. for (var i = 0; i < 6; i++) {
  14391. mipmaps = cubeImage[i].mipmaps;
  14392. for (var j = 0; j < mipmaps.length; j++) {
  14393. var mipmap = mipmaps[j];
  14394. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  14395. if (state.getCompressedTextureFormats().indexOf(glFormat) > -1) {
  14396. state.compressedTexImage2D(34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  14397. } else {
  14398. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
  14399. }
  14400. } else {
  14401. state.texImage2D(34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  14402. }
  14403. }
  14404. }
  14405. textureProperties.__maxMipLevel = mipmaps.length - 1;
  14406. } else {
  14407. mipmaps = texture.mipmaps;
  14408. for (var i = 0; i < 6; i++) {
  14409. if (isDataTexture) {
  14410. state.texImage2D(34069 + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data);
  14411. for (var j = 0; j < mipmaps.length; j++) {
  14412. var mipmap = mipmaps[j];
  14413. var mipmapImage = mipmap.image[i].image;
  14414. state.texImage2D(34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
  14415. }
  14416. } else {
  14417. state.texImage2D(34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]);
  14418. for (var j = 0; j < mipmaps.length; j++) {
  14419. var mipmap = mipmaps[j];
  14420. state.texImage2D(34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]);
  14421. }
  14422. }
  14423. }
  14424. textureProperties.__maxMipLevel = mipmaps.length;
  14425. }
  14426. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14427. // We assume images for cube map have the same size.
  14428. generateMipmap(34067, texture, image.width, image.height);
  14429. }
  14430. textureProperties.__version = texture.version;
  14431. if (texture.onUpdate) texture.onUpdate(texture);
  14432. } else {
  14433. state.activeTexture(33984 + slot);
  14434. state.bindTexture(34067, textureProperties.__webglTexture);
  14435. }
  14436. }
  14437. function setTextureCubeDynamic(texture, slot) {
  14438. state.activeTexture(33984 + slot);
  14439. state.bindTexture(34067, properties.get(texture).__webglTexture);
  14440. }
  14441. function setTextureParameters(textureType, texture, supportsMips) {
  14442. var extension;
  14443. if (supportsMips) {
  14444. _gl.texParameteri(textureType, 10242, utils.convert(texture.wrapS));
  14445. _gl.texParameteri(textureType, 10243, utils.convert(texture.wrapT));
  14446. if (textureType === 32879 || textureType === 35866) {
  14447. _gl.texParameteri(textureType, 32882, utils.convert(texture.wrapR));
  14448. }
  14449. _gl.texParameteri(textureType, 10240, utils.convert(texture.magFilter));
  14450. _gl.texParameteri(textureType, 10241, utils.convert(texture.minFilter));
  14451. } else {
  14452. _gl.texParameteri(textureType, 10242, 33071);
  14453. _gl.texParameteri(textureType, 10243, 33071);
  14454. if (textureType === 32879 || textureType === 35866) {
  14455. _gl.texParameteri(textureType, 32882, 33071);
  14456. }
  14457. if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
  14458. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
  14459. }
  14460. _gl.texParameteri(textureType, 10240, filterFallback(texture.magFilter));
  14461. _gl.texParameteri(textureType, 10241, filterFallback(texture.minFilter));
  14462. if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  14463. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
  14464. }
  14465. }
  14466. extension = extensions.get('EXT_texture_filter_anisotropic');
  14467. if (extension) {
  14468. if (texture.type === FloatType && extensions.get('OES_texture_float_linear') === null) return;
  14469. if (texture.type === HalfFloatType && (capabilities.isWebGL2 || extensions.get('OES_texture_half_float_linear')) === null) return;
  14470. if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
  14471. _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
  14472. properties.get(texture).__currentAnisotropy = texture.anisotropy;
  14473. }
  14474. }
  14475. }
  14476. function initTexture(textureProperties, texture) {
  14477. if (textureProperties.__webglInit === undefined) {
  14478. textureProperties.__webglInit = true;
  14479. texture.addEventListener('dispose', onTextureDispose);
  14480. textureProperties.__webglTexture = _gl.createTexture();
  14481. info.memory.textures++;
  14482. }
  14483. }
  14484. function uploadTexture(textureProperties, texture, slot) {
  14485. var textureType = 3553;
  14486. if (texture.isDataTexture2DArray) textureType = 35866;
  14487. if (texture.isDataTexture3D) textureType = 32879;
  14488. initTexture(textureProperties, texture);
  14489. state.activeTexture(33984 + slot);
  14490. state.bindTexture(textureType, textureProperties.__webglTexture);
  14491. _gl.pixelStorei(37440, texture.flipY);
  14492. _gl.pixelStorei(37441, texture.premultiplyAlpha);
  14493. _gl.pixelStorei(3317, texture.unpackAlignment);
  14494. var needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo(texture.image) === false;
  14495. var image = resizeImage(texture.image, needsPowerOfTwo, false, capabilities.maxTextureSize);
  14496. var supportsMips = isPowerOfTwo(image) || capabilities.isWebGL2,
  14497. glFormat = utils.convert(texture.format),
  14498. glType = utils.convert(texture.type),
  14499. glInternalFormat = getInternalFormat(glFormat, glType);
  14500. setTextureParameters(textureType, texture, supportsMips);
  14501. var mipmap,
  14502. mipmaps = texture.mipmaps;
  14503. if (texture.isDepthTexture) {
  14504. // populate depth texture with dummy data
  14505. glInternalFormat = 6402;
  14506. if (texture.type === FloatType) {
  14507. if (!capabilities.isWebGL2) throw new Error('Float Depth Texture only supported in WebGL2.0');
  14508. glInternalFormat = 36012;
  14509. } else if (capabilities.isWebGL2) {
  14510. // WebGL 2.0 requires signed internalformat for glTexImage2D
  14511. glInternalFormat = 33189;
  14512. }
  14513. if (texture.format === DepthFormat && glInternalFormat === 6402) {
  14514. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14515. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  14516. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14517. if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
  14518. console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
  14519. texture.type = UnsignedShortType;
  14520. glType = utils.convert(texture.type);
  14521. }
  14522. } // Depth stencil textures need the DEPTH_STENCIL internal format
  14523. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14524. if (texture.format === DepthStencilFormat) {
  14525. glInternalFormat = 34041; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14526. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  14527. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14528. if (texture.type !== UnsignedInt248Type) {
  14529. console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
  14530. texture.type = UnsignedInt248Type;
  14531. glType = utils.convert(texture.type);
  14532. }
  14533. }
  14534. state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  14535. } else if (texture.isDataTexture) {
  14536. // use manually created mipmaps if available
  14537. // if there are no manual mipmaps
  14538. // set 0 level mipmap and then use GL to generate other mipmap levels
  14539. if (mipmaps.length > 0 && supportsMips) {
  14540. for (var i = 0, il = mipmaps.length; i < il; i++) {
  14541. mipmap = mipmaps[i];
  14542. state.texImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  14543. }
  14544. texture.generateMipmaps = false;
  14545. textureProperties.__maxMipLevel = mipmaps.length - 1;
  14546. } else {
  14547. state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
  14548. textureProperties.__maxMipLevel = 0;
  14549. }
  14550. } else if (texture.isCompressedTexture) {
  14551. for (var i = 0, il = mipmaps.length; i < il; i++) {
  14552. mipmap = mipmaps[i];
  14553. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  14554. if (state.getCompressedTextureFormats().indexOf(glFormat) > -1) {
  14555. state.compressedTexImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  14556. } else {
  14557. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  14558. }
  14559. } else {
  14560. state.texImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  14561. }
  14562. }
  14563. textureProperties.__maxMipLevel = mipmaps.length - 1;
  14564. } else if (texture.isDataTexture2DArray) {
  14565. state.texImage3D(35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  14566. textureProperties.__maxMipLevel = 0;
  14567. } else if (texture.isDataTexture3D) {
  14568. state.texImage3D(32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  14569. textureProperties.__maxMipLevel = 0;
  14570. } else {
  14571. // regular Texture (image, video, canvas)
  14572. // use manually created mipmaps if available
  14573. // if there are no manual mipmaps
  14574. // set 0 level mipmap and then use GL to generate other mipmap levels
  14575. if (mipmaps.length > 0 && supportsMips) {
  14576. for (var i = 0, il = mipmaps.length; i < il; i++) {
  14577. mipmap = mipmaps[i];
  14578. state.texImage2D(3553, i, glInternalFormat, glFormat, glType, mipmap);
  14579. }
  14580. texture.generateMipmaps = false;
  14581. textureProperties.__maxMipLevel = mipmaps.length - 1;
  14582. } else {
  14583. state.texImage2D(3553, 0, glInternalFormat, glFormat, glType, image);
  14584. textureProperties.__maxMipLevel = 0;
  14585. }
  14586. }
  14587. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14588. generateMipmap(3553, texture, image.width, image.height);
  14589. }
  14590. textureProperties.__version = texture.version;
  14591. if (texture.onUpdate) texture.onUpdate(texture);
  14592. } // Render targets
  14593. // Setup storage for target texture and bind it to correct framebuffer
  14594. function setupFrameBufferTexture(framebuffer, renderTarget, attachment, textureTarget) {
  14595. var glFormat = utils.convert(renderTarget.texture.format);
  14596. var glType = utils.convert(renderTarget.texture.type);
  14597. var glInternalFormat = getInternalFormat(glFormat, glType);
  14598. state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
  14599. _gl.bindFramebuffer(36160, framebuffer);
  14600. _gl.framebufferTexture2D(36160, attachment, textureTarget, properties.get(renderTarget.texture).__webglTexture, 0);
  14601. _gl.bindFramebuffer(36160, null);
  14602. } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  14603. function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
  14604. _gl.bindRenderbuffer(36161, renderbuffer);
  14605. if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
  14606. if (isMultisample) {
  14607. var samples = getRenderTargetSamples(renderTarget);
  14608. _gl.renderbufferStorageMultisample(36161, samples, 33189, renderTarget.width, renderTarget.height);
  14609. } else {
  14610. _gl.renderbufferStorage(36161, 33189, renderTarget.width, renderTarget.height);
  14611. }
  14612. _gl.framebufferRenderbuffer(36160, 36096, 36161, renderbuffer);
  14613. } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
  14614. if (isMultisample) {
  14615. var samples = getRenderTargetSamples(renderTarget);
  14616. _gl.renderbufferStorageMultisample(36161, samples, 35056, renderTarget.width, renderTarget.height);
  14617. } else {
  14618. _gl.renderbufferStorage(36161, 34041, renderTarget.width, renderTarget.height);
  14619. }
  14620. _gl.framebufferRenderbuffer(36160, 33306, 36161, renderbuffer);
  14621. } else {
  14622. var glFormat = utils.convert(renderTarget.texture.format);
  14623. var glType = utils.convert(renderTarget.texture.type);
  14624. var glInternalFormat = getInternalFormat(glFormat, glType);
  14625. if (isMultisample) {
  14626. var samples = getRenderTargetSamples(renderTarget);
  14627. _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14628. } else {
  14629. _gl.renderbufferStorage(36161, glInternalFormat, renderTarget.width, renderTarget.height);
  14630. }
  14631. }
  14632. _gl.bindRenderbuffer(36161, null);
  14633. } // Setup resources for a Depth Texture for a FBO (needs an extension)
  14634. function setupDepthTexture(framebuffer, renderTarget) {
  14635. var isCube = renderTarget && renderTarget.isWebGLRenderTargetCube;
  14636. if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
  14637. _gl.bindFramebuffer(36160, framebuffer);
  14638. if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
  14639. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  14640. } // upload an empty depth texture with framebuffer size
  14641. if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
  14642. renderTarget.depthTexture.image.width = renderTarget.width;
  14643. renderTarget.depthTexture.image.height = renderTarget.height;
  14644. renderTarget.depthTexture.needsUpdate = true;
  14645. }
  14646. setTexture2D(renderTarget.depthTexture, 0);
  14647. var webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
  14648. if (renderTarget.depthTexture.format === DepthFormat) {
  14649. _gl.framebufferTexture2D(36160, 36096, 3553, webglDepthTexture, 0);
  14650. } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
  14651. _gl.framebufferTexture2D(36160, 33306, 3553, webglDepthTexture, 0);
  14652. } else {
  14653. throw new Error('Unknown depthTexture format');
  14654. }
  14655. } // Setup GL resources for a non-texture depth buffer
  14656. function setupDepthRenderbuffer(renderTarget) {
  14657. var renderTargetProperties = properties.get(renderTarget);
  14658. var isCube = renderTarget.isWebGLRenderTargetCube === true;
  14659. if (renderTarget.depthTexture) {
  14660. if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
  14661. setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
  14662. } else {
  14663. if (isCube) {
  14664. renderTargetProperties.__webglDepthbuffer = [];
  14665. for (var i = 0; i < 6; i++) {
  14666. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer[i]);
  14667. renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
  14668. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget);
  14669. }
  14670. } else {
  14671. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer);
  14672. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  14673. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget);
  14674. }
  14675. }
  14676. _gl.bindFramebuffer(36160, null);
  14677. } // Set up GL resources for the render target
  14678. function setupRenderTarget(renderTarget) {
  14679. var renderTargetProperties = properties.get(renderTarget);
  14680. var textureProperties = properties.get(renderTarget.texture);
  14681. renderTarget.addEventListener('dispose', onRenderTargetDispose);
  14682. textureProperties.__webglTexture = _gl.createTexture();
  14683. info.memory.textures++;
  14684. var isCube = renderTarget.isWebGLRenderTargetCube === true;
  14685. var isMultisample = renderTarget.isWebGLMultisampleRenderTarget === true;
  14686. var isMultiview = renderTarget.isWebGLMultiviewRenderTarget === true;
  14687. var supportsMips = isPowerOfTwo(renderTarget) || capabilities.isWebGL2; // Setup framebuffer
  14688. if (isCube) {
  14689. renderTargetProperties.__webglFramebuffer = [];
  14690. for (var i = 0; i < 6; i++) {
  14691. renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
  14692. }
  14693. } else {
  14694. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  14695. if (isMultisample) {
  14696. if (capabilities.isWebGL2) {
  14697. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  14698. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  14699. _gl.bindRenderbuffer(36161, renderTargetProperties.__webglColorRenderbuffer);
  14700. var glFormat = utils.convert(renderTarget.texture.format);
  14701. var glType = utils.convert(renderTarget.texture.type);
  14702. var glInternalFormat = getInternalFormat(glFormat, glType);
  14703. var samples = getRenderTargetSamples(renderTarget);
  14704. _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14705. _gl.bindFramebuffer(36160, renderTargetProperties.__webglMultisampledFramebuffer);
  14706. _gl.framebufferRenderbuffer(36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer);
  14707. _gl.bindRenderbuffer(36161, null);
  14708. if (renderTarget.depthBuffer) {
  14709. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  14710. setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
  14711. }
  14712. _gl.bindFramebuffer(36160, null);
  14713. } else {
  14714. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  14715. }
  14716. } else if (isMultiview) {
  14717. var width = renderTarget.width;
  14718. var height = renderTarget.height;
  14719. var numViews = renderTarget.numViews;
  14720. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer);
  14721. var ext = extensions.get('OVR_multiview2');
  14722. info.memory.textures += 2;
  14723. var colorTexture = _gl.createTexture();
  14724. _gl.bindTexture(35866, colorTexture);
  14725. _gl.texParameteri(35866, 10240, 9728);
  14726. _gl.texParameteri(35866, 10241, 9728);
  14727. _gl.texImage3D(35866, 0, 32856, width, height, numViews, 0, 6408, 5121, null);
  14728. ext.framebufferTextureMultiviewOVR(36160, 36064, colorTexture, 0, 0, numViews);
  14729. var depthStencilTexture = _gl.createTexture();
  14730. _gl.bindTexture(35866, depthStencilTexture);
  14731. _gl.texParameteri(35866, 10240, 9728);
  14732. _gl.texParameteri(35866, 10241, 9728);
  14733. _gl.texImage3D(35866, 0, 35056, width, height, numViews, 0, 34041, 34042, null);
  14734. ext.framebufferTextureMultiviewOVR(36160, 33306, depthStencilTexture, 0, 0, numViews);
  14735. var viewFramebuffers = new Array(numViews);
  14736. for (var i = 0; i < numViews; ++i) {
  14737. viewFramebuffers[i] = _gl.createFramebuffer();
  14738. _gl.bindFramebuffer(36160, viewFramebuffers[i]);
  14739. _gl.framebufferTextureLayer(36160, 36064, colorTexture, 0, i);
  14740. }
  14741. renderTargetProperties.__webglColorTexture = colorTexture;
  14742. renderTargetProperties.__webglDepthStencilTexture = depthStencilTexture;
  14743. renderTargetProperties.__webglViewFramebuffers = viewFramebuffers;
  14744. _gl.bindFramebuffer(36160, null);
  14745. _gl.bindTexture(35866, null);
  14746. }
  14747. } // Setup color buffer
  14748. if (isCube) {
  14749. state.bindTexture(34067, textureProperties.__webglTexture);
  14750. setTextureParameters(34067, renderTarget.texture, supportsMips);
  14751. for (var i = 0; i < 6; i++) {
  14752. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, 36064, 34069 + i);
  14753. }
  14754. if (textureNeedsGenerateMipmaps(renderTarget.texture, supportsMips)) {
  14755. generateMipmap(34067, renderTarget.texture, renderTarget.width, renderTarget.height);
  14756. }
  14757. state.bindTexture(34067, null);
  14758. } else if (!isMultiview) {
  14759. state.bindTexture(3553, textureProperties.__webglTexture);
  14760. setTextureParameters(3553, renderTarget.texture, supportsMips);
  14761. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, 36064, 3553);
  14762. if (textureNeedsGenerateMipmaps(renderTarget.texture, supportsMips)) {
  14763. generateMipmap(3553, renderTarget.texture, renderTarget.width, renderTarget.height);
  14764. }
  14765. state.bindTexture(3553, null);
  14766. } // Setup depth and stencil buffers
  14767. if (renderTarget.depthBuffer) {
  14768. setupDepthRenderbuffer(renderTarget);
  14769. }
  14770. }
  14771. function updateRenderTargetMipmap(renderTarget) {
  14772. var texture = renderTarget.texture;
  14773. var supportsMips = isPowerOfTwo(renderTarget) || capabilities.isWebGL2;
  14774. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14775. var target = renderTarget.isWebGLRenderTargetCube ? 34067 : 3553;
  14776. var webglTexture = properties.get(texture).__webglTexture;
  14777. state.bindTexture(target, webglTexture);
  14778. generateMipmap(target, texture, renderTarget.width, renderTarget.height);
  14779. state.bindTexture(target, null);
  14780. }
  14781. }
  14782. function updateMultisampleRenderTarget(renderTarget) {
  14783. if (renderTarget.isWebGLMultisampleRenderTarget) {
  14784. if (capabilities.isWebGL2) {
  14785. var renderTargetProperties = properties.get(renderTarget);
  14786. _gl.bindFramebuffer(36008, renderTargetProperties.__webglMultisampledFramebuffer);
  14787. _gl.bindFramebuffer(36009, renderTargetProperties.__webglFramebuffer);
  14788. var width = renderTarget.width;
  14789. var height = renderTarget.height;
  14790. var mask = 16384;
  14791. if (renderTarget.depthBuffer) mask |= 256;
  14792. if (renderTarget.stencilBuffer) mask |= 1024;
  14793. _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, 9728);
  14794. } else {
  14795. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  14796. }
  14797. }
  14798. }
  14799. function getRenderTargetSamples(renderTarget) {
  14800. return capabilities.isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ? Math.min(capabilities.maxSamples, renderTarget.samples) : 0;
  14801. }
  14802. function updateVideoTexture(texture) {
  14803. var frame = info.render.frame; // Check the last frame we updated the VideoTexture
  14804. if (_videoTextures.get(texture) !== frame) {
  14805. _videoTextures.set(texture, frame);
  14806. texture.update();
  14807. }
  14808. } // backwards compatibility
  14809. var warnedTexture2D = false;
  14810. var warnedTextureCube = false;
  14811. function safeSetTexture2D(texture, slot) {
  14812. if (texture && texture.isWebGLRenderTarget) {
  14813. if (warnedTexture2D === false) {
  14814. console.warn("THREE.WebGLTextures.safeSetTexture2D: don't use render targets as textures. Use their .texture property instead.");
  14815. warnedTexture2D = true;
  14816. }
  14817. texture = texture.texture;
  14818. }
  14819. setTexture2D(texture, slot);
  14820. }
  14821. function safeSetTextureCube(texture, slot) {
  14822. if (texture && texture.isWebGLRenderTargetCube) {
  14823. if (warnedTextureCube === false) {
  14824. console.warn("THREE.WebGLTextures.safeSetTextureCube: don't use cube render targets as textures. Use their .texture property instead.");
  14825. warnedTextureCube = true;
  14826. }
  14827. texture = texture.texture;
  14828. } // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  14829. // TODO: unify these code paths
  14830. if (texture && texture.isCubeTexture || Array.isArray(texture.image) && texture.image.length === 6) {
  14831. // CompressedTexture can have Array in image :/
  14832. // this function alone should take care of cube textures
  14833. setTextureCube(texture, slot);
  14834. } else {
  14835. // assumed: texture property of THREE.WebGLRenderTargetCube
  14836. setTextureCubeDynamic(texture, slot);
  14837. }
  14838. } //
  14839. this.allocateTextureUnit = allocateTextureUnit;
  14840. this.resetTextureUnits = resetTextureUnits;
  14841. this.setTexture2D = setTexture2D;
  14842. this.setTexture2DArray = setTexture2DArray;
  14843. this.setTexture3D = setTexture3D;
  14844. this.setTextureCube = setTextureCube;
  14845. this.setTextureCubeDynamic = setTextureCubeDynamic;
  14846. this.setupRenderTarget = setupRenderTarget;
  14847. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  14848. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  14849. this.safeSetTexture2D = safeSetTexture2D;
  14850. this.safeSetTextureCube = safeSetTextureCube;
  14851. }
  14852. /**
  14853. * @author thespite / http://www.twitter.com/thespite
  14854. */
  14855. function WebGLUtils(gl, extensions, capabilities) {
  14856. function convert(p) {
  14857. var extension;
  14858. if (p === RepeatWrapping) return 10497;
  14859. if (p === ClampToEdgeWrapping) return 33071;
  14860. if (p === MirroredRepeatWrapping) return 33648;
  14861. if (p === NearestFilter) return 9728;
  14862. if (p === NearestMipmapNearestFilter) return 9984;
  14863. if (p === NearestMipmapLinearFilter) return 9986;
  14864. if (p === LinearFilter) return 9729;
  14865. if (p === LinearMipmapNearestFilter) return 9985;
  14866. if (p === LinearMipmapLinearFilter) return 9987;
  14867. if (p === UnsignedByteType) return 5121;
  14868. if (p === UnsignedShort4444Type) return 32819;
  14869. if (p === UnsignedShort5551Type) return 32820;
  14870. if (p === UnsignedShort565Type) return 33635;
  14871. if (p === ByteType) return 5120;
  14872. if (p === ShortType) return 5122;
  14873. if (p === UnsignedShortType) return 5123;
  14874. if (p === IntType) return 5124;
  14875. if (p === UnsignedIntType) return 5125;
  14876. if (p === FloatType) return 5126;
  14877. if (p === HalfFloatType) {
  14878. if (capabilities.isWebGL2) return 5131;
  14879. extension = extensions.get('OES_texture_half_float');
  14880. if (extension !== null) return extension.HALF_FLOAT_OES;
  14881. }
  14882. if (p === AlphaFormat) return 6406;
  14883. if (p === RGBFormat) return 6407;
  14884. if (p === RGBAFormat) return 6408;
  14885. if (p === LuminanceFormat) return 6409;
  14886. if (p === LuminanceAlphaFormat) return 6410;
  14887. if (p === DepthFormat) return 6402;
  14888. if (p === DepthStencilFormat) return 34041;
  14889. if (p === RedFormat) return 6403;
  14890. if (p === AddEquation) return 32774;
  14891. if (p === SubtractEquation) return 32778;
  14892. if (p === ReverseSubtractEquation) return 32779;
  14893. if (p === ZeroFactor) return 0;
  14894. if (p === OneFactor) return 1;
  14895. if (p === SrcColorFactor) return 768;
  14896. if (p === OneMinusSrcColorFactor) return 769;
  14897. if (p === SrcAlphaFactor) return 770;
  14898. if (p === OneMinusSrcAlphaFactor) return 771;
  14899. if (p === DstAlphaFactor) return 772;
  14900. if (p === OneMinusDstAlphaFactor) return 773;
  14901. if (p === DstColorFactor) return 774;
  14902. if (p === OneMinusDstColorFactor) return 775;
  14903. if (p === SrcAlphaSaturateFactor) return 776;
  14904. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  14905. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  14906. if (extension !== null) {
  14907. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14908. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14909. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14910. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14911. }
  14912. }
  14913. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  14914. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  14915. if (extension !== null) {
  14916. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  14917. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  14918. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  14919. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  14920. }
  14921. }
  14922. if (p === RGB_ETC1_Format) {
  14923. extension = extensions.get('WEBGL_compressed_texture_etc1');
  14924. if (extension !== null) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  14925. }
  14926. if (p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format || p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format || p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format || p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format || p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format) {
  14927. extension = extensions.get('WEBGL_compressed_texture_astc');
  14928. if (extension !== null) {
  14929. return p;
  14930. }
  14931. }
  14932. if (p === MinEquation || p === MaxEquation) {
  14933. if (capabilities.isWebGL2) {
  14934. if (p === MinEquation) return 32775;
  14935. if (p === MaxEquation) return 32776;
  14936. }
  14937. extension = extensions.get('EXT_blend_minmax');
  14938. if (extension !== null) {
  14939. if (p === MinEquation) return extension.MIN_EXT;
  14940. if (p === MaxEquation) return extension.MAX_EXT;
  14941. }
  14942. }
  14943. if (p === UnsignedInt248Type) {
  14944. if (capabilities.isWebGL2) return 34042;
  14945. extension = extensions.get('WEBGL_depth_texture');
  14946. if (extension !== null) return extension.UNSIGNED_INT_24_8_WEBGL;
  14947. }
  14948. return 0;
  14949. }
  14950. return {
  14951. convert: convert
  14952. };
  14953. }
  14954. /**
  14955. * @author fernandojsg / http://fernandojsg.com
  14956. * @author Takahiro https://github.com/takahirox
  14957. */
  14958. function WebGLMultiviewRenderTarget(width, height, numViews, options) {
  14959. WebGLRenderTarget.call(this, width, height, options);
  14960. this.depthBuffer = false;
  14961. this.stencilBuffer = false;
  14962. this.numViews = numViews;
  14963. }
  14964. WebGLMultiviewRenderTarget.prototype = Object.assign(Object.create(WebGLRenderTarget.prototype), {
  14965. constructor: WebGLMultiviewRenderTarget,
  14966. isWebGLMultiviewRenderTarget: true,
  14967. copy: function (source) {
  14968. WebGLRenderTarget.prototype.copy.call(this, source);
  14969. this.numViews = source.numViews;
  14970. return this;
  14971. },
  14972. setNumViews: function (numViews) {
  14973. if (this.numViews !== numViews) {
  14974. this.numViews = numViews;
  14975. this.dispose();
  14976. }
  14977. return this;
  14978. }
  14979. });
  14980. /**
  14981. * @author fernandojsg / http://fernandojsg.com
  14982. * @author Takahiro https://github.com/takahirox
  14983. */
  14984. function WebGLMultiview(renderer, gl) {
  14985. var DEFAULT_NUMVIEWS = 2;
  14986. var extensions = renderer.extensions;
  14987. var properties = renderer.properties;
  14988. var renderTarget, currentRenderTarget;
  14989. var mat3, mat4, cameraArray, renderSize;
  14990. var available;
  14991. var maxNumViews = 0; //
  14992. function isAvailable() {
  14993. if (available === undefined) {
  14994. var extension = extensions.get('OVR_multiview2');
  14995. available = extension !== null && gl.getContextAttributes().antialias === false;
  14996. if (available) {
  14997. maxNumViews = gl.getParameter(extension.MAX_VIEWS_OVR);
  14998. renderTarget = new WebGLMultiviewRenderTarget(0, 0, DEFAULT_NUMVIEWS);
  14999. renderSize = new Vector2();
  15000. mat4 = [];
  15001. mat3 = [];
  15002. cameraArray = [];
  15003. for (var i = 0; i < maxNumViews; i++) {
  15004. mat4[i] = new Matrix4();
  15005. mat3[i] = new Matrix3();
  15006. }
  15007. }
  15008. }
  15009. return available;
  15010. }
  15011. function getCameraArray(camera) {
  15012. if (camera.isArrayCamera) return camera.cameras;
  15013. cameraArray[0] = camera;
  15014. return cameraArray;
  15015. }
  15016. function updateCameraProjectionMatricesUniform(camera, uniforms) {
  15017. var cameras = getCameraArray(camera);
  15018. for (var i = 0; i < cameras.length; i++) {
  15019. mat4[i].copy(cameras[i].projectionMatrix);
  15020. }
  15021. uniforms.setValue(gl, 'projectionMatrices', mat4);
  15022. }
  15023. function updateCameraViewMatricesUniform(camera, uniforms) {
  15024. var cameras = getCameraArray(camera);
  15025. for (var i = 0; i < cameras.length; i++) {
  15026. mat4[i].copy(cameras[i].matrixWorldInverse);
  15027. }
  15028. uniforms.setValue(gl, 'viewMatrices', mat4);
  15029. }
  15030. function updateObjectMatricesUniforms(object, camera, uniforms) {
  15031. var cameras = getCameraArray(camera);
  15032. for (var i = 0; i < cameras.length; i++) {
  15033. mat4[i].multiplyMatrices(cameras[i].matrixWorldInverse, object.matrixWorld);
  15034. mat3[i].getNormalMatrix(mat4[i]);
  15035. }
  15036. uniforms.setValue(gl, 'modelViewMatrices', mat4);
  15037. uniforms.setValue(gl, 'normalMatrices', mat3);
  15038. }
  15039. function isMultiviewCompatible(camera) {
  15040. if (camera.isArrayCamera === undefined) return true;
  15041. var cameras = camera.cameras;
  15042. if (cameras.length > maxNumViews) return false;
  15043. for (var i = 1, il = cameras.length; i < il; i++) {
  15044. if (cameras[0].viewport.z !== cameras[i].viewport.z || cameras[0].viewport.w !== cameras[i].viewport.w) return false;
  15045. }
  15046. return true;
  15047. }
  15048. function resizeRenderTarget(camera) {
  15049. if (currentRenderTarget) {
  15050. renderSize.set(currentRenderTarget.width, currentRenderTarget.height);
  15051. } else {
  15052. renderer.getDrawingBufferSize(renderSize);
  15053. }
  15054. if (camera.isArrayCamera) {
  15055. var viewport = camera.cameras[0].viewport;
  15056. renderTarget.setSize(viewport.z, viewport.w);
  15057. renderTarget.setNumViews(camera.cameras.length);
  15058. } else {
  15059. renderTarget.setSize(renderSize.x, renderSize.y);
  15060. renderTarget.setNumViews(DEFAULT_NUMVIEWS);
  15061. }
  15062. }
  15063. function attachCamera(camera) {
  15064. if (isMultiviewCompatible(camera) === false) return;
  15065. currentRenderTarget = renderer.getRenderTarget();
  15066. resizeRenderTarget(camera);
  15067. renderer.setRenderTarget(renderTarget);
  15068. }
  15069. function detachCamera(camera) {
  15070. if (renderTarget !== renderer.getRenderTarget()) return;
  15071. renderer.setRenderTarget(currentRenderTarget);
  15072. flush(camera);
  15073. }
  15074. function flush(camera) {
  15075. var srcRenderTarget = renderTarget;
  15076. var numViews = srcRenderTarget.numViews;
  15077. var srcFramebuffers = properties.get(srcRenderTarget).__webglViewFramebuffers;
  15078. var viewWidth = srcRenderTarget.width;
  15079. var viewHeight = srcRenderTarget.height;
  15080. if (camera.isArrayCamera) {
  15081. for (var i = 0; i < numViews; i++) {
  15082. var viewport = camera.cameras[i].viewport;
  15083. var x1 = viewport.x;
  15084. var y1 = viewport.y;
  15085. var x2 = x1 + viewport.z;
  15086. var y2 = y1 + viewport.w;
  15087. gl.bindFramebuffer(36008, srcFramebuffers[i]);
  15088. gl.blitFramebuffer(0, 0, viewWidth, viewHeight, x1, y1, x2, y2, 16384, 9728);
  15089. }
  15090. } else {
  15091. gl.bindFramebuffer(36008, srcFramebuffers[0]);
  15092. gl.blitFramebuffer(0, 0, viewWidth, viewHeight, 0, 0, renderSize.x, renderSize.y, 16384, 9728);
  15093. }
  15094. }
  15095. this.isAvailable = isAvailable;
  15096. this.attachCamera = attachCamera;
  15097. this.detachCamera = detachCamera;
  15098. this.updateCameraProjectionMatricesUniform = updateCameraProjectionMatricesUniform;
  15099. this.updateCameraViewMatricesUniform = updateCameraViewMatricesUniform;
  15100. this.updateObjectMatricesUniforms = updateObjectMatricesUniforms;
  15101. }
  15102. /**
  15103. * @author mrdoob / http://mrdoob.com/
  15104. */
  15105. function Group() {
  15106. Object3D.call(this);
  15107. this.type = 'Group';
  15108. }
  15109. Group.prototype = Object.assign(Object.create(Object3D.prototype), {
  15110. constructor: Group,
  15111. isGroup: true
  15112. });
  15113. /**
  15114. * @author mrdoob / http://mrdoob.com/
  15115. */
  15116. function ArrayCamera(array) {
  15117. PerspectiveCamera.call(this);
  15118. this.cameras = array || [];
  15119. }
  15120. ArrayCamera.prototype = Object.assign(Object.create(PerspectiveCamera.prototype), {
  15121. constructor: ArrayCamera,
  15122. isArrayCamera: true
  15123. });
  15124. /**
  15125. * @author jsantell / https://www.jsantell.com/
  15126. * @author mrdoob / http://mrdoob.com/
  15127. */
  15128. var cameraLPos = new Vector3();
  15129. var cameraRPos = new Vector3();
  15130. /**
  15131. * Assumes 2 cameras that are parallel and share an X-axis, and that
  15132. * the cameras' projection and world matrices have already been set.
  15133. * And that near and far planes are identical for both cameras.
  15134. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  15135. */
  15136. function setProjectionFromUnion(camera, cameraL, cameraR) {
  15137. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  15138. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  15139. var ipd = cameraLPos.distanceTo(cameraRPos);
  15140. var projL = cameraL.projectionMatrix.elements;
  15141. var projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  15142. // most likely identical top and bottom frustum extents.
  15143. // Use the left camera for these values.
  15144. var near = projL[14] / (projL[10] - 1);
  15145. var far = projL[14] / (projL[10] + 1);
  15146. var topFov = (projL[9] + 1) / projL[5];
  15147. var bottomFov = (projL[9] - 1) / projL[5];
  15148. var leftFov = (projL[8] - 1) / projL[0];
  15149. var rightFov = (projR[8] + 1) / projR[0];
  15150. var left = near * leftFov;
  15151. var right = near * rightFov; // Calculate the new camera's position offset from the
  15152. // left camera. xOffset should be roughly half `ipd`.
  15153. var zOffset = ipd / (-leftFov + rightFov);
  15154. var xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  15155. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  15156. camera.translateX(xOffset);
  15157. camera.translateZ(zOffset);
  15158. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  15159. camera.matrixWorldInverse.getInverse(camera.matrixWorld); // Find the union of the frustum values of the cameras and scale
  15160. // the values so that the near plane's position does not change in world space,
  15161. // although must now be relative to the new union camera.
  15162. var near2 = near + zOffset;
  15163. var far2 = far + zOffset;
  15164. var left2 = left - xOffset;
  15165. var right2 = right + (ipd - xOffset);
  15166. var top2 = topFov * far / far2 * near2;
  15167. var bottom2 = bottomFov * far / far2 * near2;
  15168. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  15169. }
  15170. /**
  15171. * @author mrdoob / http://mrdoob.com/
  15172. */
  15173. function WebVRManager(renderer) {
  15174. var renderWidth, renderHeight;
  15175. var scope = this;
  15176. var device = null;
  15177. var frameData = null;
  15178. var poseTarget = null;
  15179. var controllers = [];
  15180. var standingMatrix = new Matrix4();
  15181. var standingMatrixInverse = new Matrix4();
  15182. var framebufferScaleFactor = 1.0;
  15183. var referenceSpaceType = 'local-floor';
  15184. if (typeof window !== 'undefined' && 'VRFrameData' in window) {
  15185. frameData = new window.VRFrameData();
  15186. window.addEventListener('vrdisplaypresentchange', onVRDisplayPresentChange, false);
  15187. }
  15188. var matrixWorldInverse = new Matrix4();
  15189. var tempQuaternion = new Quaternion();
  15190. var tempPosition = new Vector3();
  15191. var cameraL = new PerspectiveCamera();
  15192. cameraL.viewport = new Vector4();
  15193. cameraL.layers.enable(1);
  15194. var cameraR = new PerspectiveCamera();
  15195. cameraR.viewport = new Vector4();
  15196. cameraR.layers.enable(2);
  15197. var cameraVR = new ArrayCamera([cameraL, cameraR]);
  15198. cameraVR.layers.enable(1);
  15199. cameraVR.layers.enable(2); //
  15200. function isPresenting() {
  15201. return device !== null && device.isPresenting === true;
  15202. }
  15203. var currentSize = new Vector2(),
  15204. currentPixelRatio;
  15205. function onVRDisplayPresentChange() {
  15206. if (isPresenting()) {
  15207. var eyeParameters = device.getEyeParameters('left');
  15208. renderWidth = 2 * eyeParameters.renderWidth * framebufferScaleFactor;
  15209. renderHeight = eyeParameters.renderHeight * framebufferScaleFactor;
  15210. currentPixelRatio = renderer.getPixelRatio();
  15211. renderer.getSize(currentSize);
  15212. renderer.setDrawingBufferSize(renderWidth, renderHeight, 1);
  15213. cameraL.viewport.set(0, 0, renderWidth / 2, renderHeight);
  15214. cameraR.viewport.set(renderWidth / 2, 0, renderWidth / 2, renderHeight);
  15215. animation.start();
  15216. scope.dispatchEvent({
  15217. type: 'sessionstart'
  15218. });
  15219. } else {
  15220. if (scope.enabled) {
  15221. renderer.setDrawingBufferSize(currentSize.width, currentSize.height, currentPixelRatio);
  15222. }
  15223. animation.stop();
  15224. scope.dispatchEvent({
  15225. type: 'sessionend'
  15226. });
  15227. }
  15228. } //
  15229. var triggers = [];
  15230. function findGamepad(id) {
  15231. var gamepads = navigator.getGamepads && navigator.getGamepads();
  15232. for (var i = 0, j = 0, l = gamepads.length; i < l; i++) {
  15233. var gamepad = gamepads[i];
  15234. if (gamepad && (gamepad.id === 'Daydream Controller' || gamepad.id === 'Gear VR Controller' || gamepad.id === 'Oculus Go Controller' || gamepad.id === 'OpenVR Gamepad' || gamepad.id.startsWith('Oculus Touch') || gamepad.id.startsWith('HTC Vive Focus') || gamepad.id.startsWith('Spatial Controller'))) {
  15235. if (j === id) return gamepad;
  15236. j++;
  15237. }
  15238. }
  15239. }
  15240. function updateControllers() {
  15241. for (var i = 0; i < controllers.length; i++) {
  15242. var controller = controllers[i];
  15243. var gamepad = findGamepad(i);
  15244. if (gamepad !== undefined && gamepad.pose !== undefined) {
  15245. if (gamepad.pose === null) return; // Pose
  15246. var pose = gamepad.pose;
  15247. if (pose.hasPosition === false) controller.position.set(0.2, -0.6, -0.05);
  15248. if (pose.position !== null) controller.position.fromArray(pose.position);
  15249. if (pose.orientation !== null) controller.quaternion.fromArray(pose.orientation);
  15250. controller.matrix.compose(controller.position, controller.quaternion, controller.scale);
  15251. controller.matrix.premultiply(standingMatrix);
  15252. controller.matrix.decompose(controller.position, controller.quaternion, controller.scale);
  15253. controller.matrixWorldNeedsUpdate = true;
  15254. controller.visible = true; // Trigger
  15255. var buttonId = gamepad.id === 'Daydream Controller' ? 0 : 1;
  15256. if (triggers[i] === undefined) triggers[i] = false;
  15257. if (triggers[i] !== gamepad.buttons[buttonId].pressed) {
  15258. triggers[i] = gamepad.buttons[buttonId].pressed;
  15259. if (triggers[i] === true) {
  15260. controller.dispatchEvent({
  15261. type: 'selectstart'
  15262. });
  15263. } else {
  15264. controller.dispatchEvent({
  15265. type: 'selectend'
  15266. });
  15267. controller.dispatchEvent({
  15268. type: 'select'
  15269. });
  15270. }
  15271. }
  15272. } else {
  15273. controller.visible = false;
  15274. }
  15275. }
  15276. }
  15277. function updateViewportFromBounds(viewport, bounds) {
  15278. if (bounds !== null && bounds.length === 4) {
  15279. viewport.set(bounds[0] * renderWidth, bounds[1] * renderHeight, bounds[2] * renderWidth, bounds[3] * renderHeight);
  15280. }
  15281. } //
  15282. this.enabled = false;
  15283. this.getController = function (id) {
  15284. var controller = controllers[id];
  15285. if (controller === undefined) {
  15286. controller = new Group();
  15287. controller.matrixAutoUpdate = false;
  15288. controller.visible = false;
  15289. controllers[id] = controller;
  15290. }
  15291. return controller;
  15292. };
  15293. this.getDevice = function () {
  15294. return device;
  15295. };
  15296. this.setDevice = function (value) {
  15297. if (value !== undefined) device = value;
  15298. animation.setContext(value);
  15299. };
  15300. this.setFramebufferScaleFactor = function (value) {
  15301. framebufferScaleFactor = value;
  15302. };
  15303. this.setReferenceSpaceType = function (value) {
  15304. referenceSpaceType = value;
  15305. };
  15306. this.setPoseTarget = function (object) {
  15307. if (object !== undefined) poseTarget = object;
  15308. };
  15309. this.getCamera = function (camera) {
  15310. var userHeight = referenceSpaceType === 'local-floor' ? 1.6 : 0;
  15311. if (isPresenting() === false) {
  15312. camera.position.set(0, userHeight, 0);
  15313. camera.rotation.set(0, 0, 0);
  15314. return camera;
  15315. }
  15316. device.depthNear = camera.near;
  15317. device.depthFar = camera.far;
  15318. device.getFrameData(frameData); //
  15319. if (referenceSpaceType === 'local-floor') {
  15320. var stageParameters = device.stageParameters;
  15321. if (stageParameters) {
  15322. standingMatrix.fromArray(stageParameters.sittingToStandingTransform);
  15323. } else {
  15324. standingMatrix.makeTranslation(0, userHeight, 0);
  15325. }
  15326. }
  15327. var pose = frameData.pose;
  15328. var poseObject = poseTarget !== null ? poseTarget : camera; // We want to manipulate poseObject by its position and quaternion components since users may rely on them.
  15329. poseObject.matrix.copy(standingMatrix);
  15330. poseObject.matrix.decompose(poseObject.position, poseObject.quaternion, poseObject.scale);
  15331. if (pose.orientation !== null) {
  15332. tempQuaternion.fromArray(pose.orientation);
  15333. poseObject.quaternion.multiply(tempQuaternion);
  15334. }
  15335. if (pose.position !== null) {
  15336. tempQuaternion.setFromRotationMatrix(standingMatrix);
  15337. tempPosition.fromArray(pose.position);
  15338. tempPosition.applyQuaternion(tempQuaternion);
  15339. poseObject.position.add(tempPosition);
  15340. }
  15341. poseObject.updateMatrixWorld(); //
  15342. cameraL.near = camera.near;
  15343. cameraR.near = camera.near;
  15344. cameraL.far = camera.far;
  15345. cameraR.far = camera.far;
  15346. cameraL.matrixWorldInverse.fromArray(frameData.leftViewMatrix);
  15347. cameraR.matrixWorldInverse.fromArray(frameData.rightViewMatrix); // TODO (mrdoob) Double check this code
  15348. standingMatrixInverse.getInverse(standingMatrix);
  15349. if (referenceSpaceType === 'local-floor') {
  15350. cameraL.matrixWorldInverse.multiply(standingMatrixInverse);
  15351. cameraR.matrixWorldInverse.multiply(standingMatrixInverse);
  15352. }
  15353. var parent = poseObject.parent;
  15354. if (parent !== null) {
  15355. matrixWorldInverse.getInverse(parent.matrixWorld);
  15356. cameraL.matrixWorldInverse.multiply(matrixWorldInverse);
  15357. cameraR.matrixWorldInverse.multiply(matrixWorldInverse);
  15358. } // envMap and Mirror needs camera.matrixWorld
  15359. cameraL.matrixWorld.getInverse(cameraL.matrixWorldInverse);
  15360. cameraR.matrixWorld.getInverse(cameraR.matrixWorldInverse);
  15361. cameraL.projectionMatrix.fromArray(frameData.leftProjectionMatrix);
  15362. cameraR.projectionMatrix.fromArray(frameData.rightProjectionMatrix);
  15363. setProjectionFromUnion(cameraVR, cameraL, cameraR); //
  15364. var layers = device.getLayers();
  15365. if (layers.length) {
  15366. var layer = layers[0];
  15367. updateViewportFromBounds(cameraL.viewport, layer.leftBounds);
  15368. updateViewportFromBounds(cameraR.viewport, layer.rightBounds);
  15369. }
  15370. updateControllers();
  15371. return cameraVR;
  15372. };
  15373. this.getStandingMatrix = function () {
  15374. return standingMatrix;
  15375. };
  15376. this.isPresenting = isPresenting; // Animation Loop
  15377. var animation = new WebGLAnimation();
  15378. this.setAnimationLoop = function (callback) {
  15379. animation.setAnimationLoop(callback);
  15380. if (isPresenting()) animation.start();
  15381. };
  15382. this.submitFrame = function () {
  15383. if (isPresenting()) device.submitFrame();
  15384. };
  15385. this.dispose = function () {
  15386. if (typeof window !== 'undefined') {
  15387. window.removeEventListener('vrdisplaypresentchange', onVRDisplayPresentChange);
  15388. }
  15389. }; // DEPRECATED
  15390. this.setFrameOfReferenceType = function () {
  15391. console.warn('THREE.WebVRManager: setFrameOfReferenceType() has been deprecated.');
  15392. };
  15393. }
  15394. Object.assign(WebVRManager.prototype, EventDispatcher.prototype);
  15395. /**
  15396. * @author mrdoob / http://mrdoob.com/
  15397. */
  15398. function WebXRManager(renderer, gl) {
  15399. var scope = this;
  15400. var session = null; // var framebufferScaleFactor = 1.0;
  15401. var referenceSpace = null;
  15402. var referenceSpaceType = 'local-floor';
  15403. var pose = null;
  15404. var controllers = [];
  15405. var inputSources = [];
  15406. function isPresenting() {
  15407. return session !== null && referenceSpace !== null;
  15408. } //
  15409. var cameraL = new PerspectiveCamera();
  15410. cameraL.layers.enable(1);
  15411. cameraL.viewport = new Vector4();
  15412. var cameraR = new PerspectiveCamera();
  15413. cameraR.layers.enable(2);
  15414. cameraR.viewport = new Vector4();
  15415. var cameraVR = new ArrayCamera([cameraL, cameraR]);
  15416. cameraVR.layers.enable(1);
  15417. cameraVR.layers.enable(2); //
  15418. this.enabled = false;
  15419. this.getController = function (id) {
  15420. var controller = controllers[id];
  15421. if (controller === undefined) {
  15422. controller = new Group();
  15423. controller.matrixAutoUpdate = false;
  15424. controller.visible = false;
  15425. controllers[id] = controller;
  15426. }
  15427. return controller;
  15428. }; //
  15429. function onSessionEvent(event) {
  15430. for (var i = 0; i < controllers.length; i++) {
  15431. if (inputSources[i] === event.inputSource) {
  15432. controllers[i].dispatchEvent({
  15433. type: event.type
  15434. });
  15435. }
  15436. }
  15437. }
  15438. function onSessionEnd() {
  15439. renderer.setFramebuffer(null);
  15440. renderer.setRenderTarget(renderer.getRenderTarget()); // Hack #15830
  15441. animation.stop();
  15442. scope.dispatchEvent({
  15443. type: 'sessionend'
  15444. });
  15445. }
  15446. function onRequestReferenceSpace(value) {
  15447. referenceSpace = value;
  15448. animation.setContext(session);
  15449. animation.start();
  15450. scope.dispatchEvent({
  15451. type: 'sessionstart'
  15452. });
  15453. }
  15454. this.setFramebufferScaleFactor = function ()
  15455. /* value */
  15456. {// framebufferScaleFactor = value;
  15457. };
  15458. this.setReferenceSpaceType = function (value) {
  15459. referenceSpaceType = value;
  15460. };
  15461. this.getSession = function () {
  15462. return session;
  15463. };
  15464. this.setSession = function (value) {
  15465. session = value;
  15466. if (session !== null) {
  15467. session.addEventListener('select', onSessionEvent);
  15468. session.addEventListener('selectstart', onSessionEvent);
  15469. session.addEventListener('selectend', onSessionEvent);
  15470. session.addEventListener('end', onSessionEnd); // eslint-disable-next-line no-undef
  15471. session.updateRenderState({
  15472. baseLayer: new XRWebGLLayer(session, gl)
  15473. });
  15474. session.requestReferenceSpace(referenceSpaceType).then(onRequestReferenceSpace); //
  15475. inputSources = session.inputSources;
  15476. session.addEventListener('inputsourceschange', function () {
  15477. inputSources = session.inputSources;
  15478. console.log(inputSources);
  15479. for (var i = 0; i < controllers.length; i++) {
  15480. var controller = controllers[i];
  15481. controller.userData.inputSource = inputSources[i];
  15482. }
  15483. });
  15484. }
  15485. };
  15486. function updateCamera(camera, parent) {
  15487. if (parent === null) {
  15488. camera.matrixWorld.copy(camera.matrix);
  15489. } else {
  15490. camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
  15491. }
  15492. camera.matrixWorldInverse.getInverse(camera.matrixWorld);
  15493. }
  15494. this.getCamera = function (camera) {
  15495. if (isPresenting()) {
  15496. var parent = camera.parent;
  15497. var cameras = cameraVR.cameras;
  15498. updateCamera(cameraVR, parent);
  15499. for (var i = 0; i < cameras.length; i++) {
  15500. updateCamera(cameras[i], parent);
  15501. } // update camera and its children
  15502. camera.matrixWorld.copy(cameraVR.matrixWorld);
  15503. var children = camera.children;
  15504. for (var i = 0, l = children.length; i < l; i++) {
  15505. children[i].updateMatrixWorld(true);
  15506. }
  15507. setProjectionFromUnion(cameraVR, cameraL, cameraR);
  15508. return cameraVR;
  15509. }
  15510. return camera;
  15511. };
  15512. this.isPresenting = isPresenting; // Animation Loop
  15513. var onAnimationFrameCallback = null;
  15514. function onAnimationFrame(time, frame) {
  15515. pose = frame.getViewerPose(referenceSpace);
  15516. if (pose !== null) {
  15517. var views = pose.views;
  15518. var baseLayer = session.renderState.baseLayer;
  15519. renderer.setFramebuffer(baseLayer.framebuffer);
  15520. for (var i = 0; i < views.length; i++) {
  15521. var view = views[i];
  15522. var viewport = baseLayer.getViewport(view);
  15523. var viewMatrix = view.transform.inverse.matrix;
  15524. var camera = cameraVR.cameras[i];
  15525. camera.matrix.fromArray(viewMatrix).getInverse(camera.matrix);
  15526. camera.projectionMatrix.fromArray(view.projectionMatrix);
  15527. camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
  15528. if (i === 0) {
  15529. cameraVR.matrix.copy(camera.matrix);
  15530. }
  15531. }
  15532. } //
  15533. for (var i = 0; i < controllers.length; i++) {
  15534. var controller = controllers[i];
  15535. var inputSource = inputSources[i];
  15536. if (inputSource) {
  15537. var inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace);
  15538. if (inputPose !== null) {
  15539. controller.matrix.fromArray(inputPose.transform.matrix);
  15540. controller.matrix.decompose(controller.position, controller.rotation, controller.scale);
  15541. controller.visible = true;
  15542. continue;
  15543. }
  15544. }
  15545. controller.visible = false;
  15546. }
  15547. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  15548. }
  15549. var animation = new WebGLAnimation();
  15550. animation.setAnimationLoop(onAnimationFrame);
  15551. this.setAnimationLoop = function (callback) {
  15552. onAnimationFrameCallback = callback;
  15553. };
  15554. this.dispose = function () {}; // DEPRECATED
  15555. this.getStandingMatrix = function () {
  15556. console.warn('THREE.WebXRManager: getStandingMatrix() is no longer needed.');
  15557. return new Matrix4();
  15558. };
  15559. this.getDevice = function () {
  15560. console.warn('THREE.WebXRManager: getDevice() has been deprecated.');
  15561. };
  15562. this.setDevice = function () {
  15563. console.warn('THREE.WebXRManager: setDevice() has been deprecated.');
  15564. };
  15565. this.setFrameOfReferenceType = function () {
  15566. console.warn('THREE.WebXRManager: setFrameOfReferenceType() has been deprecated.');
  15567. };
  15568. this.submitFrame = function () {};
  15569. }
  15570. Object.assign(WebXRManager.prototype, EventDispatcher.prototype);
  15571. /**
  15572. * @author supereggbert / http://www.paulbrunt.co.uk/
  15573. * @author mrdoob / http://mrdoob.com/
  15574. * @author alteredq / http://alteredqualia.com/
  15575. * @author szimek / https://github.com/szimek/
  15576. * @author tschw
  15577. */
  15578. function WebGLRenderer(parameters) {
  15579. parameters = parameters || {};
  15580. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas'),
  15581. _context = parameters.context !== undefined ? parameters.context : null,
  15582. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  15583. _depth = parameters.depth !== undefined ? parameters.depth : true,
  15584. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  15585. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  15586. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  15587. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  15588. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  15589. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  15590. var currentRenderList = null;
  15591. var currentRenderState = null; // public properties
  15592. this.domElement = _canvas; // Debug configuration container
  15593. this.debug = {
  15594. /**
  15595. * Enables error checking and reporting when shader programs are being compiled
  15596. * @type {boolean}
  15597. */
  15598. checkShaderErrors: true
  15599. }; // clearing
  15600. this.autoClear = true;
  15601. this.autoClearColor = true;
  15602. this.autoClearDepth = true;
  15603. this.autoClearStencil = true; // scene graph
  15604. this.sortObjects = true; // user-defined clipping
  15605. this.clippingPlanes = [];
  15606. this.localClippingEnabled = false; // physically based shading
  15607. this.gammaFactor = 2.0; // for backwards compatibility
  15608. this.gammaInput = false;
  15609. this.gammaOutput = false; // physical lights
  15610. this.physicallyCorrectLights = false; // tone mapping
  15611. this.toneMapping = LinearToneMapping;
  15612. this.toneMappingExposure = 1.0;
  15613. this.toneMappingWhitePoint = 1.0; // morphs
  15614. this.maxMorphTargets = 8;
  15615. this.maxMorphNormals = 4; // internal properties
  15616. var _this = this,
  15617. _isContextLost = false,
  15618. // internal state cache
  15619. _framebuffer = null,
  15620. _currentActiveCubeFace = 0,
  15621. _currentActiveMipmapLevel = 0,
  15622. _currentRenderTarget = null,
  15623. _currentFramebuffer = null,
  15624. _currentMaterialId = -1,
  15625. // geometry and program caching
  15626. _currentGeometryProgram = {
  15627. geometry: null,
  15628. program: null,
  15629. wireframe: false
  15630. },
  15631. _currentCamera = null,
  15632. _currentArrayCamera = null,
  15633. _currentViewport = new Vector4(),
  15634. _currentScissor = new Vector4(),
  15635. _currentScissorTest = null,
  15636. //
  15637. _width = _canvas.width,
  15638. _height = _canvas.height,
  15639. _pixelRatio = 1,
  15640. _viewport = new Vector4(0, 0, _width, _height),
  15641. _scissor = new Vector4(0, 0, _width, _height),
  15642. _scissorTest = false,
  15643. // frustum
  15644. _frustum = new Frustum(),
  15645. // clipping
  15646. _clipping = new WebGLClipping(),
  15647. _clippingEnabled = false,
  15648. _localClippingEnabled = false,
  15649. // camera matrices cache
  15650. _projScreenMatrix = new Matrix4(),
  15651. _vector3 = new Vector3();
  15652. function getTargetPixelRatio() {
  15653. return _currentRenderTarget === null ? _pixelRatio : 1;
  15654. } // initialize
  15655. var _gl;
  15656. try {
  15657. var contextAttributes = {
  15658. alpha: _alpha,
  15659. depth: _depth,
  15660. stencil: _stencil,
  15661. antialias: _antialias,
  15662. premultipliedAlpha: _premultipliedAlpha,
  15663. preserveDrawingBuffer: _preserveDrawingBuffer,
  15664. powerPreference: _powerPreference,
  15665. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat,
  15666. xrCompatible: true
  15667. }; // event listeners must be registered before WebGL context is created, see #12753
  15668. _canvas.addEventListener('webglcontextlost', onContextLost, false);
  15669. _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
  15670. _gl = _context || _canvas.getContext('webgl', contextAttributes) || _canvas.getContext('experimental-webgl', contextAttributes);
  15671. if (_gl === null) {
  15672. if (_canvas.getContext('webgl') !== null) {
  15673. throw new Error('Error creating WebGL context with your selected attributes.');
  15674. } else {
  15675. throw new Error('Error creating WebGL context.');
  15676. }
  15677. } // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  15678. if (_gl.getShaderPrecisionFormat === undefined) {
  15679. _gl.getShaderPrecisionFormat = function () {
  15680. return {
  15681. 'rangeMin': 1,
  15682. 'rangeMax': 1,
  15683. 'precision': 1
  15684. };
  15685. };
  15686. }
  15687. } catch (error) {
  15688. console.error('THREE.WebGLRenderer: ' + error.message);
  15689. throw error;
  15690. }
  15691. var extensions, capabilities, state, info;
  15692. var properties, textures, attributes, geometries, objects;
  15693. var programCache, renderLists, renderStates;
  15694. var background, morphtargets, bufferRenderer, indexedBufferRenderer;
  15695. var utils;
  15696. function initGLContext() {
  15697. extensions = new WebGLExtensions(_gl);
  15698. capabilities = new WebGLCapabilities(_gl, extensions, parameters);
  15699. if (capabilities.isWebGL2 === false) {
  15700. extensions.get('WEBGL_depth_texture');
  15701. extensions.get('OES_texture_float');
  15702. extensions.get('OES_texture_half_float');
  15703. extensions.get('OES_texture_half_float_linear');
  15704. extensions.get('OES_standard_derivatives');
  15705. extensions.get('OES_element_index_uint');
  15706. extensions.get('ANGLE_instanced_arrays');
  15707. }
  15708. extensions.get('OES_texture_float_linear');
  15709. utils = new WebGLUtils(_gl, extensions, capabilities);
  15710. state = new WebGLState(_gl, extensions, utils, capabilities);
  15711. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  15712. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  15713. info = new WebGLInfo(_gl);
  15714. properties = new WebGLProperties();
  15715. textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
  15716. attributes = new WebGLAttributes(_gl);
  15717. geometries = new WebGLGeometries(_gl, attributes, info);
  15718. objects = new WebGLObjects(_gl, geometries, attributes, info);
  15719. morphtargets = new WebGLMorphtargets(_gl);
  15720. programCache = new WebGLPrograms(_this, extensions, capabilities);
  15721. renderLists = new WebGLRenderLists();
  15722. renderStates = new WebGLRenderStates();
  15723. background = new WebGLBackground(_this, state, objects, _premultipliedAlpha);
  15724. bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
  15725. indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
  15726. info.programs = programCache.programs;
  15727. _this.capabilities = capabilities;
  15728. _this.extensions = extensions;
  15729. _this.properties = properties;
  15730. _this.renderLists = renderLists;
  15731. _this.state = state;
  15732. _this.info = info;
  15733. }
  15734. initGLContext(); // vr
  15735. var vr = typeof navigator !== 'undefined' && 'xr' in navigator && 'supportsSession' in navigator.xr ? new WebXRManager(_this, _gl) : new WebVRManager(_this);
  15736. this.vr = vr; // Multiview
  15737. var multiview = new WebGLMultiview(_this, _gl); // shadow map
  15738. var shadowMap = new WebGLShadowMap(_this, objects, capabilities.maxTextureSize);
  15739. this.shadowMap = shadowMap; // API
  15740. this.getContext = function () {
  15741. return _gl;
  15742. };
  15743. this.getContextAttributes = function () {
  15744. return _gl.getContextAttributes();
  15745. };
  15746. this.forceContextLoss = function () {
  15747. var extension = extensions.get('WEBGL_lose_context');
  15748. if (extension) extension.loseContext();
  15749. };
  15750. this.forceContextRestore = function () {
  15751. var extension = extensions.get('WEBGL_lose_context');
  15752. if (extension) extension.restoreContext();
  15753. };
  15754. this.getPixelRatio = function () {
  15755. return _pixelRatio;
  15756. };
  15757. this.setPixelRatio = function (value) {
  15758. if (value === undefined) return;
  15759. _pixelRatio = value;
  15760. this.setSize(_width, _height, false);
  15761. };
  15762. this.getSize = function (target) {
  15763. if (target === undefined) {
  15764. console.warn('WebGLRenderer: .getsize() now requires a Vector2 as an argument');
  15765. target = new Vector2();
  15766. }
  15767. return target.set(_width, _height);
  15768. };
  15769. this.setSize = function (width, height, updateStyle) {
  15770. if (vr.isPresenting()) {
  15771. console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');
  15772. return;
  15773. }
  15774. _width = width;
  15775. _height = height;
  15776. _canvas.width = Math.floor(width * _pixelRatio);
  15777. _canvas.height = Math.floor(height * _pixelRatio);
  15778. if (updateStyle !== false) {
  15779. _canvas.style.width = width + 'px';
  15780. _canvas.style.height = height + 'px';
  15781. }
  15782. this.setViewport(0, 0, width, height);
  15783. };
  15784. this.getDrawingBufferSize = function (target) {
  15785. if (target === undefined) {
  15786. console.warn('WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument');
  15787. target = new Vector2();
  15788. }
  15789. return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
  15790. };
  15791. this.setDrawingBufferSize = function (width, height, pixelRatio) {
  15792. _width = width;
  15793. _height = height;
  15794. _pixelRatio = pixelRatio;
  15795. _canvas.width = Math.floor(width * pixelRatio);
  15796. _canvas.height = Math.floor(height * pixelRatio);
  15797. this.setViewport(0, 0, width, height);
  15798. };
  15799. this.getCurrentViewport = function (target) {
  15800. if (target === undefined) {
  15801. console.warn('WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument');
  15802. target = new Vector4();
  15803. }
  15804. return target.copy(_currentViewport);
  15805. };
  15806. this.getViewport = function (target) {
  15807. return target.copy(_viewport);
  15808. };
  15809. this.setViewport = function (x, y, width, height) {
  15810. if (x.isVector4) {
  15811. _viewport.set(x.x, x.y, x.z, x.w);
  15812. } else {
  15813. _viewport.set(x, y, width, height);
  15814. }
  15815. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  15816. };
  15817. this.getScissor = function (target) {
  15818. return target.copy(_scissor);
  15819. };
  15820. this.setScissor = function (x, y, width, height) {
  15821. if (x.isVector4) {
  15822. _scissor.set(x.x, x.y, x.z, x.w);
  15823. } else {
  15824. _scissor.set(x, y, width, height);
  15825. }
  15826. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  15827. };
  15828. this.getScissorTest = function () {
  15829. return _scissorTest;
  15830. };
  15831. this.setScissorTest = function (boolean) {
  15832. state.setScissorTest(_scissorTest = boolean);
  15833. }; // Clearing
  15834. this.getClearColor = function () {
  15835. return background.getClearColor();
  15836. };
  15837. this.setClearColor = function () {
  15838. background.setClearColor.apply(background, arguments);
  15839. };
  15840. this.getClearAlpha = function () {
  15841. return background.getClearAlpha();
  15842. };
  15843. this.setClearAlpha = function () {
  15844. background.setClearAlpha.apply(background, arguments);
  15845. };
  15846. this.clear = function (color, depth, stencil) {
  15847. var bits = 0;
  15848. if (color === undefined || color) bits |= 16384;
  15849. if (depth === undefined || depth) bits |= 256;
  15850. if (stencil === undefined || stencil) bits |= 1024;
  15851. _gl.clear(bits);
  15852. };
  15853. this.clearColor = function () {
  15854. this.clear(true, false, false);
  15855. };
  15856. this.clearDepth = function () {
  15857. this.clear(false, true, false);
  15858. };
  15859. this.clearStencil = function () {
  15860. this.clear(false, false, true);
  15861. }; //
  15862. this.dispose = function () {
  15863. _canvas.removeEventListener('webglcontextlost', onContextLost, false);
  15864. _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
  15865. renderLists.dispose();
  15866. renderStates.dispose();
  15867. properties.dispose();
  15868. objects.dispose();
  15869. vr.dispose();
  15870. animation.stop();
  15871. }; // Events
  15872. function onContextLost(event) {
  15873. event.preventDefault();
  15874. console.log('THREE.WebGLRenderer: Context Lost.');
  15875. _isContextLost = true;
  15876. }
  15877. function onContextRestore()
  15878. /* event */
  15879. {
  15880. console.log('THREE.WebGLRenderer: Context Restored.');
  15881. _isContextLost = false;
  15882. initGLContext();
  15883. }
  15884. function onMaterialDispose(event) {
  15885. var material = event.target;
  15886. material.removeEventListener('dispose', onMaterialDispose);
  15887. deallocateMaterial(material);
  15888. } // Buffer deallocation
  15889. function deallocateMaterial(material) {
  15890. releaseMaterialProgramReference(material);
  15891. properties.remove(material);
  15892. }
  15893. function releaseMaterialProgramReference(material) {
  15894. var programInfo = properties.get(material).program;
  15895. material.program = undefined;
  15896. if (programInfo !== undefined) {
  15897. programCache.releaseProgram(programInfo);
  15898. }
  15899. } // Buffer rendering
  15900. function renderObjectImmediate(object, program) {
  15901. object.render(function (object) {
  15902. _this.renderBufferImmediate(object, program);
  15903. });
  15904. }
  15905. this.renderBufferImmediate = function (object, program) {
  15906. state.initAttributes();
  15907. var buffers = properties.get(object);
  15908. if (object.hasPositions && !buffers.position) buffers.position = _gl.createBuffer();
  15909. if (object.hasNormals && !buffers.normal) buffers.normal = _gl.createBuffer();
  15910. if (object.hasUvs && !buffers.uv) buffers.uv = _gl.createBuffer();
  15911. if (object.hasColors && !buffers.color) buffers.color = _gl.createBuffer();
  15912. var programAttributes = program.getAttributes();
  15913. if (object.hasPositions) {
  15914. _gl.bindBuffer(34962, buffers.position);
  15915. _gl.bufferData(34962, object.positionArray, 35048);
  15916. state.enableAttribute(programAttributes.position);
  15917. _gl.vertexAttribPointer(programAttributes.position, 3, 5126, false, 0, 0);
  15918. }
  15919. if (object.hasNormals) {
  15920. _gl.bindBuffer(34962, buffers.normal);
  15921. _gl.bufferData(34962, object.normalArray, 35048);
  15922. state.enableAttribute(programAttributes.normal);
  15923. _gl.vertexAttribPointer(programAttributes.normal, 3, 5126, false, 0, 0);
  15924. }
  15925. if (object.hasUvs) {
  15926. _gl.bindBuffer(34962, buffers.uv);
  15927. _gl.bufferData(34962, object.uvArray, 35048);
  15928. state.enableAttribute(programAttributes.uv);
  15929. _gl.vertexAttribPointer(programAttributes.uv, 2, 5126, false, 0, 0);
  15930. }
  15931. if (object.hasColors) {
  15932. _gl.bindBuffer(34962, buffers.color);
  15933. _gl.bufferData(34962, object.colorArray, 35048);
  15934. state.enableAttribute(programAttributes.color);
  15935. _gl.vertexAttribPointer(programAttributes.color, 3, 5126, false, 0, 0);
  15936. }
  15937. state.disableUnusedAttributes();
  15938. _gl.drawArrays(4, 0, object.count);
  15939. object.count = 0;
  15940. };
  15941. this.renderBufferDirect = function (camera, fog, geometry, material, object, group) {
  15942. var frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
  15943. state.setMaterial(material, frontFaceCW);
  15944. var program = setProgram(camera, fog, material, object);
  15945. var updateBuffers = false;
  15946. if (_currentGeometryProgram.geometry !== geometry.id || _currentGeometryProgram.program !== program.id || _currentGeometryProgram.wireframe !== (material.wireframe === true)) {
  15947. _currentGeometryProgram.geometry = geometry.id;
  15948. _currentGeometryProgram.program = program.id;
  15949. _currentGeometryProgram.wireframe = material.wireframe === true;
  15950. updateBuffers = true;
  15951. }
  15952. if (object.morphTargetInfluences) {
  15953. morphtargets.update(object, geometry, material, program);
  15954. updateBuffers = true;
  15955. } //
  15956. var index = geometry.index;
  15957. var position = geometry.attributes.position;
  15958. var rangeFactor = 1;
  15959. if (material.wireframe === true) {
  15960. index = geometries.getWireframeAttribute(geometry);
  15961. rangeFactor = 2;
  15962. }
  15963. var attribute;
  15964. var renderer = bufferRenderer;
  15965. if (index !== null) {
  15966. attribute = attributes.get(index);
  15967. renderer = indexedBufferRenderer;
  15968. renderer.setIndex(attribute);
  15969. }
  15970. if (updateBuffers) {
  15971. setupVertexAttributes(object, geometry, material, program);
  15972. if (index !== null) {
  15973. _gl.bindBuffer(34963, attribute.buffer);
  15974. }
  15975. } //
  15976. var dataCount = Infinity;
  15977. if (index !== null) {
  15978. dataCount = index.count;
  15979. } else if (position !== undefined) {
  15980. dataCount = position.count;
  15981. }
  15982. var rangeStart = geometry.drawRange.start * rangeFactor;
  15983. var rangeCount = geometry.drawRange.count * rangeFactor;
  15984. var groupStart = group !== null ? group.start * rangeFactor : 0;
  15985. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  15986. var drawStart = Math.max(rangeStart, groupStart);
  15987. var drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1;
  15988. var drawCount = Math.max(0, drawEnd - drawStart + 1);
  15989. if (drawCount === 0) return; //
  15990. if (object.isMesh) {
  15991. if (material.wireframe === true) {
  15992. state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
  15993. renderer.setMode(1);
  15994. } else {
  15995. switch (object.drawMode) {
  15996. case TrianglesDrawMode:
  15997. renderer.setMode(4);
  15998. break;
  15999. case TriangleStripDrawMode:
  16000. renderer.setMode(5);
  16001. break;
  16002. case TriangleFanDrawMode:
  16003. renderer.setMode(6);
  16004. break;
  16005. }
  16006. }
  16007. } else if (object.isLine) {
  16008. var lineWidth = material.linewidth;
  16009. if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material
  16010. state.setLineWidth(lineWidth * getTargetPixelRatio());
  16011. if (object.isLineSegments) {
  16012. renderer.setMode(1);
  16013. } else if (object.isLineLoop) {
  16014. renderer.setMode(2);
  16015. } else {
  16016. renderer.setMode(3);
  16017. }
  16018. } else if (object.isPoints) {
  16019. renderer.setMode(0);
  16020. } else if (object.isSprite) {
  16021. renderer.setMode(4);
  16022. }
  16023. if (object.isInstancedMesh) {
  16024. renderer.renderInstances(geometry, drawStart, drawCount, object.count);
  16025. } else if (geometry.isInstancedBufferGeometry) {
  16026. renderer.renderInstances(geometry, drawStart, drawCount, geometry.maxInstancedCount);
  16027. } else {
  16028. renderer.render(drawStart, drawCount);
  16029. }
  16030. };
  16031. function setupVertexAttributes(object, geometry, material, program) {
  16032. if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
  16033. if (extensions.get('ANGLE_instanced_arrays') === null) return;
  16034. }
  16035. state.initAttributes();
  16036. var geometryAttributes = geometry.attributes;
  16037. var programAttributes = program.getAttributes();
  16038. var materialDefaultAttributeValues = material.defaultAttributeValues;
  16039. for (var name in programAttributes) {
  16040. var programAttribute = programAttributes[name];
  16041. if (programAttribute >= 0) {
  16042. var geometryAttribute = geometryAttributes[name];
  16043. if (geometryAttribute !== undefined) {
  16044. var normalized = geometryAttribute.normalized;
  16045. var size = geometryAttribute.itemSize;
  16046. var attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restore
  16047. if (attribute === undefined) continue;
  16048. var buffer = attribute.buffer;
  16049. var type = attribute.type;
  16050. var bytesPerElement = attribute.bytesPerElement;
  16051. if (geometryAttribute.isInterleavedBufferAttribute) {
  16052. var data = geometryAttribute.data;
  16053. var stride = data.stride;
  16054. var offset = geometryAttribute.offset;
  16055. if (data && data.isInstancedInterleavedBuffer) {
  16056. state.enableAttributeAndDivisor(programAttribute, data.meshPerAttribute);
  16057. if (geometry.maxInstancedCount === undefined) {
  16058. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  16059. }
  16060. } else {
  16061. state.enableAttribute(programAttribute);
  16062. }
  16063. _gl.bindBuffer(34962, buffer);
  16064. _gl.vertexAttribPointer(programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement);
  16065. } else {
  16066. if (geometryAttribute.isInstancedBufferAttribute) {
  16067. state.enableAttributeAndDivisor(programAttribute, geometryAttribute.meshPerAttribute);
  16068. if (geometry.maxInstancedCount === undefined) {
  16069. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  16070. }
  16071. } else {
  16072. state.enableAttribute(programAttribute);
  16073. }
  16074. _gl.bindBuffer(34962, buffer);
  16075. _gl.vertexAttribPointer(programAttribute, size, type, normalized, 0, 0);
  16076. }
  16077. } else if (name === 'instanceMatrix') {
  16078. var attribute = attributes.get(object.instanceMatrix); // TODO Attribute may not be available on context restore
  16079. if (attribute === undefined) continue;
  16080. var buffer = attribute.buffer;
  16081. var type = attribute.type;
  16082. state.enableAttributeAndDivisor(programAttribute + 0, 1);
  16083. state.enableAttributeAndDivisor(programAttribute + 1, 1);
  16084. state.enableAttributeAndDivisor(programAttribute + 2, 1);
  16085. state.enableAttributeAndDivisor(programAttribute + 3, 1);
  16086. _gl.bindBuffer(34962, buffer);
  16087. _gl.vertexAttribPointer(programAttribute + 0, 4, type, false, 64, 0);
  16088. _gl.vertexAttribPointer(programAttribute + 1, 4, type, false, 64, 16);
  16089. _gl.vertexAttribPointer(programAttribute + 2, 4, type, false, 64, 32);
  16090. _gl.vertexAttribPointer(programAttribute + 3, 4, type, false, 64, 48);
  16091. } else if (materialDefaultAttributeValues !== undefined) {
  16092. var value = materialDefaultAttributeValues[name];
  16093. if (value !== undefined) {
  16094. switch (value.length) {
  16095. case 2:
  16096. _gl.vertexAttrib2fv(programAttribute, value);
  16097. break;
  16098. case 3:
  16099. _gl.vertexAttrib3fv(programAttribute, value);
  16100. break;
  16101. case 4:
  16102. _gl.vertexAttrib4fv(programAttribute, value);
  16103. break;
  16104. default:
  16105. _gl.vertexAttrib1fv(programAttribute, value);
  16106. }
  16107. }
  16108. }
  16109. }
  16110. }
  16111. state.disableUnusedAttributes();
  16112. } // Compile
  16113. this.compile = function (scene, camera) {
  16114. currentRenderState = renderStates.get(scene, camera);
  16115. currentRenderState.init();
  16116. scene.traverse(function (object) {
  16117. if (object.isLight) {
  16118. currentRenderState.pushLight(object);
  16119. if (object.castShadow) {
  16120. currentRenderState.pushShadow(object);
  16121. }
  16122. }
  16123. });
  16124. currentRenderState.setupLights(camera);
  16125. scene.traverse(function (object) {
  16126. if (object.material) {
  16127. if (Array.isArray(object.material)) {
  16128. for (var i = 0; i < object.material.length; i++) {
  16129. initMaterial(object.material[i], scene.fog, object);
  16130. }
  16131. } else {
  16132. initMaterial(object.material, scene.fog, object);
  16133. }
  16134. }
  16135. });
  16136. }; // Animation Loop
  16137. var onAnimationFrameCallback = null;
  16138. function onAnimationFrame(time) {
  16139. if (vr.isPresenting()) return;
  16140. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  16141. }
  16142. var animation = new WebGLAnimation();
  16143. animation.setAnimationLoop(onAnimationFrame);
  16144. if (typeof window !== 'undefined') animation.setContext(window);
  16145. this.setAnimationLoop = function (callback) {
  16146. onAnimationFrameCallback = callback;
  16147. vr.setAnimationLoop(callback);
  16148. animation.start();
  16149. }; // Rendering
  16150. this.render = function (scene, camera) {
  16151. var renderTarget, forceClear;
  16152. if (arguments[2] !== undefined) {
  16153. console.warn('THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.');
  16154. renderTarget = arguments[2];
  16155. }
  16156. if (arguments[3] !== undefined) {
  16157. console.warn('THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.');
  16158. forceClear = arguments[3];
  16159. }
  16160. if (!(camera && camera.isCamera)) {
  16161. console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
  16162. return;
  16163. }
  16164. if (_isContextLost) return; // reset caching for this frame
  16165. _currentGeometryProgram.geometry = null;
  16166. _currentGeometryProgram.program = null;
  16167. _currentGeometryProgram.wireframe = false;
  16168. _currentMaterialId = -1;
  16169. _currentCamera = null; // update scene graph
  16170. if (scene.autoUpdate === true) scene.updateMatrixWorld(); // update camera matrices and frustum
  16171. if (camera.parent === null) camera.updateMatrixWorld();
  16172. if (vr.enabled) {
  16173. camera = vr.getCamera(camera);
  16174. } //
  16175. currentRenderState = renderStates.get(scene, camera);
  16176. currentRenderState.init();
  16177. scene.onBeforeRender(_this, scene, camera, renderTarget || _currentRenderTarget);
  16178. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  16179. _frustum.setFromMatrix(_projScreenMatrix);
  16180. _localClippingEnabled = this.localClippingEnabled;
  16181. _clippingEnabled = _clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
  16182. currentRenderList = renderLists.get(scene, camera);
  16183. currentRenderList.init();
  16184. projectObject(scene, camera, 0, _this.sortObjects);
  16185. if (_this.sortObjects === true) {
  16186. currentRenderList.sort();
  16187. } //
  16188. if (_clippingEnabled) _clipping.beginShadows();
  16189. var shadowsArray = currentRenderState.state.shadowsArray;
  16190. shadowMap.render(shadowsArray, scene, camera);
  16191. currentRenderState.setupLights(camera);
  16192. if (_clippingEnabled) _clipping.endShadows(); //
  16193. if (this.info.autoReset) this.info.reset();
  16194. if (renderTarget !== undefined) {
  16195. this.setRenderTarget(renderTarget);
  16196. }
  16197. if (vr.enabled && multiview.isAvailable()) {
  16198. multiview.attachCamera(camera);
  16199. } //
  16200. background.render(currentRenderList, scene, camera, forceClear); // render scene
  16201. var opaqueObjects = currentRenderList.opaque;
  16202. var transparentObjects = currentRenderList.transparent;
  16203. if (scene.overrideMaterial) {
  16204. var overrideMaterial = scene.overrideMaterial;
  16205. if (opaqueObjects.length) renderObjects(opaqueObjects, scene, camera, overrideMaterial);
  16206. if (transparentObjects.length) renderObjects(transparentObjects, scene, camera, overrideMaterial);
  16207. } else {
  16208. // opaque pass (front-to-back order)
  16209. if (opaqueObjects.length) renderObjects(opaqueObjects, scene, camera); // transparent pass (back-to-front order)
  16210. if (transparentObjects.length) renderObjects(transparentObjects, scene, camera);
  16211. } //
  16212. scene.onAfterRender(_this, scene, camera); //
  16213. if (_currentRenderTarget !== null) {
  16214. // Generate mipmap if we're using any kind of mipmap filtering
  16215. textures.updateRenderTargetMipmap(_currentRenderTarget); // resolve multisample renderbuffers to a single-sample texture if necessary
  16216. textures.updateMultisampleRenderTarget(_currentRenderTarget);
  16217. } // Ensure depth buffer writing is enabled so it can be cleared on next render
  16218. state.buffers.depth.setTest(true);
  16219. state.buffers.depth.setMask(true);
  16220. state.buffers.color.setMask(true);
  16221. state.setPolygonOffset(false);
  16222. if (vr.enabled) {
  16223. if (multiview.isAvailable()) {
  16224. multiview.detachCamera(camera);
  16225. }
  16226. vr.submitFrame();
  16227. } // _gl.finish();
  16228. currentRenderList = null;
  16229. currentRenderState = null;
  16230. };
  16231. function projectObject(object, camera, groupOrder, sortObjects) {
  16232. if (object.visible === false) return;
  16233. var visible = object.layers.test(camera.layers);
  16234. if (visible) {
  16235. if (object.isGroup) {
  16236. groupOrder = object.renderOrder;
  16237. } else if (object.isLOD) {
  16238. if (object.autoUpdate === true) object.update(camera);
  16239. } else if (object.isLight) {
  16240. currentRenderState.pushLight(object);
  16241. if (object.castShadow) {
  16242. currentRenderState.pushShadow(object);
  16243. }
  16244. } else if (object.isSprite) {
  16245. if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
  16246. if (sortObjects) {
  16247. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  16248. }
  16249. var geometry = objects.update(object);
  16250. var material = object.material;
  16251. if (material.visible) {
  16252. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  16253. }
  16254. }
  16255. } else if (object.isImmediateRenderObject) {
  16256. if (sortObjects) {
  16257. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  16258. }
  16259. currentRenderList.push(object, null, object.material, groupOrder, _vector3.z, null);
  16260. } else if (object.isMesh || object.isLine || object.isPoints) {
  16261. if (object.isSkinnedMesh) {
  16262. // update skeleton only once in a frame
  16263. if (object.skeleton.frame !== info.render.frame) {
  16264. object.skeleton.update();
  16265. object.skeleton.frame = info.render.frame;
  16266. }
  16267. }
  16268. if (!object.frustumCulled || _frustum.intersectsObject(object)) {
  16269. if (sortObjects) {
  16270. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  16271. }
  16272. var geometry = objects.update(object);
  16273. var material = object.material;
  16274. if (Array.isArray(material)) {
  16275. var groups = geometry.groups;
  16276. for (var i = 0, l = groups.length; i < l; i++) {
  16277. var group = groups[i];
  16278. var groupMaterial = material[group.materialIndex];
  16279. if (groupMaterial && groupMaterial.visible) {
  16280. currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector3.z, group);
  16281. }
  16282. }
  16283. } else if (material.visible) {
  16284. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  16285. }
  16286. }
  16287. }
  16288. }
  16289. var children = object.children;
  16290. for (var i = 0, l = children.length; i < l; i++) {
  16291. projectObject(children[i], camera, groupOrder, sortObjects);
  16292. }
  16293. }
  16294. function renderObjects(renderList, scene, camera, overrideMaterial) {
  16295. for (var i = 0, l = renderList.length; i < l; i++) {
  16296. var renderItem = renderList[i];
  16297. var object = renderItem.object;
  16298. var geometry = renderItem.geometry;
  16299. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  16300. var group = renderItem.group;
  16301. if (camera.isArrayCamera) {
  16302. _currentArrayCamera = camera;
  16303. if (vr.enabled && multiview.isAvailable()) {
  16304. renderObject(object, scene, camera, geometry, material, group);
  16305. } else {
  16306. var cameras = camera.cameras;
  16307. for (var j = 0, jl = cameras.length; j < jl; j++) {
  16308. var camera2 = cameras[j];
  16309. if (object.layers.test(camera2.layers)) {
  16310. state.viewport(_currentViewport.copy(camera2.viewport));
  16311. currentRenderState.setupLights(camera2);
  16312. renderObject(object, scene, camera2, geometry, material, group);
  16313. }
  16314. }
  16315. }
  16316. } else {
  16317. _currentArrayCamera = null;
  16318. renderObject(object, scene, camera, geometry, material, group);
  16319. }
  16320. }
  16321. }
  16322. function renderObject(object, scene, camera, geometry, material, group) {
  16323. object.onBeforeRender(_this, scene, camera, geometry, material, group);
  16324. currentRenderState = renderStates.get(scene, _currentArrayCamera || camera);
  16325. object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
  16326. object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
  16327. if (object.isImmediateRenderObject) {
  16328. state.setMaterial(material);
  16329. var program = setProgram(camera, scene.fog, material, object);
  16330. _currentGeometryProgram.geometry = null;
  16331. _currentGeometryProgram.program = null;
  16332. _currentGeometryProgram.wireframe = false;
  16333. renderObjectImmediate(object, program);
  16334. } else {
  16335. _this.renderBufferDirect(camera, scene.fog, geometry, material, object, group);
  16336. }
  16337. object.onAfterRender(_this, scene, camera, geometry, material, group);
  16338. currentRenderState = renderStates.get(scene, _currentArrayCamera || camera);
  16339. }
  16340. function initMaterial(material, fog, object) {
  16341. var materialProperties = properties.get(material);
  16342. var lights = currentRenderState.state.lights;
  16343. var shadowsArray = currentRenderState.state.shadowsArray;
  16344. var lightsStateVersion = lights.state.version;
  16345. var parameters = programCache.getParameters(material, lights.state, shadowsArray, fog, _clipping.numPlanes, _clipping.numIntersection, object);
  16346. var code = programCache.getProgramCode(material, parameters);
  16347. var program = materialProperties.program;
  16348. var programChange = true;
  16349. if (program === undefined) {
  16350. // new material
  16351. material.addEventListener('dispose', onMaterialDispose);
  16352. } else if (program.code !== code) {
  16353. // changed glsl or parameters
  16354. releaseMaterialProgramReference(material);
  16355. } else if (materialProperties.lightsStateVersion !== lightsStateVersion) {
  16356. materialProperties.lightsStateVersion = lightsStateVersion;
  16357. programChange = false;
  16358. } else if (parameters.shaderID !== undefined) {
  16359. // same glsl and uniform list
  16360. return;
  16361. } else {
  16362. // only rebuild uniform list
  16363. programChange = false;
  16364. }
  16365. if (programChange) {
  16366. if (parameters.shaderID) {
  16367. var shader = ShaderLib[parameters.shaderID];
  16368. materialProperties.shader = {
  16369. name: material.type,
  16370. uniforms: cloneUniforms(shader.uniforms),
  16371. vertexShader: shader.vertexShader,
  16372. fragmentShader: shader.fragmentShader
  16373. };
  16374. } else {
  16375. materialProperties.shader = {
  16376. name: material.type,
  16377. uniforms: material.uniforms,
  16378. vertexShader: material.vertexShader,
  16379. fragmentShader: material.fragmentShader
  16380. };
  16381. }
  16382. material.onBeforeCompile(materialProperties.shader, _this); // Computing code again as onBeforeCompile may have changed the shaders
  16383. code = programCache.getProgramCode(material, parameters);
  16384. program = programCache.acquireProgram(material, materialProperties.shader, parameters, code);
  16385. materialProperties.program = program;
  16386. material.program = program;
  16387. }
  16388. var programAttributes = program.getAttributes();
  16389. if (material.morphTargets) {
  16390. material.numSupportedMorphTargets = 0;
  16391. for (var i = 0; i < _this.maxMorphTargets; i++) {
  16392. if (programAttributes['morphTarget' + i] >= 0) {
  16393. material.numSupportedMorphTargets++;
  16394. }
  16395. }
  16396. }
  16397. if (material.morphNormals) {
  16398. material.numSupportedMorphNormals = 0;
  16399. for (var i = 0; i < _this.maxMorphNormals; i++) {
  16400. if (programAttributes['morphNormal' + i] >= 0) {
  16401. material.numSupportedMorphNormals++;
  16402. }
  16403. }
  16404. }
  16405. var uniforms = materialProperties.shader.uniforms;
  16406. if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
  16407. materialProperties.numClippingPlanes = _clipping.numPlanes;
  16408. materialProperties.numIntersection = _clipping.numIntersection;
  16409. uniforms.clippingPlanes = _clipping.uniform;
  16410. }
  16411. materialProperties.fog = fog; // store the light setup it was created for
  16412. materialProperties.needsLights = materialNeedsLights(material);
  16413. materialProperties.lightsStateVersion = lightsStateVersion;
  16414. if (materialProperties.needsLights) {
  16415. // wire up the material to this renderer's lighting state
  16416. uniforms.ambientLightColor.value = lights.state.ambient;
  16417. uniforms.lightProbe.value = lights.state.probe;
  16418. uniforms.directionalLights.value = lights.state.directional;
  16419. uniforms.spotLights.value = lights.state.spot;
  16420. uniforms.rectAreaLights.value = lights.state.rectArea;
  16421. uniforms.pointLights.value = lights.state.point;
  16422. uniforms.hemisphereLights.value = lights.state.hemi;
  16423. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  16424. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  16425. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  16426. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  16427. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  16428. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms
  16429. }
  16430. var progUniforms = materialProperties.program.getUniforms(),
  16431. uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
  16432. materialProperties.uniformsList = uniformsList;
  16433. }
  16434. function setProgram(camera, fog, material, object) {
  16435. textures.resetTextureUnits();
  16436. var materialProperties = properties.get(material);
  16437. var lights = currentRenderState.state.lights;
  16438. if (_clippingEnabled) {
  16439. if (_localClippingEnabled || camera !== _currentCamera) {
  16440. var useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroup
  16441. // object instead of the material, once it becomes feasible
  16442. // (#8465, #8379)
  16443. _clipping.setState(material.clippingPlanes, material.clipIntersection, material.clipShadows, camera, materialProperties, useCache);
  16444. }
  16445. }
  16446. if (material.needsUpdate === false) {
  16447. if (materialProperties.program === undefined) {
  16448. material.needsUpdate = true;
  16449. } else if (material.fog && materialProperties.fog !== fog) {
  16450. material.needsUpdate = true;
  16451. } else if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
  16452. material.needsUpdate = true;
  16453. } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== _clipping.numPlanes || materialProperties.numIntersection !== _clipping.numIntersection)) {
  16454. material.needsUpdate = true;
  16455. }
  16456. }
  16457. if (material.needsUpdate) {
  16458. initMaterial(material, fog, object);
  16459. material.needsUpdate = false;
  16460. }
  16461. var refreshProgram = false;
  16462. var refreshMaterial = false;
  16463. var refreshLights = false;
  16464. var program = materialProperties.program,
  16465. p_uniforms = program.getUniforms(),
  16466. m_uniforms = materialProperties.shader.uniforms;
  16467. if (state.useProgram(program.program)) {
  16468. refreshProgram = true;
  16469. refreshMaterial = true;
  16470. refreshLights = true;
  16471. }
  16472. if (material.id !== _currentMaterialId) {
  16473. _currentMaterialId = material.id;
  16474. refreshMaterial = true;
  16475. }
  16476. if (refreshProgram || _currentCamera !== camera) {
  16477. if (program.numMultiviewViews > 0) {
  16478. multiview.updateCameraProjectionMatricesUniform(camera, p_uniforms);
  16479. } else {
  16480. p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
  16481. }
  16482. if (capabilities.logarithmicDepthBuffer) {
  16483. p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  16484. }
  16485. if (_currentCamera !== camera) {
  16486. _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update
  16487. // now, in case this material supports lights - or later, when
  16488. // the next material that does gets activated:
  16489. refreshMaterial = true; // set to true on material change
  16490. refreshLights = true; // remains set until update done
  16491. } // load material specific uniforms
  16492. // (shader material also gets them for the sake of genericity)
  16493. if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.envMap) {
  16494. var uCamPos = p_uniforms.map.cameraPosition;
  16495. if (uCamPos !== undefined) {
  16496. uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
  16497. }
  16498. }
  16499. if (material.isMeshPhongMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.skinning) {
  16500. if (program.numMultiviewViews > 0) {
  16501. multiview.updateCameraViewMatricesUniform(camera, p_uniforms);
  16502. } else {
  16503. p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
  16504. }
  16505. }
  16506. } // skinning uniforms must be set even if material didn't change
  16507. // auto-setting of texture unit for bone texture must go before other textures
  16508. // not sure why, but otherwise weird things happen
  16509. if (material.skinning) {
  16510. p_uniforms.setOptional(_gl, object, 'bindMatrix');
  16511. p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
  16512. var skeleton = object.skeleton;
  16513. if (skeleton) {
  16514. var bones = skeleton.bones;
  16515. if (capabilities.floatVertexTextures) {
  16516. if (skeleton.boneTexture === undefined) {
  16517. // layout (1 matrix = 4 pixels)
  16518. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  16519. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  16520. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  16521. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  16522. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  16523. var size = Math.sqrt(bones.length * 4); // 4 pixels needed for 1 matrix
  16524. size = _Math.ceilPowerOfTwo(size);
  16525. size = Math.max(size, 4);
  16526. var boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
  16527. boneMatrices.set(skeleton.boneMatrices); // copy current values
  16528. var boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
  16529. skeleton.boneMatrices = boneMatrices;
  16530. skeleton.boneTexture = boneTexture;
  16531. skeleton.boneTextureSize = size;
  16532. }
  16533. p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
  16534. p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
  16535. } else {
  16536. p_uniforms.setOptional(_gl, skeleton, 'boneMatrices');
  16537. }
  16538. }
  16539. }
  16540. if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
  16541. materialProperties.receiveShadow = object.receiveShadow;
  16542. p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
  16543. }
  16544. if (refreshMaterial) {
  16545. p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
  16546. p_uniforms.setValue(_gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint);
  16547. if (materialProperties.needsLights) {
  16548. // the current material requires lighting info
  16549. // note: all lighting uniforms are always set correctly
  16550. // they simply reference the renderer's state for their
  16551. // values
  16552. //
  16553. // use the current material's .needsUpdate flags to set
  16554. // the GL state when required
  16555. markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
  16556. } // refresh uniforms common to several materials
  16557. if (fog && material.fog) {
  16558. refreshUniformsFog(m_uniforms, fog);
  16559. }
  16560. if (material.isMeshBasicMaterial) {
  16561. refreshUniformsCommon(m_uniforms, material);
  16562. } else if (material.isMeshLambertMaterial) {
  16563. refreshUniformsCommon(m_uniforms, material);
  16564. refreshUniformsLambert(m_uniforms, material);
  16565. } else if (material.isMeshPhongMaterial) {
  16566. refreshUniformsCommon(m_uniforms, material);
  16567. if (material.isMeshToonMaterial) {
  16568. refreshUniformsToon(m_uniforms, material);
  16569. } else {
  16570. refreshUniformsPhong(m_uniforms, material);
  16571. }
  16572. } else if (material.isMeshStandardMaterial) {
  16573. refreshUniformsCommon(m_uniforms, material);
  16574. if (material.isMeshPhysicalMaterial) {
  16575. refreshUniformsPhysical(m_uniforms, material);
  16576. } else {
  16577. refreshUniformsStandard(m_uniforms, material);
  16578. }
  16579. } else if (material.isMeshMatcapMaterial) {
  16580. refreshUniformsCommon(m_uniforms, material);
  16581. refreshUniformsMatcap(m_uniforms, material);
  16582. } else if (material.isMeshDepthMaterial) {
  16583. refreshUniformsCommon(m_uniforms, material);
  16584. refreshUniformsDepth(m_uniforms, material);
  16585. } else if (material.isMeshDistanceMaterial) {
  16586. refreshUniformsCommon(m_uniforms, material);
  16587. refreshUniformsDistance(m_uniforms, material);
  16588. } else if (material.isMeshNormalMaterial) {
  16589. refreshUniformsCommon(m_uniforms, material);
  16590. refreshUniformsNormal(m_uniforms, material);
  16591. } else if (material.isLineBasicMaterial) {
  16592. refreshUniformsLine(m_uniforms, material);
  16593. if (material.isLineDashedMaterial) {
  16594. refreshUniformsDash(m_uniforms, material);
  16595. }
  16596. } else if (material.isPointsMaterial) {
  16597. refreshUniformsPoints(m_uniforms, material);
  16598. } else if (material.isSpriteMaterial) {
  16599. refreshUniformsSprites(m_uniforms, material);
  16600. } else if (material.isShadowMaterial) {
  16601. m_uniforms.color.value.copy(material.color);
  16602. m_uniforms.opacity.value = material.opacity;
  16603. } // RectAreaLight Texture
  16604. // TODO (mrdoob): Find a nicer implementation
  16605. if (m_uniforms.ltc_1 !== undefined) m_uniforms.ltc_1.value = UniformsLib.LTC_1;
  16606. if (m_uniforms.ltc_2 !== undefined) m_uniforms.ltc_2.value = UniformsLib.LTC_2;
  16607. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  16608. }
  16609. if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
  16610. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  16611. material.uniformsNeedUpdate = false;
  16612. }
  16613. if (material.isSpriteMaterial) {
  16614. p_uniforms.setValue(_gl, 'center', object.center);
  16615. } // common matrices
  16616. if (program.numMultiviewViews > 0) {
  16617. multiview.updateObjectMatricesUniforms(object, camera, p_uniforms);
  16618. } else {
  16619. p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
  16620. p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
  16621. }
  16622. p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld);
  16623. return program;
  16624. } // Uniforms (refresh uniforms objects)
  16625. function refreshUniformsCommon(uniforms, material) {
  16626. uniforms.opacity.value = material.opacity;
  16627. if (material.color) {
  16628. uniforms.diffuse.value.copy(material.color);
  16629. }
  16630. if (material.emissive) {
  16631. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  16632. }
  16633. if (material.map) {
  16634. uniforms.map.value = material.map;
  16635. }
  16636. if (material.alphaMap) {
  16637. uniforms.alphaMap.value = material.alphaMap;
  16638. }
  16639. if (material.specularMap) {
  16640. uniforms.specularMap.value = material.specularMap;
  16641. }
  16642. if (material.envMap) {
  16643. uniforms.envMap.value = material.envMap; // don't flip CubeTexture envMaps, flip everything else:
  16644. // WebGLRenderTargetCube will be flipped for backwards compatibility
  16645. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  16646. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  16647. uniforms.flipEnvMap.value = material.envMap.isCubeTexture ? -1 : 1;
  16648. uniforms.reflectivity.value = material.reflectivity;
  16649. uniforms.refractionRatio.value = material.refractionRatio;
  16650. uniforms.maxMipLevel.value = properties.get(material.envMap).__maxMipLevel;
  16651. }
  16652. if (material.lightMap) {
  16653. uniforms.lightMap.value = material.lightMap;
  16654. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  16655. }
  16656. if (material.aoMap) {
  16657. uniforms.aoMap.value = material.aoMap;
  16658. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  16659. } // uv repeat and offset setting priorities
  16660. // 1. color map
  16661. // 2. specular map
  16662. // 3. normal map
  16663. // 4. bump map
  16664. // 5. alpha map
  16665. // 6. emissive map
  16666. var uvScaleMap;
  16667. if (material.map) {
  16668. uvScaleMap = material.map;
  16669. } else if (material.specularMap) {
  16670. uvScaleMap = material.specularMap;
  16671. } else if (material.displacementMap) {
  16672. uvScaleMap = material.displacementMap;
  16673. } else if (material.normalMap) {
  16674. uvScaleMap = material.normalMap;
  16675. } else if (material.bumpMap) {
  16676. uvScaleMap = material.bumpMap;
  16677. } else if (material.roughnessMap) {
  16678. uvScaleMap = material.roughnessMap;
  16679. } else if (material.metalnessMap) {
  16680. uvScaleMap = material.metalnessMap;
  16681. } else if (material.alphaMap) {
  16682. uvScaleMap = material.alphaMap;
  16683. } else if (material.emissiveMap) {
  16684. uvScaleMap = material.emissiveMap;
  16685. }
  16686. if (uvScaleMap !== undefined) {
  16687. // backwards compatibility
  16688. if (uvScaleMap.isWebGLRenderTarget) {
  16689. uvScaleMap = uvScaleMap.texture;
  16690. }
  16691. if (uvScaleMap.matrixAutoUpdate === true) {
  16692. uvScaleMap.updateMatrix();
  16693. }
  16694. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  16695. }
  16696. }
  16697. function refreshUniformsLine(uniforms, material) {
  16698. uniforms.diffuse.value.copy(material.color);
  16699. uniforms.opacity.value = material.opacity;
  16700. }
  16701. function refreshUniformsDash(uniforms, material) {
  16702. uniforms.dashSize.value = material.dashSize;
  16703. uniforms.totalSize.value = material.dashSize + material.gapSize;
  16704. uniforms.scale.value = material.scale;
  16705. }
  16706. function refreshUniformsPoints(uniforms, material) {
  16707. uniforms.diffuse.value.copy(material.color);
  16708. uniforms.opacity.value = material.opacity;
  16709. uniforms.size.value = material.size * _pixelRatio;
  16710. uniforms.scale.value = _height * 0.5;
  16711. uniforms.map.value = material.map;
  16712. if (material.map !== null) {
  16713. if (material.map.matrixAutoUpdate === true) {
  16714. material.map.updateMatrix();
  16715. }
  16716. uniforms.uvTransform.value.copy(material.map.matrix);
  16717. }
  16718. }
  16719. function refreshUniformsSprites(uniforms, material) {
  16720. uniforms.diffuse.value.copy(material.color);
  16721. uniforms.opacity.value = material.opacity;
  16722. uniforms.rotation.value = material.rotation;
  16723. uniforms.map.value = material.map;
  16724. if (material.map !== null) {
  16725. if (material.map.matrixAutoUpdate === true) {
  16726. material.map.updateMatrix();
  16727. }
  16728. uniforms.uvTransform.value.copy(material.map.matrix);
  16729. }
  16730. }
  16731. function refreshUniformsFog(uniforms, fog) {
  16732. uniforms.fogColor.value.copy(fog.color);
  16733. if (fog.isFog) {
  16734. uniforms.fogNear.value = fog.near;
  16735. uniforms.fogFar.value = fog.far;
  16736. } else if (fog.isFogExp2) {
  16737. uniforms.fogDensity.value = fog.density;
  16738. }
  16739. }
  16740. function refreshUniformsLambert(uniforms, material) {
  16741. if (material.emissiveMap) {
  16742. uniforms.emissiveMap.value = material.emissiveMap;
  16743. }
  16744. }
  16745. function refreshUniformsPhong(uniforms, material) {
  16746. uniforms.specular.value.copy(material.specular);
  16747. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  16748. if (material.emissiveMap) {
  16749. uniforms.emissiveMap.value = material.emissiveMap;
  16750. }
  16751. if (material.bumpMap) {
  16752. uniforms.bumpMap.value = material.bumpMap;
  16753. uniforms.bumpScale.value = material.bumpScale;
  16754. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  16755. }
  16756. if (material.normalMap) {
  16757. uniforms.normalMap.value = material.normalMap;
  16758. uniforms.normalScale.value.copy(material.normalScale);
  16759. if (material.side === BackSide) uniforms.normalScale.value.negate();
  16760. }
  16761. if (material.displacementMap) {
  16762. uniforms.displacementMap.value = material.displacementMap;
  16763. uniforms.displacementScale.value = material.displacementScale;
  16764. uniforms.displacementBias.value = material.displacementBias;
  16765. }
  16766. }
  16767. function refreshUniformsToon(uniforms, material) {
  16768. refreshUniformsPhong(uniforms, material);
  16769. if (material.gradientMap) {
  16770. uniforms.gradientMap.value = material.gradientMap;
  16771. }
  16772. }
  16773. function refreshUniformsStandard(uniforms, material) {
  16774. uniforms.roughness.value = material.roughness;
  16775. uniforms.metalness.value = material.metalness;
  16776. if (material.roughnessMap) {
  16777. uniforms.roughnessMap.value = material.roughnessMap;
  16778. }
  16779. if (material.metalnessMap) {
  16780. uniforms.metalnessMap.value = material.metalnessMap;
  16781. }
  16782. if (material.emissiveMap) {
  16783. uniforms.emissiveMap.value = material.emissiveMap;
  16784. }
  16785. if (material.bumpMap) {
  16786. uniforms.bumpMap.value = material.bumpMap;
  16787. uniforms.bumpScale.value = material.bumpScale;
  16788. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  16789. }
  16790. if (material.normalMap) {
  16791. uniforms.normalMap.value = material.normalMap;
  16792. uniforms.normalScale.value.copy(material.normalScale);
  16793. if (material.side === BackSide) uniforms.normalScale.value.negate();
  16794. }
  16795. if (material.displacementMap) {
  16796. uniforms.displacementMap.value = material.displacementMap;
  16797. uniforms.displacementScale.value = material.displacementScale;
  16798. uniforms.displacementBias.value = material.displacementBias;
  16799. }
  16800. if (material.envMap) {
  16801. //uniforms.envMap.value = material.envMap; // part of uniforms common
  16802. uniforms.envMapIntensity.value = material.envMapIntensity;
  16803. }
  16804. }
  16805. function refreshUniformsPhysical(uniforms, material) {
  16806. refreshUniformsStandard(uniforms, material);
  16807. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  16808. uniforms.clearcoat.value = material.clearcoat;
  16809. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  16810. if (material.sheen) uniforms.sheen.value.copy(material.sheen);
  16811. if (material.clearcoatNormalMap) {
  16812. uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
  16813. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  16814. if (material.side === BackSide) {
  16815. uniforms.clearcoatNormalScale.value.negate();
  16816. }
  16817. }
  16818. uniforms.transparency.value = material.transparency;
  16819. }
  16820. function refreshUniformsMatcap(uniforms, material) {
  16821. if (material.matcap) {
  16822. uniforms.matcap.value = material.matcap;
  16823. }
  16824. if (material.bumpMap) {
  16825. uniforms.bumpMap.value = material.bumpMap;
  16826. uniforms.bumpScale.value = material.bumpScale;
  16827. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  16828. }
  16829. if (material.normalMap) {
  16830. uniforms.normalMap.value = material.normalMap;
  16831. uniforms.normalScale.value.copy(material.normalScale);
  16832. if (material.side === BackSide) uniforms.normalScale.value.negate();
  16833. }
  16834. if (material.displacementMap) {
  16835. uniforms.displacementMap.value = material.displacementMap;
  16836. uniforms.displacementScale.value = material.displacementScale;
  16837. uniforms.displacementBias.value = material.displacementBias;
  16838. }
  16839. }
  16840. function refreshUniformsDepth(uniforms, material) {
  16841. if (material.displacementMap) {
  16842. uniforms.displacementMap.value = material.displacementMap;
  16843. uniforms.displacementScale.value = material.displacementScale;
  16844. uniforms.displacementBias.value = material.displacementBias;
  16845. }
  16846. }
  16847. function refreshUniformsDistance(uniforms, material) {
  16848. if (material.displacementMap) {
  16849. uniforms.displacementMap.value = material.displacementMap;
  16850. uniforms.displacementScale.value = material.displacementScale;
  16851. uniforms.displacementBias.value = material.displacementBias;
  16852. }
  16853. uniforms.referencePosition.value.copy(material.referencePosition);
  16854. uniforms.nearDistance.value = material.nearDistance;
  16855. uniforms.farDistance.value = material.farDistance;
  16856. }
  16857. function refreshUniformsNormal(uniforms, material) {
  16858. if (material.bumpMap) {
  16859. uniforms.bumpMap.value = material.bumpMap;
  16860. uniforms.bumpScale.value = material.bumpScale;
  16861. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  16862. }
  16863. if (material.normalMap) {
  16864. uniforms.normalMap.value = material.normalMap;
  16865. uniforms.normalScale.value.copy(material.normalScale);
  16866. if (material.side === BackSide) uniforms.normalScale.value.negate();
  16867. }
  16868. if (material.displacementMap) {
  16869. uniforms.displacementMap.value = material.displacementMap;
  16870. uniforms.displacementScale.value = material.displacementScale;
  16871. uniforms.displacementBias.value = material.displacementBias;
  16872. }
  16873. } // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  16874. function markUniformsLightsNeedsUpdate(uniforms, value) {
  16875. uniforms.ambientLightColor.needsUpdate = value;
  16876. uniforms.lightProbe.needsUpdate = value;
  16877. uniforms.directionalLights.needsUpdate = value;
  16878. uniforms.pointLights.needsUpdate = value;
  16879. uniforms.spotLights.needsUpdate = value;
  16880. uniforms.rectAreaLights.needsUpdate = value;
  16881. uniforms.hemisphereLights.needsUpdate = value;
  16882. }
  16883. function materialNeedsLights(material) {
  16884. return material.isMeshLambertMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
  16885. } //
  16886. this.setFramebuffer = function (value) {
  16887. if (_framebuffer !== value) _gl.bindFramebuffer(36160, value);
  16888. _framebuffer = value;
  16889. };
  16890. this.getActiveCubeFace = function () {
  16891. return _currentActiveCubeFace;
  16892. };
  16893. this.getActiveMipmapLevel = function () {
  16894. return _currentActiveMipmapLevel;
  16895. };
  16896. this.getRenderTarget = function () {
  16897. return _currentRenderTarget;
  16898. };
  16899. this.setRenderTarget = function (renderTarget, activeCubeFace, activeMipmapLevel) {
  16900. _currentRenderTarget = renderTarget;
  16901. _currentActiveCubeFace = activeCubeFace;
  16902. _currentActiveMipmapLevel = activeMipmapLevel;
  16903. if (renderTarget && properties.get(renderTarget).__webglFramebuffer === undefined) {
  16904. textures.setupRenderTarget(renderTarget);
  16905. }
  16906. var framebuffer = _framebuffer;
  16907. var isCube = false;
  16908. if (renderTarget) {
  16909. var __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
  16910. if (renderTarget.isWebGLRenderTargetCube) {
  16911. framebuffer = __webglFramebuffer[activeCubeFace || 0];
  16912. isCube = true;
  16913. } else if (renderTarget.isWebGLMultisampleRenderTarget) {
  16914. framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
  16915. } else {
  16916. framebuffer = __webglFramebuffer;
  16917. }
  16918. _currentViewport.copy(renderTarget.viewport);
  16919. _currentScissor.copy(renderTarget.scissor);
  16920. _currentScissorTest = renderTarget.scissorTest;
  16921. } else {
  16922. _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
  16923. _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
  16924. _currentScissorTest = _scissorTest;
  16925. }
  16926. if (_currentFramebuffer !== framebuffer) {
  16927. _gl.bindFramebuffer(36160, framebuffer);
  16928. _currentFramebuffer = framebuffer;
  16929. }
  16930. state.viewport(_currentViewport);
  16931. state.scissor(_currentScissor);
  16932. state.setScissorTest(_currentScissorTest);
  16933. if (isCube) {
  16934. var textureProperties = properties.get(renderTarget.texture);
  16935. _gl.framebufferTexture2D(36160, 36064, 34069 + (activeCubeFace || 0), textureProperties.__webglTexture, activeMipmapLevel || 0);
  16936. }
  16937. };
  16938. this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
  16939. if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
  16940. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
  16941. return;
  16942. }
  16943. var framebuffer = properties.get(renderTarget).__webglFramebuffer;
  16944. if (renderTarget.isWebGLRenderTargetCube && activeCubeFaceIndex !== undefined) {
  16945. framebuffer = framebuffer[activeCubeFaceIndex];
  16946. }
  16947. if (framebuffer) {
  16948. var restore = false;
  16949. if (framebuffer !== _currentFramebuffer) {
  16950. _gl.bindFramebuffer(36160, framebuffer);
  16951. restore = true;
  16952. }
  16953. try {
  16954. var texture = renderTarget.texture;
  16955. var textureFormat = texture.format;
  16956. var textureType = texture.type;
  16957. if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(35739)) {
  16958. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
  16959. return;
  16960. }
  16961. if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(35738) && // IE11, Edge and Chrome Mac < 52 (#9513)
  16962. !(textureType === FloatType && (capabilities.isWebGL2 || extensions.get('OES_texture_float') || extensions.get('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefox
  16963. !(textureType === HalfFloatType && (capabilities.isWebGL2 ? extensions.get('EXT_color_buffer_float') : extensions.get('EXT_color_buffer_half_float')))) {
  16964. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
  16965. return;
  16966. }
  16967. if (_gl.checkFramebufferStatus(36160) === 36053) {
  16968. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  16969. if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
  16970. _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
  16971. }
  16972. } else {
  16973. console.error('THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.');
  16974. }
  16975. } finally {
  16976. if (restore) {
  16977. _gl.bindFramebuffer(36160, _currentFramebuffer);
  16978. }
  16979. }
  16980. }
  16981. };
  16982. this.copyFramebufferToTexture = function (position, texture, level) {
  16983. var width = texture.image.width;
  16984. var height = texture.image.height;
  16985. var glFormat = utils.convert(texture.format);
  16986. textures.setTexture2D(texture, 0);
  16987. _gl.copyTexImage2D(3553, level || 0, glFormat, position.x, position.y, width, height, 0);
  16988. };
  16989. this.copyTextureToTexture = function (position, srcTexture, dstTexture, level) {
  16990. var width = srcTexture.image.width;
  16991. var height = srcTexture.image.height;
  16992. var glFormat = utils.convert(dstTexture.format);
  16993. var glType = utils.convert(dstTexture.type);
  16994. textures.setTexture2D(dstTexture, 0);
  16995. if (srcTexture.isDataTexture) {
  16996. _gl.texSubImage2D(3553, level || 0, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
  16997. } else {
  16998. _gl.texSubImage2D(3553, level || 0, position.x, position.y, glFormat, glType, srcTexture.image);
  16999. }
  17000. };
  17001. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  17002. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  17003. detail: this
  17004. })); // eslint-disable-line no-undef
  17005. }
  17006. }
  17007. /**
  17008. * @author mrdoob / http://mrdoob.com/
  17009. * @author alteredq / http://alteredqualia.com/
  17010. */
  17011. function FogExp2(color, density) {
  17012. this.name = '';
  17013. this.color = new Color(color);
  17014. this.density = density !== undefined ? density : 0.00025;
  17015. }
  17016. Object.assign(FogExp2.prototype, {
  17017. isFogExp2: true,
  17018. clone: function () {
  17019. return new FogExp2(this.color, this.density);
  17020. },
  17021. toJSON: function ()
  17022. /* meta */
  17023. {
  17024. return {
  17025. type: 'FogExp2',
  17026. color: this.color.getHex(),
  17027. density: this.density
  17028. };
  17029. }
  17030. });
  17031. /**
  17032. * @author mrdoob / http://mrdoob.com/
  17033. * @author alteredq / http://alteredqualia.com/
  17034. */
  17035. function Fog(color, near, far) {
  17036. this.name = '';
  17037. this.color = new Color(color);
  17038. this.near = near !== undefined ? near : 1;
  17039. this.far = far !== undefined ? far : 1000;
  17040. }
  17041. Object.assign(Fog.prototype, {
  17042. isFog: true,
  17043. clone: function () {
  17044. return new Fog(this.color, this.near, this.far);
  17045. },
  17046. toJSON: function ()
  17047. /* meta */
  17048. {
  17049. return {
  17050. type: 'Fog',
  17051. color: this.color.getHex(),
  17052. near: this.near,
  17053. far: this.far
  17054. };
  17055. }
  17056. });
  17057. /**
  17058. * @author benaadams / https://twitter.com/ben_a_adams
  17059. */
  17060. function InterleavedBuffer(array, stride) {
  17061. this.array = array;
  17062. this.stride = stride;
  17063. this.count = array !== undefined ? array.length / stride : 0;
  17064. this.dynamic = false;
  17065. this.updateRange = {
  17066. offset: 0,
  17067. count: -1
  17068. };
  17069. this.version = 0;
  17070. }
  17071. Object.defineProperty(InterleavedBuffer.prototype, 'needsUpdate', {
  17072. set: function (value) {
  17073. if (value === true) this.version++;
  17074. }
  17075. });
  17076. Object.assign(InterleavedBuffer.prototype, {
  17077. isInterleavedBuffer: true,
  17078. onUploadCallback: function () {},
  17079. setDynamic: function (value) {
  17080. this.dynamic = value;
  17081. return this;
  17082. },
  17083. copy: function (source) {
  17084. this.array = new source.array.constructor(source.array);
  17085. this.count = source.count;
  17086. this.stride = source.stride;
  17087. this.dynamic = source.dynamic;
  17088. return this;
  17089. },
  17090. copyAt: function (index1, attribute, index2) {
  17091. index1 *= this.stride;
  17092. index2 *= attribute.stride;
  17093. for (var i = 0, l = this.stride; i < l; i++) {
  17094. this.array[index1 + i] = attribute.array[index2 + i];
  17095. }
  17096. return this;
  17097. },
  17098. set: function (value, offset) {
  17099. if (offset === undefined) offset = 0;
  17100. this.array.set(value, offset);
  17101. return this;
  17102. },
  17103. clone: function () {
  17104. return new this.constructor().copy(this);
  17105. },
  17106. onUpload: function (callback) {
  17107. this.onUploadCallback = callback;
  17108. return this;
  17109. }
  17110. });
  17111. /**
  17112. * @author benaadams / https://twitter.com/ben_a_adams
  17113. */
  17114. function InterleavedBufferAttribute(interleavedBuffer, itemSize, offset, normalized) {
  17115. this.data = interleavedBuffer;
  17116. this.itemSize = itemSize;
  17117. this.offset = offset;
  17118. this.normalized = normalized === true;
  17119. }
  17120. Object.defineProperties(InterleavedBufferAttribute.prototype, {
  17121. count: {
  17122. get: function () {
  17123. return this.data.count;
  17124. }
  17125. },
  17126. array: {
  17127. get: function () {
  17128. return this.data.array;
  17129. }
  17130. }
  17131. });
  17132. Object.assign(InterleavedBufferAttribute.prototype, {
  17133. isInterleavedBufferAttribute: true,
  17134. setX: function (index, x) {
  17135. this.data.array[index * this.data.stride + this.offset] = x;
  17136. return this;
  17137. },
  17138. setY: function (index, y) {
  17139. this.data.array[index * this.data.stride + this.offset + 1] = y;
  17140. return this;
  17141. },
  17142. setZ: function (index, z) {
  17143. this.data.array[index * this.data.stride + this.offset + 2] = z;
  17144. return this;
  17145. },
  17146. setW: function (index, w) {
  17147. this.data.array[index * this.data.stride + this.offset + 3] = w;
  17148. return this;
  17149. },
  17150. getX: function (index) {
  17151. return this.data.array[index * this.data.stride + this.offset];
  17152. },
  17153. getY: function (index) {
  17154. return this.data.array[index * this.data.stride + this.offset + 1];
  17155. },
  17156. getZ: function (index) {
  17157. return this.data.array[index * this.data.stride + this.offset + 2];
  17158. },
  17159. getW: function (index) {
  17160. return this.data.array[index * this.data.stride + this.offset + 3];
  17161. },
  17162. setXY: function (index, x, y) {
  17163. index = index * this.data.stride + this.offset;
  17164. this.data.array[index + 0] = x;
  17165. this.data.array[index + 1] = y;
  17166. return this;
  17167. },
  17168. setXYZ: function (index, x, y, z) {
  17169. index = index * this.data.stride + this.offset;
  17170. this.data.array[index + 0] = x;
  17171. this.data.array[index + 1] = y;
  17172. this.data.array[index + 2] = z;
  17173. return this;
  17174. },
  17175. setXYZW: function (index, x, y, z, w) {
  17176. index = index * this.data.stride + this.offset;
  17177. this.data.array[index + 0] = x;
  17178. this.data.array[index + 1] = y;
  17179. this.data.array[index + 2] = z;
  17180. this.data.array[index + 3] = w;
  17181. return this;
  17182. }
  17183. });
  17184. /**
  17185. * @author alteredq / http://alteredqualia.com/
  17186. *
  17187. * parameters = {
  17188. * color: <hex>,
  17189. * map: new THREE.Texture( <Image> ),
  17190. * rotation: <float>,
  17191. * sizeAttenuation: <bool>
  17192. * }
  17193. */
  17194. function SpriteMaterial(parameters) {
  17195. Material.call(this);
  17196. this.type = 'SpriteMaterial';
  17197. this.color = new Color(0xffffff);
  17198. this.map = null;
  17199. this.rotation = 0;
  17200. this.sizeAttenuation = true;
  17201. this.transparent = true;
  17202. this.setValues(parameters);
  17203. }
  17204. SpriteMaterial.prototype = Object.create(Material.prototype);
  17205. SpriteMaterial.prototype.constructor = SpriteMaterial;
  17206. SpriteMaterial.prototype.isSpriteMaterial = true;
  17207. SpriteMaterial.prototype.copy = function (source) {
  17208. Material.prototype.copy.call(this, source);
  17209. this.color.copy(source.color);
  17210. this.map = source.map;
  17211. this.rotation = source.rotation;
  17212. this.sizeAttenuation = source.sizeAttenuation;
  17213. return this;
  17214. };
  17215. /**
  17216. * @author mikael emtinger / http://gomo.se/
  17217. * @author alteredq / http://alteredqualia.com/
  17218. */
  17219. var _geometry;
  17220. var _intersectPoint = new Vector3();
  17221. var _worldScale = new Vector3();
  17222. var _mvPosition = new Vector3();
  17223. var _alignedPosition = new Vector2();
  17224. var _rotatedPosition = new Vector2();
  17225. var _viewWorldMatrix = new Matrix4();
  17226. var _vA$1 = new Vector3();
  17227. var _vB$1 = new Vector3();
  17228. var _vC$1 = new Vector3();
  17229. var _uvA$1 = new Vector2();
  17230. var _uvB$1 = new Vector2();
  17231. var _uvC$1 = new Vector2();
  17232. function Sprite(material) {
  17233. Object3D.call(this);
  17234. this.type = 'Sprite';
  17235. if (_geometry === undefined) {
  17236. _geometry = new BufferGeometry();
  17237. var float32Array = new Float32Array([-0.5, -0.5, 0, 0, 0, 0.5, -0.5, 0, 1, 0, 0.5, 0.5, 0, 1, 1, -0.5, 0.5, 0, 0, 1]);
  17238. var interleavedBuffer = new InterleavedBuffer(float32Array, 5);
  17239. _geometry.setIndex([0, 1, 2, 0, 2, 3]);
  17240. _geometry.addAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
  17241. _geometry.addAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
  17242. }
  17243. this.geometry = _geometry;
  17244. this.material = material !== undefined ? material : new SpriteMaterial();
  17245. this.center = new Vector2(0.5, 0.5);
  17246. }
  17247. Sprite.prototype = Object.assign(Object.create(Object3D.prototype), {
  17248. constructor: Sprite,
  17249. isSprite: true,
  17250. raycast: function (raycaster, intersects) {
  17251. if (raycaster.camera === null) {
  17252. console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
  17253. }
  17254. _worldScale.setFromMatrixScale(this.matrixWorld);
  17255. _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
  17256. this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
  17257. _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
  17258. if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
  17259. _worldScale.multiplyScalar(-_mvPosition.z);
  17260. }
  17261. var rotation = this.material.rotation;
  17262. var sin, cos;
  17263. if (rotation !== 0) {
  17264. cos = Math.cos(rotation);
  17265. sin = Math.sin(rotation);
  17266. }
  17267. var center = this.center;
  17268. transformVertex(_vA$1.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17269. transformVertex(_vB$1.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17270. transformVertex(_vC$1.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17271. _uvA$1.set(0, 0);
  17272. _uvB$1.set(1, 0);
  17273. _uvC$1.set(1, 1); // check first triangle
  17274. var intersect = raycaster.ray.intersectTriangle(_vA$1, _vB$1, _vC$1, false, _intersectPoint);
  17275. if (intersect === null) {
  17276. // check second triangle
  17277. transformVertex(_vB$1.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17278. _uvB$1.set(0, 1);
  17279. intersect = raycaster.ray.intersectTriangle(_vA$1, _vC$1, _vB$1, false, _intersectPoint);
  17280. if (intersect === null) {
  17281. return;
  17282. }
  17283. }
  17284. var distance = raycaster.ray.origin.distanceTo(_intersectPoint);
  17285. if (distance < raycaster.near || distance > raycaster.far) return;
  17286. intersects.push({
  17287. distance: distance,
  17288. point: _intersectPoint.clone(),
  17289. uv: Triangle.getUV(_intersectPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2()),
  17290. face: null,
  17291. object: this
  17292. });
  17293. },
  17294. clone: function () {
  17295. return new this.constructor(this.material).copy(this);
  17296. },
  17297. copy: function (source) {
  17298. Object3D.prototype.copy.call(this, source);
  17299. if (source.center !== undefined) this.center.copy(source.center);
  17300. return this;
  17301. }
  17302. });
  17303. function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
  17304. // compute position in camera space
  17305. _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zero
  17306. if (sin !== undefined) {
  17307. _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
  17308. _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
  17309. } else {
  17310. _rotatedPosition.copy(_alignedPosition);
  17311. }
  17312. vertexPosition.copy(mvPosition);
  17313. vertexPosition.x += _rotatedPosition.x;
  17314. vertexPosition.y += _rotatedPosition.y; // transform to world space
  17315. vertexPosition.applyMatrix4(_viewWorldMatrix);
  17316. }
  17317. /**
  17318. * @author mikael emtinger / http://gomo.se/
  17319. * @author alteredq / http://alteredqualia.com/
  17320. * @author mrdoob / http://mrdoob.com/
  17321. */
  17322. var _v1$4 = new Vector3();
  17323. var _v2$2 = new Vector3();
  17324. function LOD() {
  17325. Object3D.call(this);
  17326. this.type = 'LOD';
  17327. Object.defineProperties(this, {
  17328. levels: {
  17329. enumerable: true,
  17330. value: []
  17331. }
  17332. });
  17333. this.autoUpdate = true;
  17334. }
  17335. LOD.prototype = Object.assign(Object.create(Object3D.prototype), {
  17336. constructor: LOD,
  17337. isLOD: true,
  17338. copy: function (source) {
  17339. Object3D.prototype.copy.call(this, source, false);
  17340. var levels = source.levels;
  17341. for (var i = 0, l = levels.length; i < l; i++) {
  17342. var level = levels[i];
  17343. this.addLevel(level.object.clone(), level.distance);
  17344. }
  17345. return this;
  17346. },
  17347. addLevel: function (object, distance) {
  17348. if (distance === undefined) distance = 0;
  17349. distance = Math.abs(distance);
  17350. var levels = this.levels;
  17351. for (var l = 0; l < levels.length; l++) {
  17352. if (distance < levels[l].distance) {
  17353. break;
  17354. }
  17355. }
  17356. levels.splice(l, 0, {
  17357. distance: distance,
  17358. object: object
  17359. });
  17360. this.add(object);
  17361. return this;
  17362. },
  17363. getObjectForDistance: function (distance) {
  17364. var levels = this.levels;
  17365. for (var i = 1, l = levels.length; i < l; i++) {
  17366. if (distance < levels[i].distance) {
  17367. break;
  17368. }
  17369. }
  17370. return levels[i - 1].object;
  17371. },
  17372. raycast: function (raycaster, intersects) {
  17373. _v1$4.setFromMatrixPosition(this.matrixWorld);
  17374. var distance = raycaster.ray.origin.distanceTo(_v1$4);
  17375. this.getObjectForDistance(distance).raycast(raycaster, intersects);
  17376. },
  17377. update: function (camera) {
  17378. var levels = this.levels;
  17379. if (levels.length > 1) {
  17380. _v1$4.setFromMatrixPosition(camera.matrixWorld);
  17381. _v2$2.setFromMatrixPosition(this.matrixWorld);
  17382. var distance = _v1$4.distanceTo(_v2$2);
  17383. levels[0].object.visible = true;
  17384. for (var i = 1, l = levels.length; i < l; i++) {
  17385. if (distance >= levels[i].distance) {
  17386. levels[i - 1].object.visible = false;
  17387. levels[i].object.visible = true;
  17388. } else {
  17389. break;
  17390. }
  17391. }
  17392. for (; i < l; i++) {
  17393. levels[i].object.visible = false;
  17394. }
  17395. }
  17396. },
  17397. toJSON: function (meta) {
  17398. var data = Object3D.prototype.toJSON.call(this, meta);
  17399. data.object.levels = [];
  17400. var levels = this.levels;
  17401. for (var i = 0, l = levels.length; i < l; i++) {
  17402. var level = levels[i];
  17403. data.object.levels.push({
  17404. object: level.object.uuid,
  17405. distance: level.distance
  17406. });
  17407. }
  17408. return data;
  17409. }
  17410. });
  17411. /**
  17412. * @author mikael emtinger / http://gomo.se/
  17413. * @author alteredq / http://alteredqualia.com/
  17414. * @author ikerr / http://verold.com
  17415. */
  17416. function SkinnedMesh(geometry, material) {
  17417. if (geometry && geometry.isGeometry) {
  17418. console.error('THREE.SkinnedMesh no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17419. }
  17420. Mesh.call(this, geometry, material);
  17421. this.type = 'SkinnedMesh';
  17422. this.bindMode = 'attached';
  17423. this.bindMatrix = new Matrix4();
  17424. this.bindMatrixInverse = new Matrix4();
  17425. }
  17426. SkinnedMesh.prototype = Object.assign(Object.create(Mesh.prototype), {
  17427. constructor: SkinnedMesh,
  17428. isSkinnedMesh: true,
  17429. bind: function (skeleton, bindMatrix) {
  17430. this.skeleton = skeleton;
  17431. if (bindMatrix === undefined) {
  17432. this.updateMatrixWorld(true);
  17433. this.skeleton.calculateInverses();
  17434. bindMatrix = this.matrixWorld;
  17435. }
  17436. this.bindMatrix.copy(bindMatrix);
  17437. this.bindMatrixInverse.getInverse(bindMatrix);
  17438. },
  17439. pose: function () {
  17440. this.skeleton.pose();
  17441. },
  17442. normalizeSkinWeights: function () {
  17443. var vector = new Vector4();
  17444. var skinWeight = this.geometry.attributes.skinWeight;
  17445. for (var i = 0, l = skinWeight.count; i < l; i++) {
  17446. vector.x = skinWeight.getX(i);
  17447. vector.y = skinWeight.getY(i);
  17448. vector.z = skinWeight.getZ(i);
  17449. vector.w = skinWeight.getW(i);
  17450. var scale = 1.0 / vector.manhattanLength();
  17451. if (scale !== Infinity) {
  17452. vector.multiplyScalar(scale);
  17453. } else {
  17454. vector.set(1, 0, 0, 0); // do something reasonable
  17455. }
  17456. skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
  17457. }
  17458. },
  17459. updateMatrixWorld: function (force) {
  17460. Mesh.prototype.updateMatrixWorld.call(this, force);
  17461. if (this.bindMode === 'attached') {
  17462. this.bindMatrixInverse.getInverse(this.matrixWorld);
  17463. } else if (this.bindMode === 'detached') {
  17464. this.bindMatrixInverse.getInverse(this.bindMatrix);
  17465. } else {
  17466. console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
  17467. }
  17468. },
  17469. clone: function () {
  17470. return new this.constructor(this.geometry, this.material).copy(this);
  17471. }
  17472. });
  17473. /**
  17474. * @author mikael emtinger / http://gomo.se/
  17475. * @author alteredq / http://alteredqualia.com/
  17476. * @author michael guerrero / http://realitymeltdown.com
  17477. * @author ikerr / http://verold.com
  17478. */
  17479. var _offsetMatrix = new Matrix4();
  17480. var _identityMatrix = new Matrix4();
  17481. function Skeleton(bones, boneInverses) {
  17482. // copy the bone array
  17483. bones = bones || [];
  17484. this.bones = bones.slice(0);
  17485. this.boneMatrices = new Float32Array(this.bones.length * 16);
  17486. this.frame = -1; // use the supplied bone inverses or calculate the inverses
  17487. if (boneInverses === undefined) {
  17488. this.calculateInverses();
  17489. } else {
  17490. if (this.bones.length === boneInverses.length) {
  17491. this.boneInverses = boneInverses.slice(0);
  17492. } else {
  17493. console.warn('THREE.Skeleton boneInverses is the wrong length.');
  17494. this.boneInverses = [];
  17495. for (var i = 0, il = this.bones.length; i < il; i++) {
  17496. this.boneInverses.push(new Matrix4());
  17497. }
  17498. }
  17499. }
  17500. }
  17501. Object.assign(Skeleton.prototype, {
  17502. calculateInverses: function () {
  17503. this.boneInverses = [];
  17504. for (var i = 0, il = this.bones.length; i < il; i++) {
  17505. var inverse = new Matrix4();
  17506. if (this.bones[i]) {
  17507. inverse.getInverse(this.bones[i].matrixWorld);
  17508. }
  17509. this.boneInverses.push(inverse);
  17510. }
  17511. },
  17512. pose: function () {
  17513. var bone, i, il; // recover the bind-time world matrices
  17514. for (i = 0, il = this.bones.length; i < il; i++) {
  17515. bone = this.bones[i];
  17516. if (bone) {
  17517. bone.matrixWorld.getInverse(this.boneInverses[i]);
  17518. }
  17519. } // compute the local matrices, positions, rotations and scales
  17520. for (i = 0, il = this.bones.length; i < il; i++) {
  17521. bone = this.bones[i];
  17522. if (bone) {
  17523. if (bone.parent && bone.parent.isBone) {
  17524. bone.matrix.getInverse(bone.parent.matrixWorld);
  17525. bone.matrix.multiply(bone.matrixWorld);
  17526. } else {
  17527. bone.matrix.copy(bone.matrixWorld);
  17528. }
  17529. bone.matrix.decompose(bone.position, bone.quaternion, bone.scale);
  17530. }
  17531. }
  17532. },
  17533. update: function () {
  17534. var bones = this.bones;
  17535. var boneInverses = this.boneInverses;
  17536. var boneMatrices = this.boneMatrices;
  17537. var boneTexture = this.boneTexture; // flatten bone matrices to array
  17538. for (var i = 0, il = bones.length; i < il; i++) {
  17539. // compute the offset between the current and the original transform
  17540. var matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
  17541. _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
  17542. _offsetMatrix.toArray(boneMatrices, i * 16);
  17543. }
  17544. if (boneTexture !== undefined) {
  17545. boneTexture.needsUpdate = true;
  17546. }
  17547. },
  17548. clone: function () {
  17549. return new Skeleton(this.bones, this.boneInverses);
  17550. },
  17551. getBoneByName: function (name) {
  17552. for (var i = 0, il = this.bones.length; i < il; i++) {
  17553. var bone = this.bones[i];
  17554. if (bone.name === name) {
  17555. return bone;
  17556. }
  17557. }
  17558. return undefined;
  17559. }
  17560. });
  17561. /**
  17562. * @author mikael emtinger / http://gomo.se/
  17563. * @author alteredq / http://alteredqualia.com/
  17564. * @author ikerr / http://verold.com
  17565. */
  17566. function Bone() {
  17567. Object3D.call(this);
  17568. this.type = 'Bone';
  17569. }
  17570. Bone.prototype = Object.assign(Object.create(Object3D.prototype), {
  17571. constructor: Bone,
  17572. isBone: true
  17573. });
  17574. /**
  17575. * @author mrdoob / http://mrdoob.com/
  17576. */
  17577. function InstancedMesh(geometry, material, count) {
  17578. Mesh.call(this, geometry, material);
  17579. this.instanceMatrix = new BufferAttribute(new Float32Array(count * 16), 16);
  17580. this.count = count;
  17581. }
  17582. InstancedMesh.prototype = Object.assign(Object.create(Mesh.prototype), {
  17583. constructor: InstancedMesh,
  17584. isInstancedMesh: true,
  17585. raycast: function () {},
  17586. setMatrixAt: function (index, matrix) {
  17587. matrix.toArray(this.instanceMatrix.array, index * 16);
  17588. },
  17589. updateMorphTargets: function () {}
  17590. });
  17591. /**
  17592. * @author mrdoob / http://mrdoob.com/
  17593. * @author alteredq / http://alteredqualia.com/
  17594. *
  17595. * parameters = {
  17596. * color: <hex>,
  17597. * opacity: <float>,
  17598. *
  17599. * linewidth: <float>,
  17600. * linecap: "round",
  17601. * linejoin: "round"
  17602. * }
  17603. */
  17604. function LineBasicMaterial(parameters) {
  17605. Material.call(this);
  17606. this.type = 'LineBasicMaterial';
  17607. this.color = new Color(0xffffff);
  17608. this.linewidth = 1;
  17609. this.linecap = 'round';
  17610. this.linejoin = 'round';
  17611. this.setValues(parameters);
  17612. }
  17613. LineBasicMaterial.prototype = Object.create(Material.prototype);
  17614. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  17615. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  17616. LineBasicMaterial.prototype.copy = function (source) {
  17617. Material.prototype.copy.call(this, source);
  17618. this.color.copy(source.color);
  17619. this.linewidth = source.linewidth;
  17620. this.linecap = source.linecap;
  17621. this.linejoin = source.linejoin;
  17622. return this;
  17623. };
  17624. /**
  17625. * @author mrdoob / http://mrdoob.com/
  17626. */
  17627. var _start = new Vector3();
  17628. var _end = new Vector3();
  17629. var _inverseMatrix$1 = new Matrix4();
  17630. var _ray$1 = new Ray();
  17631. var _sphere$2 = new Sphere();
  17632. function Line(geometry, material, mode) {
  17633. if (mode === 1) {
  17634. console.error('THREE.Line: parameter THREE.LinePieces no longer supported. Use THREE.LineSegments instead.');
  17635. }
  17636. Object3D.call(this);
  17637. this.type = 'Line';
  17638. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  17639. this.material = material !== undefined ? material : new LineBasicMaterial({
  17640. color: Math.random() * 0xffffff
  17641. });
  17642. }
  17643. Line.prototype = Object.assign(Object.create(Object3D.prototype), {
  17644. constructor: Line,
  17645. isLine: true,
  17646. computeLineDistances: function () {
  17647. var geometry = this.geometry;
  17648. if (geometry.isBufferGeometry) {
  17649. // we assume non-indexed geometry
  17650. if (geometry.index === null) {
  17651. var positionAttribute = geometry.attributes.position;
  17652. var lineDistances = [0];
  17653. for (var i = 1, l = positionAttribute.count; i < l; i++) {
  17654. _start.fromBufferAttribute(positionAttribute, i - 1);
  17655. _end.fromBufferAttribute(positionAttribute, i);
  17656. lineDistances[i] = lineDistances[i - 1];
  17657. lineDistances[i] += _start.distanceTo(_end);
  17658. }
  17659. geometry.addAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  17660. } else {
  17661. console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  17662. }
  17663. } else if (geometry.isGeometry) {
  17664. var vertices = geometry.vertices;
  17665. var lineDistances = geometry.lineDistances;
  17666. lineDistances[0] = 0;
  17667. for (var i = 1, l = vertices.length; i < l; i++) {
  17668. lineDistances[i] = lineDistances[i - 1];
  17669. lineDistances[i] += vertices[i - 1].distanceTo(vertices[i]);
  17670. }
  17671. }
  17672. return this;
  17673. },
  17674. raycast: function (raycaster, intersects) {
  17675. var precision = raycaster.linePrecision;
  17676. var geometry = this.geometry;
  17677. var matrixWorld = this.matrixWorld; // Checking boundingSphere distance to ray
  17678. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  17679. _sphere$2.copy(geometry.boundingSphere);
  17680. _sphere$2.applyMatrix4(matrixWorld);
  17681. _sphere$2.radius += precision;
  17682. if (raycaster.ray.intersectsSphere(_sphere$2) === false) return; //
  17683. _inverseMatrix$1.getInverse(matrixWorld);
  17684. _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
  17685. var localPrecision = precision / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  17686. var localPrecisionSq = localPrecision * localPrecision;
  17687. var vStart = new Vector3();
  17688. var vEnd = new Vector3();
  17689. var interSegment = new Vector3();
  17690. var interRay = new Vector3();
  17691. var step = this && this.isLineSegments ? 2 : 1;
  17692. if (geometry.isBufferGeometry) {
  17693. var index = geometry.index;
  17694. var attributes = geometry.attributes;
  17695. var positions = attributes.position.array;
  17696. if (index !== null) {
  17697. var indices = index.array;
  17698. for (var i = 0, l = indices.length - 1; i < l; i += step) {
  17699. var a = indices[i];
  17700. var b = indices[i + 1];
  17701. vStart.fromArray(positions, a * 3);
  17702. vEnd.fromArray(positions, b * 3);
  17703. var distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  17704. if (distSq > localPrecisionSq) continue;
  17705. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  17706. var distance = raycaster.ray.origin.distanceTo(interRay);
  17707. if (distance < raycaster.near || distance > raycaster.far) continue;
  17708. intersects.push({
  17709. distance: distance,
  17710. // What do we want? intersection point on the ray or on the segment??
  17711. // point: raycaster.ray.at( distance ),
  17712. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  17713. index: i,
  17714. face: null,
  17715. faceIndex: null,
  17716. object: this
  17717. });
  17718. }
  17719. } else {
  17720. for (var i = 0, l = positions.length / 3 - 1; i < l; i += step) {
  17721. vStart.fromArray(positions, 3 * i);
  17722. vEnd.fromArray(positions, 3 * i + 3);
  17723. var distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  17724. if (distSq > localPrecisionSq) continue;
  17725. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  17726. var distance = raycaster.ray.origin.distanceTo(interRay);
  17727. if (distance < raycaster.near || distance > raycaster.far) continue;
  17728. intersects.push({
  17729. distance: distance,
  17730. // What do we want? intersection point on the ray or on the segment??
  17731. // point: raycaster.ray.at( distance ),
  17732. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  17733. index: i,
  17734. face: null,
  17735. faceIndex: null,
  17736. object: this
  17737. });
  17738. }
  17739. }
  17740. } else if (geometry.isGeometry) {
  17741. var vertices = geometry.vertices;
  17742. var nbVertices = vertices.length;
  17743. for (var i = 0; i < nbVertices - 1; i += step) {
  17744. var distSq = _ray$1.distanceSqToSegment(vertices[i], vertices[i + 1], interRay, interSegment);
  17745. if (distSq > localPrecisionSq) continue;
  17746. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  17747. var distance = raycaster.ray.origin.distanceTo(interRay);
  17748. if (distance < raycaster.near || distance > raycaster.far) continue;
  17749. intersects.push({
  17750. distance: distance,
  17751. // What do we want? intersection point on the ray or on the segment??
  17752. // point: raycaster.ray.at( distance ),
  17753. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  17754. index: i,
  17755. face: null,
  17756. faceIndex: null,
  17757. object: this
  17758. });
  17759. }
  17760. }
  17761. },
  17762. clone: function () {
  17763. return new this.constructor(this.geometry, this.material).copy(this);
  17764. }
  17765. });
  17766. /**
  17767. * @author mrdoob / http://mrdoob.com/
  17768. */
  17769. var _start$1 = new Vector3();
  17770. var _end$1 = new Vector3();
  17771. function LineSegments(geometry, material) {
  17772. Line.call(this, geometry, material);
  17773. this.type = 'LineSegments';
  17774. }
  17775. LineSegments.prototype = Object.assign(Object.create(Line.prototype), {
  17776. constructor: LineSegments,
  17777. isLineSegments: true,
  17778. computeLineDistances: function () {
  17779. var geometry = this.geometry;
  17780. if (geometry.isBufferGeometry) {
  17781. // we assume non-indexed geometry
  17782. if (geometry.index === null) {
  17783. var positionAttribute = geometry.attributes.position;
  17784. var lineDistances = [];
  17785. for (var i = 0, l = positionAttribute.count; i < l; i += 2) {
  17786. _start$1.fromBufferAttribute(positionAttribute, i);
  17787. _end$1.fromBufferAttribute(positionAttribute, i + 1);
  17788. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  17789. lineDistances[i + 1] = lineDistances[i] + _start$1.distanceTo(_end$1);
  17790. }
  17791. geometry.addAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  17792. } else {
  17793. console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  17794. }
  17795. } else if (geometry.isGeometry) {
  17796. var vertices = geometry.vertices;
  17797. var lineDistances = geometry.lineDistances;
  17798. for (var i = 0, l = vertices.length; i < l; i += 2) {
  17799. _start$1.copy(vertices[i]);
  17800. _end$1.copy(vertices[i + 1]);
  17801. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  17802. lineDistances[i + 1] = lineDistances[i] + _start$1.distanceTo(_end$1);
  17803. }
  17804. }
  17805. return this;
  17806. }
  17807. });
  17808. /**
  17809. * @author mgreter / http://github.com/mgreter
  17810. */
  17811. function LineLoop(geometry, material) {
  17812. Line.call(this, geometry, material);
  17813. this.type = 'LineLoop';
  17814. }
  17815. LineLoop.prototype = Object.assign(Object.create(Line.prototype), {
  17816. constructor: LineLoop,
  17817. isLineLoop: true
  17818. });
  17819. /**
  17820. * @author mrdoob / http://mrdoob.com/
  17821. * @author alteredq / http://alteredqualia.com/
  17822. *
  17823. * parameters = {
  17824. * color: <hex>,
  17825. * opacity: <float>,
  17826. * map: new THREE.Texture( <Image> ),
  17827. *
  17828. * size: <float>,
  17829. * sizeAttenuation: <bool>
  17830. *
  17831. * morphTargets: <bool>
  17832. * }
  17833. */
  17834. function PointsMaterial(parameters) {
  17835. Material.call(this);
  17836. this.type = 'PointsMaterial';
  17837. this.color = new Color(0xffffff);
  17838. this.map = null;
  17839. this.size = 1;
  17840. this.sizeAttenuation = true;
  17841. this.morphTargets = false;
  17842. this.setValues(parameters);
  17843. }
  17844. PointsMaterial.prototype = Object.create(Material.prototype);
  17845. PointsMaterial.prototype.constructor = PointsMaterial;
  17846. PointsMaterial.prototype.isPointsMaterial = true;
  17847. PointsMaterial.prototype.copy = function (source) {
  17848. Material.prototype.copy.call(this, source);
  17849. this.color.copy(source.color);
  17850. this.map = source.map;
  17851. this.size = source.size;
  17852. this.sizeAttenuation = source.sizeAttenuation;
  17853. this.morphTargets = source.morphTargets;
  17854. return this;
  17855. };
  17856. /**
  17857. * @author alteredq / http://alteredqualia.com/
  17858. */
  17859. var _inverseMatrix$2 = new Matrix4();
  17860. var _ray$2 = new Ray();
  17861. var _sphere$3 = new Sphere();
  17862. var _position$1 = new Vector3();
  17863. function Points(geometry, material) {
  17864. Object3D.call(this);
  17865. this.type = 'Points';
  17866. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  17867. this.material = material !== undefined ? material : new PointsMaterial({
  17868. color: Math.random() * 0xffffff
  17869. });
  17870. this.updateMorphTargets();
  17871. }
  17872. Points.prototype = Object.assign(Object.create(Object3D.prototype), {
  17873. constructor: Points,
  17874. isPoints: true,
  17875. raycast: function (raycaster, intersects) {
  17876. var geometry = this.geometry;
  17877. var matrixWorld = this.matrixWorld;
  17878. var threshold = raycaster.params.Points.threshold; // Checking boundingSphere distance to ray
  17879. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  17880. _sphere$3.copy(geometry.boundingSphere);
  17881. _sphere$3.applyMatrix4(matrixWorld);
  17882. _sphere$3.radius += threshold;
  17883. if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //
  17884. _inverseMatrix$2.getInverse(matrixWorld);
  17885. _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2);
  17886. var localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  17887. var localThresholdSq = localThreshold * localThreshold;
  17888. if (geometry.isBufferGeometry) {
  17889. var index = geometry.index;
  17890. var attributes = geometry.attributes;
  17891. var positions = attributes.position.array;
  17892. if (index !== null) {
  17893. var indices = index.array;
  17894. for (var i = 0, il = indices.length; i < il; i++) {
  17895. var a = indices[i];
  17896. _position$1.fromArray(positions, a * 3);
  17897. testPoint(_position$1, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17898. }
  17899. } else {
  17900. for (var i = 0, l = positions.length / 3; i < l; i++) {
  17901. _position$1.fromArray(positions, i * 3);
  17902. testPoint(_position$1, i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17903. }
  17904. }
  17905. } else {
  17906. var vertices = geometry.vertices;
  17907. for (var i = 0, l = vertices.length; i < l; i++) {
  17908. testPoint(vertices[i], i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17909. }
  17910. }
  17911. },
  17912. updateMorphTargets: function () {
  17913. var geometry = this.geometry;
  17914. var m, ml, name;
  17915. if (geometry.isBufferGeometry) {
  17916. var morphAttributes = geometry.morphAttributes;
  17917. var keys = Object.keys(morphAttributes);
  17918. if (keys.length > 0) {
  17919. var morphAttribute = morphAttributes[keys[0]];
  17920. if (morphAttribute !== undefined) {
  17921. this.morphTargetInfluences = [];
  17922. this.morphTargetDictionary = {};
  17923. for (m = 0, ml = morphAttribute.length; m < ml; m++) {
  17924. name = morphAttribute[m].name || String(m);
  17925. this.morphTargetInfluences.push(0);
  17926. this.morphTargetDictionary[name] = m;
  17927. }
  17928. }
  17929. }
  17930. } else {
  17931. var morphTargets = geometry.morphTargets;
  17932. if (morphTargets !== undefined && morphTargets.length > 0) {
  17933. console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  17934. }
  17935. }
  17936. },
  17937. clone: function () {
  17938. return new this.constructor(this.geometry, this.material).copy(this);
  17939. }
  17940. });
  17941. function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
  17942. var rayPointDistanceSq = _ray$2.distanceSqToPoint(point);
  17943. if (rayPointDistanceSq < localThresholdSq) {
  17944. var intersectPoint = new Vector3();
  17945. _ray$2.closestPointToPoint(point, intersectPoint);
  17946. intersectPoint.applyMatrix4(matrixWorld);
  17947. var distance = raycaster.ray.origin.distanceTo(intersectPoint);
  17948. if (distance < raycaster.near || distance > raycaster.far) return;
  17949. intersects.push({
  17950. distance: distance,
  17951. distanceToRay: Math.sqrt(rayPointDistanceSq),
  17952. point: intersectPoint,
  17953. index: index,
  17954. face: null,
  17955. object: object
  17956. });
  17957. }
  17958. }
  17959. /**
  17960. * @author mrdoob / http://mrdoob.com/
  17961. */
  17962. function VideoTexture(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  17963. Texture.call(this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  17964. this.format = format !== undefined ? format : RGBFormat;
  17965. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  17966. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  17967. this.generateMipmaps = false;
  17968. }
  17969. VideoTexture.prototype = Object.assign(Object.create(Texture.prototype), {
  17970. constructor: VideoTexture,
  17971. isVideoTexture: true,
  17972. update: function () {
  17973. var video = this.image;
  17974. if (video.readyState >= video.HAVE_CURRENT_DATA) {
  17975. this.needsUpdate = true;
  17976. }
  17977. }
  17978. });
  17979. /**
  17980. * @author alteredq / http://alteredqualia.com/
  17981. */
  17982. function CompressedTexture(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  17983. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  17984. this.image = {
  17985. width: width,
  17986. height: height
  17987. };
  17988. this.mipmaps = mipmaps; // no flipping for cube textures
  17989. // (also flipping doesn't work for compressed textures )
  17990. this.flipY = false; // can't generate mipmaps for compressed textures
  17991. // mips must be embedded in DDS files
  17992. this.generateMipmaps = false;
  17993. }
  17994. CompressedTexture.prototype = Object.create(Texture.prototype);
  17995. CompressedTexture.prototype.constructor = CompressedTexture;
  17996. CompressedTexture.prototype.isCompressedTexture = true;
  17997. /**
  17998. * @author mrdoob / http://mrdoob.com/
  17999. */
  18000. function CanvasTexture(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  18001. Texture.call(this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  18002. this.needsUpdate = true;
  18003. }
  18004. CanvasTexture.prototype = Object.create(Texture.prototype);
  18005. CanvasTexture.prototype.constructor = CanvasTexture;
  18006. CanvasTexture.prototype.isCanvasTexture = true;
  18007. /**
  18008. * @author Matt DesLauriers / @mattdesl
  18009. * @author atix / arthursilber.de
  18010. */
  18011. function DepthTexture(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
  18012. format = format !== undefined ? format : DepthFormat;
  18013. if (format !== DepthFormat && format !== DepthStencilFormat) {
  18014. throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
  18015. }
  18016. if (type === undefined && format === DepthFormat) type = UnsignedShortType;
  18017. if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
  18018. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  18019. this.image = {
  18020. width: width,
  18021. height: height
  18022. };
  18023. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  18024. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  18025. this.flipY = false;
  18026. this.generateMipmaps = false;
  18027. }
  18028. DepthTexture.prototype = Object.create(Texture.prototype);
  18029. DepthTexture.prototype.constructor = DepthTexture;
  18030. DepthTexture.prototype.isDepthTexture = true;
  18031. /**
  18032. * @author mrdoob / http://mrdoob.com/
  18033. * @author Mugen87 / https://github.com/Mugen87
  18034. */
  18035. function WireframeGeometry(geometry) {
  18036. BufferGeometry.call(this);
  18037. this.type = 'WireframeGeometry'; // buffer
  18038. var vertices = []; // helper variables
  18039. var i, j, l, o, ol;
  18040. var edge = [0, 0],
  18041. edges = {},
  18042. e,
  18043. edge1,
  18044. edge2;
  18045. var key,
  18046. keys = ['a', 'b', 'c'];
  18047. var vertex; // different logic for Geometry and BufferGeometry
  18048. if (geometry && geometry.isGeometry) {
  18049. // create a data structure that contains all edges without duplicates
  18050. var faces = geometry.faces;
  18051. for (i = 0, l = faces.length; i < l; i++) {
  18052. var face = faces[i];
  18053. for (j = 0; j < 3; j++) {
  18054. edge1 = face[keys[j]];
  18055. edge2 = face[keys[(j + 1) % 3]];
  18056. edge[0] = Math.min(edge1, edge2); // sorting prevents duplicates
  18057. edge[1] = Math.max(edge1, edge2);
  18058. key = edge[0] + ',' + edge[1];
  18059. if (edges[key] === undefined) {
  18060. edges[key] = {
  18061. index1: edge[0],
  18062. index2: edge[1]
  18063. };
  18064. }
  18065. }
  18066. } // generate vertices
  18067. for (key in edges) {
  18068. e = edges[key];
  18069. vertex = geometry.vertices[e.index1];
  18070. vertices.push(vertex.x, vertex.y, vertex.z);
  18071. vertex = geometry.vertices[e.index2];
  18072. vertices.push(vertex.x, vertex.y, vertex.z);
  18073. }
  18074. } else if (geometry && geometry.isBufferGeometry) {
  18075. var position, indices, groups;
  18076. var group, start, count;
  18077. var index1, index2;
  18078. vertex = new Vector3();
  18079. if (geometry.index !== null) {
  18080. // indexed BufferGeometry
  18081. position = geometry.attributes.position;
  18082. indices = geometry.index;
  18083. groups = geometry.groups;
  18084. if (groups.length === 0) {
  18085. groups = [{
  18086. start: 0,
  18087. count: indices.count,
  18088. materialIndex: 0
  18089. }];
  18090. } // create a data structure that contains all eges without duplicates
  18091. for (o = 0, ol = groups.length; o < ol; ++o) {
  18092. group = groups[o];
  18093. start = group.start;
  18094. count = group.count;
  18095. for (i = start, l = start + count; i < l; i += 3) {
  18096. for (j = 0; j < 3; j++) {
  18097. edge1 = indices.getX(i + j);
  18098. edge2 = indices.getX(i + (j + 1) % 3);
  18099. edge[0] = Math.min(edge1, edge2); // sorting prevents duplicates
  18100. edge[1] = Math.max(edge1, edge2);
  18101. key = edge[0] + ',' + edge[1];
  18102. if (edges[key] === undefined) {
  18103. edges[key] = {
  18104. index1: edge[0],
  18105. index2: edge[1]
  18106. };
  18107. }
  18108. }
  18109. }
  18110. } // generate vertices
  18111. for (key in edges) {
  18112. e = edges[key];
  18113. vertex.fromBufferAttribute(position, e.index1);
  18114. vertices.push(vertex.x, vertex.y, vertex.z);
  18115. vertex.fromBufferAttribute(position, e.index2);
  18116. vertices.push(vertex.x, vertex.y, vertex.z);
  18117. }
  18118. } else {
  18119. // non-indexed BufferGeometry
  18120. position = geometry.attributes.position;
  18121. for (i = 0, l = position.count / 3; i < l; i++) {
  18122. for (j = 0; j < 3; j++) {
  18123. // three edges per triangle, an edge is represented as (index1, index2)
  18124. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  18125. index1 = 3 * i + j;
  18126. vertex.fromBufferAttribute(position, index1);
  18127. vertices.push(vertex.x, vertex.y, vertex.z);
  18128. index2 = 3 * i + (j + 1) % 3;
  18129. vertex.fromBufferAttribute(position, index2);
  18130. vertices.push(vertex.x, vertex.y, vertex.z);
  18131. }
  18132. }
  18133. }
  18134. } // build geometry
  18135. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  18136. }
  18137. WireframeGeometry.prototype = Object.create(BufferGeometry.prototype);
  18138. WireframeGeometry.prototype.constructor = WireframeGeometry;
  18139. /**
  18140. * @author zz85 / https://github.com/zz85
  18141. * @author Mugen87 / https://github.com/Mugen87
  18142. *
  18143. * Parametric Surfaces Geometry
  18144. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  18145. */
  18146. // ParametricGeometry
  18147. function ParametricGeometry(func, slices, stacks) {
  18148. Geometry.call(this);
  18149. this.type = 'ParametricGeometry';
  18150. this.parameters = {
  18151. func: func,
  18152. slices: slices,
  18153. stacks: stacks
  18154. };
  18155. this.fromBufferGeometry(new ParametricBufferGeometry(func, slices, stacks));
  18156. this.mergeVertices();
  18157. }
  18158. ParametricGeometry.prototype = Object.create(Geometry.prototype);
  18159. ParametricGeometry.prototype.constructor = ParametricGeometry; // ParametricBufferGeometry
  18160. function ParametricBufferGeometry(func, slices, stacks) {
  18161. BufferGeometry.call(this);
  18162. this.type = 'ParametricBufferGeometry';
  18163. this.parameters = {
  18164. func: func,
  18165. slices: slices,
  18166. stacks: stacks
  18167. }; // buffers
  18168. var indices = [];
  18169. var vertices = [];
  18170. var normals = [];
  18171. var uvs = [];
  18172. var EPS = 0.00001;
  18173. var normal = new Vector3();
  18174. var p0 = new Vector3(),
  18175. p1 = new Vector3();
  18176. var pu = new Vector3(),
  18177. pv = new Vector3();
  18178. var i, j;
  18179. if (func.length < 3) {
  18180. console.error('THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.');
  18181. } // generate vertices, normals and uvs
  18182. var sliceCount = slices + 1;
  18183. for (i = 0; i <= stacks; i++) {
  18184. var v = i / stacks;
  18185. for (j = 0; j <= slices; j++) {
  18186. var u = j / slices; // vertex
  18187. func(u, v, p0);
  18188. vertices.push(p0.x, p0.y, p0.z); // normal
  18189. // approximate tangent vectors via finite differences
  18190. if (u - EPS >= 0) {
  18191. func(u - EPS, v, p1);
  18192. pu.subVectors(p0, p1);
  18193. } else {
  18194. func(u + EPS, v, p1);
  18195. pu.subVectors(p1, p0);
  18196. }
  18197. if (v - EPS >= 0) {
  18198. func(u, v - EPS, p1);
  18199. pv.subVectors(p0, p1);
  18200. } else {
  18201. func(u, v + EPS, p1);
  18202. pv.subVectors(p1, p0);
  18203. } // cross product of tangent vectors returns surface normal
  18204. normal.crossVectors(pu, pv).normalize();
  18205. normals.push(normal.x, normal.y, normal.z); // uv
  18206. uvs.push(u, v);
  18207. }
  18208. } // generate indices
  18209. for (i = 0; i < stacks; i++) {
  18210. for (j = 0; j < slices; j++) {
  18211. var a = i * sliceCount + j;
  18212. var b = i * sliceCount + j + 1;
  18213. var c = (i + 1) * sliceCount + j + 1;
  18214. var d = (i + 1) * sliceCount + j; // faces one and two
  18215. indices.push(a, b, d);
  18216. indices.push(b, c, d);
  18217. }
  18218. } // build geometry
  18219. this.setIndex(indices);
  18220. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  18221. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  18222. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  18223. }
  18224. ParametricBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18225. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  18226. /**
  18227. * @author clockworkgeek / https://github.com/clockworkgeek
  18228. * @author timothypratley / https://github.com/timothypratley
  18229. * @author WestLangley / http://github.com/WestLangley
  18230. * @author Mugen87 / https://github.com/Mugen87
  18231. */
  18232. // PolyhedronGeometry
  18233. function PolyhedronGeometry(vertices, indices, radius, detail) {
  18234. Geometry.call(this);
  18235. this.type = 'PolyhedronGeometry';
  18236. this.parameters = {
  18237. vertices: vertices,
  18238. indices: indices,
  18239. radius: radius,
  18240. detail: detail
  18241. };
  18242. this.fromBufferGeometry(new PolyhedronBufferGeometry(vertices, indices, radius, detail));
  18243. this.mergeVertices();
  18244. }
  18245. PolyhedronGeometry.prototype = Object.create(Geometry.prototype);
  18246. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry; // PolyhedronBufferGeometry
  18247. function PolyhedronBufferGeometry(vertices, indices, radius, detail) {
  18248. BufferGeometry.call(this);
  18249. this.type = 'PolyhedronBufferGeometry';
  18250. this.parameters = {
  18251. vertices: vertices,
  18252. indices: indices,
  18253. radius: radius,
  18254. detail: detail
  18255. };
  18256. radius = radius || 1;
  18257. detail = detail || 0; // default buffer data
  18258. var vertexBuffer = [];
  18259. var uvBuffer = []; // the subdivision creates the vertex buffer data
  18260. subdivide(detail); // all vertices should lie on a conceptual sphere with a given radius
  18261. applyRadius(radius); // finally, create the uv data
  18262. generateUVs(); // build non-indexed geometry
  18263. this.addAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
  18264. this.addAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
  18265. this.addAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
  18266. if (detail === 0) {
  18267. this.computeVertexNormals(); // flat normals
  18268. } else {
  18269. this.normalizeNormals(); // smooth normals
  18270. } // helper functions
  18271. function subdivide(detail) {
  18272. var a = new Vector3();
  18273. var b = new Vector3();
  18274. var c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value
  18275. for (var i = 0; i < indices.length; i += 3) {
  18276. // get the vertices of the face
  18277. getVertexByIndex(indices[i + 0], a);
  18278. getVertexByIndex(indices[i + 1], b);
  18279. getVertexByIndex(indices[i + 2], c); // perform subdivision
  18280. subdivideFace(a, b, c, detail);
  18281. }
  18282. }
  18283. function subdivideFace(a, b, c, detail) {
  18284. var cols = Math.pow(2, detail); // we use this multidimensional array as a data structure for creating the subdivision
  18285. var v = [];
  18286. var i, j; // construct all of the vertices for this subdivision
  18287. for (i = 0; i <= cols; i++) {
  18288. v[i] = [];
  18289. var aj = a.clone().lerp(c, i / cols);
  18290. var bj = b.clone().lerp(c, i / cols);
  18291. var rows = cols - i;
  18292. for (j = 0; j <= rows; j++) {
  18293. if (j === 0 && i === cols) {
  18294. v[i][j] = aj;
  18295. } else {
  18296. v[i][j] = aj.clone().lerp(bj, j / rows);
  18297. }
  18298. }
  18299. } // construct all of the faces
  18300. for (i = 0; i < cols; i++) {
  18301. for (j = 0; j < 2 * (cols - i) - 1; j++) {
  18302. var k = Math.floor(j / 2);
  18303. if (j % 2 === 0) {
  18304. pushVertex(v[i][k + 1]);
  18305. pushVertex(v[i + 1][k]);
  18306. pushVertex(v[i][k]);
  18307. } else {
  18308. pushVertex(v[i][k + 1]);
  18309. pushVertex(v[i + 1][k + 1]);
  18310. pushVertex(v[i + 1][k]);
  18311. }
  18312. }
  18313. }
  18314. }
  18315. function applyRadius(radius) {
  18316. var vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex
  18317. for (var i = 0; i < vertexBuffer.length; i += 3) {
  18318. vertex.x = vertexBuffer[i + 0];
  18319. vertex.y = vertexBuffer[i + 1];
  18320. vertex.z = vertexBuffer[i + 2];
  18321. vertex.normalize().multiplyScalar(radius);
  18322. vertexBuffer[i + 0] = vertex.x;
  18323. vertexBuffer[i + 1] = vertex.y;
  18324. vertexBuffer[i + 2] = vertex.z;
  18325. }
  18326. }
  18327. function generateUVs() {
  18328. var vertex = new Vector3();
  18329. for (var i = 0; i < vertexBuffer.length; i += 3) {
  18330. vertex.x = vertexBuffer[i + 0];
  18331. vertex.y = vertexBuffer[i + 1];
  18332. vertex.z = vertexBuffer[i + 2];
  18333. var u = azimuth(vertex) / 2 / Math.PI + 0.5;
  18334. var v = inclination(vertex) / Math.PI + 0.5;
  18335. uvBuffer.push(u, 1 - v);
  18336. }
  18337. correctUVs();
  18338. correctSeam();
  18339. }
  18340. function correctSeam() {
  18341. // handle case when face straddles the seam, see #3269
  18342. for (var i = 0; i < uvBuffer.length; i += 6) {
  18343. // uv data of a single face
  18344. var x0 = uvBuffer[i + 0];
  18345. var x1 = uvBuffer[i + 2];
  18346. var x2 = uvBuffer[i + 4];
  18347. var max = Math.max(x0, x1, x2);
  18348. var min = Math.min(x0, x1, x2); // 0.9 is somewhat arbitrary
  18349. if (max > 0.9 && min < 0.1) {
  18350. if (x0 < 0.2) uvBuffer[i + 0] += 1;
  18351. if (x1 < 0.2) uvBuffer[i + 2] += 1;
  18352. if (x2 < 0.2) uvBuffer[i + 4] += 1;
  18353. }
  18354. }
  18355. }
  18356. function pushVertex(vertex) {
  18357. vertexBuffer.push(vertex.x, vertex.y, vertex.z);
  18358. }
  18359. function getVertexByIndex(index, vertex) {
  18360. var stride = index * 3;
  18361. vertex.x = vertices[stride + 0];
  18362. vertex.y = vertices[stride + 1];
  18363. vertex.z = vertices[stride + 2];
  18364. }
  18365. function correctUVs() {
  18366. var a = new Vector3();
  18367. var b = new Vector3();
  18368. var c = new Vector3();
  18369. var centroid = new Vector3();
  18370. var uvA = new Vector2();
  18371. var uvB = new Vector2();
  18372. var uvC = new Vector2();
  18373. for (var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
  18374. a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
  18375. b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
  18376. c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
  18377. uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
  18378. uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
  18379. uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
  18380. centroid.copy(a).add(b).add(c).divideScalar(3);
  18381. var azi = azimuth(centroid);
  18382. correctUV(uvA, j + 0, a, azi);
  18383. correctUV(uvB, j + 2, b, azi);
  18384. correctUV(uvC, j + 4, c, azi);
  18385. }
  18386. }
  18387. function correctUV(uv, stride, vector, azimuth) {
  18388. if (azimuth < 0 && uv.x === 1) {
  18389. uvBuffer[stride] = uv.x - 1;
  18390. }
  18391. if (vector.x === 0 && vector.z === 0) {
  18392. uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
  18393. }
  18394. } // Angle around the Y axis, counter-clockwise when looking from above.
  18395. function azimuth(vector) {
  18396. return Math.atan2(vector.z, -vector.x);
  18397. } // Angle above the XZ plane.
  18398. function inclination(vector) {
  18399. return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
  18400. }
  18401. }
  18402. PolyhedronBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18403. PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;
  18404. /**
  18405. * @author timothypratley / https://github.com/timothypratley
  18406. * @author Mugen87 / https://github.com/Mugen87
  18407. */
  18408. // TetrahedronGeometry
  18409. function TetrahedronGeometry(radius, detail) {
  18410. Geometry.call(this);
  18411. this.type = 'TetrahedronGeometry';
  18412. this.parameters = {
  18413. radius: radius,
  18414. detail: detail
  18415. };
  18416. this.fromBufferGeometry(new TetrahedronBufferGeometry(radius, detail));
  18417. this.mergeVertices();
  18418. }
  18419. TetrahedronGeometry.prototype = Object.create(Geometry.prototype);
  18420. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry; // TetrahedronBufferGeometry
  18421. function TetrahedronBufferGeometry(radius, detail) {
  18422. var vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
  18423. var indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
  18424. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  18425. this.type = 'TetrahedronBufferGeometry';
  18426. this.parameters = {
  18427. radius: radius,
  18428. detail: detail
  18429. };
  18430. }
  18431. TetrahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  18432. TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;
  18433. /**
  18434. * @author timothypratley / https://github.com/timothypratley
  18435. * @author Mugen87 / https://github.com/Mugen87
  18436. */
  18437. // OctahedronGeometry
  18438. function OctahedronGeometry(radius, detail) {
  18439. Geometry.call(this);
  18440. this.type = 'OctahedronGeometry';
  18441. this.parameters = {
  18442. radius: radius,
  18443. detail: detail
  18444. };
  18445. this.fromBufferGeometry(new OctahedronBufferGeometry(radius, detail));
  18446. this.mergeVertices();
  18447. }
  18448. OctahedronGeometry.prototype = Object.create(Geometry.prototype);
  18449. OctahedronGeometry.prototype.constructor = OctahedronGeometry; // OctahedronBufferGeometry
  18450. function OctahedronBufferGeometry(radius, detail) {
  18451. var vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
  18452. var indices = [0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2];
  18453. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  18454. this.type = 'OctahedronBufferGeometry';
  18455. this.parameters = {
  18456. radius: radius,
  18457. detail: detail
  18458. };
  18459. }
  18460. OctahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  18461. OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;
  18462. /**
  18463. * @author timothypratley / https://github.com/timothypratley
  18464. * @author Mugen87 / https://github.com/Mugen87
  18465. */
  18466. // IcosahedronGeometry
  18467. function IcosahedronGeometry(radius, detail) {
  18468. Geometry.call(this);
  18469. this.type = 'IcosahedronGeometry';
  18470. this.parameters = {
  18471. radius: radius,
  18472. detail: detail
  18473. };
  18474. this.fromBufferGeometry(new IcosahedronBufferGeometry(radius, detail));
  18475. this.mergeVertices();
  18476. }
  18477. IcosahedronGeometry.prototype = Object.create(Geometry.prototype);
  18478. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry; // IcosahedronBufferGeometry
  18479. function IcosahedronBufferGeometry(radius, detail) {
  18480. var t = (1 + Math.sqrt(5)) / 2;
  18481. var vertices = [-1, t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, 0, -1, t, 0, 1, t, 0, -1, -t, 0, 1, -t, t, 0, -1, t, 0, 1, -t, 0, -1, -t, 0, 1];
  18482. var indices = [0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11, 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8, 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9, 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1];
  18483. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  18484. this.type = 'IcosahedronBufferGeometry';
  18485. this.parameters = {
  18486. radius: radius,
  18487. detail: detail
  18488. };
  18489. }
  18490. IcosahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  18491. IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;
  18492. /**
  18493. * @author Abe Pazos / https://hamoid.com
  18494. * @author Mugen87 / https://github.com/Mugen87
  18495. */
  18496. // DodecahedronGeometry
  18497. function DodecahedronGeometry(radius, detail) {
  18498. Geometry.call(this);
  18499. this.type = 'DodecahedronGeometry';
  18500. this.parameters = {
  18501. radius: radius,
  18502. detail: detail
  18503. };
  18504. this.fromBufferGeometry(new DodecahedronBufferGeometry(radius, detail));
  18505. this.mergeVertices();
  18506. }
  18507. DodecahedronGeometry.prototype = Object.create(Geometry.prototype);
  18508. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry; // DodecahedronBufferGeometry
  18509. function DodecahedronBufferGeometry(radius, detail) {
  18510. var t = (1 + Math.sqrt(5)) / 2;
  18511. var r = 1 / t;
  18512. var vertices = [// (±1, ±1, ±1)
  18513. -1, -1, -1, -1, -1, 1, -1, 1, -1, -1, 1, 1, 1, -1, -1, 1, -1, 1, 1, 1, -1, 1, 1, 1, // (0, ±1/φ, ±φ)
  18514. 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0)
  18515. -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ)
  18516. -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
  18517. var indices = [3, 11, 7, 3, 7, 15, 3, 15, 13, 7, 19, 17, 7, 17, 6, 7, 6, 15, 17, 4, 8, 17, 8, 10, 17, 10, 6, 8, 0, 16, 8, 16, 2, 8, 2, 10, 0, 12, 1, 0, 1, 18, 0, 18, 16, 6, 10, 2, 6, 2, 13, 6, 13, 15, 2, 16, 18, 2, 18, 3, 2, 3, 13, 18, 1, 9, 18, 9, 11, 18, 11, 3, 4, 14, 12, 4, 12, 0, 4, 0, 8, 11, 9, 5, 11, 5, 19, 11, 19, 7, 19, 5, 14, 19, 14, 4, 19, 4, 17, 1, 12, 14, 1, 14, 5, 1, 5, 9];
  18518. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  18519. this.type = 'DodecahedronBufferGeometry';
  18520. this.parameters = {
  18521. radius: radius,
  18522. detail: detail
  18523. };
  18524. }
  18525. DodecahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  18526. DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;
  18527. /**
  18528. * @author oosmoxiecode / https://github.com/oosmoxiecode
  18529. * @author WestLangley / https://github.com/WestLangley
  18530. * @author zz85 / https://github.com/zz85
  18531. * @author miningold / https://github.com/miningold
  18532. * @author jonobr1 / https://github.com/jonobr1
  18533. * @author Mugen87 / https://github.com/Mugen87
  18534. *
  18535. */
  18536. // TubeGeometry
  18537. function TubeGeometry(path, tubularSegments, radius, radialSegments, closed, taper) {
  18538. Geometry.call(this);
  18539. this.type = 'TubeGeometry';
  18540. this.parameters = {
  18541. path: path,
  18542. tubularSegments: tubularSegments,
  18543. radius: radius,
  18544. radialSegments: radialSegments,
  18545. closed: closed
  18546. };
  18547. if (taper !== undefined) console.warn('THREE.TubeGeometry: taper has been removed.');
  18548. var bufferGeometry = new TubeBufferGeometry(path, tubularSegments, radius, radialSegments, closed); // expose internals
  18549. this.tangents = bufferGeometry.tangents;
  18550. this.normals = bufferGeometry.normals;
  18551. this.binormals = bufferGeometry.binormals; // create geometry
  18552. this.fromBufferGeometry(bufferGeometry);
  18553. this.mergeVertices();
  18554. }
  18555. TubeGeometry.prototype = Object.create(Geometry.prototype);
  18556. TubeGeometry.prototype.constructor = TubeGeometry; // TubeBufferGeometry
  18557. function TubeBufferGeometry(path, tubularSegments, radius, radialSegments, closed) {
  18558. BufferGeometry.call(this);
  18559. this.type = 'TubeBufferGeometry';
  18560. this.parameters = {
  18561. path: path,
  18562. tubularSegments: tubularSegments,
  18563. radius: radius,
  18564. radialSegments: radialSegments,
  18565. closed: closed
  18566. };
  18567. tubularSegments = tubularSegments || 64;
  18568. radius = radius || 1;
  18569. radialSegments = radialSegments || 8;
  18570. closed = closed || false;
  18571. var frames = path.computeFrenetFrames(tubularSegments, closed); // expose internals
  18572. this.tangents = frames.tangents;
  18573. this.normals = frames.normals;
  18574. this.binormals = frames.binormals; // helper variables
  18575. var vertex = new Vector3();
  18576. var normal = new Vector3();
  18577. var uv = new Vector2();
  18578. var P = new Vector3();
  18579. var i, j; // buffer
  18580. var vertices = [];
  18581. var normals = [];
  18582. var uvs = [];
  18583. var indices = []; // create buffer data
  18584. generateBufferData(); // build geometry
  18585. this.setIndex(indices);
  18586. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  18587. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  18588. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functions
  18589. function generateBufferData() {
  18590. for (i = 0; i < tubularSegments; i++) {
  18591. generateSegment(i);
  18592. } // if the geometry is not closed, generate the last row of vertices and normals
  18593. // at the regular position on the given path
  18594. //
  18595. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  18596. generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.
  18597. // this makes it easy compute correct values for closed geometries
  18598. generateUVs(); // finally create faces
  18599. generateIndices();
  18600. }
  18601. function generateSegment(i) {
  18602. // we use getPointAt to sample evenly distributed points from the given path
  18603. P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormal
  18604. var N = frames.normals[i];
  18605. var B = frames.binormals[i]; // generate normals and vertices for the current segment
  18606. for (j = 0; j <= radialSegments; j++) {
  18607. var v = j / radialSegments * Math.PI * 2;
  18608. var sin = Math.sin(v);
  18609. var cos = -Math.cos(v); // normal
  18610. normal.x = cos * N.x + sin * B.x;
  18611. normal.y = cos * N.y + sin * B.y;
  18612. normal.z = cos * N.z + sin * B.z;
  18613. normal.normalize();
  18614. normals.push(normal.x, normal.y, normal.z); // vertex
  18615. vertex.x = P.x + radius * normal.x;
  18616. vertex.y = P.y + radius * normal.y;
  18617. vertex.z = P.z + radius * normal.z;
  18618. vertices.push(vertex.x, vertex.y, vertex.z);
  18619. }
  18620. }
  18621. function generateIndices() {
  18622. for (j = 1; j <= tubularSegments; j++) {
  18623. for (i = 1; i <= radialSegments; i++) {
  18624. var a = (radialSegments + 1) * (j - 1) + (i - 1);
  18625. var b = (radialSegments + 1) * j + (i - 1);
  18626. var c = (radialSegments + 1) * j + i;
  18627. var d = (radialSegments + 1) * (j - 1) + i; // faces
  18628. indices.push(a, b, d);
  18629. indices.push(b, c, d);
  18630. }
  18631. }
  18632. }
  18633. function generateUVs() {
  18634. for (i = 0; i <= tubularSegments; i++) {
  18635. for (j = 0; j <= radialSegments; j++) {
  18636. uv.x = i / tubularSegments;
  18637. uv.y = j / radialSegments;
  18638. uvs.push(uv.x, uv.y);
  18639. }
  18640. }
  18641. }
  18642. }
  18643. TubeBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18644. TubeBufferGeometry.prototype.constructor = TubeBufferGeometry;
  18645. TubeBufferGeometry.prototype.toJSON = function () {
  18646. var data = BufferGeometry.prototype.toJSON.call(this);
  18647. data.path = this.parameters.path.toJSON();
  18648. return data;
  18649. };
  18650. /**
  18651. * @author oosmoxiecode
  18652. * @author Mugen87 / https://github.com/Mugen87
  18653. *
  18654. * based on http://www.blackpawn.com/texts/pqtorus/
  18655. */
  18656. // TorusKnotGeometry
  18657. function TorusKnotGeometry(radius, tube, tubularSegments, radialSegments, p, q, heightScale) {
  18658. Geometry.call(this);
  18659. this.type = 'TorusKnotGeometry';
  18660. this.parameters = {
  18661. radius: radius,
  18662. tube: tube,
  18663. tubularSegments: tubularSegments,
  18664. radialSegments: radialSegments,
  18665. p: p,
  18666. q: q
  18667. };
  18668. if (heightScale !== undefined) console.warn('THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.');
  18669. this.fromBufferGeometry(new TorusKnotBufferGeometry(radius, tube, tubularSegments, radialSegments, p, q));
  18670. this.mergeVertices();
  18671. }
  18672. TorusKnotGeometry.prototype = Object.create(Geometry.prototype);
  18673. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry; // TorusKnotBufferGeometry
  18674. function TorusKnotBufferGeometry(radius, tube, tubularSegments, radialSegments, p, q) {
  18675. BufferGeometry.call(this);
  18676. this.type = 'TorusKnotBufferGeometry';
  18677. this.parameters = {
  18678. radius: radius,
  18679. tube: tube,
  18680. tubularSegments: tubularSegments,
  18681. radialSegments: radialSegments,
  18682. p: p,
  18683. q: q
  18684. };
  18685. radius = radius || 1;
  18686. tube = tube || 0.4;
  18687. tubularSegments = Math.floor(tubularSegments) || 64;
  18688. radialSegments = Math.floor(radialSegments) || 8;
  18689. p = p || 2;
  18690. q = q || 3; // buffers
  18691. var indices = [];
  18692. var vertices = [];
  18693. var normals = [];
  18694. var uvs = []; // helper variables
  18695. var i, j;
  18696. var vertex = new Vector3();
  18697. var normal = new Vector3();
  18698. var P1 = new Vector3();
  18699. var P2 = new Vector3();
  18700. var B = new Vector3();
  18701. var T = new Vector3();
  18702. var N = new Vector3(); // generate vertices, normals and uvs
  18703. for (i = 0; i <= tubularSegments; ++i) {
  18704. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  18705. var u = i / tubularSegments * p * Math.PI * 2; // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  18706. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  18707. calculatePositionOnCurve(u, p, q, radius, P1);
  18708. calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basis
  18709. T.subVectors(P2, P1);
  18710. N.addVectors(P2, P1);
  18711. B.crossVectors(T, N);
  18712. N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use it
  18713. B.normalize();
  18714. N.normalize();
  18715. for (j = 0; j <= radialSegments; ++j) {
  18716. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  18717. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  18718. var v = j / radialSegments * Math.PI * 2;
  18719. var cx = -tube * Math.cos(v);
  18720. var cy = tube * Math.sin(v); // now calculate the final vertex position.
  18721. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  18722. vertex.x = P1.x + (cx * N.x + cy * B.x);
  18723. vertex.y = P1.y + (cx * N.y + cy * B.y);
  18724. vertex.z = P1.z + (cx * N.z + cy * B.z);
  18725. vertices.push(vertex.x, vertex.y, vertex.z); // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  18726. normal.subVectors(vertex, P1).normalize();
  18727. normals.push(normal.x, normal.y, normal.z); // uv
  18728. uvs.push(i / tubularSegments);
  18729. uvs.push(j / radialSegments);
  18730. }
  18731. } // generate indices
  18732. for (j = 1; j <= tubularSegments; j++) {
  18733. for (i = 1; i <= radialSegments; i++) {
  18734. // indices
  18735. var a = (radialSegments + 1) * (j - 1) + (i - 1);
  18736. var b = (radialSegments + 1) * j + (i - 1);
  18737. var c = (radialSegments + 1) * j + i;
  18738. var d = (radialSegments + 1) * (j - 1) + i; // faces
  18739. indices.push(a, b, d);
  18740. indices.push(b, c, d);
  18741. }
  18742. } // build geometry
  18743. this.setIndex(indices);
  18744. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  18745. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  18746. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curve
  18747. function calculatePositionOnCurve(u, p, q, radius, position) {
  18748. var cu = Math.cos(u);
  18749. var su = Math.sin(u);
  18750. var quOverP = q / p * u;
  18751. var cs = Math.cos(quOverP);
  18752. position.x = radius * (2 + cs) * 0.5 * cu;
  18753. position.y = radius * (2 + cs) * su * 0.5;
  18754. position.z = radius * Math.sin(quOverP) * 0.5;
  18755. }
  18756. }
  18757. TorusKnotBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18758. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  18759. /**
  18760. * @author oosmoxiecode
  18761. * @author mrdoob / http://mrdoob.com/
  18762. * @author Mugen87 / https://github.com/Mugen87
  18763. */
  18764. // TorusGeometry
  18765. function TorusGeometry(radius, tube, radialSegments, tubularSegments, arc) {
  18766. Geometry.call(this);
  18767. this.type = 'TorusGeometry';
  18768. this.parameters = {
  18769. radius: radius,
  18770. tube: tube,
  18771. radialSegments: radialSegments,
  18772. tubularSegments: tubularSegments,
  18773. arc: arc
  18774. };
  18775. this.fromBufferGeometry(new TorusBufferGeometry(radius, tube, radialSegments, tubularSegments, arc));
  18776. this.mergeVertices();
  18777. }
  18778. TorusGeometry.prototype = Object.create(Geometry.prototype);
  18779. TorusGeometry.prototype.constructor = TorusGeometry; // TorusBufferGeometry
  18780. function TorusBufferGeometry(radius, tube, radialSegments, tubularSegments, arc) {
  18781. BufferGeometry.call(this);
  18782. this.type = 'TorusBufferGeometry';
  18783. this.parameters = {
  18784. radius: radius,
  18785. tube: tube,
  18786. radialSegments: radialSegments,
  18787. tubularSegments: tubularSegments,
  18788. arc: arc
  18789. };
  18790. radius = radius || 1;
  18791. tube = tube || 0.4;
  18792. radialSegments = Math.floor(radialSegments) || 8;
  18793. tubularSegments = Math.floor(tubularSegments) || 6;
  18794. arc = arc || Math.PI * 2; // buffers
  18795. var indices = [];
  18796. var vertices = [];
  18797. var normals = [];
  18798. var uvs = []; // helper variables
  18799. var center = new Vector3();
  18800. var vertex = new Vector3();
  18801. var normal = new Vector3();
  18802. var j, i; // generate vertices, normals and uvs
  18803. for (j = 0; j <= radialSegments; j++) {
  18804. for (i = 0; i <= tubularSegments; i++) {
  18805. var u = i / tubularSegments * arc;
  18806. var v = j / radialSegments * Math.PI * 2; // vertex
  18807. vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
  18808. vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
  18809. vertex.z = tube * Math.sin(v);
  18810. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  18811. center.x = radius * Math.cos(u);
  18812. center.y = radius * Math.sin(u);
  18813. normal.subVectors(vertex, center).normalize();
  18814. normals.push(normal.x, normal.y, normal.z); // uv
  18815. uvs.push(i / tubularSegments);
  18816. uvs.push(j / radialSegments);
  18817. }
  18818. } // generate indices
  18819. for (j = 1; j <= radialSegments; j++) {
  18820. for (i = 1; i <= tubularSegments; i++) {
  18821. // indices
  18822. var a = (tubularSegments + 1) * j + i - 1;
  18823. var b = (tubularSegments + 1) * (j - 1) + i - 1;
  18824. var c = (tubularSegments + 1) * (j - 1) + i;
  18825. var d = (tubularSegments + 1) * j + i; // faces
  18826. indices.push(a, b, d);
  18827. indices.push(b, c, d);
  18828. }
  18829. } // build geometry
  18830. this.setIndex(indices);
  18831. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  18832. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  18833. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  18834. }
  18835. TorusBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18836. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  18837. /**
  18838. * @author Mugen87 / https://github.com/Mugen87
  18839. * Port from https://github.com/mapbox/earcut (v2.1.5)
  18840. */
  18841. var Earcut = {
  18842. triangulate: function (data, holeIndices, dim) {
  18843. dim = dim || 2;
  18844. var hasHoles = holeIndices && holeIndices.length,
  18845. outerLen = hasHoles ? holeIndices[0] * dim : data.length,
  18846. outerNode = linkedList(data, 0, outerLen, dim, true),
  18847. triangles = [];
  18848. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  18849. var minX, minY, maxX, maxY, x, y, invSize;
  18850. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  18851. if (data.length > 80 * dim) {
  18852. minX = maxX = data[0];
  18853. minY = maxY = data[1];
  18854. for (var i = dim; i < outerLen; i += dim) {
  18855. x = data[i];
  18856. y = data[i + 1];
  18857. if (x < minX) minX = x;
  18858. if (y < minY) minY = y;
  18859. if (x > maxX) maxX = x;
  18860. if (y > maxY) maxY = y;
  18861. } // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  18862. invSize = Math.max(maxX - minX, maxY - minY);
  18863. invSize = invSize !== 0 ? 1 / invSize : 0;
  18864. }
  18865. earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
  18866. return triangles;
  18867. }
  18868. }; // create a circular doubly linked list from polygon points in the specified winding order
  18869. function linkedList(data, start, end, dim, clockwise) {
  18870. var i, last;
  18871. if (clockwise === signedArea(data, start, end, dim) > 0) {
  18872. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  18873. } else {
  18874. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  18875. }
  18876. if (last && equals(last, last.next)) {
  18877. removeNode(last);
  18878. last = last.next;
  18879. }
  18880. return last;
  18881. } // eliminate colinear or duplicate points
  18882. function filterPoints(start, end) {
  18883. if (!start) return start;
  18884. if (!end) end = start;
  18885. var p = start,
  18886. again;
  18887. do {
  18888. again = false;
  18889. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  18890. removeNode(p);
  18891. p = end = p.prev;
  18892. if (p === p.next) break;
  18893. again = true;
  18894. } else {
  18895. p = p.next;
  18896. }
  18897. } while (again || p !== end);
  18898. return end;
  18899. } // main ear slicing loop which triangulates a polygon (given as a linked list)
  18900. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  18901. if (!ear) return; // interlink polygon nodes in z-order
  18902. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  18903. var stop = ear,
  18904. prev,
  18905. next; // iterate through ears, slicing them one by one
  18906. while (ear.prev !== ear.next) {
  18907. prev = ear.prev;
  18908. next = ear.next;
  18909. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  18910. // cut off the triangle
  18911. triangles.push(prev.i / dim);
  18912. triangles.push(ear.i / dim);
  18913. triangles.push(next.i / dim);
  18914. removeNode(ear); // skipping the next vertex leads to less sliver triangles
  18915. ear = next.next;
  18916. stop = next.next;
  18917. continue;
  18918. }
  18919. ear = next; // if we looped through the whole remaining polygon and can't find any more ears
  18920. if (ear === stop) {
  18921. // try filtering points and slicing again
  18922. if (!pass) {
  18923. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally
  18924. } else if (pass === 1) {
  18925. ear = cureLocalIntersections(ear, triangles, dim);
  18926. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two
  18927. } else if (pass === 2) {
  18928. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  18929. }
  18930. break;
  18931. }
  18932. }
  18933. } // check whether a polygon node forms a valid ear with adjacent nodes
  18934. function isEar(ear) {
  18935. var a = ear.prev,
  18936. b = ear,
  18937. c = ear.next;
  18938. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  18939. // now make sure we don't have other points inside the potential ear
  18940. var p = ear.next.next;
  18941. while (p !== ear.prev) {
  18942. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  18943. p = p.next;
  18944. }
  18945. return true;
  18946. }
  18947. function isEarHashed(ear, minX, minY, invSize) {
  18948. var a = ear.prev,
  18949. b = ear,
  18950. c = ear.next;
  18951. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  18952. // triangle bbox; min & max are calculated like this for speed
  18953. var minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,
  18954. minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,
  18955. maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,
  18956. maxTY = a.y > b.y ? a.y > c.y ? a.y : c.y : b.y > c.y ? b.y : c.y; // z-order range for the current triangle bbox;
  18957. var minZ = zOrder(minTX, minTY, minX, minY, invSize),
  18958. maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
  18959. var p = ear.prevZ,
  18960. n = ear.nextZ; // look for points inside the triangle in both directions
  18961. while (p && p.z >= minZ && n && n.z <= maxZ) {
  18962. if (p !== ear.prev && p !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  18963. p = p.prevZ;
  18964. if (n !== ear.prev && n !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  18965. n = n.nextZ;
  18966. } // look for remaining points in decreasing z-order
  18967. while (p && p.z >= minZ) {
  18968. if (p !== ear.prev && p !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  18969. p = p.prevZ;
  18970. } // look for remaining points in increasing z-order
  18971. while (n && n.z <= maxZ) {
  18972. if (n !== ear.prev && n !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  18973. n = n.nextZ;
  18974. }
  18975. return true;
  18976. } // go through all polygon nodes and cure small local self-intersections
  18977. function cureLocalIntersections(start, triangles, dim) {
  18978. var p = start;
  18979. do {
  18980. var a = p.prev,
  18981. b = p.next.next;
  18982. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  18983. triangles.push(a.i / dim);
  18984. triangles.push(p.i / dim);
  18985. triangles.push(b.i / dim); // remove two nodes involved
  18986. removeNode(p);
  18987. removeNode(p.next);
  18988. p = start = b;
  18989. }
  18990. p = p.next;
  18991. } while (p !== start);
  18992. return p;
  18993. } // try splitting polygon into two and triangulate them independently
  18994. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  18995. // look for a valid diagonal that divides the polygon into two
  18996. var a = start;
  18997. do {
  18998. var b = a.next.next;
  18999. while (b !== a.prev) {
  19000. if (a.i !== b.i && isValidDiagonal(a, b)) {
  19001. // split the polygon in two by the diagonal
  19002. var c = splitPolygon(a, b); // filter colinear points around the cuts
  19003. a = filterPoints(a, a.next);
  19004. c = filterPoints(c, c.next); // run earcut on each half
  19005. earcutLinked(a, triangles, dim, minX, minY, invSize);
  19006. earcutLinked(c, triangles, dim, minX, minY, invSize);
  19007. return;
  19008. }
  19009. b = b.next;
  19010. }
  19011. a = a.next;
  19012. } while (a !== start);
  19013. } // link every hole into the outer loop, producing a single-ring polygon without holes
  19014. function eliminateHoles(data, holeIndices, outerNode, dim) {
  19015. var queue = [],
  19016. i,
  19017. len,
  19018. start,
  19019. end,
  19020. list;
  19021. for (i = 0, len = holeIndices.length; i < len; i++) {
  19022. start = holeIndices[i] * dim;
  19023. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  19024. list = linkedList(data, start, end, dim, false);
  19025. if (list === list.next) list.steiner = true;
  19026. queue.push(getLeftmost(list));
  19027. }
  19028. queue.sort(compareX); // process holes from left to right
  19029. for (i = 0; i < queue.length; i++) {
  19030. eliminateHole(queue[i], outerNode);
  19031. outerNode = filterPoints(outerNode, outerNode.next);
  19032. }
  19033. return outerNode;
  19034. }
  19035. function compareX(a, b) {
  19036. return a.x - b.x;
  19037. } // find a bridge between vertices that connects hole with an outer ring and and link it
  19038. function eliminateHole(hole, outerNode) {
  19039. outerNode = findHoleBridge(hole, outerNode);
  19040. if (outerNode) {
  19041. var b = splitPolygon(outerNode, hole);
  19042. filterPoints(b, b.next);
  19043. }
  19044. } // David Eberly's algorithm for finding a bridge between hole and outer polygon
  19045. function findHoleBridge(hole, outerNode) {
  19046. var p = outerNode,
  19047. hx = hole.x,
  19048. hy = hole.y,
  19049. qx = -Infinity,
  19050. m; // find a segment intersected by a ray from the hole's leftmost point to the left;
  19051. // segment's endpoint with lesser x will be potential connection point
  19052. do {
  19053. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  19054. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  19055. if (x <= hx && x > qx) {
  19056. qx = x;
  19057. if (x === hx) {
  19058. if (hy === p.y) return p;
  19059. if (hy === p.next.y) return p.next;
  19060. }
  19061. m = p.x < p.next.x ? p : p.next;
  19062. }
  19063. }
  19064. p = p.next;
  19065. } while (p !== outerNode);
  19066. if (!m) return null;
  19067. if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint
  19068. // look for points inside the triangle of hole point, segment intersection and endpoint;
  19069. // if there are no points found, we have a valid connection;
  19070. // otherwise choose the point of the minimum angle with the ray as connection point
  19071. var stop = m,
  19072. mx = m.x,
  19073. my = m.y,
  19074. tanMin = Infinity,
  19075. tan;
  19076. p = m.next;
  19077. while (p !== stop) {
  19078. if (hx >= p.x && p.x >= mx && hx !== p.x && pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  19079. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  19080. if ((tan < tanMin || tan === tanMin && p.x > m.x) && locallyInside(p, hole)) {
  19081. m = p;
  19082. tanMin = tan;
  19083. }
  19084. }
  19085. p = p.next;
  19086. }
  19087. return m;
  19088. } // interlink polygon nodes in z-order
  19089. function indexCurve(start, minX, minY, invSize) {
  19090. var p = start;
  19091. do {
  19092. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  19093. p.prevZ = p.prev;
  19094. p.nextZ = p.next;
  19095. p = p.next;
  19096. } while (p !== start);
  19097. p.prevZ.nextZ = null;
  19098. p.prevZ = null;
  19099. sortLinked(p);
  19100. } // Simon Tatham's linked list merge sort algorithm
  19101. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  19102. function sortLinked(list) {
  19103. var i,
  19104. p,
  19105. q,
  19106. e,
  19107. tail,
  19108. numMerges,
  19109. pSize,
  19110. qSize,
  19111. inSize = 1;
  19112. do {
  19113. p = list;
  19114. list = null;
  19115. tail = null;
  19116. numMerges = 0;
  19117. while (p) {
  19118. numMerges++;
  19119. q = p;
  19120. pSize = 0;
  19121. for (i = 0; i < inSize; i++) {
  19122. pSize++;
  19123. q = q.nextZ;
  19124. if (!q) break;
  19125. }
  19126. qSize = inSize;
  19127. while (pSize > 0 || qSize > 0 && q) {
  19128. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  19129. e = p;
  19130. p = p.nextZ;
  19131. pSize--;
  19132. } else {
  19133. e = q;
  19134. q = q.nextZ;
  19135. qSize--;
  19136. }
  19137. if (tail) tail.nextZ = e;else list = e;
  19138. e.prevZ = tail;
  19139. tail = e;
  19140. }
  19141. p = q;
  19142. }
  19143. tail.nextZ = null;
  19144. inSize *= 2;
  19145. } while (numMerges > 1);
  19146. return list;
  19147. } // z-order of a point given coords and inverse of the longer side of data bbox
  19148. function zOrder(x, y, minX, minY, invSize) {
  19149. // coords are transformed into non-negative 15-bit integer range
  19150. x = 32767 * (x - minX) * invSize;
  19151. y = 32767 * (y - minY) * invSize;
  19152. x = (x | x << 8) & 0x00FF00FF;
  19153. x = (x | x << 4) & 0x0F0F0F0F;
  19154. x = (x | x << 2) & 0x33333333;
  19155. x = (x | x << 1) & 0x55555555;
  19156. y = (y | y << 8) & 0x00FF00FF;
  19157. y = (y | y << 4) & 0x0F0F0F0F;
  19158. y = (y | y << 2) & 0x33333333;
  19159. y = (y | y << 1) & 0x55555555;
  19160. return x | y << 1;
  19161. } // find the leftmost node of a polygon ring
  19162. function getLeftmost(start) {
  19163. var p = start,
  19164. leftmost = start;
  19165. do {
  19166. if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
  19167. p = p.next;
  19168. } while (p !== start);
  19169. return leftmost;
  19170. } // check if a point lies within a convex triangle
  19171. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  19172. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  19173. } // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  19174. function isValidDiagonal(a, b) {
  19175. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b);
  19176. } // signed area of a triangle
  19177. function area(p, q, r) {
  19178. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  19179. } // check if two points are equal
  19180. function equals(p1, p2) {
  19181. return p1.x === p2.x && p1.y === p2.y;
  19182. } // check if two segments intersect
  19183. function intersects(p1, q1, p2, q2) {
  19184. if (equals(p1, p2) && equals(q1, q2) || equals(p1, q2) && equals(p2, q1)) return true;
  19185. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 && area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  19186. } // check if a polygon diagonal intersects any polygon segments
  19187. function intersectsPolygon(a, b) {
  19188. var p = a;
  19189. do {
  19190. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && intersects(p, p.next, a, b)) return true;
  19191. p = p.next;
  19192. } while (p !== a);
  19193. return false;
  19194. } // check if a polygon diagonal is locally inside the polygon
  19195. function locallyInside(a, b) {
  19196. return area(a.prev, a, a.next) < 0 ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  19197. } // check if the middle point of a polygon diagonal is inside the polygon
  19198. function middleInside(a, b) {
  19199. var p = a,
  19200. inside = false,
  19201. px = (a.x + b.x) / 2,
  19202. py = (a.y + b.y) / 2;
  19203. do {
  19204. if (p.y > py !== p.next.y > py && p.next.y !== p.y && px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x) inside = !inside;
  19205. p = p.next;
  19206. } while (p !== a);
  19207. return inside;
  19208. } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  19209. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  19210. function splitPolygon(a, b) {
  19211. var a2 = new Node(a.i, a.x, a.y),
  19212. b2 = new Node(b.i, b.x, b.y),
  19213. an = a.next,
  19214. bp = b.prev;
  19215. a.next = b;
  19216. b.prev = a;
  19217. a2.next = an;
  19218. an.prev = a2;
  19219. b2.next = a2;
  19220. a2.prev = b2;
  19221. bp.next = b2;
  19222. b2.prev = bp;
  19223. return b2;
  19224. } // create a node and optionally link it with previous one (in a circular doubly linked list)
  19225. function insertNode(i, x, y, last) {
  19226. var p = new Node(i, x, y);
  19227. if (!last) {
  19228. p.prev = p;
  19229. p.next = p;
  19230. } else {
  19231. p.next = last.next;
  19232. p.prev = last;
  19233. last.next.prev = p;
  19234. last.next = p;
  19235. }
  19236. return p;
  19237. }
  19238. function removeNode(p) {
  19239. p.next.prev = p.prev;
  19240. p.prev.next = p.next;
  19241. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  19242. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  19243. }
  19244. function Node(i, x, y) {
  19245. // vertex index in coordinates array
  19246. this.i = i; // vertex coordinates
  19247. this.x = x;
  19248. this.y = y; // previous and next vertex nodes in a polygon ring
  19249. this.prev = null;
  19250. this.next = null; // z-order curve value
  19251. this.z = null; // previous and next nodes in z-order
  19252. this.prevZ = null;
  19253. this.nextZ = null; // indicates whether this is a steiner point
  19254. this.steiner = false;
  19255. }
  19256. function signedArea(data, start, end, dim) {
  19257. var sum = 0;
  19258. for (var i = start, j = end - dim; i < end; i += dim) {
  19259. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  19260. j = i;
  19261. }
  19262. return sum;
  19263. }
  19264. /**
  19265. * @author zz85 / http://www.lab4games.net/zz85/blog
  19266. */
  19267. var ShapeUtils = {
  19268. // calculate area of the contour polygon
  19269. area: function (contour) {
  19270. var n = contour.length;
  19271. var a = 0.0;
  19272. for (var p = n - 1, q = 0; q < n; p = q++) {
  19273. a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
  19274. }
  19275. return a * 0.5;
  19276. },
  19277. isClockWise: function (pts) {
  19278. return ShapeUtils.area(pts) < 0;
  19279. },
  19280. triangulateShape: function (contour, holes) {
  19281. var vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  19282. var holeIndices = []; // array of hole indices
  19283. var faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  19284. removeDupEndPts(contour);
  19285. addContour(vertices, contour); //
  19286. var holeIndex = contour.length;
  19287. holes.forEach(removeDupEndPts);
  19288. for (var i = 0; i < holes.length; i++) {
  19289. holeIndices.push(holeIndex);
  19290. holeIndex += holes[i].length;
  19291. addContour(vertices, holes[i]);
  19292. } //
  19293. var triangles = Earcut.triangulate(vertices, holeIndices); //
  19294. for (var i = 0; i < triangles.length; i += 3) {
  19295. faces.push(triangles.slice(i, i + 3));
  19296. }
  19297. return faces;
  19298. }
  19299. };
  19300. exports.ShapeUtils = ShapeUtils;
  19301. function removeDupEndPts(points) {
  19302. var l = points.length;
  19303. if (l > 2 && points[l - 1].equals(points[0])) {
  19304. points.pop();
  19305. }
  19306. }
  19307. function addContour(vertices, contour) {
  19308. for (var i = 0; i < contour.length; i++) {
  19309. vertices.push(contour[i].x);
  19310. vertices.push(contour[i].y);
  19311. }
  19312. }
  19313. /**
  19314. * @author zz85 / http://www.lab4games.net/zz85/blog
  19315. *
  19316. * Creates extruded geometry from a path shape.
  19317. *
  19318. * parameters = {
  19319. *
  19320. * curveSegments: <int>, // number of points on the curves
  19321. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  19322. * depth: <float>, // Depth to extrude the shape
  19323. *
  19324. * bevelEnabled: <bool>, // turn on bevel
  19325. * bevelThickness: <float>, // how deep into the original shape bevel goes
  19326. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  19327. * bevelOffset: <float>, // how far from shape outline does bevel start
  19328. * bevelSegments: <int>, // number of bevel layers
  19329. *
  19330. * extrudePath: <THREE.Curve> // curve to extrude shape along
  19331. *
  19332. * UVGenerator: <Object> // object that provides UV generator functions
  19333. *
  19334. * }
  19335. */
  19336. // ExtrudeGeometry
  19337. function ExtrudeGeometry(shapes, options) {
  19338. Geometry.call(this);
  19339. this.type = 'ExtrudeGeometry';
  19340. this.parameters = {
  19341. shapes: shapes,
  19342. options: options
  19343. };
  19344. this.fromBufferGeometry(new ExtrudeBufferGeometry(shapes, options));
  19345. this.mergeVertices();
  19346. }
  19347. ExtrudeGeometry.prototype = Object.create(Geometry.prototype);
  19348. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  19349. ExtrudeGeometry.prototype.toJSON = function () {
  19350. var data = Geometry.prototype.toJSON.call(this);
  19351. var shapes = this.parameters.shapes;
  19352. var options = this.parameters.options;
  19353. return toJSON(shapes, options, data);
  19354. }; // ExtrudeBufferGeometry
  19355. function ExtrudeBufferGeometry(shapes, options) {
  19356. BufferGeometry.call(this);
  19357. this.type = 'ExtrudeBufferGeometry';
  19358. this.parameters = {
  19359. shapes: shapes,
  19360. options: options
  19361. };
  19362. shapes = Array.isArray(shapes) ? shapes : [shapes];
  19363. var scope = this;
  19364. var verticesArray = [];
  19365. var uvArray = [];
  19366. for (var i = 0, l = shapes.length; i < l; i++) {
  19367. var shape = shapes[i];
  19368. addShape(shape);
  19369. } // build geometry
  19370. this.addAttribute('position', new Float32BufferAttribute(verticesArray, 3));
  19371. this.addAttribute('uv', new Float32BufferAttribute(uvArray, 2));
  19372. this.computeVertexNormals(); // functions
  19373. function addShape(shape) {
  19374. var placeholder = []; // options
  19375. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19376. var steps = options.steps !== undefined ? options.steps : 1;
  19377. var depth = options.depth !== undefined ? options.depth : 100;
  19378. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  19379. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  19380. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  19381. var bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  19382. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  19383. var extrudePath = options.extrudePath;
  19384. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; // deprecated options
  19385. if (options.amount !== undefined) {
  19386. console.warn('THREE.ExtrudeBufferGeometry: amount has been renamed to depth.');
  19387. depth = options.amount;
  19388. } //
  19389. var extrudePts,
  19390. extrudeByPath = false;
  19391. var splineTube, binormal, normal, position2;
  19392. if (extrudePath) {
  19393. extrudePts = extrudePath.getSpacedPoints(steps);
  19394. extrudeByPath = true;
  19395. bevelEnabled = false; // bevels not supported for path extrusion
  19396. // SETUP TNB variables
  19397. // TODO1 - have a .isClosed in spline?
  19398. splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  19399. binormal = new Vector3();
  19400. normal = new Vector3();
  19401. position2 = new Vector3();
  19402. } // Safeguards if bevels are not enabled
  19403. if (!bevelEnabled) {
  19404. bevelSegments = 0;
  19405. bevelThickness = 0;
  19406. bevelSize = 0;
  19407. bevelOffset = 0;
  19408. } // Variables initialization
  19409. var ahole, h, hl; // looping of holes
  19410. var shapePoints = shape.extractPoints(curveSegments);
  19411. var vertices = shapePoints.shape;
  19412. var holes = shapePoints.holes;
  19413. var reverse = !ShapeUtils.isClockWise(vertices);
  19414. if (reverse) {
  19415. vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  19416. for (h = 0, hl = holes.length; h < hl; h++) {
  19417. ahole = holes[h];
  19418. if (ShapeUtils.isClockWise(ahole)) {
  19419. holes[h] = ahole.reverse();
  19420. }
  19421. }
  19422. }
  19423. var faces = ShapeUtils.triangulateShape(vertices, holes);
  19424. /* Vertices */
  19425. var contour = vertices; // vertices has all points but contour has only points of circumference
  19426. for (h = 0, hl = holes.length; h < hl; h++) {
  19427. ahole = holes[h];
  19428. vertices = vertices.concat(ahole);
  19429. }
  19430. function scalePt2(pt, vec, size) {
  19431. if (!vec) console.error("THREE.ExtrudeGeometry: vec does not exist");
  19432. return vec.clone().multiplyScalar(size).add(pt);
  19433. }
  19434. var b,
  19435. bs,
  19436. t,
  19437. z,
  19438. vert,
  19439. vlen = vertices.length,
  19440. face,
  19441. flen = faces.length; // Find directions for point movement
  19442. function getBevelVec(inPt, inPrev, inNext) {
  19443. // computes for inPt the corresponding point inPt' on a new contour
  19444. // shifted by 1 unit (length of normalized vector) to the left
  19445. // if we walk along contour clockwise, this new contour is outside the old one
  19446. //
  19447. // inPt' is the intersection of the two lines parallel to the two
  19448. // adjacent edges of inPt at a distance of 1 unit on the left side.
  19449. var v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  19450. // good reading for geometry algorithms (here: line-line intersection)
  19451. // http://geomalgorithms.com/a05-_intersect-1.html
  19452. var v_prev_x = inPt.x - inPrev.x,
  19453. v_prev_y = inPt.y - inPrev.y;
  19454. var v_next_x = inNext.x - inPt.x,
  19455. v_next_y = inNext.y - inPt.y;
  19456. var v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; // check for collinear edges
  19457. var collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
  19458. if (Math.abs(collinear0) > Number.EPSILON) {
  19459. // not collinear
  19460. // length of vectors for normalizing
  19461. var v_prev_len = Math.sqrt(v_prev_lensq);
  19462. var v_next_len = Math.sqrt(v_next_x * v_next_x + v_next_y * v_next_y); // shift adjacent points by unit vectors to the left
  19463. var ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
  19464. var ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
  19465. var ptNextShift_x = inNext.x - v_next_y / v_next_len;
  19466. var ptNextShift_y = inNext.y + v_next_x / v_next_len; // scaling factor for v_prev to intersection point
  19467. var sf = ((ptNextShift_x - ptPrevShift_x) * v_next_y - (ptNextShift_y - ptPrevShift_y) * v_next_x) / (v_prev_x * v_next_y - v_prev_y * v_next_x); // vector from inPt to intersection point
  19468. v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
  19469. v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; // Don't normalize!, otherwise sharp corners become ugly
  19470. // but prevent crazy spikes
  19471. var v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
  19472. if (v_trans_lensq <= 2) {
  19473. return new Vector2(v_trans_x, v_trans_y);
  19474. } else {
  19475. shrink_by = Math.sqrt(v_trans_lensq / 2);
  19476. }
  19477. } else {
  19478. // handle special case of collinear edges
  19479. var direction_eq = false; // assumes: opposite
  19480. if (v_prev_x > Number.EPSILON) {
  19481. if (v_next_x > Number.EPSILON) {
  19482. direction_eq = true;
  19483. }
  19484. } else {
  19485. if (v_prev_x < -Number.EPSILON) {
  19486. if (v_next_x < -Number.EPSILON) {
  19487. direction_eq = true;
  19488. }
  19489. } else {
  19490. if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
  19491. direction_eq = true;
  19492. }
  19493. }
  19494. }
  19495. if (direction_eq) {
  19496. // console.log("Warning: lines are a straight sequence");
  19497. v_trans_x = -v_prev_y;
  19498. v_trans_y = v_prev_x;
  19499. shrink_by = Math.sqrt(v_prev_lensq);
  19500. } else {
  19501. // console.log("Warning: lines are a straight spike");
  19502. v_trans_x = v_prev_x;
  19503. v_trans_y = v_prev_y;
  19504. shrink_by = Math.sqrt(v_prev_lensq / 2);
  19505. }
  19506. }
  19507. return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
  19508. }
  19509. var contourMovements = [];
  19510. for (var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  19511. if (j === il) j = 0;
  19512. if (k === il) k = 0; // (j)---(i)---(k)
  19513. // console.log('i,j,k', i, j , k)
  19514. contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]);
  19515. }
  19516. var holesMovements = [],
  19517. oneHoleMovements,
  19518. verticesMovements = contourMovements.concat();
  19519. for (h = 0, hl = holes.length; h < hl; h++) {
  19520. ahole = holes[h];
  19521. oneHoleMovements = [];
  19522. for (i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  19523. if (j === il) j = 0;
  19524. if (k === il) k = 0; // (j)---(i)---(k)
  19525. oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]);
  19526. }
  19527. holesMovements.push(oneHoleMovements);
  19528. verticesMovements = verticesMovements.concat(oneHoleMovements);
  19529. } // Loop bevelSegments, 1 for the front, 1 for the back
  19530. for (b = 0; b < bevelSegments; b++) {
  19531. //for ( b = bevelSegments; b > 0; b -- ) {
  19532. t = b / bevelSegments;
  19533. z = bevelThickness * Math.cos(t * Math.PI / 2);
  19534. bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  19535. for (i = 0, il = contour.length; i < il; i++) {
  19536. vert = scalePt2(contour[i], contourMovements[i], bs);
  19537. v(vert.x, vert.y, -z);
  19538. } // expand holes
  19539. for (h = 0, hl = holes.length; h < hl; h++) {
  19540. ahole = holes[h];
  19541. oneHoleMovements = holesMovements[h];
  19542. for (i = 0, il = ahole.length; i < il; i++) {
  19543. vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  19544. v(vert.x, vert.y, -z);
  19545. }
  19546. }
  19547. }
  19548. bs = bevelSize + bevelOffset; // Back facing vertices
  19549. for (i = 0; i < vlen; i++) {
  19550. vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  19551. if (!extrudeByPath) {
  19552. v(vert.x, vert.y, 0);
  19553. } else {
  19554. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19555. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  19556. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  19557. position2.copy(extrudePts[0]).add(normal).add(binormal);
  19558. v(position2.x, position2.y, position2.z);
  19559. }
  19560. } // Add stepped vertices...
  19561. // Including front facing vertices
  19562. var s;
  19563. for (s = 1; s <= steps; s++) {
  19564. for (i = 0; i < vlen; i++) {
  19565. vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  19566. if (!extrudeByPath) {
  19567. v(vert.x, vert.y, depth / steps * s);
  19568. } else {
  19569. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19570. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  19571. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  19572. position2.copy(extrudePts[s]).add(normal).add(binormal);
  19573. v(position2.x, position2.y, position2.z);
  19574. }
  19575. }
  19576. } // Add bevel segments planes
  19577. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19578. for (b = bevelSegments - 1; b >= 0; b--) {
  19579. t = b / bevelSegments;
  19580. z = bevelThickness * Math.cos(t * Math.PI / 2);
  19581. bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  19582. for (i = 0, il = contour.length; i < il; i++) {
  19583. vert = scalePt2(contour[i], contourMovements[i], bs);
  19584. v(vert.x, vert.y, depth + z);
  19585. } // expand holes
  19586. for (h = 0, hl = holes.length; h < hl; h++) {
  19587. ahole = holes[h];
  19588. oneHoleMovements = holesMovements[h];
  19589. for (i = 0, il = ahole.length; i < il; i++) {
  19590. vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  19591. if (!extrudeByPath) {
  19592. v(vert.x, vert.y, depth + z);
  19593. } else {
  19594. v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z);
  19595. }
  19596. }
  19597. }
  19598. }
  19599. /* Faces */
  19600. // Top and bottom faces
  19601. buildLidFaces(); // Sides faces
  19602. buildSideFaces(); ///// Internal functions
  19603. function buildLidFaces() {
  19604. var start = verticesArray.length / 3;
  19605. if (bevelEnabled) {
  19606. var layer = 0; // steps + 1
  19607. var offset = vlen * layer; // Bottom faces
  19608. for (i = 0; i < flen; i++) {
  19609. face = faces[i];
  19610. f3(face[2] + offset, face[1] + offset, face[0] + offset);
  19611. }
  19612. layer = steps + bevelSegments * 2;
  19613. offset = vlen * layer; // Top faces
  19614. for (i = 0; i < flen; i++) {
  19615. face = faces[i];
  19616. f3(face[0] + offset, face[1] + offset, face[2] + offset);
  19617. }
  19618. } else {
  19619. // Bottom faces
  19620. for (i = 0; i < flen; i++) {
  19621. face = faces[i];
  19622. f3(face[2], face[1], face[0]);
  19623. } // Top faces
  19624. for (i = 0; i < flen; i++) {
  19625. face = faces[i];
  19626. f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps);
  19627. }
  19628. }
  19629. scope.addGroup(start, verticesArray.length / 3 - start, 0);
  19630. } // Create faces for the z-sides of the shape
  19631. function buildSideFaces() {
  19632. var start = verticesArray.length / 3;
  19633. var layeroffset = 0;
  19634. sidewalls(contour, layeroffset);
  19635. layeroffset += contour.length;
  19636. for (h = 0, hl = holes.length; h < hl; h++) {
  19637. ahole = holes[h];
  19638. sidewalls(ahole, layeroffset); //, true
  19639. layeroffset += ahole.length;
  19640. }
  19641. scope.addGroup(start, verticesArray.length / 3 - start, 1);
  19642. }
  19643. function sidewalls(contour, layeroffset) {
  19644. var j, k;
  19645. i = contour.length;
  19646. while (--i >= 0) {
  19647. j = i;
  19648. k = i - 1;
  19649. if (k < 0) k = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);
  19650. var s = 0,
  19651. sl = steps + bevelSegments * 2;
  19652. for (s = 0; s < sl; s++) {
  19653. var slen1 = vlen * s;
  19654. var slen2 = vlen * (s + 1);
  19655. var a = layeroffset + j + slen1,
  19656. b = layeroffset + k + slen1,
  19657. c = layeroffset + k + slen2,
  19658. d = layeroffset + j + slen2;
  19659. f4(a, b, c, d);
  19660. }
  19661. }
  19662. }
  19663. function v(x, y, z) {
  19664. placeholder.push(x);
  19665. placeholder.push(y);
  19666. placeholder.push(z);
  19667. }
  19668. function f3(a, b, c) {
  19669. addVertex(a);
  19670. addVertex(b);
  19671. addVertex(c);
  19672. var nextIndex = verticesArray.length / 3;
  19673. var uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  19674. addUV(uvs[0]);
  19675. addUV(uvs[1]);
  19676. addUV(uvs[2]);
  19677. }
  19678. function f4(a, b, c, d) {
  19679. addVertex(a);
  19680. addVertex(b);
  19681. addVertex(d);
  19682. addVertex(b);
  19683. addVertex(c);
  19684. addVertex(d);
  19685. var nextIndex = verticesArray.length / 3;
  19686. var uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  19687. addUV(uvs[0]);
  19688. addUV(uvs[1]);
  19689. addUV(uvs[3]);
  19690. addUV(uvs[1]);
  19691. addUV(uvs[2]);
  19692. addUV(uvs[3]);
  19693. }
  19694. function addVertex(index) {
  19695. verticesArray.push(placeholder[index * 3 + 0]);
  19696. verticesArray.push(placeholder[index * 3 + 1]);
  19697. verticesArray.push(placeholder[index * 3 + 2]);
  19698. }
  19699. function addUV(vector2) {
  19700. uvArray.push(vector2.x);
  19701. uvArray.push(vector2.y);
  19702. }
  19703. }
  19704. }
  19705. ExtrudeBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19706. ExtrudeBufferGeometry.prototype.constructor = ExtrudeBufferGeometry;
  19707. ExtrudeBufferGeometry.prototype.toJSON = function () {
  19708. var data = BufferGeometry.prototype.toJSON.call(this);
  19709. var shapes = this.parameters.shapes;
  19710. var options = this.parameters.options;
  19711. return toJSON(shapes, options, data);
  19712. }; //
  19713. var WorldUVGenerator = {
  19714. generateTopUV: function (geometry, vertices, indexA, indexB, indexC) {
  19715. var a_x = vertices[indexA * 3];
  19716. var a_y = vertices[indexA * 3 + 1];
  19717. var b_x = vertices[indexB * 3];
  19718. var b_y = vertices[indexB * 3 + 1];
  19719. var c_x = vertices[indexC * 3];
  19720. var c_y = vertices[indexC * 3 + 1];
  19721. return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
  19722. },
  19723. generateSideWallUV: function (geometry, vertices, indexA, indexB, indexC, indexD) {
  19724. var a_x = vertices[indexA * 3];
  19725. var a_y = vertices[indexA * 3 + 1];
  19726. var a_z = vertices[indexA * 3 + 2];
  19727. var b_x = vertices[indexB * 3];
  19728. var b_y = vertices[indexB * 3 + 1];
  19729. var b_z = vertices[indexB * 3 + 2];
  19730. var c_x = vertices[indexC * 3];
  19731. var c_y = vertices[indexC * 3 + 1];
  19732. var c_z = vertices[indexC * 3 + 2];
  19733. var d_x = vertices[indexD * 3];
  19734. var d_y = vertices[indexD * 3 + 1];
  19735. var d_z = vertices[indexD * 3 + 2];
  19736. if (Math.abs(a_y - b_y) < 0.01) {
  19737. return [new Vector2(a_x, 1 - a_z), new Vector2(b_x, 1 - b_z), new Vector2(c_x, 1 - c_z), new Vector2(d_x, 1 - d_z)];
  19738. } else {
  19739. return [new Vector2(a_y, 1 - a_z), new Vector2(b_y, 1 - b_z), new Vector2(c_y, 1 - c_z), new Vector2(d_y, 1 - d_z)];
  19740. }
  19741. }
  19742. };
  19743. function toJSON(shapes, options, data) {
  19744. //
  19745. data.shapes = [];
  19746. if (Array.isArray(shapes)) {
  19747. for (var i = 0, l = shapes.length; i < l; i++) {
  19748. var shape = shapes[i];
  19749. data.shapes.push(shape.uuid);
  19750. }
  19751. } else {
  19752. data.shapes.push(shapes.uuid);
  19753. } //
  19754. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  19755. return data;
  19756. }
  19757. /**
  19758. * @author zz85 / http://www.lab4games.net/zz85/blog
  19759. * @author alteredq / http://alteredqualia.com/
  19760. *
  19761. * Text = 3D Text
  19762. *
  19763. * parameters = {
  19764. * font: <THREE.Font>, // font
  19765. *
  19766. * size: <float>, // size of the text
  19767. * height: <float>, // thickness to extrude text
  19768. * curveSegments: <int>, // number of points on the curves
  19769. *
  19770. * bevelEnabled: <bool>, // turn on bevel
  19771. * bevelThickness: <float>, // how deep into text bevel goes
  19772. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  19773. * bevelOffset: <float> // how far from text outline does bevel start
  19774. * }
  19775. */
  19776. // TextGeometry
  19777. function TextGeometry(text, parameters) {
  19778. Geometry.call(this);
  19779. this.type = 'TextGeometry';
  19780. this.parameters = {
  19781. text: text,
  19782. parameters: parameters
  19783. };
  19784. this.fromBufferGeometry(new TextBufferGeometry(text, parameters));
  19785. this.mergeVertices();
  19786. }
  19787. TextGeometry.prototype = Object.create(Geometry.prototype);
  19788. TextGeometry.prototype.constructor = TextGeometry; // TextBufferGeometry
  19789. function TextBufferGeometry(text, parameters) {
  19790. parameters = parameters || {};
  19791. var font = parameters.font;
  19792. if (!(font && font.isFont)) {
  19793. console.error('THREE.TextGeometry: font parameter is not an instance of THREE.Font.');
  19794. return new Geometry();
  19795. }
  19796. var shapes = font.generateShapes(text, parameters.size); // translate parameters to ExtrudeGeometry API
  19797. parameters.depth = parameters.height !== undefined ? parameters.height : 50; // defaults
  19798. if (parameters.bevelThickness === undefined) parameters.bevelThickness = 10;
  19799. if (parameters.bevelSize === undefined) parameters.bevelSize = 8;
  19800. if (parameters.bevelEnabled === undefined) parameters.bevelEnabled = false;
  19801. ExtrudeBufferGeometry.call(this, shapes, parameters);
  19802. this.type = 'TextBufferGeometry';
  19803. }
  19804. TextBufferGeometry.prototype = Object.create(ExtrudeBufferGeometry.prototype);
  19805. TextBufferGeometry.prototype.constructor = TextBufferGeometry;
  19806. /**
  19807. * @author mrdoob / http://mrdoob.com/
  19808. * @author benaadams / https://twitter.com/ben_a_adams
  19809. * @author Mugen87 / https://github.com/Mugen87
  19810. */
  19811. // SphereGeometry
  19812. function SphereGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) {
  19813. Geometry.call(this);
  19814. this.type = 'SphereGeometry';
  19815. this.parameters = {
  19816. radius: radius,
  19817. widthSegments: widthSegments,
  19818. heightSegments: heightSegments,
  19819. phiStart: phiStart,
  19820. phiLength: phiLength,
  19821. thetaStart: thetaStart,
  19822. thetaLength: thetaLength
  19823. };
  19824. this.fromBufferGeometry(new SphereBufferGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength));
  19825. this.mergeVertices();
  19826. }
  19827. SphereGeometry.prototype = Object.create(Geometry.prototype);
  19828. SphereGeometry.prototype.constructor = SphereGeometry; // SphereBufferGeometry
  19829. function SphereBufferGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) {
  19830. BufferGeometry.call(this);
  19831. this.type = 'SphereBufferGeometry';
  19832. this.parameters = {
  19833. radius: radius,
  19834. widthSegments: widthSegments,
  19835. heightSegments: heightSegments,
  19836. phiStart: phiStart,
  19837. phiLength: phiLength,
  19838. thetaStart: thetaStart,
  19839. thetaLength: thetaLength
  19840. };
  19841. radius = radius || 1;
  19842. widthSegments = Math.max(3, Math.floor(widthSegments) || 8);
  19843. heightSegments = Math.max(2, Math.floor(heightSegments) || 6);
  19844. phiStart = phiStart !== undefined ? phiStart : 0;
  19845. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19846. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19847. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19848. var thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
  19849. var ix, iy;
  19850. var index = 0;
  19851. var grid = [];
  19852. var vertex = new Vector3();
  19853. var normal = new Vector3(); // buffers
  19854. var indices = [];
  19855. var vertices = [];
  19856. var normals = [];
  19857. var uvs = []; // generate vertices, normals and uvs
  19858. for (iy = 0; iy <= heightSegments; iy++) {
  19859. var verticesRow = [];
  19860. var v = iy / heightSegments; // special case for the poles
  19861. var uOffset = 0;
  19862. if (iy == 0 && thetaStart == 0) {
  19863. uOffset = 0.5 / widthSegments;
  19864. } else if (iy == heightSegments && thetaEnd == Math.PI) {
  19865. uOffset = -0.5 / widthSegments;
  19866. }
  19867. for (ix = 0; ix <= widthSegments; ix++) {
  19868. var u = ix / widthSegments; // vertex
  19869. vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  19870. vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
  19871. vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  19872. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19873. normal.copy(vertex).normalize();
  19874. normals.push(normal.x, normal.y, normal.z); // uv
  19875. uvs.push(u + uOffset, 1 - v);
  19876. verticesRow.push(index++);
  19877. }
  19878. grid.push(verticesRow);
  19879. } // indices
  19880. for (iy = 0; iy < heightSegments; iy++) {
  19881. for (ix = 0; ix < widthSegments; ix++) {
  19882. var a = grid[iy][ix + 1];
  19883. var b = grid[iy][ix];
  19884. var c = grid[iy + 1][ix];
  19885. var d = grid[iy + 1][ix + 1];
  19886. if (iy !== 0 || thetaStart > 0) indices.push(a, b, d);
  19887. if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
  19888. }
  19889. } // build geometry
  19890. this.setIndex(indices);
  19891. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  19892. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  19893. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19894. }
  19895. SphereBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19896. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  19897. /**
  19898. * @author Kaleb Murphy
  19899. * @author Mugen87 / https://github.com/Mugen87
  19900. */
  19901. // RingGeometry
  19902. function RingGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength) {
  19903. Geometry.call(this);
  19904. this.type = 'RingGeometry';
  19905. this.parameters = {
  19906. innerRadius: innerRadius,
  19907. outerRadius: outerRadius,
  19908. thetaSegments: thetaSegments,
  19909. phiSegments: phiSegments,
  19910. thetaStart: thetaStart,
  19911. thetaLength: thetaLength
  19912. };
  19913. this.fromBufferGeometry(new RingBufferGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength));
  19914. this.mergeVertices();
  19915. }
  19916. RingGeometry.prototype = Object.create(Geometry.prototype);
  19917. RingGeometry.prototype.constructor = RingGeometry; // RingBufferGeometry
  19918. function RingBufferGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength) {
  19919. BufferGeometry.call(this);
  19920. this.type = 'RingBufferGeometry';
  19921. this.parameters = {
  19922. innerRadius: innerRadius,
  19923. outerRadius: outerRadius,
  19924. thetaSegments: thetaSegments,
  19925. phiSegments: phiSegments,
  19926. thetaStart: thetaStart,
  19927. thetaLength: thetaLength
  19928. };
  19929. innerRadius = innerRadius || 0.5;
  19930. outerRadius = outerRadius || 1;
  19931. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19932. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19933. thetaSegments = thetaSegments !== undefined ? Math.max(3, thetaSegments) : 8;
  19934. phiSegments = phiSegments !== undefined ? Math.max(1, phiSegments) : 1; // buffers
  19935. var indices = [];
  19936. var vertices = [];
  19937. var normals = [];
  19938. var uvs = []; // some helper variables
  19939. var segment;
  19940. var radius = innerRadius;
  19941. var radiusStep = (outerRadius - innerRadius) / phiSegments;
  19942. var vertex = new Vector3();
  19943. var uv = new Vector2();
  19944. var j, i; // generate vertices, normals and uvs
  19945. for (j = 0; j <= phiSegments; j++) {
  19946. for (i = 0; i <= thetaSegments; i++) {
  19947. // values are generate from the inside of the ring to the outside
  19948. segment = thetaStart + i / thetaSegments * thetaLength; // vertex
  19949. vertex.x = radius * Math.cos(segment);
  19950. vertex.y = radius * Math.sin(segment);
  19951. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19952. normals.push(0, 0, 1); // uv
  19953. uv.x = (vertex.x / outerRadius + 1) / 2;
  19954. uv.y = (vertex.y / outerRadius + 1) / 2;
  19955. uvs.push(uv.x, uv.y);
  19956. } // increase the radius for next row of vertices
  19957. radius += radiusStep;
  19958. } // indices
  19959. for (j = 0; j < phiSegments; j++) {
  19960. var thetaSegmentLevel = j * (thetaSegments + 1);
  19961. for (i = 0; i < thetaSegments; i++) {
  19962. segment = i + thetaSegmentLevel;
  19963. var a = segment;
  19964. var b = segment + thetaSegments + 1;
  19965. var c = segment + thetaSegments + 2;
  19966. var d = segment + 1; // faces
  19967. indices.push(a, b, d);
  19968. indices.push(b, c, d);
  19969. }
  19970. } // build geometry
  19971. this.setIndex(indices);
  19972. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  19973. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  19974. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19975. }
  19976. RingBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19977. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  19978. /**
  19979. * @author zz85 / https://github.com/zz85
  19980. * @author bhouston / http://clara.io
  19981. * @author Mugen87 / https://github.com/Mugen87
  19982. */
  19983. // LatheGeometry
  19984. function LatheGeometry(points, segments, phiStart, phiLength) {
  19985. Geometry.call(this);
  19986. this.type = 'LatheGeometry';
  19987. this.parameters = {
  19988. points: points,
  19989. segments: segments,
  19990. phiStart: phiStart,
  19991. phiLength: phiLength
  19992. };
  19993. this.fromBufferGeometry(new LatheBufferGeometry(points, segments, phiStart, phiLength));
  19994. this.mergeVertices();
  19995. }
  19996. LatheGeometry.prototype = Object.create(Geometry.prototype);
  19997. LatheGeometry.prototype.constructor = LatheGeometry; // LatheBufferGeometry
  19998. function LatheBufferGeometry(points, segments, phiStart, phiLength) {
  19999. BufferGeometry.call(this);
  20000. this.type = 'LatheBufferGeometry';
  20001. this.parameters = {
  20002. points: points,
  20003. segments: segments,
  20004. phiStart: phiStart,
  20005. phiLength: phiLength
  20006. };
  20007. segments = Math.floor(segments) || 12;
  20008. phiStart = phiStart || 0;
  20009. phiLength = phiLength || Math.PI * 2; // clamp phiLength so it's in range of [ 0, 2PI ]
  20010. phiLength = _Math.clamp(phiLength, 0, Math.PI * 2); // buffers
  20011. var indices = [];
  20012. var vertices = [];
  20013. var uvs = []; // helper variables
  20014. var base;
  20015. var inverseSegments = 1.0 / segments;
  20016. var vertex = new Vector3();
  20017. var uv = new Vector2();
  20018. var i, j; // generate vertices and uvs
  20019. for (i = 0; i <= segments; i++) {
  20020. var phi = phiStart + i * inverseSegments * phiLength;
  20021. var sin = Math.sin(phi);
  20022. var cos = Math.cos(phi);
  20023. for (j = 0; j <= points.length - 1; j++) {
  20024. // vertex
  20025. vertex.x = points[j].x * sin;
  20026. vertex.y = points[j].y;
  20027. vertex.z = points[j].x * cos;
  20028. vertices.push(vertex.x, vertex.y, vertex.z); // uv
  20029. uv.x = i / segments;
  20030. uv.y = j / (points.length - 1);
  20031. uvs.push(uv.x, uv.y);
  20032. }
  20033. } // indices
  20034. for (i = 0; i < segments; i++) {
  20035. for (j = 0; j < points.length - 1; j++) {
  20036. base = j + i * points.length;
  20037. var a = base;
  20038. var b = base + points.length;
  20039. var c = base + points.length + 1;
  20040. var d = base + 1; // faces
  20041. indices.push(a, b, d);
  20042. indices.push(b, c, d);
  20043. }
  20044. } // build geometry
  20045. this.setIndex(indices);
  20046. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  20047. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2)); // generate normals
  20048. this.computeVertexNormals(); // if the geometry is closed, we need to average the normals along the seam.
  20049. // because the corresponding vertices are identical (but still have different UVs).
  20050. if (phiLength === Math.PI * 2) {
  20051. var normals = this.attributes.normal.array;
  20052. var n1 = new Vector3();
  20053. var n2 = new Vector3();
  20054. var n = new Vector3(); // this is the buffer offset for the last line of vertices
  20055. base = segments * points.length * 3;
  20056. for (i = 0, j = 0; i < points.length; i++, j += 3) {
  20057. // select the normal of the vertex in the first line
  20058. n1.x = normals[j + 0];
  20059. n1.y = normals[j + 1];
  20060. n1.z = normals[j + 2]; // select the normal of the vertex in the last line
  20061. n2.x = normals[base + j + 0];
  20062. n2.y = normals[base + j + 1];
  20063. n2.z = normals[base + j + 2]; // average normals
  20064. n.addVectors(n1, n2).normalize(); // assign the new values to both normals
  20065. normals[j + 0] = normals[base + j + 0] = n.x;
  20066. normals[j + 1] = normals[base + j + 1] = n.y;
  20067. normals[j + 2] = normals[base + j + 2] = n.z;
  20068. }
  20069. }
  20070. }
  20071. LatheBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  20072. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  20073. /**
  20074. * @author jonobr1 / http://jonobr1.com
  20075. * @author Mugen87 / https://github.com/Mugen87
  20076. */
  20077. // ShapeGeometry
  20078. function ShapeGeometry(shapes, curveSegments) {
  20079. Geometry.call(this);
  20080. this.type = 'ShapeGeometry';
  20081. if (typeof curveSegments === 'object') {
  20082. console.warn('THREE.ShapeGeometry: Options parameter has been removed.');
  20083. curveSegments = curveSegments.curveSegments;
  20084. }
  20085. this.parameters = {
  20086. shapes: shapes,
  20087. curveSegments: curveSegments
  20088. };
  20089. this.fromBufferGeometry(new ShapeBufferGeometry(shapes, curveSegments));
  20090. this.mergeVertices();
  20091. }
  20092. ShapeGeometry.prototype = Object.create(Geometry.prototype);
  20093. ShapeGeometry.prototype.constructor = ShapeGeometry;
  20094. ShapeGeometry.prototype.toJSON = function () {
  20095. var data = Geometry.prototype.toJSON.call(this);
  20096. var shapes = this.parameters.shapes;
  20097. return toJSON$1(shapes, data);
  20098. }; // ShapeBufferGeometry
  20099. function ShapeBufferGeometry(shapes, curveSegments) {
  20100. BufferGeometry.call(this);
  20101. this.type = 'ShapeBufferGeometry';
  20102. this.parameters = {
  20103. shapes: shapes,
  20104. curveSegments: curveSegments
  20105. };
  20106. curveSegments = curveSegments || 12; // buffers
  20107. var indices = [];
  20108. var vertices = [];
  20109. var normals = [];
  20110. var uvs = []; // helper variables
  20111. var groupStart = 0;
  20112. var groupCount = 0; // allow single and array values for "shapes" parameter
  20113. if (Array.isArray(shapes) === false) {
  20114. addShape(shapes);
  20115. } else {
  20116. for (var i = 0; i < shapes.length; i++) {
  20117. addShape(shapes[i]);
  20118. this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
  20119. groupStart += groupCount;
  20120. groupCount = 0;
  20121. }
  20122. } // build geometry
  20123. this.setIndex(indices);
  20124. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  20125. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  20126. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functions
  20127. function addShape(shape) {
  20128. var i, l, shapeHole;
  20129. var indexOffset = vertices.length / 3;
  20130. var points = shape.extractPoints(curveSegments);
  20131. var shapeVertices = points.shape;
  20132. var shapeHoles = points.holes; // check direction of vertices
  20133. if (ShapeUtils.isClockWise(shapeVertices) === false) {
  20134. shapeVertices = shapeVertices.reverse();
  20135. }
  20136. for (i = 0, l = shapeHoles.length; i < l; i++) {
  20137. shapeHole = shapeHoles[i];
  20138. if (ShapeUtils.isClockWise(shapeHole) === true) {
  20139. shapeHoles[i] = shapeHole.reverse();
  20140. }
  20141. }
  20142. var faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); // join vertices of inner and outer paths to a single array
  20143. for (i = 0, l = shapeHoles.length; i < l; i++) {
  20144. shapeHole = shapeHoles[i];
  20145. shapeVertices = shapeVertices.concat(shapeHole);
  20146. } // vertices, normals, uvs
  20147. for (i = 0, l = shapeVertices.length; i < l; i++) {
  20148. var vertex = shapeVertices[i];
  20149. vertices.push(vertex.x, vertex.y, 0);
  20150. normals.push(0, 0, 1);
  20151. uvs.push(vertex.x, vertex.y); // world uvs
  20152. } // incides
  20153. for (i = 0, l = faces.length; i < l; i++) {
  20154. var face = faces[i];
  20155. var a = face[0] + indexOffset;
  20156. var b = face[1] + indexOffset;
  20157. var c = face[2] + indexOffset;
  20158. indices.push(a, b, c);
  20159. groupCount += 3;
  20160. }
  20161. }
  20162. }
  20163. ShapeBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  20164. ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;
  20165. ShapeBufferGeometry.prototype.toJSON = function () {
  20166. var data = BufferGeometry.prototype.toJSON.call(this);
  20167. var shapes = this.parameters.shapes;
  20168. return toJSON$1(shapes, data);
  20169. }; //
  20170. function toJSON$1(shapes, data) {
  20171. data.shapes = [];
  20172. if (Array.isArray(shapes)) {
  20173. for (var i = 0, l = shapes.length; i < l; i++) {
  20174. var shape = shapes[i];
  20175. data.shapes.push(shape.uuid);
  20176. }
  20177. } else {
  20178. data.shapes.push(shapes.uuid);
  20179. }
  20180. return data;
  20181. }
  20182. /**
  20183. * @author WestLangley / http://github.com/WestLangley
  20184. * @author Mugen87 / https://github.com/Mugen87
  20185. */
  20186. function EdgesGeometry(geometry, thresholdAngle) {
  20187. BufferGeometry.call(this);
  20188. this.type = 'EdgesGeometry';
  20189. this.parameters = {
  20190. thresholdAngle: thresholdAngle
  20191. };
  20192. thresholdAngle = thresholdAngle !== undefined ? thresholdAngle : 1; // buffer
  20193. var vertices = []; // helper variables
  20194. var thresholdDot = Math.cos(_Math.DEG2RAD * thresholdAngle);
  20195. var edge = [0, 0],
  20196. edges = {},
  20197. edge1,
  20198. edge2;
  20199. var key,
  20200. keys = ['a', 'b', 'c']; // prepare source geometry
  20201. var geometry2;
  20202. if (geometry.isBufferGeometry) {
  20203. geometry2 = new Geometry();
  20204. geometry2.fromBufferGeometry(geometry);
  20205. } else {
  20206. geometry2 = geometry.clone();
  20207. }
  20208. geometry2.mergeVertices();
  20209. geometry2.computeFaceNormals();
  20210. var sourceVertices = geometry2.vertices;
  20211. var faces = geometry2.faces; // now create a data structure where each entry represents an edge with its adjoining faces
  20212. for (var i = 0, l = faces.length; i < l; i++) {
  20213. var face = faces[i];
  20214. for (var j = 0; j < 3; j++) {
  20215. edge1 = face[keys[j]];
  20216. edge2 = face[keys[(j + 1) % 3]];
  20217. edge[0] = Math.min(edge1, edge2);
  20218. edge[1] = Math.max(edge1, edge2);
  20219. key = edge[0] + ',' + edge[1];
  20220. if (edges[key] === undefined) {
  20221. edges[key] = {
  20222. index1: edge[0],
  20223. index2: edge[1],
  20224. face1: i,
  20225. face2: undefined
  20226. };
  20227. } else {
  20228. edges[key].face2 = i;
  20229. }
  20230. }
  20231. } // generate vertices
  20232. for (key in edges) {
  20233. var e = edges[key]; // an edge is only rendered if the angle (in degrees) between the face normals of the adjoining faces exceeds this value. default = 1 degree.
  20234. if (e.face2 === undefined || faces[e.face1].normal.dot(faces[e.face2].normal) <= thresholdDot) {
  20235. var vertex = sourceVertices[e.index1];
  20236. vertices.push(vertex.x, vertex.y, vertex.z);
  20237. vertex = sourceVertices[e.index2];
  20238. vertices.push(vertex.x, vertex.y, vertex.z);
  20239. }
  20240. } // build geometry
  20241. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  20242. }
  20243. EdgesGeometry.prototype = Object.create(BufferGeometry.prototype);
  20244. EdgesGeometry.prototype.constructor = EdgesGeometry;
  20245. /**
  20246. * @author mrdoob / http://mrdoob.com/
  20247. * @author Mugen87 / https://github.com/Mugen87
  20248. */
  20249. // CylinderGeometry
  20250. function CylinderGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  20251. Geometry.call(this);
  20252. this.type = 'CylinderGeometry';
  20253. this.parameters = {
  20254. radiusTop: radiusTop,
  20255. radiusBottom: radiusBottom,
  20256. height: height,
  20257. radialSegments: radialSegments,
  20258. heightSegments: heightSegments,
  20259. openEnded: openEnded,
  20260. thetaStart: thetaStart,
  20261. thetaLength: thetaLength
  20262. };
  20263. this.fromBufferGeometry(new CylinderBufferGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength));
  20264. this.mergeVertices();
  20265. }
  20266. CylinderGeometry.prototype = Object.create(Geometry.prototype);
  20267. CylinderGeometry.prototype.constructor = CylinderGeometry; // CylinderBufferGeometry
  20268. function CylinderBufferGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  20269. BufferGeometry.call(this);
  20270. this.type = 'CylinderBufferGeometry';
  20271. this.parameters = {
  20272. radiusTop: radiusTop,
  20273. radiusBottom: radiusBottom,
  20274. height: height,
  20275. radialSegments: radialSegments,
  20276. heightSegments: heightSegments,
  20277. openEnded: openEnded,
  20278. thetaStart: thetaStart,
  20279. thetaLength: thetaLength
  20280. };
  20281. var scope = this;
  20282. radiusTop = radiusTop !== undefined ? radiusTop : 1;
  20283. radiusBottom = radiusBottom !== undefined ? radiusBottom : 1;
  20284. height = height || 1;
  20285. radialSegments = Math.floor(radialSegments) || 8;
  20286. heightSegments = Math.floor(heightSegments) || 1;
  20287. openEnded = openEnded !== undefined ? openEnded : false;
  20288. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  20289. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; // buffers
  20290. var indices = [];
  20291. var vertices = [];
  20292. var normals = [];
  20293. var uvs = []; // helper variables
  20294. var index = 0;
  20295. var indexArray = [];
  20296. var halfHeight = height / 2;
  20297. var groupStart = 0; // generate geometry
  20298. generateTorso();
  20299. if (openEnded === false) {
  20300. if (radiusTop > 0) generateCap(true);
  20301. if (radiusBottom > 0) generateCap(false);
  20302. } // build geometry
  20303. this.setIndex(indices);
  20304. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  20305. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  20306. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20307. function generateTorso() {
  20308. var x, y;
  20309. var normal = new Vector3();
  20310. var vertex = new Vector3();
  20311. var groupCount = 0; // this will be used to calculate the normal
  20312. var slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvs
  20313. for (y = 0; y <= heightSegments; y++) {
  20314. var indexRow = [];
  20315. var v = y / heightSegments; // calculate the radius of the current row
  20316. var radius = v * (radiusBottom - radiusTop) + radiusTop;
  20317. for (x = 0; x <= radialSegments; x++) {
  20318. var u = x / radialSegments;
  20319. var theta = u * thetaLength + thetaStart;
  20320. var sinTheta = Math.sin(theta);
  20321. var cosTheta = Math.cos(theta); // vertex
  20322. vertex.x = radius * sinTheta;
  20323. vertex.y = -v * height + halfHeight;
  20324. vertex.z = radius * cosTheta;
  20325. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20326. normal.set(sinTheta, slope, cosTheta).normalize();
  20327. normals.push(normal.x, normal.y, normal.z); // uv
  20328. uvs.push(u, 1 - v); // save index of vertex in respective row
  20329. indexRow.push(index++);
  20330. } // now save vertices of the row in our index array
  20331. indexArray.push(indexRow);
  20332. } // generate indices
  20333. for (x = 0; x < radialSegments; x++) {
  20334. for (y = 0; y < heightSegments; y++) {
  20335. // we use the index array to access the correct indices
  20336. var a = indexArray[y][x];
  20337. var b = indexArray[y + 1][x];
  20338. var c = indexArray[y + 1][x + 1];
  20339. var d = indexArray[y][x + 1]; // faces
  20340. indices.push(a, b, d);
  20341. indices.push(b, c, d); // update group counter
  20342. groupCount += 6;
  20343. }
  20344. } // add a group to the geometry. this will ensure multi material support
  20345. scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groups
  20346. groupStart += groupCount;
  20347. }
  20348. function generateCap(top) {
  20349. var x, centerIndexStart, centerIndexEnd;
  20350. var uv = new Vector2();
  20351. var vertex = new Vector3();
  20352. var groupCount = 0;
  20353. var radius = top === true ? radiusTop : radiusBottom;
  20354. var sign = top === true ? 1 : -1; // save the index of the first center vertex
  20355. centerIndexStart = index; // first we generate the center vertex data of the cap.
  20356. // because the geometry needs one set of uvs per face,
  20357. // we must generate a center vertex per face/segment
  20358. for (x = 1; x <= radialSegments; x++) {
  20359. // vertex
  20360. vertices.push(0, halfHeight * sign, 0); // normal
  20361. normals.push(0, sign, 0); // uv
  20362. uvs.push(0.5, 0.5); // increase index
  20363. index++;
  20364. } // save the index of the last center vertex
  20365. centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs
  20366. for (x = 0; x <= radialSegments; x++) {
  20367. var u = x / radialSegments;
  20368. var theta = u * thetaLength + thetaStart;
  20369. var cosTheta = Math.cos(theta);
  20370. var sinTheta = Math.sin(theta); // vertex
  20371. vertex.x = radius * sinTheta;
  20372. vertex.y = halfHeight * sign;
  20373. vertex.z = radius * cosTheta;
  20374. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20375. normals.push(0, sign, 0); // uv
  20376. uv.x = cosTheta * 0.5 + 0.5;
  20377. uv.y = sinTheta * 0.5 * sign + 0.5;
  20378. uvs.push(uv.x, uv.y); // increase index
  20379. index++;
  20380. } // generate indices
  20381. for (x = 0; x < radialSegments; x++) {
  20382. var c = centerIndexStart + x;
  20383. var i = centerIndexEnd + x;
  20384. if (top === true) {
  20385. // face top
  20386. indices.push(i, i + 1, c);
  20387. } else {
  20388. // face bottom
  20389. indices.push(i + 1, i, c);
  20390. }
  20391. groupCount += 3;
  20392. } // add a group to the geometry. this will ensure multi material support
  20393. scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groups
  20394. groupStart += groupCount;
  20395. }
  20396. }
  20397. CylinderBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  20398. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  20399. /**
  20400. * @author abelnation / http://github.com/abelnation
  20401. */
  20402. // ConeGeometry
  20403. function ConeGeometry(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  20404. CylinderGeometry.call(this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  20405. this.type = 'ConeGeometry';
  20406. this.parameters = {
  20407. radius: radius,
  20408. height: height,
  20409. radialSegments: radialSegments,
  20410. heightSegments: heightSegments,
  20411. openEnded: openEnded,
  20412. thetaStart: thetaStart,
  20413. thetaLength: thetaLength
  20414. };
  20415. }
  20416. ConeGeometry.prototype = Object.create(CylinderGeometry.prototype);
  20417. ConeGeometry.prototype.constructor = ConeGeometry; // ConeBufferGeometry
  20418. function ConeBufferGeometry(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  20419. CylinderBufferGeometry.call(this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  20420. this.type = 'ConeBufferGeometry';
  20421. this.parameters = {
  20422. radius: radius,
  20423. height: height,
  20424. radialSegments: radialSegments,
  20425. heightSegments: heightSegments,
  20426. openEnded: openEnded,
  20427. thetaStart: thetaStart,
  20428. thetaLength: thetaLength
  20429. };
  20430. }
  20431. ConeBufferGeometry.prototype = Object.create(CylinderBufferGeometry.prototype);
  20432. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  20433. /**
  20434. * @author benaadams / https://twitter.com/ben_a_adams
  20435. * @author Mugen87 / https://github.com/Mugen87
  20436. * @author hughes
  20437. */
  20438. // CircleGeometry
  20439. function CircleGeometry(radius, segments, thetaStart, thetaLength) {
  20440. Geometry.call(this);
  20441. this.type = 'CircleGeometry';
  20442. this.parameters = {
  20443. radius: radius,
  20444. segments: segments,
  20445. thetaStart: thetaStart,
  20446. thetaLength: thetaLength
  20447. };
  20448. this.fromBufferGeometry(new CircleBufferGeometry(radius, segments, thetaStart, thetaLength));
  20449. this.mergeVertices();
  20450. }
  20451. CircleGeometry.prototype = Object.create(Geometry.prototype);
  20452. CircleGeometry.prototype.constructor = CircleGeometry; // CircleBufferGeometry
  20453. function CircleBufferGeometry(radius, segments, thetaStart, thetaLength) {
  20454. BufferGeometry.call(this);
  20455. this.type = 'CircleBufferGeometry';
  20456. this.parameters = {
  20457. radius: radius,
  20458. segments: segments,
  20459. thetaStart: thetaStart,
  20460. thetaLength: thetaLength
  20461. };
  20462. radius = radius || 1;
  20463. segments = segments !== undefined ? Math.max(3, segments) : 8;
  20464. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  20465. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; // buffers
  20466. var indices = [];
  20467. var vertices = [];
  20468. var normals = [];
  20469. var uvs = []; // helper variables
  20470. var i, s;
  20471. var vertex = new Vector3();
  20472. var uv = new Vector2(); // center point
  20473. vertices.push(0, 0, 0);
  20474. normals.push(0, 0, 1);
  20475. uvs.push(0.5, 0.5);
  20476. for (s = 0, i = 3; s <= segments; s++, i += 3) {
  20477. var segment = thetaStart + s / segments * thetaLength; // vertex
  20478. vertex.x = radius * Math.cos(segment);
  20479. vertex.y = radius * Math.sin(segment);
  20480. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20481. normals.push(0, 0, 1); // uvs
  20482. uv.x = (vertices[i] / radius + 1) / 2;
  20483. uv.y = (vertices[i + 1] / radius + 1) / 2;
  20484. uvs.push(uv.x, uv.y);
  20485. } // indices
  20486. for (i = 1; i <= segments; i++) {
  20487. indices.push(i, i + 1, 0);
  20488. } // build geometry
  20489. this.setIndex(indices);
  20490. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  20491. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  20492. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20493. }
  20494. CircleBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  20495. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  20496. var Geometries =
  20497. /*#__PURE__*/
  20498. Object.freeze({
  20499. WireframeGeometry: WireframeGeometry,
  20500. ParametricGeometry: ParametricGeometry,
  20501. ParametricBufferGeometry: ParametricBufferGeometry,
  20502. TetrahedronGeometry: TetrahedronGeometry,
  20503. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  20504. OctahedronGeometry: OctahedronGeometry,
  20505. OctahedronBufferGeometry: OctahedronBufferGeometry,
  20506. IcosahedronGeometry: IcosahedronGeometry,
  20507. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  20508. DodecahedronGeometry: DodecahedronGeometry,
  20509. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  20510. PolyhedronGeometry: PolyhedronGeometry,
  20511. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  20512. TubeGeometry: TubeGeometry,
  20513. TubeBufferGeometry: TubeBufferGeometry,
  20514. TorusKnotGeometry: TorusKnotGeometry,
  20515. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  20516. TorusGeometry: TorusGeometry,
  20517. TorusBufferGeometry: TorusBufferGeometry,
  20518. TextGeometry: TextGeometry,
  20519. TextBufferGeometry: TextBufferGeometry,
  20520. SphereGeometry: SphereGeometry,
  20521. SphereBufferGeometry: SphereBufferGeometry,
  20522. RingGeometry: RingGeometry,
  20523. RingBufferGeometry: RingBufferGeometry,
  20524. PlaneGeometry: PlaneGeometry,
  20525. PlaneBufferGeometry: PlaneBufferGeometry,
  20526. LatheGeometry: LatheGeometry,
  20527. LatheBufferGeometry: LatheBufferGeometry,
  20528. ShapeGeometry: ShapeGeometry,
  20529. ShapeBufferGeometry: ShapeBufferGeometry,
  20530. ExtrudeGeometry: ExtrudeGeometry,
  20531. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  20532. EdgesGeometry: EdgesGeometry,
  20533. ConeGeometry: ConeGeometry,
  20534. ConeBufferGeometry: ConeBufferGeometry,
  20535. CylinderGeometry: CylinderGeometry,
  20536. CylinderBufferGeometry: CylinderBufferGeometry,
  20537. CircleGeometry: CircleGeometry,
  20538. CircleBufferGeometry: CircleBufferGeometry,
  20539. BoxGeometry: BoxGeometry,
  20540. BoxBufferGeometry: BoxBufferGeometry
  20541. });
  20542. /**
  20543. * @author mrdoob / http://mrdoob.com/
  20544. *
  20545. * parameters = {
  20546. * color: <THREE.Color>
  20547. * }
  20548. */
  20549. function ShadowMaterial(parameters) {
  20550. Material.call(this);
  20551. this.type = 'ShadowMaterial';
  20552. this.color = new Color(0x000000);
  20553. this.transparent = true;
  20554. this.setValues(parameters);
  20555. }
  20556. ShadowMaterial.prototype = Object.create(Material.prototype);
  20557. ShadowMaterial.prototype.constructor = ShadowMaterial;
  20558. ShadowMaterial.prototype.isShadowMaterial = true;
  20559. ShadowMaterial.prototype.copy = function (source) {
  20560. Material.prototype.copy.call(this, source);
  20561. this.color.copy(source.color);
  20562. return this;
  20563. };
  20564. /**
  20565. * @author mrdoob / http://mrdoob.com/
  20566. */
  20567. function RawShaderMaterial(parameters) {
  20568. ShaderMaterial.call(this, parameters);
  20569. this.type = 'RawShaderMaterial';
  20570. }
  20571. RawShaderMaterial.prototype = Object.create(ShaderMaterial.prototype);
  20572. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  20573. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  20574. /**
  20575. * @author WestLangley / http://github.com/WestLangley
  20576. *
  20577. * parameters = {
  20578. * color: <hex>,
  20579. * roughness: <float>,
  20580. * metalness: <float>,
  20581. * opacity: <float>,
  20582. *
  20583. * map: new THREE.Texture( <Image> ),
  20584. *
  20585. * lightMap: new THREE.Texture( <Image> ),
  20586. * lightMapIntensity: <float>
  20587. *
  20588. * aoMap: new THREE.Texture( <Image> ),
  20589. * aoMapIntensity: <float>
  20590. *
  20591. * emissive: <hex>,
  20592. * emissiveIntensity: <float>
  20593. * emissiveMap: new THREE.Texture( <Image> ),
  20594. *
  20595. * bumpMap: new THREE.Texture( <Image> ),
  20596. * bumpScale: <float>,
  20597. *
  20598. * normalMap: new THREE.Texture( <Image> ),
  20599. * normalMapType: THREE.TangentSpaceNormalMap,
  20600. * normalScale: <Vector2>,
  20601. *
  20602. * displacementMap: new THREE.Texture( <Image> ),
  20603. * displacementScale: <float>,
  20604. * displacementBias: <float>,
  20605. *
  20606. * roughnessMap: new THREE.Texture( <Image> ),
  20607. *
  20608. * metalnessMap: new THREE.Texture( <Image> ),
  20609. *
  20610. * alphaMap: new THREE.Texture( <Image> ),
  20611. *
  20612. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20613. * envMapIntensity: <float>
  20614. *
  20615. * refractionRatio: <float>,
  20616. *
  20617. * wireframe: <boolean>,
  20618. * wireframeLinewidth: <float>,
  20619. *
  20620. * skinning: <bool>,
  20621. * morphTargets: <bool>,
  20622. * morphNormals: <bool>
  20623. * }
  20624. */
  20625. function MeshStandardMaterial(parameters) {
  20626. Material.call(this);
  20627. this.defines = {
  20628. 'STANDARD': ''
  20629. };
  20630. this.type = 'MeshStandardMaterial';
  20631. this.color = new Color(0xffffff); // diffuse
  20632. this.roughness = 0.5;
  20633. this.metalness = 0.5;
  20634. this.map = null;
  20635. this.lightMap = null;
  20636. this.lightMapIntensity = 1.0;
  20637. this.aoMap = null;
  20638. this.aoMapIntensity = 1.0;
  20639. this.emissive = new Color(0x000000);
  20640. this.emissiveIntensity = 1.0;
  20641. this.emissiveMap = null;
  20642. this.bumpMap = null;
  20643. this.bumpScale = 1;
  20644. this.normalMap = null;
  20645. this.normalMapType = TangentSpaceNormalMap;
  20646. this.normalScale = new Vector2(1, 1);
  20647. this.displacementMap = null;
  20648. this.displacementScale = 1;
  20649. this.displacementBias = 0;
  20650. this.roughnessMap = null;
  20651. this.metalnessMap = null;
  20652. this.alphaMap = null;
  20653. this.envMap = null;
  20654. this.envMapIntensity = 1.0;
  20655. this.refractionRatio = 0.98;
  20656. this.wireframe = false;
  20657. this.wireframeLinewidth = 1;
  20658. this.wireframeLinecap = 'round';
  20659. this.wireframeLinejoin = 'round';
  20660. this.skinning = false;
  20661. this.morphTargets = false;
  20662. this.morphNormals = false;
  20663. this.setValues(parameters);
  20664. }
  20665. MeshStandardMaterial.prototype = Object.create(Material.prototype);
  20666. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  20667. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  20668. MeshStandardMaterial.prototype.copy = function (source) {
  20669. Material.prototype.copy.call(this, source);
  20670. this.defines = {
  20671. 'STANDARD': ''
  20672. };
  20673. this.color.copy(source.color);
  20674. this.roughness = source.roughness;
  20675. this.metalness = source.metalness;
  20676. this.map = source.map;
  20677. this.lightMap = source.lightMap;
  20678. this.lightMapIntensity = source.lightMapIntensity;
  20679. this.aoMap = source.aoMap;
  20680. this.aoMapIntensity = source.aoMapIntensity;
  20681. this.emissive.copy(source.emissive);
  20682. this.emissiveMap = source.emissiveMap;
  20683. this.emissiveIntensity = source.emissiveIntensity;
  20684. this.bumpMap = source.bumpMap;
  20685. this.bumpScale = source.bumpScale;
  20686. this.normalMap = source.normalMap;
  20687. this.normalMapType = source.normalMapType;
  20688. this.normalScale.copy(source.normalScale);
  20689. this.displacementMap = source.displacementMap;
  20690. this.displacementScale = source.displacementScale;
  20691. this.displacementBias = source.displacementBias;
  20692. this.roughnessMap = source.roughnessMap;
  20693. this.metalnessMap = source.metalnessMap;
  20694. this.alphaMap = source.alphaMap;
  20695. this.envMap = source.envMap;
  20696. this.envMapIntensity = source.envMapIntensity;
  20697. this.refractionRatio = source.refractionRatio;
  20698. this.wireframe = source.wireframe;
  20699. this.wireframeLinewidth = source.wireframeLinewidth;
  20700. this.wireframeLinecap = source.wireframeLinecap;
  20701. this.wireframeLinejoin = source.wireframeLinejoin;
  20702. this.skinning = source.skinning;
  20703. this.morphTargets = source.morphTargets;
  20704. this.morphNormals = source.morphNormals;
  20705. return this;
  20706. };
  20707. /**
  20708. * @author WestLangley / http://github.com/WestLangley
  20709. *
  20710. * parameters = {
  20711. * reflectivity: <float>
  20712. * clearcoat: <float>
  20713. * clearcoatRoughness: <float>
  20714. *
  20715. * sheen: <Color>
  20716. *
  20717. * clearcoatNormalScale: <Vector2>,
  20718. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  20719. * }
  20720. */
  20721. function MeshPhysicalMaterial(parameters) {
  20722. MeshStandardMaterial.call(this);
  20723. this.defines = {
  20724. 'STANDARD': '',
  20725. 'PHYSICAL': ''
  20726. };
  20727. this.type = 'MeshPhysicalMaterial';
  20728. this.reflectivity = 0.5; // maps to F0 = 0.04
  20729. this.clearcoat = 0.0;
  20730. this.clearcoatRoughness = 0.0;
  20731. this.sheen = null; // null will disable sheen bsdf
  20732. this.clearcoatNormalScale = new Vector2(1, 1);
  20733. this.clearcoatNormalMap = null;
  20734. this.transparency = 0.0;
  20735. this.setValues(parameters);
  20736. }
  20737. MeshPhysicalMaterial.prototype = Object.create(MeshStandardMaterial.prototype);
  20738. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  20739. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  20740. MeshPhysicalMaterial.prototype.copy = function (source) {
  20741. MeshStandardMaterial.prototype.copy.call(this, source);
  20742. this.defines = {
  20743. 'STANDARD': '',
  20744. 'PHYSICAL': ''
  20745. };
  20746. this.reflectivity = source.reflectivity;
  20747. this.clearcoat = source.clearcoat;
  20748. this.clearcoatRoughness = source.clearcoatRoughness;
  20749. if (source.sheen) this.sheen = (this.sheen || new Color()).copy(source.sheen);else this.sheen = null;
  20750. this.clearcoatNormalMap = source.clearcoatNormalMap;
  20751. this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
  20752. this.transparency = source.transparency;
  20753. return this;
  20754. };
  20755. /**
  20756. * @author mrdoob / http://mrdoob.com/
  20757. * @author alteredq / http://alteredqualia.com/
  20758. *
  20759. * parameters = {
  20760. * color: <hex>,
  20761. * specular: <hex>,
  20762. * shininess: <float>,
  20763. * opacity: <float>,
  20764. *
  20765. * map: new THREE.Texture( <Image> ),
  20766. *
  20767. * lightMap: new THREE.Texture( <Image> ),
  20768. * lightMapIntensity: <float>
  20769. *
  20770. * aoMap: new THREE.Texture( <Image> ),
  20771. * aoMapIntensity: <float>
  20772. *
  20773. * emissive: <hex>,
  20774. * emissiveIntensity: <float>
  20775. * emissiveMap: new THREE.Texture( <Image> ),
  20776. *
  20777. * bumpMap: new THREE.Texture( <Image> ),
  20778. * bumpScale: <float>,
  20779. *
  20780. * normalMap: new THREE.Texture( <Image> ),
  20781. * normalMapType: THREE.TangentSpaceNormalMap,
  20782. * normalScale: <Vector2>,
  20783. *
  20784. * displacementMap: new THREE.Texture( <Image> ),
  20785. * displacementScale: <float>,
  20786. * displacementBias: <float>,
  20787. *
  20788. * specularMap: new THREE.Texture( <Image> ),
  20789. *
  20790. * alphaMap: new THREE.Texture( <Image> ),
  20791. *
  20792. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20793. * combine: THREE.Multiply,
  20794. * reflectivity: <float>,
  20795. * refractionRatio: <float>,
  20796. *
  20797. * wireframe: <boolean>,
  20798. * wireframeLinewidth: <float>,
  20799. *
  20800. * skinning: <bool>,
  20801. * morphTargets: <bool>,
  20802. * morphNormals: <bool>
  20803. * }
  20804. */
  20805. function MeshPhongMaterial(parameters) {
  20806. Material.call(this);
  20807. this.type = 'MeshPhongMaterial';
  20808. this.color = new Color(0xffffff); // diffuse
  20809. this.specular = new Color(0x111111);
  20810. this.shininess = 30;
  20811. this.map = null;
  20812. this.lightMap = null;
  20813. this.lightMapIntensity = 1.0;
  20814. this.aoMap = null;
  20815. this.aoMapIntensity = 1.0;
  20816. this.emissive = new Color(0x000000);
  20817. this.emissiveIntensity = 1.0;
  20818. this.emissiveMap = null;
  20819. this.bumpMap = null;
  20820. this.bumpScale = 1;
  20821. this.normalMap = null;
  20822. this.normalMapType = TangentSpaceNormalMap;
  20823. this.normalScale = new Vector2(1, 1);
  20824. this.displacementMap = null;
  20825. this.displacementScale = 1;
  20826. this.displacementBias = 0;
  20827. this.specularMap = null;
  20828. this.alphaMap = null;
  20829. this.envMap = null;
  20830. this.combine = MultiplyOperation;
  20831. this.reflectivity = 1;
  20832. this.refractionRatio = 0.98;
  20833. this.wireframe = false;
  20834. this.wireframeLinewidth = 1;
  20835. this.wireframeLinecap = 'round';
  20836. this.wireframeLinejoin = 'round';
  20837. this.skinning = false;
  20838. this.morphTargets = false;
  20839. this.morphNormals = false;
  20840. this.setValues(parameters);
  20841. }
  20842. MeshPhongMaterial.prototype = Object.create(Material.prototype);
  20843. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  20844. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  20845. MeshPhongMaterial.prototype.copy = function (source) {
  20846. Material.prototype.copy.call(this, source);
  20847. this.color.copy(source.color);
  20848. this.specular.copy(source.specular);
  20849. this.shininess = source.shininess;
  20850. this.map = source.map;
  20851. this.lightMap = source.lightMap;
  20852. this.lightMapIntensity = source.lightMapIntensity;
  20853. this.aoMap = source.aoMap;
  20854. this.aoMapIntensity = source.aoMapIntensity;
  20855. this.emissive.copy(source.emissive);
  20856. this.emissiveMap = source.emissiveMap;
  20857. this.emissiveIntensity = source.emissiveIntensity;
  20858. this.bumpMap = source.bumpMap;
  20859. this.bumpScale = source.bumpScale;
  20860. this.normalMap = source.normalMap;
  20861. this.normalMapType = source.normalMapType;
  20862. this.normalScale.copy(source.normalScale);
  20863. this.displacementMap = source.displacementMap;
  20864. this.displacementScale = source.displacementScale;
  20865. this.displacementBias = source.displacementBias;
  20866. this.specularMap = source.specularMap;
  20867. this.alphaMap = source.alphaMap;
  20868. this.envMap = source.envMap;
  20869. this.combine = source.combine;
  20870. this.reflectivity = source.reflectivity;
  20871. this.refractionRatio = source.refractionRatio;
  20872. this.wireframe = source.wireframe;
  20873. this.wireframeLinewidth = source.wireframeLinewidth;
  20874. this.wireframeLinecap = source.wireframeLinecap;
  20875. this.wireframeLinejoin = source.wireframeLinejoin;
  20876. this.skinning = source.skinning;
  20877. this.morphTargets = source.morphTargets;
  20878. this.morphNormals = source.morphNormals;
  20879. return this;
  20880. };
  20881. /**
  20882. * @author takahirox / http://github.com/takahirox
  20883. *
  20884. * parameters = {
  20885. * gradientMap: new THREE.Texture( <Image> )
  20886. * }
  20887. */
  20888. function MeshToonMaterial(parameters) {
  20889. MeshPhongMaterial.call(this);
  20890. this.defines = {
  20891. 'TOON': ''
  20892. };
  20893. this.type = 'MeshToonMaterial';
  20894. this.gradientMap = null;
  20895. this.setValues(parameters);
  20896. }
  20897. MeshToonMaterial.prototype = Object.create(MeshPhongMaterial.prototype);
  20898. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  20899. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  20900. MeshToonMaterial.prototype.copy = function (source) {
  20901. MeshPhongMaterial.prototype.copy.call(this, source);
  20902. this.gradientMap = source.gradientMap;
  20903. return this;
  20904. };
  20905. /**
  20906. * @author mrdoob / http://mrdoob.com/
  20907. * @author WestLangley / http://github.com/WestLangley
  20908. *
  20909. * parameters = {
  20910. * opacity: <float>,
  20911. *
  20912. * bumpMap: new THREE.Texture( <Image> ),
  20913. * bumpScale: <float>,
  20914. *
  20915. * normalMap: new THREE.Texture( <Image> ),
  20916. * normalMapType: THREE.TangentSpaceNormalMap,
  20917. * normalScale: <Vector2>,
  20918. *
  20919. * displacementMap: new THREE.Texture( <Image> ),
  20920. * displacementScale: <float>,
  20921. * displacementBias: <float>,
  20922. *
  20923. * wireframe: <boolean>,
  20924. * wireframeLinewidth: <float>
  20925. *
  20926. * skinning: <bool>,
  20927. * morphTargets: <bool>,
  20928. * morphNormals: <bool>
  20929. * }
  20930. */
  20931. function MeshNormalMaterial(parameters) {
  20932. Material.call(this);
  20933. this.type = 'MeshNormalMaterial';
  20934. this.bumpMap = null;
  20935. this.bumpScale = 1;
  20936. this.normalMap = null;
  20937. this.normalMapType = TangentSpaceNormalMap;
  20938. this.normalScale = new Vector2(1, 1);
  20939. this.displacementMap = null;
  20940. this.displacementScale = 1;
  20941. this.displacementBias = 0;
  20942. this.wireframe = false;
  20943. this.wireframeLinewidth = 1;
  20944. this.fog = false;
  20945. this.skinning = false;
  20946. this.morphTargets = false;
  20947. this.morphNormals = false;
  20948. this.setValues(parameters);
  20949. }
  20950. MeshNormalMaterial.prototype = Object.create(Material.prototype);
  20951. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  20952. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  20953. MeshNormalMaterial.prototype.copy = function (source) {
  20954. Material.prototype.copy.call(this, source);
  20955. this.bumpMap = source.bumpMap;
  20956. this.bumpScale = source.bumpScale;
  20957. this.normalMap = source.normalMap;
  20958. this.normalMapType = source.normalMapType;
  20959. this.normalScale.copy(source.normalScale);
  20960. this.displacementMap = source.displacementMap;
  20961. this.displacementScale = source.displacementScale;
  20962. this.displacementBias = source.displacementBias;
  20963. this.wireframe = source.wireframe;
  20964. this.wireframeLinewidth = source.wireframeLinewidth;
  20965. this.skinning = source.skinning;
  20966. this.morphTargets = source.morphTargets;
  20967. this.morphNormals = source.morphNormals;
  20968. return this;
  20969. };
  20970. /**
  20971. * @author mrdoob / http://mrdoob.com/
  20972. * @author alteredq / http://alteredqualia.com/
  20973. *
  20974. * parameters = {
  20975. * color: <hex>,
  20976. * opacity: <float>,
  20977. *
  20978. * map: new THREE.Texture( <Image> ),
  20979. *
  20980. * lightMap: new THREE.Texture( <Image> ),
  20981. * lightMapIntensity: <float>
  20982. *
  20983. * aoMap: new THREE.Texture( <Image> ),
  20984. * aoMapIntensity: <float>
  20985. *
  20986. * emissive: <hex>,
  20987. * emissiveIntensity: <float>
  20988. * emissiveMap: new THREE.Texture( <Image> ),
  20989. *
  20990. * specularMap: new THREE.Texture( <Image> ),
  20991. *
  20992. * alphaMap: new THREE.Texture( <Image> ),
  20993. *
  20994. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20995. * combine: THREE.Multiply,
  20996. * reflectivity: <float>,
  20997. * refractionRatio: <float>,
  20998. *
  20999. * wireframe: <boolean>,
  21000. * wireframeLinewidth: <float>,
  21001. *
  21002. * skinning: <bool>,
  21003. * morphTargets: <bool>,
  21004. * morphNormals: <bool>
  21005. * }
  21006. */
  21007. function MeshLambertMaterial(parameters) {
  21008. Material.call(this);
  21009. this.type = 'MeshLambertMaterial';
  21010. this.color = new Color(0xffffff); // diffuse
  21011. this.map = null;
  21012. this.lightMap = null;
  21013. this.lightMapIntensity = 1.0;
  21014. this.aoMap = null;
  21015. this.aoMapIntensity = 1.0;
  21016. this.emissive = new Color(0x000000);
  21017. this.emissiveIntensity = 1.0;
  21018. this.emissiveMap = null;
  21019. this.specularMap = null;
  21020. this.alphaMap = null;
  21021. this.envMap = null;
  21022. this.combine = MultiplyOperation;
  21023. this.reflectivity = 1;
  21024. this.refractionRatio = 0.98;
  21025. this.wireframe = false;
  21026. this.wireframeLinewidth = 1;
  21027. this.wireframeLinecap = 'round';
  21028. this.wireframeLinejoin = 'round';
  21029. this.skinning = false;
  21030. this.morphTargets = false;
  21031. this.morphNormals = false;
  21032. this.setValues(parameters);
  21033. }
  21034. MeshLambertMaterial.prototype = Object.create(Material.prototype);
  21035. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  21036. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  21037. MeshLambertMaterial.prototype.copy = function (source) {
  21038. Material.prototype.copy.call(this, source);
  21039. this.color.copy(source.color);
  21040. this.map = source.map;
  21041. this.lightMap = source.lightMap;
  21042. this.lightMapIntensity = source.lightMapIntensity;
  21043. this.aoMap = source.aoMap;
  21044. this.aoMapIntensity = source.aoMapIntensity;
  21045. this.emissive.copy(source.emissive);
  21046. this.emissiveMap = source.emissiveMap;
  21047. this.emissiveIntensity = source.emissiveIntensity;
  21048. this.specularMap = source.specularMap;
  21049. this.alphaMap = source.alphaMap;
  21050. this.envMap = source.envMap;
  21051. this.combine = source.combine;
  21052. this.reflectivity = source.reflectivity;
  21053. this.refractionRatio = source.refractionRatio;
  21054. this.wireframe = source.wireframe;
  21055. this.wireframeLinewidth = source.wireframeLinewidth;
  21056. this.wireframeLinecap = source.wireframeLinecap;
  21057. this.wireframeLinejoin = source.wireframeLinejoin;
  21058. this.skinning = source.skinning;
  21059. this.morphTargets = source.morphTargets;
  21060. this.morphNormals = source.morphNormals;
  21061. return this;
  21062. };
  21063. /**
  21064. * @author WestLangley / http://github.com/WestLangley
  21065. *
  21066. * parameters = {
  21067. * color: <hex>,
  21068. * opacity: <float>,
  21069. *
  21070. * matcap: new THREE.Texture( <Image> ),
  21071. *
  21072. * map: new THREE.Texture( <Image> ),
  21073. *
  21074. * bumpMap: new THREE.Texture( <Image> ),
  21075. * bumpScale: <float>,
  21076. *
  21077. * normalMap: new THREE.Texture( <Image> ),
  21078. * normalMapType: THREE.TangentSpaceNormalMap,
  21079. * normalScale: <Vector2>,
  21080. *
  21081. * displacementMap: new THREE.Texture( <Image> ),
  21082. * displacementScale: <float>,
  21083. * displacementBias: <float>,
  21084. *
  21085. * alphaMap: new THREE.Texture( <Image> ),
  21086. *
  21087. * skinning: <bool>,
  21088. * morphTargets: <bool>,
  21089. * morphNormals: <bool>
  21090. * }
  21091. */
  21092. function MeshMatcapMaterial(parameters) {
  21093. Material.call(this);
  21094. this.defines = {
  21095. 'MATCAP': ''
  21096. };
  21097. this.type = 'MeshMatcapMaterial';
  21098. this.color = new Color(0xffffff); // diffuse
  21099. this.matcap = null;
  21100. this.map = null;
  21101. this.bumpMap = null;
  21102. this.bumpScale = 1;
  21103. this.normalMap = null;
  21104. this.normalMapType = TangentSpaceNormalMap;
  21105. this.normalScale = new Vector2(1, 1);
  21106. this.displacementMap = null;
  21107. this.displacementScale = 1;
  21108. this.displacementBias = 0;
  21109. this.alphaMap = null;
  21110. this.skinning = false;
  21111. this.morphTargets = false;
  21112. this.morphNormals = false;
  21113. this.setValues(parameters);
  21114. }
  21115. MeshMatcapMaterial.prototype = Object.create(Material.prototype);
  21116. MeshMatcapMaterial.prototype.constructor = MeshMatcapMaterial;
  21117. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  21118. MeshMatcapMaterial.prototype.copy = function (source) {
  21119. Material.prototype.copy.call(this, source);
  21120. this.defines = {
  21121. 'MATCAP': ''
  21122. };
  21123. this.color.copy(source.color);
  21124. this.matcap = source.matcap;
  21125. this.map = source.map;
  21126. this.bumpMap = source.bumpMap;
  21127. this.bumpScale = source.bumpScale;
  21128. this.normalMap = source.normalMap;
  21129. this.normalMapType = source.normalMapType;
  21130. this.normalScale.copy(source.normalScale);
  21131. this.displacementMap = source.displacementMap;
  21132. this.displacementScale = source.displacementScale;
  21133. this.displacementBias = source.displacementBias;
  21134. this.alphaMap = source.alphaMap;
  21135. this.skinning = source.skinning;
  21136. this.morphTargets = source.morphTargets;
  21137. this.morphNormals = source.morphNormals;
  21138. return this;
  21139. };
  21140. /**
  21141. * @author alteredq / http://alteredqualia.com/
  21142. *
  21143. * parameters = {
  21144. * color: <hex>,
  21145. * opacity: <float>,
  21146. *
  21147. * linewidth: <float>,
  21148. *
  21149. * scale: <float>,
  21150. * dashSize: <float>,
  21151. * gapSize: <float>
  21152. * }
  21153. */
  21154. function LineDashedMaterial(parameters) {
  21155. LineBasicMaterial.call(this);
  21156. this.type = 'LineDashedMaterial';
  21157. this.scale = 1;
  21158. this.dashSize = 3;
  21159. this.gapSize = 1;
  21160. this.setValues(parameters);
  21161. }
  21162. LineDashedMaterial.prototype = Object.create(LineBasicMaterial.prototype);
  21163. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  21164. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  21165. LineDashedMaterial.prototype.copy = function (source) {
  21166. LineBasicMaterial.prototype.copy.call(this, source);
  21167. this.scale = source.scale;
  21168. this.dashSize = source.dashSize;
  21169. this.gapSize = source.gapSize;
  21170. return this;
  21171. };
  21172. var Materials =
  21173. /*#__PURE__*/
  21174. Object.freeze({
  21175. ShadowMaterial: ShadowMaterial,
  21176. SpriteMaterial: SpriteMaterial,
  21177. RawShaderMaterial: RawShaderMaterial,
  21178. ShaderMaterial: ShaderMaterial,
  21179. PointsMaterial: PointsMaterial,
  21180. MeshPhysicalMaterial: MeshPhysicalMaterial,
  21181. MeshStandardMaterial: MeshStandardMaterial,
  21182. MeshPhongMaterial: MeshPhongMaterial,
  21183. MeshToonMaterial: MeshToonMaterial,
  21184. MeshNormalMaterial: MeshNormalMaterial,
  21185. MeshLambertMaterial: MeshLambertMaterial,
  21186. MeshDepthMaterial: MeshDepthMaterial,
  21187. MeshDistanceMaterial: MeshDistanceMaterial,
  21188. MeshBasicMaterial: MeshBasicMaterial,
  21189. MeshMatcapMaterial: MeshMatcapMaterial,
  21190. LineDashedMaterial: LineDashedMaterial,
  21191. LineBasicMaterial: LineBasicMaterial,
  21192. Material: Material
  21193. });
  21194. /**
  21195. * @author tschw
  21196. * @author Ben Houston / http://clara.io/
  21197. * @author David Sarno / http://lighthaus.us/
  21198. */
  21199. var AnimationUtils = {
  21200. // same as Array.prototype.slice, but also works on typed arrays
  21201. arraySlice: function (array, from, to) {
  21202. if (AnimationUtils.isTypedArray(array)) {
  21203. // in ios9 array.subarray(from, undefined) will return empty array
  21204. // but array.subarray(from) or array.subarray(from, len) is correct
  21205. return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
  21206. }
  21207. return array.slice(from, to);
  21208. },
  21209. // converts an array to a specific type
  21210. convertArray: function (array, type, forceClone) {
  21211. if (!array || // let 'undefined' and 'null' pass
  21212. !forceClone && array.constructor === type) return array;
  21213. if (typeof type.BYTES_PER_ELEMENT === 'number') {
  21214. return new type(array); // create typed array
  21215. }
  21216. return Array.prototype.slice.call(array); // create Array
  21217. },
  21218. isTypedArray: function (object) {
  21219. return ArrayBuffer.isView(object) && !(object instanceof DataView);
  21220. },
  21221. // returns an array by which times and values can be sorted
  21222. getKeyframeOrder: function (times) {
  21223. function compareTime(i, j) {
  21224. return times[i] - times[j];
  21225. }
  21226. var n = times.length;
  21227. var result = new Array(n);
  21228. for (var i = 0; i !== n; ++i) result[i] = i;
  21229. result.sort(compareTime);
  21230. return result;
  21231. },
  21232. // uses the array previously returned by 'getKeyframeOrder' to sort data
  21233. sortedArray: function (values, stride, order) {
  21234. var nValues = values.length;
  21235. var result = new values.constructor(nValues);
  21236. for (var i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
  21237. var srcOffset = order[i] * stride;
  21238. for (var j = 0; j !== stride; ++j) {
  21239. result[dstOffset++] = values[srcOffset + j];
  21240. }
  21241. }
  21242. return result;
  21243. },
  21244. // function for parsing AOS keyframe formats
  21245. flattenJSON: function (jsonKeys, times, values, valuePropertyName) {
  21246. var i = 1,
  21247. key = jsonKeys[0];
  21248. while (key !== undefined && key[valuePropertyName] === undefined) {
  21249. key = jsonKeys[i++];
  21250. }
  21251. if (key === undefined) return; // no data
  21252. var value = key[valuePropertyName];
  21253. if (value === undefined) return; // no data
  21254. if (Array.isArray(value)) {
  21255. do {
  21256. value = key[valuePropertyName];
  21257. if (value !== undefined) {
  21258. times.push(key.time);
  21259. values.push.apply(values, value); // push all elements
  21260. }
  21261. key = jsonKeys[i++];
  21262. } while (key !== undefined);
  21263. } else if (value.toArray !== undefined) {
  21264. // ...assume THREE.Math-ish
  21265. do {
  21266. value = key[valuePropertyName];
  21267. if (value !== undefined) {
  21268. times.push(key.time);
  21269. value.toArray(values, values.length);
  21270. }
  21271. key = jsonKeys[i++];
  21272. } while (key !== undefined);
  21273. } else {
  21274. // otherwise push as-is
  21275. do {
  21276. value = key[valuePropertyName];
  21277. if (value !== undefined) {
  21278. times.push(key.time);
  21279. values.push(value);
  21280. }
  21281. key = jsonKeys[i++];
  21282. } while (key !== undefined);
  21283. }
  21284. }
  21285. };
  21286. /**
  21287. * Abstract base class of interpolants over parametric samples.
  21288. *
  21289. * The parameter domain is one dimensional, typically the time or a path
  21290. * along a curve defined by the data.
  21291. *
  21292. * The sample values can have any dimensionality and derived classes may
  21293. * apply special interpretations to the data.
  21294. *
  21295. * This class provides the interval seek in a Template Method, deferring
  21296. * the actual interpolation to derived classes.
  21297. *
  21298. * Time complexity is O(1) for linear access crossing at most two points
  21299. * and O(log N) for random access, where N is the number of positions.
  21300. *
  21301. * References:
  21302. *
  21303. * http://www.oodesign.com/template-method-pattern.html
  21304. *
  21305. * @author tschw
  21306. */
  21307. exports.AnimationUtils = AnimationUtils;
  21308. function Interpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21309. this.parameterPositions = parameterPositions;
  21310. this._cachedIndex = 0;
  21311. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
  21312. this.sampleValues = sampleValues;
  21313. this.valueSize = sampleSize;
  21314. }
  21315. Object.assign(Interpolant.prototype, {
  21316. evaluate: function (t) {
  21317. var pp = this.parameterPositions,
  21318. i1 = this._cachedIndex,
  21319. t1 = pp[i1],
  21320. t0 = pp[i1 - 1];
  21321. validate_interval: {
  21322. seek: {
  21323. var right;
  21324. linear_scan: {
  21325. //- See http://jsperf.com/comparison-to-undefined/3
  21326. //- slower code:
  21327. //-
  21328. //- if ( t >= t1 || t1 === undefined ) {
  21329. forward_scan: if (!(t < t1)) {
  21330. for (var giveUpAt = i1 + 2;;) {
  21331. if (t1 === undefined) {
  21332. if (t < t0) break forward_scan; // after end
  21333. i1 = pp.length;
  21334. this._cachedIndex = i1;
  21335. return this.afterEnd_(i1 - 1, t, t0);
  21336. }
  21337. if (i1 === giveUpAt) break; // this loop
  21338. t0 = t1;
  21339. t1 = pp[++i1];
  21340. if (t < t1) {
  21341. // we have arrived at the sought interval
  21342. break seek;
  21343. }
  21344. } // prepare binary search on the right side of the index
  21345. right = pp.length;
  21346. break linear_scan;
  21347. } //- slower code:
  21348. //- if ( t < t0 || t0 === undefined ) {
  21349. if (!(t >= t0)) {
  21350. // looping?
  21351. var t1global = pp[1];
  21352. if (t < t1global) {
  21353. i1 = 2; // + 1, using the scan for the details
  21354. t0 = t1global;
  21355. } // linear reverse scan
  21356. for (var giveUpAt = i1 - 2;;) {
  21357. if (t0 === undefined) {
  21358. // before start
  21359. this._cachedIndex = 0;
  21360. return this.beforeStart_(0, t, t1);
  21361. }
  21362. if (i1 === giveUpAt) break; // this loop
  21363. t1 = t0;
  21364. t0 = pp[--i1 - 1];
  21365. if (t >= t0) {
  21366. // we have arrived at the sought interval
  21367. break seek;
  21368. }
  21369. } // prepare binary search on the left side of the index
  21370. right = i1;
  21371. i1 = 0;
  21372. break linear_scan;
  21373. } // the interval is valid
  21374. break validate_interval;
  21375. } // linear scan
  21376. // binary search
  21377. while (i1 < right) {
  21378. var mid = i1 + right >>> 1;
  21379. if (t < pp[mid]) {
  21380. right = mid;
  21381. } else {
  21382. i1 = mid + 1;
  21383. }
  21384. }
  21385. t1 = pp[i1];
  21386. t0 = pp[i1 - 1]; // check boundary cases, again
  21387. if (t0 === undefined) {
  21388. this._cachedIndex = 0;
  21389. return this.beforeStart_(0, t, t1);
  21390. }
  21391. if (t1 === undefined) {
  21392. i1 = pp.length;
  21393. this._cachedIndex = i1;
  21394. return this.afterEnd_(i1 - 1, t0, t);
  21395. }
  21396. } // seek
  21397. this._cachedIndex = i1;
  21398. this.intervalChanged_(i1, t0, t1);
  21399. } // validate_interval
  21400. return this.interpolate_(i1, t0, t, t1);
  21401. },
  21402. settings: null,
  21403. // optional, subclass-specific settings structure
  21404. // Note: The indirection allows central control of many interpolants.
  21405. // --- Protected interface
  21406. DefaultSettings_: {},
  21407. getSettings_: function () {
  21408. return this.settings || this.DefaultSettings_;
  21409. },
  21410. copySampleValue_: function (index) {
  21411. // copies a sample value to the result buffer
  21412. var result = this.resultBuffer,
  21413. values = this.sampleValues,
  21414. stride = this.valueSize,
  21415. offset = index * stride;
  21416. for (var i = 0; i !== stride; ++i) {
  21417. result[i] = values[offset + i];
  21418. }
  21419. return result;
  21420. },
  21421. // Template methods for derived classes:
  21422. interpolate_: function ()
  21423. /* i1, t0, t, t1 */
  21424. {
  21425. throw new Error('call to abstract method'); // implementations shall return this.resultBuffer
  21426. },
  21427. intervalChanged_: function ()
  21428. /* i1, t0, t1 */
  21429. {// empty
  21430. }
  21431. }); //!\ DECLARE ALIAS AFTER assign prototype !
  21432. Object.assign(Interpolant.prototype, {
  21433. //( 0, t, t0 ), returns this.resultBuffer
  21434. beforeStart_: Interpolant.prototype.copySampleValue_,
  21435. //( N-1, tN-1, t ), returns this.resultBuffer
  21436. afterEnd_: Interpolant.prototype.copySampleValue_
  21437. });
  21438. /**
  21439. * Fast and simple cubic spline interpolant.
  21440. *
  21441. * It was derived from a Hermitian construction setting the first derivative
  21442. * at each sample position to the linear slope between neighboring positions
  21443. * over their parameter interval.
  21444. *
  21445. * @author tschw
  21446. */
  21447. function CubicInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21448. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  21449. this._weightPrev = -0;
  21450. this._offsetPrev = -0;
  21451. this._weightNext = -0;
  21452. this._offsetNext = -0;
  21453. }
  21454. CubicInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  21455. constructor: CubicInterpolant,
  21456. DefaultSettings_: {
  21457. endingStart: ZeroCurvatureEnding,
  21458. endingEnd: ZeroCurvatureEnding
  21459. },
  21460. intervalChanged_: function (i1, t0, t1) {
  21461. var pp = this.parameterPositions,
  21462. iPrev = i1 - 2,
  21463. iNext = i1 + 1,
  21464. tPrev = pp[iPrev],
  21465. tNext = pp[iNext];
  21466. if (tPrev === undefined) {
  21467. switch (this.getSettings_().endingStart) {
  21468. case ZeroSlopeEnding:
  21469. // f'(t0) = 0
  21470. iPrev = i1;
  21471. tPrev = 2 * t0 - t1;
  21472. break;
  21473. case WrapAroundEnding:
  21474. // use the other end of the curve
  21475. iPrev = pp.length - 2;
  21476. tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
  21477. break;
  21478. default:
  21479. // ZeroCurvatureEnding
  21480. // f''(t0) = 0 a.k.a. Natural Spline
  21481. iPrev = i1;
  21482. tPrev = t1;
  21483. }
  21484. }
  21485. if (tNext === undefined) {
  21486. switch (this.getSettings_().endingEnd) {
  21487. case ZeroSlopeEnding:
  21488. // f'(tN) = 0
  21489. iNext = i1;
  21490. tNext = 2 * t1 - t0;
  21491. break;
  21492. case WrapAroundEnding:
  21493. // use the other end of the curve
  21494. iNext = 1;
  21495. tNext = t1 + pp[1] - pp[0];
  21496. break;
  21497. default:
  21498. // ZeroCurvatureEnding
  21499. // f''(tN) = 0, a.k.a. Natural Spline
  21500. iNext = i1 - 1;
  21501. tNext = t0;
  21502. }
  21503. }
  21504. var halfDt = (t1 - t0) * 0.5,
  21505. stride = this.valueSize;
  21506. this._weightPrev = halfDt / (t0 - tPrev);
  21507. this._weightNext = halfDt / (tNext - t1);
  21508. this._offsetPrev = iPrev * stride;
  21509. this._offsetNext = iNext * stride;
  21510. },
  21511. interpolate_: function (i1, t0, t, t1) {
  21512. var result = this.resultBuffer,
  21513. values = this.sampleValues,
  21514. stride = this.valueSize,
  21515. o1 = i1 * stride,
  21516. o0 = o1 - stride,
  21517. oP = this._offsetPrev,
  21518. oN = this._offsetNext,
  21519. wP = this._weightPrev,
  21520. wN = this._weightNext,
  21521. p = (t - t0) / (t1 - t0),
  21522. pp = p * p,
  21523. ppp = pp * p; // evaluate polynomials
  21524. var sP = -wP * ppp + 2 * wP * pp - wP * p;
  21525. var s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
  21526. var s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
  21527. var sN = wN * ppp - wN * pp; // combine data linearly
  21528. for (var i = 0; i !== stride; ++i) {
  21529. result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
  21530. }
  21531. return result;
  21532. }
  21533. });
  21534. /**
  21535. * @author tschw
  21536. */
  21537. function LinearInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21538. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  21539. }
  21540. LinearInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  21541. constructor: LinearInterpolant,
  21542. interpolate_: function (i1, t0, t, t1) {
  21543. var result = this.resultBuffer,
  21544. values = this.sampleValues,
  21545. stride = this.valueSize,
  21546. offset1 = i1 * stride,
  21547. offset0 = offset1 - stride,
  21548. weight1 = (t - t0) / (t1 - t0),
  21549. weight0 = 1 - weight1;
  21550. for (var i = 0; i !== stride; ++i) {
  21551. result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
  21552. }
  21553. return result;
  21554. }
  21555. });
  21556. /**
  21557. *
  21558. * Interpolant that evaluates to the sample value at the position preceeding
  21559. * the parameter.
  21560. *
  21561. * @author tschw
  21562. */
  21563. function DiscreteInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21564. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  21565. }
  21566. DiscreteInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  21567. constructor: DiscreteInterpolant,
  21568. interpolate_: function (i1
  21569. /*, t0, t, t1 */
  21570. ) {
  21571. return this.copySampleValue_(i1 - 1);
  21572. }
  21573. });
  21574. /**
  21575. *
  21576. * A timed sequence of keyframes for a specific property.
  21577. *
  21578. *
  21579. * @author Ben Houston / http://clara.io/
  21580. * @author David Sarno / http://lighthaus.us/
  21581. * @author tschw
  21582. */
  21583. function KeyframeTrack(name, times, values, interpolation) {
  21584. if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
  21585. if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
  21586. this.name = name;
  21587. this.times = AnimationUtils.convertArray(times, this.TimeBufferType);
  21588. this.values = AnimationUtils.convertArray(values, this.ValueBufferType);
  21589. this.setInterpolation(interpolation || this.DefaultInterpolation);
  21590. } // Static methods
  21591. Object.assign(KeyframeTrack, {
  21592. // Serialization (in static context, because of constructor invocation
  21593. // and automatic invocation of .toJSON):
  21594. toJSON: function (track) {
  21595. var trackType = track.constructor;
  21596. var json; // derived classes can define a static toJSON method
  21597. if (trackType.toJSON !== undefined) {
  21598. json = trackType.toJSON(track);
  21599. } else {
  21600. // by default, we assume the data can be serialized as-is
  21601. json = {
  21602. 'name': track.name,
  21603. 'times': AnimationUtils.convertArray(track.times, Array),
  21604. 'values': AnimationUtils.convertArray(track.values, Array)
  21605. };
  21606. var interpolation = track.getInterpolation();
  21607. if (interpolation !== track.DefaultInterpolation) {
  21608. json.interpolation = interpolation;
  21609. }
  21610. }
  21611. json.type = track.ValueTypeName; // mandatory
  21612. return json;
  21613. }
  21614. });
  21615. Object.assign(KeyframeTrack.prototype, {
  21616. constructor: KeyframeTrack,
  21617. TimeBufferType: Float32Array,
  21618. ValueBufferType: Float32Array,
  21619. DefaultInterpolation: InterpolateLinear,
  21620. InterpolantFactoryMethodDiscrete: function (result) {
  21621. return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  21622. },
  21623. InterpolantFactoryMethodLinear: function (result) {
  21624. return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  21625. },
  21626. InterpolantFactoryMethodSmooth: function (result) {
  21627. return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  21628. },
  21629. setInterpolation: function (interpolation) {
  21630. var factoryMethod;
  21631. switch (interpolation) {
  21632. case InterpolateDiscrete:
  21633. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  21634. break;
  21635. case InterpolateLinear:
  21636. factoryMethod = this.InterpolantFactoryMethodLinear;
  21637. break;
  21638. case InterpolateSmooth:
  21639. factoryMethod = this.InterpolantFactoryMethodSmooth;
  21640. break;
  21641. }
  21642. if (factoryMethod === undefined) {
  21643. var message = "unsupported interpolation for " + this.ValueTypeName + " keyframe track named " + this.name;
  21644. if (this.createInterpolant === undefined) {
  21645. // fall back to default, unless the default itself is messed up
  21646. if (interpolation !== this.DefaultInterpolation) {
  21647. this.setInterpolation(this.DefaultInterpolation);
  21648. } else {
  21649. throw new Error(message); // fatal, in this case
  21650. }
  21651. }
  21652. console.warn('THREE.KeyframeTrack:', message);
  21653. return this;
  21654. }
  21655. this.createInterpolant = factoryMethod;
  21656. return this;
  21657. },
  21658. getInterpolation: function () {
  21659. switch (this.createInterpolant) {
  21660. case this.InterpolantFactoryMethodDiscrete:
  21661. return InterpolateDiscrete;
  21662. case this.InterpolantFactoryMethodLinear:
  21663. return InterpolateLinear;
  21664. case this.InterpolantFactoryMethodSmooth:
  21665. return InterpolateSmooth;
  21666. }
  21667. },
  21668. getValueSize: function () {
  21669. return this.values.length / this.times.length;
  21670. },
  21671. // move all keyframes either forwards or backwards in time
  21672. shift: function (timeOffset) {
  21673. if (timeOffset !== 0.0) {
  21674. var times = this.times;
  21675. for (var i = 0, n = times.length; i !== n; ++i) {
  21676. times[i] += timeOffset;
  21677. }
  21678. }
  21679. return this;
  21680. },
  21681. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  21682. scale: function (timeScale) {
  21683. if (timeScale !== 1.0) {
  21684. var times = this.times;
  21685. for (var i = 0, n = times.length; i !== n; ++i) {
  21686. times[i] *= timeScale;
  21687. }
  21688. }
  21689. return this;
  21690. },
  21691. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  21692. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  21693. trim: function (startTime, endTime) {
  21694. var times = this.times,
  21695. nKeys = times.length,
  21696. from = 0,
  21697. to = nKeys - 1;
  21698. while (from !== nKeys && times[from] < startTime) {
  21699. ++from;
  21700. }
  21701. while (to !== -1 && times[to] > endTime) {
  21702. --to;
  21703. }
  21704. ++to; // inclusive -> exclusive bound
  21705. if (from !== 0 || to !== nKeys) {
  21706. // empty tracks are forbidden, so keep at least one keyframe
  21707. if (from >= to) to = Math.max(to, 1), from = to - 1;
  21708. var stride = this.getValueSize();
  21709. this.times = AnimationUtils.arraySlice(times, from, to);
  21710. this.values = AnimationUtils.arraySlice(this.values, from * stride, to * stride);
  21711. }
  21712. return this;
  21713. },
  21714. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  21715. validate: function () {
  21716. var valid = true;
  21717. var valueSize = this.getValueSize();
  21718. if (valueSize - Math.floor(valueSize) !== 0) {
  21719. console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
  21720. valid = false;
  21721. }
  21722. var times = this.times,
  21723. values = this.values,
  21724. nKeys = times.length;
  21725. if (nKeys === 0) {
  21726. console.error('THREE.KeyframeTrack: Track is empty.', this);
  21727. valid = false;
  21728. }
  21729. var prevTime = null;
  21730. for (var i = 0; i !== nKeys; i++) {
  21731. var currTime = times[i];
  21732. if (typeof currTime === 'number' && isNaN(currTime)) {
  21733. console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
  21734. valid = false;
  21735. break;
  21736. }
  21737. if (prevTime !== null && prevTime > currTime) {
  21738. console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
  21739. valid = false;
  21740. break;
  21741. }
  21742. prevTime = currTime;
  21743. }
  21744. if (values !== undefined) {
  21745. if (AnimationUtils.isTypedArray(values)) {
  21746. for (var i = 0, n = values.length; i !== n; ++i) {
  21747. var value = values[i];
  21748. if (isNaN(value)) {
  21749. console.error('THREE.KeyframeTrack: Value is not a valid number.', this, i, value);
  21750. valid = false;
  21751. break;
  21752. }
  21753. }
  21754. }
  21755. }
  21756. return valid;
  21757. },
  21758. // removes equivalent sequential keys as common in morph target sequences
  21759. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  21760. optimize: function () {
  21761. var times = this.times,
  21762. values = this.values,
  21763. stride = this.getValueSize(),
  21764. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  21765. writeIndex = 1,
  21766. lastIndex = times.length - 1;
  21767. for (var i = 1; i < lastIndex; ++i) {
  21768. var keep = false;
  21769. var time = times[i];
  21770. var timeNext = times[i + 1]; // remove adjacent keyframes scheduled at the same time
  21771. if (time !== timeNext && (i !== 1 || time !== time[0])) {
  21772. if (!smoothInterpolation) {
  21773. // remove unnecessary keyframes same as their neighbors
  21774. var offset = i * stride,
  21775. offsetP = offset - stride,
  21776. offsetN = offset + stride;
  21777. for (var j = 0; j !== stride; ++j) {
  21778. var value = values[offset + j];
  21779. if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
  21780. keep = true;
  21781. break;
  21782. }
  21783. }
  21784. } else {
  21785. keep = true;
  21786. }
  21787. } // in-place compaction
  21788. if (keep) {
  21789. if (i !== writeIndex) {
  21790. times[writeIndex] = times[i];
  21791. var readOffset = i * stride,
  21792. writeOffset = writeIndex * stride;
  21793. for (var j = 0; j !== stride; ++j) {
  21794. values[writeOffset + j] = values[readOffset + j];
  21795. }
  21796. }
  21797. ++writeIndex;
  21798. }
  21799. } // flush last keyframe (compaction looks ahead)
  21800. if (lastIndex > 0) {
  21801. times[writeIndex] = times[lastIndex];
  21802. for (var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++j) {
  21803. values[writeOffset + j] = values[readOffset + j];
  21804. }
  21805. ++writeIndex;
  21806. }
  21807. if (writeIndex !== times.length) {
  21808. this.times = AnimationUtils.arraySlice(times, 0, writeIndex);
  21809. this.values = AnimationUtils.arraySlice(values, 0, writeIndex * stride);
  21810. }
  21811. return this;
  21812. },
  21813. clone: function () {
  21814. var times = AnimationUtils.arraySlice(this.times, 0);
  21815. var values = AnimationUtils.arraySlice(this.values, 0);
  21816. var TypedKeyframeTrack = this.constructor;
  21817. var track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.
  21818. track.createInterpolant = this.createInterpolant;
  21819. return track;
  21820. }
  21821. });
  21822. /**
  21823. *
  21824. * A Track of Boolean keyframe values.
  21825. *
  21826. *
  21827. * @author Ben Houston / http://clara.io/
  21828. * @author David Sarno / http://lighthaus.us/
  21829. * @author tschw
  21830. */
  21831. function BooleanKeyframeTrack(name, times, values) {
  21832. KeyframeTrack.call(this, name, times, values);
  21833. }
  21834. BooleanKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21835. constructor: BooleanKeyframeTrack,
  21836. ValueTypeName: 'bool',
  21837. ValueBufferType: Array,
  21838. DefaultInterpolation: InterpolateDiscrete,
  21839. InterpolantFactoryMethodLinear: undefined,
  21840. InterpolantFactoryMethodSmooth: undefined // Note: Actually this track could have a optimized / compressed
  21841. // representation of a single value and a custom interpolant that
  21842. // computes "firstValue ^ isOdd( index )".
  21843. });
  21844. /**
  21845. *
  21846. * A Track of keyframe values that represent color.
  21847. *
  21848. *
  21849. * @author Ben Houston / http://clara.io/
  21850. * @author David Sarno / http://lighthaus.us/
  21851. * @author tschw
  21852. */
  21853. function ColorKeyframeTrack(name, times, values, interpolation) {
  21854. KeyframeTrack.call(this, name, times, values, interpolation);
  21855. }
  21856. ColorKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21857. constructor: ColorKeyframeTrack,
  21858. ValueTypeName: 'color' // ValueBufferType is inherited
  21859. // DefaultInterpolation is inherited
  21860. // Note: Very basic implementation and nothing special yet.
  21861. // However, this is the place for color space parameterization.
  21862. });
  21863. /**
  21864. *
  21865. * A Track of numeric keyframe values.
  21866. *
  21867. * @author Ben Houston / http://clara.io/
  21868. * @author David Sarno / http://lighthaus.us/
  21869. * @author tschw
  21870. */
  21871. function NumberKeyframeTrack(name, times, values, interpolation) {
  21872. KeyframeTrack.call(this, name, times, values, interpolation);
  21873. }
  21874. NumberKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21875. constructor: NumberKeyframeTrack,
  21876. ValueTypeName: 'number' // ValueBufferType is inherited
  21877. // DefaultInterpolation is inherited
  21878. });
  21879. /**
  21880. * Spherical linear unit quaternion interpolant.
  21881. *
  21882. * @author tschw
  21883. */
  21884. function QuaternionLinearInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21885. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  21886. }
  21887. QuaternionLinearInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  21888. constructor: QuaternionLinearInterpolant,
  21889. interpolate_: function (i1, t0, t, t1) {
  21890. var result = this.resultBuffer,
  21891. values = this.sampleValues,
  21892. stride = this.valueSize,
  21893. offset = i1 * stride,
  21894. alpha = (t - t0) / (t1 - t0);
  21895. for (var end = offset + stride; offset !== end; offset += 4) {
  21896. Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
  21897. }
  21898. return result;
  21899. }
  21900. });
  21901. /**
  21902. *
  21903. * A Track of quaternion keyframe values.
  21904. *
  21905. * @author Ben Houston / http://clara.io/
  21906. * @author David Sarno / http://lighthaus.us/
  21907. * @author tschw
  21908. */
  21909. function QuaternionKeyframeTrack(name, times, values, interpolation) {
  21910. KeyframeTrack.call(this, name, times, values, interpolation);
  21911. }
  21912. QuaternionKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21913. constructor: QuaternionKeyframeTrack,
  21914. ValueTypeName: 'quaternion',
  21915. // ValueBufferType is inherited
  21916. DefaultInterpolation: InterpolateLinear,
  21917. InterpolantFactoryMethodLinear: function (result) {
  21918. return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  21919. },
  21920. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  21921. });
  21922. /**
  21923. *
  21924. * A Track that interpolates Strings
  21925. *
  21926. *
  21927. * @author Ben Houston / http://clara.io/
  21928. * @author David Sarno / http://lighthaus.us/
  21929. * @author tschw
  21930. */
  21931. function StringKeyframeTrack(name, times, values, interpolation) {
  21932. KeyframeTrack.call(this, name, times, values, interpolation);
  21933. }
  21934. StringKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21935. constructor: StringKeyframeTrack,
  21936. ValueTypeName: 'string',
  21937. ValueBufferType: Array,
  21938. DefaultInterpolation: InterpolateDiscrete,
  21939. InterpolantFactoryMethodLinear: undefined,
  21940. InterpolantFactoryMethodSmooth: undefined
  21941. });
  21942. /**
  21943. *
  21944. * A Track of vectored keyframe values.
  21945. *
  21946. *
  21947. * @author Ben Houston / http://clara.io/
  21948. * @author David Sarno / http://lighthaus.us/
  21949. * @author tschw
  21950. */
  21951. function VectorKeyframeTrack(name, times, values, interpolation) {
  21952. KeyframeTrack.call(this, name, times, values, interpolation);
  21953. }
  21954. VectorKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21955. constructor: VectorKeyframeTrack,
  21956. ValueTypeName: 'vector' // ValueBufferType is inherited
  21957. // DefaultInterpolation is inherited
  21958. });
  21959. /**
  21960. *
  21961. * Reusable set of Tracks that represent an animation.
  21962. *
  21963. * @author Ben Houston / http://clara.io/
  21964. * @author David Sarno / http://lighthaus.us/
  21965. */
  21966. function AnimationClip(name, duration, tracks) {
  21967. this.name = name;
  21968. this.tracks = tracks;
  21969. this.duration = duration !== undefined ? duration : -1;
  21970. this.uuid = _Math.generateUUID(); // this means it should figure out its duration by scanning the tracks
  21971. if (this.duration < 0) {
  21972. this.resetDuration();
  21973. }
  21974. }
  21975. function getTrackTypeForValueTypeName(typeName) {
  21976. switch (typeName.toLowerCase()) {
  21977. case 'scalar':
  21978. case 'double':
  21979. case 'float':
  21980. case 'number':
  21981. case 'integer':
  21982. return NumberKeyframeTrack;
  21983. case 'vector':
  21984. case 'vector2':
  21985. case 'vector3':
  21986. case 'vector4':
  21987. return VectorKeyframeTrack;
  21988. case 'color':
  21989. return ColorKeyframeTrack;
  21990. case 'quaternion':
  21991. return QuaternionKeyframeTrack;
  21992. case 'bool':
  21993. case 'boolean':
  21994. return BooleanKeyframeTrack;
  21995. case 'string':
  21996. return StringKeyframeTrack;
  21997. }
  21998. throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
  21999. }
  22000. function parseKeyframeTrack(json) {
  22001. if (json.type === undefined) {
  22002. throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
  22003. }
  22004. var trackType = getTrackTypeForValueTypeName(json.type);
  22005. if (json.times === undefined) {
  22006. var times = [],
  22007. values = [];
  22008. AnimationUtils.flattenJSON(json.keys, times, values, 'value');
  22009. json.times = times;
  22010. json.values = values;
  22011. } // derived classes can define a static parse method
  22012. if (trackType.parse !== undefined) {
  22013. return trackType.parse(json);
  22014. } else {
  22015. // by default, we assume a constructor compatible with the base
  22016. return new trackType(json.name, json.times, json.values, json.interpolation);
  22017. }
  22018. }
  22019. Object.assign(AnimationClip, {
  22020. parse: function (json) {
  22021. var tracks = [],
  22022. jsonTracks = json.tracks,
  22023. frameTime = 1.0 / (json.fps || 1.0);
  22024. for (var i = 0, n = jsonTracks.length; i !== n; ++i) {
  22025. tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
  22026. }
  22027. return new AnimationClip(json.name, json.duration, tracks);
  22028. },
  22029. toJSON: function (clip) {
  22030. var tracks = [],
  22031. clipTracks = clip.tracks;
  22032. var json = {
  22033. 'name': clip.name,
  22034. 'duration': clip.duration,
  22035. 'tracks': tracks,
  22036. 'uuid': clip.uuid
  22037. };
  22038. for (var i = 0, n = clipTracks.length; i !== n; ++i) {
  22039. tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
  22040. }
  22041. return json;
  22042. },
  22043. CreateFromMorphTargetSequence: function (name, morphTargetSequence, fps, noLoop) {
  22044. var numMorphTargets = morphTargetSequence.length;
  22045. var tracks = [];
  22046. for (var i = 0; i < numMorphTargets; i++) {
  22047. var times = [];
  22048. var values = [];
  22049. times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
  22050. values.push(0, 1, 0);
  22051. var order = AnimationUtils.getKeyframeOrder(times);
  22052. times = AnimationUtils.sortedArray(times, 1, order);
  22053. values = AnimationUtils.sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as the
  22054. // last frame as well for perfect loop.
  22055. if (!noLoop && times[0] === 0) {
  22056. times.push(numMorphTargets);
  22057. values.push(values[0]);
  22058. }
  22059. tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
  22060. }
  22061. return new AnimationClip(name, -1, tracks);
  22062. },
  22063. findByName: function (objectOrClipArray, name) {
  22064. var clipArray = objectOrClipArray;
  22065. if (!Array.isArray(objectOrClipArray)) {
  22066. var o = objectOrClipArray;
  22067. clipArray = o.geometry && o.geometry.animations || o.animations;
  22068. }
  22069. for (var i = 0; i < clipArray.length; i++) {
  22070. if (clipArray[i].name === name) {
  22071. return clipArray[i];
  22072. }
  22073. }
  22074. return null;
  22075. },
  22076. CreateClipsFromMorphTargetSequences: function (morphTargets, fps, noLoop) {
  22077. var animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences
  22078. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  22079. var pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based
  22080. // patterns like Walk_001, Walk_002, Run_001, Run_002
  22081. for (var i = 0, il = morphTargets.length; i < il; i++) {
  22082. var morphTarget = morphTargets[i];
  22083. var parts = morphTarget.name.match(pattern);
  22084. if (parts && parts.length > 1) {
  22085. var name = parts[1];
  22086. var animationMorphTargets = animationToMorphTargets[name];
  22087. if (!animationMorphTargets) {
  22088. animationToMorphTargets[name] = animationMorphTargets = [];
  22089. }
  22090. animationMorphTargets.push(morphTarget);
  22091. }
  22092. }
  22093. var clips = [];
  22094. for (var name in animationToMorphTargets) {
  22095. clips.push(AnimationClip.CreateFromMorphTargetSequence(name, animationToMorphTargets[name], fps, noLoop));
  22096. }
  22097. return clips;
  22098. },
  22099. // parse the animation.hierarchy format
  22100. parseAnimation: function (animation, bones) {
  22101. if (!animation) {
  22102. console.error('THREE.AnimationClip: No animation in JSONLoader data.');
  22103. return null;
  22104. }
  22105. var addNonemptyTrack = function (trackType, trackName, animationKeys, propertyName, destTracks) {
  22106. // only return track if there are actually keys.
  22107. if (animationKeys.length !== 0) {
  22108. var times = [];
  22109. var values = [];
  22110. AnimationUtils.flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check again
  22111. if (times.length !== 0) {
  22112. destTracks.push(new trackType(trackName, times, values));
  22113. }
  22114. }
  22115. };
  22116. var tracks = [];
  22117. var clipName = animation.name || 'default'; // automatic length determination in AnimationClip.
  22118. var duration = animation.length || -1;
  22119. var fps = animation.fps || 30;
  22120. var hierarchyTracks = animation.hierarchy || [];
  22121. for (var h = 0; h < hierarchyTracks.length; h++) {
  22122. var animationKeys = hierarchyTracks[h].keys; // skip empty tracks
  22123. if (!animationKeys || animationKeys.length === 0) continue; // process morph targets
  22124. if (animationKeys[0].morphTargets) {
  22125. // figure out all morph targets used in this track
  22126. var morphTargetNames = {};
  22127. for (var k = 0; k < animationKeys.length; k++) {
  22128. if (animationKeys[k].morphTargets) {
  22129. for (var m = 0; m < animationKeys[k].morphTargets.length; m++) {
  22130. morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
  22131. }
  22132. }
  22133. } // create a track for each morph target with all zero
  22134. // morphTargetInfluences except for the keys in which
  22135. // the morphTarget is named.
  22136. for (var morphTargetName in morphTargetNames) {
  22137. var times = [];
  22138. var values = [];
  22139. for (var m = 0; m !== animationKeys[k].morphTargets.length; ++m) {
  22140. var animationKey = animationKeys[k];
  22141. times.push(animationKey.time);
  22142. values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
  22143. }
  22144. tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
  22145. }
  22146. duration = morphTargetNames.length * (fps || 1.0);
  22147. } else {
  22148. // ...assume skeletal animation
  22149. var boneName = '.bones[' + bones[h].name + ']';
  22150. addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
  22151. addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
  22152. addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
  22153. }
  22154. }
  22155. if (tracks.length === 0) {
  22156. return null;
  22157. }
  22158. var clip = new AnimationClip(clipName, duration, tracks);
  22159. return clip;
  22160. }
  22161. });
  22162. Object.assign(AnimationClip.prototype, {
  22163. resetDuration: function () {
  22164. var tracks = this.tracks,
  22165. duration = 0;
  22166. for (var i = 0, n = tracks.length; i !== n; ++i) {
  22167. var track = this.tracks[i];
  22168. duration = Math.max(duration, track.times[track.times.length - 1]);
  22169. }
  22170. this.duration = duration;
  22171. return this;
  22172. },
  22173. trim: function () {
  22174. for (var i = 0; i < this.tracks.length; i++) {
  22175. this.tracks[i].trim(0, this.duration);
  22176. }
  22177. return this;
  22178. },
  22179. validate: function () {
  22180. var valid = true;
  22181. for (var i = 0; i < this.tracks.length; i++) {
  22182. valid = valid && this.tracks[i].validate();
  22183. }
  22184. return valid;
  22185. },
  22186. optimize: function () {
  22187. for (var i = 0; i < this.tracks.length; i++) {
  22188. this.tracks[i].optimize();
  22189. }
  22190. return this;
  22191. },
  22192. clone: function () {
  22193. var tracks = [];
  22194. for (var i = 0; i < this.tracks.length; i++) {
  22195. tracks.push(this.tracks[i].clone());
  22196. }
  22197. return new AnimationClip(this.name, this.duration, tracks);
  22198. }
  22199. });
  22200. /**
  22201. * @author mrdoob / http://mrdoob.com/
  22202. */
  22203. var Cache = {
  22204. enabled: false,
  22205. files: {},
  22206. add: function (key, file) {
  22207. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );
  22208. this.files[key] = file;
  22209. },
  22210. get: function (key) {
  22211. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );
  22212. return this.files[key];
  22213. },
  22214. remove: function (key) {
  22215. delete this.files[key];
  22216. },
  22217. clear: function () {
  22218. this.files = {};
  22219. }
  22220. };
  22221. /**
  22222. * @author mrdoob / http://mrdoob.com/
  22223. */
  22224. exports.Cache = Cache;
  22225. function LoadingManager(onLoad, onProgress, onError) {
  22226. var scope = this;
  22227. var isLoading = false;
  22228. var itemsLoaded = 0;
  22229. var itemsTotal = 0;
  22230. var urlModifier = undefined;
  22231. var handlers = []; // Refer to #5689 for the reason why we don't set .onStart
  22232. // in the constructor
  22233. this.onStart = undefined;
  22234. this.onLoad = onLoad;
  22235. this.onProgress = onProgress;
  22236. this.onError = onError;
  22237. this.itemStart = function (url) {
  22238. itemsTotal++;
  22239. if (isLoading === false) {
  22240. if (scope.onStart !== undefined) {
  22241. scope.onStart(url, itemsLoaded, itemsTotal);
  22242. }
  22243. }
  22244. isLoading = true;
  22245. };
  22246. this.itemEnd = function (url) {
  22247. itemsLoaded++;
  22248. if (scope.onProgress !== undefined) {
  22249. scope.onProgress(url, itemsLoaded, itemsTotal);
  22250. }
  22251. if (itemsLoaded === itemsTotal) {
  22252. isLoading = false;
  22253. if (scope.onLoad !== undefined) {
  22254. scope.onLoad();
  22255. }
  22256. }
  22257. };
  22258. this.itemError = function (url) {
  22259. if (scope.onError !== undefined) {
  22260. scope.onError(url);
  22261. }
  22262. };
  22263. this.resolveURL = function (url) {
  22264. if (urlModifier) {
  22265. return urlModifier(url);
  22266. }
  22267. return url;
  22268. };
  22269. this.setURLModifier = function (transform) {
  22270. urlModifier = transform;
  22271. return this;
  22272. };
  22273. this.addHandler = function (regex, loader) {
  22274. handlers.push(regex, loader);
  22275. return this;
  22276. };
  22277. this.removeHandler = function (regex) {
  22278. var index = handlers.indexOf(regex);
  22279. if (index !== -1) {
  22280. handlers.splice(index, 2);
  22281. }
  22282. return this;
  22283. };
  22284. this.getHandler = function (file) {
  22285. for (var i = 0, l = handlers.length; i < l; i += 2) {
  22286. var regex = handlers[i];
  22287. var loader = handlers[i + 1];
  22288. if (regex.test(file)) {
  22289. return loader;
  22290. }
  22291. }
  22292. return null;
  22293. };
  22294. }
  22295. var DefaultLoadingManager = new LoadingManager();
  22296. /**
  22297. * @author alteredq / http://alteredqualia.com/
  22298. */
  22299. exports.DefaultLoadingManager = DefaultLoadingManager;
  22300. function Loader(manager) {
  22301. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  22302. this.crossOrigin = 'anonymous';
  22303. this.path = '';
  22304. this.resourcePath = '';
  22305. }
  22306. Object.assign(Loader.prototype, {
  22307. load: function ()
  22308. /* url, onLoad, onProgress, onError */
  22309. {},
  22310. parse: function ()
  22311. /* data */
  22312. {},
  22313. setCrossOrigin: function (crossOrigin) {
  22314. this.crossOrigin = crossOrigin;
  22315. return this;
  22316. },
  22317. setPath: function (path) {
  22318. this.path = path;
  22319. return this;
  22320. },
  22321. setResourcePath: function (resourcePath) {
  22322. this.resourcePath = resourcePath;
  22323. return this;
  22324. }
  22325. });
  22326. /**
  22327. * @author mrdoob / http://mrdoob.com/
  22328. */
  22329. var loading = {};
  22330. function FileLoader(manager) {
  22331. Loader.call(this, manager);
  22332. }
  22333. FileLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22334. constructor: FileLoader,
  22335. load: function (url, onLoad, onProgress, onError) {
  22336. if (url === undefined) url = '';
  22337. if (this.path !== undefined) url = this.path + url;
  22338. url = this.manager.resolveURL(url);
  22339. var scope = this;
  22340. var cached = Cache.get(url);
  22341. if (cached !== undefined) {
  22342. scope.manager.itemStart(url);
  22343. setTimeout(function () {
  22344. if (onLoad) onLoad(cached);
  22345. scope.manager.itemEnd(url);
  22346. }, 0);
  22347. return cached;
  22348. } // Check if request is duplicate
  22349. if (loading[url] !== undefined) {
  22350. loading[url].push({
  22351. onLoad: onLoad,
  22352. onProgress: onProgress,
  22353. onError: onError
  22354. });
  22355. return;
  22356. } // Check for data: URI
  22357. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  22358. var dataUriRegexResult = url.match(dataUriRegex); // Safari can not handle Data URIs through XMLHttpRequest so process manually
  22359. if (dataUriRegexResult) {
  22360. var mimeType = dataUriRegexResult[1];
  22361. var isBase64 = !!dataUriRegexResult[2];
  22362. var data = dataUriRegexResult[3];
  22363. data = decodeURIComponent(data);
  22364. if (isBase64) data = atob(data);
  22365. try {
  22366. var response;
  22367. var responseType = (this.responseType || '').toLowerCase();
  22368. switch (responseType) {
  22369. case 'arraybuffer':
  22370. case 'blob':
  22371. var view = new Uint8Array(data.length);
  22372. for (var i = 0; i < data.length; i++) {
  22373. view[i] = data.charCodeAt(i);
  22374. }
  22375. if (responseType === 'blob') {
  22376. response = new Blob([view.buffer], {
  22377. type: mimeType
  22378. });
  22379. } else {
  22380. response = view.buffer;
  22381. }
  22382. break;
  22383. case 'document':
  22384. var parser = new DOMParser();
  22385. response = parser.parseFromString(data, mimeType);
  22386. break;
  22387. case 'json':
  22388. response = JSON.parse(data);
  22389. break;
  22390. default:
  22391. // 'text' or other
  22392. response = data;
  22393. break;
  22394. } // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  22395. setTimeout(function () {
  22396. if (onLoad) onLoad(response);
  22397. scope.manager.itemEnd(url);
  22398. }, 0);
  22399. } catch (error) {
  22400. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  22401. setTimeout(function () {
  22402. if (onError) onError(error);
  22403. scope.manager.itemError(url);
  22404. scope.manager.itemEnd(url);
  22405. }, 0);
  22406. }
  22407. } else {
  22408. // Initialise array for duplicate requests
  22409. loading[url] = [];
  22410. loading[url].push({
  22411. onLoad: onLoad,
  22412. onProgress: onProgress,
  22413. onError: onError
  22414. });
  22415. var request = new XMLHttpRequest();
  22416. request.open('GET', url, true);
  22417. request.addEventListener('load', function (event) {
  22418. var response = this.response;
  22419. Cache.add(url, response);
  22420. var callbacks = loading[url];
  22421. delete loading[url];
  22422. if (this.status === 200 || this.status === 0) {
  22423. // Some browsers return HTTP Status 0 when using non-http protocol
  22424. // e.g. 'file://' or 'data://'. Handle as success.
  22425. if (this.status === 0) console.warn('THREE.FileLoader: HTTP Status 0 received.');
  22426. for (var i = 0, il = callbacks.length; i < il; i++) {
  22427. var callback = callbacks[i];
  22428. if (callback.onLoad) callback.onLoad(response);
  22429. }
  22430. scope.manager.itemEnd(url);
  22431. } else {
  22432. for (var i = 0, il = callbacks.length; i < il; i++) {
  22433. var callback = callbacks[i];
  22434. if (callback.onError) callback.onError(event);
  22435. }
  22436. scope.manager.itemError(url);
  22437. scope.manager.itemEnd(url);
  22438. }
  22439. }, false);
  22440. request.addEventListener('progress', function (event) {
  22441. var callbacks = loading[url];
  22442. for (var i = 0, il = callbacks.length; i < il; i++) {
  22443. var callback = callbacks[i];
  22444. if (callback.onProgress) callback.onProgress(event);
  22445. }
  22446. }, false);
  22447. request.addEventListener('error', function (event) {
  22448. var callbacks = loading[url];
  22449. delete loading[url];
  22450. for (var i = 0, il = callbacks.length; i < il; i++) {
  22451. var callback = callbacks[i];
  22452. if (callback.onError) callback.onError(event);
  22453. }
  22454. scope.manager.itemError(url);
  22455. scope.manager.itemEnd(url);
  22456. }, false);
  22457. request.addEventListener('abort', function (event) {
  22458. var callbacks = loading[url];
  22459. delete loading[url];
  22460. for (var i = 0, il = callbacks.length; i < il; i++) {
  22461. var callback = callbacks[i];
  22462. if (callback.onError) callback.onError(event);
  22463. }
  22464. scope.manager.itemError(url);
  22465. scope.manager.itemEnd(url);
  22466. }, false);
  22467. if (this.responseType !== undefined) request.responseType = this.responseType;
  22468. if (this.withCredentials !== undefined) request.withCredentials = this.withCredentials;
  22469. if (request.overrideMimeType) request.overrideMimeType(this.mimeType !== undefined ? this.mimeType : 'text/plain');
  22470. for (var header in this.requestHeader) {
  22471. request.setRequestHeader(header, this.requestHeader[header]);
  22472. }
  22473. request.send(null);
  22474. }
  22475. scope.manager.itemStart(url);
  22476. return request;
  22477. },
  22478. setResponseType: function (value) {
  22479. this.responseType = value;
  22480. return this;
  22481. },
  22482. setWithCredentials: function (value) {
  22483. this.withCredentials = value;
  22484. return this;
  22485. },
  22486. setMimeType: function (value) {
  22487. this.mimeType = value;
  22488. return this;
  22489. },
  22490. setRequestHeader: function (value) {
  22491. this.requestHeader = value;
  22492. return this;
  22493. }
  22494. });
  22495. /**
  22496. * @author bhouston / http://clara.io/
  22497. */
  22498. function AnimationLoader(manager) {
  22499. Loader.call(this, manager);
  22500. }
  22501. AnimationLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22502. constructor: AnimationLoader,
  22503. load: function (url, onLoad, onProgress, onError) {
  22504. var scope = this;
  22505. var loader = new FileLoader(scope.manager);
  22506. loader.setPath(scope.path);
  22507. loader.load(url, function (text) {
  22508. onLoad(scope.parse(JSON.parse(text)));
  22509. }, onProgress, onError);
  22510. },
  22511. parse: function (json) {
  22512. var animations = [];
  22513. for (var i = 0; i < json.length; i++) {
  22514. var clip = AnimationClip.parse(json[i]);
  22515. animations.push(clip);
  22516. }
  22517. return animations;
  22518. }
  22519. });
  22520. /**
  22521. * @author mrdoob / http://mrdoob.com/
  22522. *
  22523. * Abstract Base class to block based textures loader (dds, pvr, ...)
  22524. *
  22525. * Sub classes have to implement the parse() method which will be used in load().
  22526. */
  22527. function CompressedTextureLoader(manager) {
  22528. Loader.call(this, manager);
  22529. }
  22530. CompressedTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22531. constructor: CompressedTextureLoader,
  22532. load: function (url, onLoad, onProgress, onError) {
  22533. var scope = this;
  22534. var images = [];
  22535. var texture = new CompressedTexture();
  22536. texture.image = images;
  22537. var loader = new FileLoader(this.manager);
  22538. loader.setPath(this.path);
  22539. loader.setResponseType('arraybuffer');
  22540. function loadTexture(i) {
  22541. loader.load(url[i], function (buffer) {
  22542. var texDatas = scope.parse(buffer, true);
  22543. images[i] = {
  22544. width: texDatas.width,
  22545. height: texDatas.height,
  22546. format: texDatas.format,
  22547. mipmaps: texDatas.mipmaps
  22548. };
  22549. loaded += 1;
  22550. if (loaded === 6) {
  22551. if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
  22552. texture.format = texDatas.format;
  22553. texture.needsUpdate = true;
  22554. if (onLoad) onLoad(texture);
  22555. }
  22556. }, onProgress, onError);
  22557. }
  22558. if (Array.isArray(url)) {
  22559. var loaded = 0;
  22560. for (var i = 0, il = url.length; i < il; ++i) {
  22561. loadTexture(i);
  22562. }
  22563. } else {
  22564. // compressed cubemap texture stored in a single DDS file
  22565. loader.load(url, function (buffer) {
  22566. var texDatas = scope.parse(buffer, true);
  22567. if (texDatas.isCubemap) {
  22568. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  22569. for (var f = 0; f < faces; f++) {
  22570. images[f] = {
  22571. mipmaps: []
  22572. };
  22573. for (var i = 0; i < texDatas.mipmapCount; i++) {
  22574. images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]);
  22575. images[f].format = texDatas.format;
  22576. images[f].width = texDatas.width;
  22577. images[f].height = texDatas.height;
  22578. }
  22579. }
  22580. } else {
  22581. texture.image.width = texDatas.width;
  22582. texture.image.height = texDatas.height;
  22583. texture.mipmaps = texDatas.mipmaps;
  22584. }
  22585. if (texDatas.mipmapCount === 1) {
  22586. texture.minFilter = LinearFilter;
  22587. }
  22588. texture.format = texDatas.format;
  22589. texture.needsUpdate = true;
  22590. if (onLoad) onLoad(texture);
  22591. }, onProgress, onError);
  22592. }
  22593. return texture;
  22594. }
  22595. });
  22596. /**
  22597. * @author Nikos M. / https://github.com/foo123/
  22598. *
  22599. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  22600. *
  22601. * Sub classes have to implement the parse() method which will be used in load().
  22602. */
  22603. function DataTextureLoader(manager) {
  22604. Loader.call(this, manager);
  22605. }
  22606. DataTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22607. constructor: DataTextureLoader,
  22608. load: function (url, onLoad, onProgress, onError) {
  22609. var scope = this;
  22610. var texture = new DataTexture();
  22611. var loader = new FileLoader(this.manager);
  22612. loader.setResponseType('arraybuffer');
  22613. loader.setPath(this.path);
  22614. loader.load(url, function (buffer) {
  22615. var texData = scope.parse(buffer);
  22616. if (!texData) return;
  22617. if (texData.image !== undefined) {
  22618. texture.image = texData.image;
  22619. } else if (texData.data !== undefined) {
  22620. texture.image.width = texData.width;
  22621. texture.image.height = texData.height;
  22622. texture.image.data = texData.data;
  22623. }
  22624. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  22625. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  22626. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  22627. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearMipmapLinearFilter;
  22628. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  22629. if (texData.format !== undefined) {
  22630. texture.format = texData.format;
  22631. }
  22632. if (texData.type !== undefined) {
  22633. texture.type = texData.type;
  22634. }
  22635. if (texData.mipmaps !== undefined) {
  22636. texture.mipmaps = texData.mipmaps;
  22637. }
  22638. if (texData.mipmapCount === 1) {
  22639. texture.minFilter = LinearFilter;
  22640. }
  22641. texture.needsUpdate = true;
  22642. if (onLoad) onLoad(texture, texData);
  22643. }, onProgress, onError);
  22644. return texture;
  22645. }
  22646. });
  22647. /**
  22648. * @author mrdoob / http://mrdoob.com/
  22649. */
  22650. function ImageLoader(manager) {
  22651. Loader.call(this, manager);
  22652. }
  22653. ImageLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22654. constructor: ImageLoader,
  22655. load: function (url, onLoad, onProgress, onError) {
  22656. if (this.path !== undefined) url = this.path + url;
  22657. url = this.manager.resolveURL(url);
  22658. var scope = this;
  22659. var cached = Cache.get(url);
  22660. if (cached !== undefined) {
  22661. scope.manager.itemStart(url);
  22662. setTimeout(function () {
  22663. if (onLoad) onLoad(cached);
  22664. scope.manager.itemEnd(url);
  22665. }, 0);
  22666. return cached;
  22667. }
  22668. var image = document.createElementNS('http://www.w3.org/1999/xhtml', 'img');
  22669. function onImageLoad() {
  22670. image.removeEventListener('load', onImageLoad, false);
  22671. image.removeEventListener('error', onImageError, false);
  22672. Cache.add(url, this);
  22673. if (onLoad) onLoad(this);
  22674. scope.manager.itemEnd(url);
  22675. }
  22676. function onImageError(event) {
  22677. image.removeEventListener('load', onImageLoad, false);
  22678. image.removeEventListener('error', onImageError, false);
  22679. if (onError) onError(event);
  22680. scope.manager.itemError(url);
  22681. scope.manager.itemEnd(url);
  22682. }
  22683. image.addEventListener('load', onImageLoad, false);
  22684. image.addEventListener('error', onImageError, false);
  22685. if (url.substr(0, 5) !== 'data:') {
  22686. if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
  22687. }
  22688. scope.manager.itemStart(url);
  22689. image.src = url;
  22690. return image;
  22691. }
  22692. });
  22693. /**
  22694. * @author mrdoob / http://mrdoob.com/
  22695. */
  22696. function CubeTextureLoader(manager) {
  22697. Loader.call(this, manager);
  22698. }
  22699. CubeTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22700. constructor: CubeTextureLoader,
  22701. load: function (urls, onLoad, onProgress, onError) {
  22702. var texture = new CubeTexture();
  22703. var loader = new ImageLoader(this.manager);
  22704. loader.setCrossOrigin(this.crossOrigin);
  22705. loader.setPath(this.path);
  22706. var loaded = 0;
  22707. function loadTexture(i) {
  22708. loader.load(urls[i], function (image) {
  22709. texture.images[i] = image;
  22710. loaded++;
  22711. if (loaded === 6) {
  22712. texture.needsUpdate = true;
  22713. if (onLoad) onLoad(texture);
  22714. }
  22715. }, undefined, onError);
  22716. }
  22717. for (var i = 0; i < urls.length; ++i) {
  22718. loadTexture(i);
  22719. }
  22720. return texture;
  22721. }
  22722. });
  22723. /**
  22724. * @author mrdoob / http://mrdoob.com/
  22725. */
  22726. function TextureLoader(manager) {
  22727. Loader.call(this, manager);
  22728. }
  22729. TextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22730. constructor: TextureLoader,
  22731. load: function (url, onLoad, onProgress, onError) {
  22732. var texture = new Texture();
  22733. var loader = new ImageLoader(this.manager);
  22734. loader.setCrossOrigin(this.crossOrigin);
  22735. loader.setPath(this.path);
  22736. loader.load(url, function (image) {
  22737. texture.image = image; // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  22738. var isJPEG = url.search(/\.jpe?g($|\?)/i) > 0 || url.search(/^data\:image\/jpeg/) === 0;
  22739. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  22740. texture.needsUpdate = true;
  22741. if (onLoad !== undefined) {
  22742. onLoad(texture);
  22743. }
  22744. }, onProgress, onError);
  22745. return texture;
  22746. }
  22747. });
  22748. /**
  22749. * @author zz85 / http://www.lab4games.net/zz85/blog
  22750. * Extensible curve object
  22751. *
  22752. * Some common of curve methods:
  22753. * .getPoint( t, optionalTarget ), .getTangent( t )
  22754. * .getPointAt( u, optionalTarget ), .getTangentAt( u )
  22755. * .getPoints(), .getSpacedPoints()
  22756. * .getLength()
  22757. * .updateArcLengths()
  22758. *
  22759. * This following curves inherit from THREE.Curve:
  22760. *
  22761. * -- 2D curves --
  22762. * THREE.ArcCurve
  22763. * THREE.CubicBezierCurve
  22764. * THREE.EllipseCurve
  22765. * THREE.LineCurve
  22766. * THREE.QuadraticBezierCurve
  22767. * THREE.SplineCurve
  22768. *
  22769. * -- 3D curves --
  22770. * THREE.CatmullRomCurve3
  22771. * THREE.CubicBezierCurve3
  22772. * THREE.LineCurve3
  22773. * THREE.QuadraticBezierCurve3
  22774. *
  22775. * A series of curves can be represented as a THREE.CurvePath.
  22776. *
  22777. **/
  22778. /**************************************************************
  22779. * Abstract Curve base class
  22780. **************************************************************/
  22781. function Curve() {
  22782. this.type = 'Curve';
  22783. this.arcLengthDivisions = 200;
  22784. }
  22785. Object.assign(Curve.prototype, {
  22786. // Virtual base class method to overwrite and implement in subclasses
  22787. // - t [0 .. 1]
  22788. getPoint: function ()
  22789. /* t, optionalTarget */
  22790. {
  22791. console.warn('THREE.Curve: .getPoint() not implemented.');
  22792. return null;
  22793. },
  22794. // Get point at relative position in curve according to arc length
  22795. // - u [0 .. 1]
  22796. getPointAt: function (u, optionalTarget) {
  22797. var t = this.getUtoTmapping(u);
  22798. return this.getPoint(t, optionalTarget);
  22799. },
  22800. // Get sequence of points using getPoint( t )
  22801. getPoints: function (divisions) {
  22802. if (divisions === undefined) divisions = 5;
  22803. var points = [];
  22804. for (var d = 0; d <= divisions; d++) {
  22805. points.push(this.getPoint(d / divisions));
  22806. }
  22807. return points;
  22808. },
  22809. // Get sequence of points using getPointAt( u )
  22810. getSpacedPoints: function (divisions) {
  22811. if (divisions === undefined) divisions = 5;
  22812. var points = [];
  22813. for (var d = 0; d <= divisions; d++) {
  22814. points.push(this.getPointAt(d / divisions));
  22815. }
  22816. return points;
  22817. },
  22818. // Get total curve arc length
  22819. getLength: function () {
  22820. var lengths = this.getLengths();
  22821. return lengths[lengths.length - 1];
  22822. },
  22823. // Get list of cumulative segment lengths
  22824. getLengths: function (divisions) {
  22825. if (divisions === undefined) divisions = this.arcLengthDivisions;
  22826. if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
  22827. return this.cacheArcLengths;
  22828. }
  22829. this.needsUpdate = false;
  22830. var cache = [];
  22831. var current,
  22832. last = this.getPoint(0);
  22833. var p,
  22834. sum = 0;
  22835. cache.push(0);
  22836. for (p = 1; p <= divisions; p++) {
  22837. current = this.getPoint(p / divisions);
  22838. sum += current.distanceTo(last);
  22839. cache.push(sum);
  22840. last = current;
  22841. }
  22842. this.cacheArcLengths = cache;
  22843. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  22844. },
  22845. updateArcLengths: function () {
  22846. this.needsUpdate = true;
  22847. this.getLengths();
  22848. },
  22849. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  22850. getUtoTmapping: function (u, distance) {
  22851. var arcLengths = this.getLengths();
  22852. var i = 0,
  22853. il = arcLengths.length;
  22854. var targetArcLength; // The targeted u distance value to get
  22855. if (distance) {
  22856. targetArcLength = distance;
  22857. } else {
  22858. targetArcLength = u * arcLengths[il - 1];
  22859. } // binary search for the index with largest value smaller than target u distance
  22860. var low = 0,
  22861. high = il - 1,
  22862. comparison;
  22863. while (low <= high) {
  22864. 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
  22865. comparison = arcLengths[i] - targetArcLength;
  22866. if (comparison < 0) {
  22867. low = i + 1;
  22868. } else if (comparison > 0) {
  22869. high = i - 1;
  22870. } else {
  22871. high = i;
  22872. break; // DONE
  22873. }
  22874. }
  22875. i = high;
  22876. if (arcLengths[i] === targetArcLength) {
  22877. return i / (il - 1);
  22878. } // we could get finer grain at lengths, or use simple interpolation between two points
  22879. var lengthBefore = arcLengths[i];
  22880. var lengthAfter = arcLengths[i + 1];
  22881. var segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points
  22882. var segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to t
  22883. var t = (i + segmentFraction) / (il - 1);
  22884. return t;
  22885. },
  22886. // Returns a unit vector tangent at t
  22887. // In case any sub curve does not implement its tangent derivation,
  22888. // 2 points a small delta apart will be used to find its gradient
  22889. // which seems to give a reasonable approximation
  22890. getTangent: function (t) {
  22891. var delta = 0.0001;
  22892. var t1 = t - delta;
  22893. var t2 = t + delta; // Capping in case of danger
  22894. if (t1 < 0) t1 = 0;
  22895. if (t2 > 1) t2 = 1;
  22896. var pt1 = this.getPoint(t1);
  22897. var pt2 = this.getPoint(t2);
  22898. var vec = pt2.clone().sub(pt1);
  22899. return vec.normalize();
  22900. },
  22901. getTangentAt: function (u) {
  22902. var t = this.getUtoTmapping(u);
  22903. return this.getTangent(t);
  22904. },
  22905. computeFrenetFrames: function (segments, closed) {
  22906. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  22907. var normal = new Vector3();
  22908. var tangents = [];
  22909. var normals = [];
  22910. var binormals = [];
  22911. var vec = new Vector3();
  22912. var mat = new Matrix4();
  22913. var i, u, theta; // compute the tangent vectors for each segment on the curve
  22914. for (i = 0; i <= segments; i++) {
  22915. u = i / segments;
  22916. tangents[i] = this.getTangentAt(u);
  22917. tangents[i].normalize();
  22918. } // select an initial normal vector perpendicular to the first tangent vector,
  22919. // and in the direction of the minimum tangent xyz component
  22920. normals[0] = new Vector3();
  22921. binormals[0] = new Vector3();
  22922. var min = Number.MAX_VALUE;
  22923. var tx = Math.abs(tangents[0].x);
  22924. var ty = Math.abs(tangents[0].y);
  22925. var tz = Math.abs(tangents[0].z);
  22926. if (tx <= min) {
  22927. min = tx;
  22928. normal.set(1, 0, 0);
  22929. }
  22930. if (ty <= min) {
  22931. min = ty;
  22932. normal.set(0, 1, 0);
  22933. }
  22934. if (tz <= min) {
  22935. normal.set(0, 0, 1);
  22936. }
  22937. vec.crossVectors(tangents[0], normal).normalize();
  22938. normals[0].crossVectors(tangents[0], vec);
  22939. binormals[0].crossVectors(tangents[0], normals[0]); // compute the slowly-varying normal and binormal vectors for each segment on the curve
  22940. for (i = 1; i <= segments; i++) {
  22941. normals[i] = normals[i - 1].clone();
  22942. binormals[i] = binormals[i - 1].clone();
  22943. vec.crossVectors(tangents[i - 1], tangents[i]);
  22944. if (vec.length() > Number.EPSILON) {
  22945. vec.normalize();
  22946. theta = Math.acos(_Math.clamp(tangents[i - 1].dot(tangents[i]), -1, 1)); // clamp for floating pt errors
  22947. normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta));
  22948. }
  22949. binormals[i].crossVectors(tangents[i], normals[i]);
  22950. } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  22951. if (closed === true) {
  22952. theta = Math.acos(_Math.clamp(normals[0].dot(normals[segments]), -1, 1));
  22953. theta /= segments;
  22954. if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
  22955. theta = -theta;
  22956. }
  22957. for (i = 1; i <= segments; i++) {
  22958. // twist a little...
  22959. normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i));
  22960. binormals[i].crossVectors(tangents[i], normals[i]);
  22961. }
  22962. }
  22963. return {
  22964. tangents: tangents,
  22965. normals: normals,
  22966. binormals: binormals
  22967. };
  22968. },
  22969. clone: function () {
  22970. return new this.constructor().copy(this);
  22971. },
  22972. copy: function (source) {
  22973. this.arcLengthDivisions = source.arcLengthDivisions;
  22974. return this;
  22975. },
  22976. toJSON: function () {
  22977. var data = {
  22978. metadata: {
  22979. version: 4.5,
  22980. type: 'Curve',
  22981. generator: 'Curve.toJSON'
  22982. }
  22983. };
  22984. data.arcLengthDivisions = this.arcLengthDivisions;
  22985. data.type = this.type;
  22986. return data;
  22987. },
  22988. fromJSON: function (json) {
  22989. this.arcLengthDivisions = json.arcLengthDivisions;
  22990. return this;
  22991. }
  22992. });
  22993. function EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  22994. Curve.call(this);
  22995. this.type = 'EllipseCurve';
  22996. this.aX = aX || 0;
  22997. this.aY = aY || 0;
  22998. this.xRadius = xRadius || 1;
  22999. this.yRadius = yRadius || 1;
  23000. this.aStartAngle = aStartAngle || 0;
  23001. this.aEndAngle = aEndAngle || 2 * Math.PI;
  23002. this.aClockwise = aClockwise || false;
  23003. this.aRotation = aRotation || 0;
  23004. }
  23005. EllipseCurve.prototype = Object.create(Curve.prototype);
  23006. EllipseCurve.prototype.constructor = EllipseCurve;
  23007. EllipseCurve.prototype.isEllipseCurve = true;
  23008. EllipseCurve.prototype.getPoint = function (t, optionalTarget) {
  23009. var point = optionalTarget || new Vector2();
  23010. var twoPi = Math.PI * 2;
  23011. var deltaAngle = this.aEndAngle - this.aStartAngle;
  23012. var samePoints = Math.abs(deltaAngle) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI
  23013. while (deltaAngle < 0) deltaAngle += twoPi;
  23014. while (deltaAngle > twoPi) deltaAngle -= twoPi;
  23015. if (deltaAngle < Number.EPSILON) {
  23016. if (samePoints) {
  23017. deltaAngle = 0;
  23018. } else {
  23019. deltaAngle = twoPi;
  23020. }
  23021. }
  23022. if (this.aClockwise === true && !samePoints) {
  23023. if (deltaAngle === twoPi) {
  23024. deltaAngle = -twoPi;
  23025. } else {
  23026. deltaAngle = deltaAngle - twoPi;
  23027. }
  23028. }
  23029. var angle = this.aStartAngle + t * deltaAngle;
  23030. var x = this.aX + this.xRadius * Math.cos(angle);
  23031. var y = this.aY + this.yRadius * Math.sin(angle);
  23032. if (this.aRotation !== 0) {
  23033. var cos = Math.cos(this.aRotation);
  23034. var sin = Math.sin(this.aRotation);
  23035. var tx = x - this.aX;
  23036. var ty = y - this.aY; // Rotate the point about the center of the ellipse.
  23037. x = tx * cos - ty * sin + this.aX;
  23038. y = tx * sin + ty * cos + this.aY;
  23039. }
  23040. return point.set(x, y);
  23041. };
  23042. EllipseCurve.prototype.copy = function (source) {
  23043. Curve.prototype.copy.call(this, source);
  23044. this.aX = source.aX;
  23045. this.aY = source.aY;
  23046. this.xRadius = source.xRadius;
  23047. this.yRadius = source.yRadius;
  23048. this.aStartAngle = source.aStartAngle;
  23049. this.aEndAngle = source.aEndAngle;
  23050. this.aClockwise = source.aClockwise;
  23051. this.aRotation = source.aRotation;
  23052. return this;
  23053. };
  23054. EllipseCurve.prototype.toJSON = function () {
  23055. var data = Curve.prototype.toJSON.call(this);
  23056. data.aX = this.aX;
  23057. data.aY = this.aY;
  23058. data.xRadius = this.xRadius;
  23059. data.yRadius = this.yRadius;
  23060. data.aStartAngle = this.aStartAngle;
  23061. data.aEndAngle = this.aEndAngle;
  23062. data.aClockwise = this.aClockwise;
  23063. data.aRotation = this.aRotation;
  23064. return data;
  23065. };
  23066. EllipseCurve.prototype.fromJSON = function (json) {
  23067. Curve.prototype.fromJSON.call(this, json);
  23068. this.aX = json.aX;
  23069. this.aY = json.aY;
  23070. this.xRadius = json.xRadius;
  23071. this.yRadius = json.yRadius;
  23072. this.aStartAngle = json.aStartAngle;
  23073. this.aEndAngle = json.aEndAngle;
  23074. this.aClockwise = json.aClockwise;
  23075. this.aRotation = json.aRotation;
  23076. return this;
  23077. };
  23078. function ArcCurve(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  23079. EllipseCurve.call(this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  23080. this.type = 'ArcCurve';
  23081. }
  23082. ArcCurve.prototype = Object.create(EllipseCurve.prototype);
  23083. ArcCurve.prototype.constructor = ArcCurve;
  23084. ArcCurve.prototype.isArcCurve = true;
  23085. /**
  23086. * @author zz85 https://github.com/zz85
  23087. *
  23088. * Centripetal CatmullRom Curve - which is useful for avoiding
  23089. * cusps and self-intersections in non-uniform catmull rom curves.
  23090. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  23091. *
  23092. * curve.type accepts centripetal(default), chordal and catmullrom
  23093. * curve.tension is used for catmullrom which defaults to 0.5
  23094. */
  23095. /*
  23096. Based on an optimized c++ solution in
  23097. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  23098. - http://ideone.com/NoEbVM
  23099. This CubicPoly class could be used for reusing some variables and calculations,
  23100. but for three.js curve use, it could be possible inlined and flatten into a single function call
  23101. which can be placed in CurveUtils.
  23102. */
  23103. function CubicPoly() {
  23104. var c0 = 0,
  23105. c1 = 0,
  23106. c2 = 0,
  23107. c3 = 0;
  23108. /*
  23109. * Compute coefficients for a cubic polynomial
  23110. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  23111. * such that
  23112. * p(0) = x0, p(1) = x1
  23113. * and
  23114. * p'(0) = t0, p'(1) = t1.
  23115. */
  23116. function init(x0, x1, t0, t1) {
  23117. c0 = x0;
  23118. c1 = t0;
  23119. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  23120. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  23121. }
  23122. return {
  23123. initCatmullRom: function (x0, x1, x2, x3, tension) {
  23124. init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
  23125. },
  23126. initNonuniformCatmullRom: function (x0, x1, x2, x3, dt0, dt1, dt2) {
  23127. // compute tangents when parameterized in [t1,t2]
  23128. var t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
  23129. var t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]
  23130. t1 *= dt1;
  23131. t2 *= dt1;
  23132. init(x1, x2, t1, t2);
  23133. },
  23134. calc: function (t) {
  23135. var t2 = t * t;
  23136. var t3 = t2 * t;
  23137. return c0 + c1 * t + c2 * t2 + c3 * t3;
  23138. }
  23139. };
  23140. } //
  23141. var tmp = new Vector3();
  23142. var px = new CubicPoly(),
  23143. py = new CubicPoly(),
  23144. pz = new CubicPoly();
  23145. function CatmullRomCurve3(points, closed, curveType, tension) {
  23146. Curve.call(this);
  23147. this.type = 'CatmullRomCurve3';
  23148. this.points = points || [];
  23149. this.closed = closed || false;
  23150. this.curveType = curveType || 'centripetal';
  23151. this.tension = tension || 0.5;
  23152. }
  23153. CatmullRomCurve3.prototype = Object.create(Curve.prototype);
  23154. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  23155. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  23156. CatmullRomCurve3.prototype.getPoint = function (t, optionalTarget) {
  23157. var point = optionalTarget || new Vector3();
  23158. var points = this.points;
  23159. var l = points.length;
  23160. var p = (l - (this.closed ? 0 : 1)) * t;
  23161. var intPoint = Math.floor(p);
  23162. var weight = p - intPoint;
  23163. if (this.closed) {
  23164. intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
  23165. } else if (weight === 0 && intPoint === l - 1) {
  23166. intPoint = l - 2;
  23167. weight = 1;
  23168. }
  23169. var p0, p1, p2, p3; // 4 points
  23170. if (this.closed || intPoint > 0) {
  23171. p0 = points[(intPoint - 1) % l];
  23172. } else {
  23173. // extrapolate first point
  23174. tmp.subVectors(points[0], points[1]).add(points[0]);
  23175. p0 = tmp;
  23176. }
  23177. p1 = points[intPoint % l];
  23178. p2 = points[(intPoint + 1) % l];
  23179. if (this.closed || intPoint + 2 < l) {
  23180. p3 = points[(intPoint + 2) % l];
  23181. } else {
  23182. // extrapolate last point
  23183. tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
  23184. p3 = tmp;
  23185. }
  23186. if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
  23187. // init Centripetal / Chordal Catmull-Rom
  23188. var pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  23189. var dt0 = Math.pow(p0.distanceToSquared(p1), pow);
  23190. var dt1 = Math.pow(p1.distanceToSquared(p2), pow);
  23191. var dt2 = Math.pow(p2.distanceToSquared(p3), pow); // safety check for repeated points
  23192. if (dt1 < 1e-4) dt1 = 1.0;
  23193. if (dt0 < 1e-4) dt0 = dt1;
  23194. if (dt2 < 1e-4) dt2 = dt1;
  23195. px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
  23196. py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
  23197. pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
  23198. } else if (this.curveType === 'catmullrom') {
  23199. px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
  23200. py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
  23201. pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
  23202. }
  23203. point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
  23204. return point;
  23205. };
  23206. CatmullRomCurve3.prototype.copy = function (source) {
  23207. Curve.prototype.copy.call(this, source);
  23208. this.points = [];
  23209. for (var i = 0, l = source.points.length; i < l; i++) {
  23210. var point = source.points[i];
  23211. this.points.push(point.clone());
  23212. }
  23213. this.closed = source.closed;
  23214. this.curveType = source.curveType;
  23215. this.tension = source.tension;
  23216. return this;
  23217. };
  23218. CatmullRomCurve3.prototype.toJSON = function () {
  23219. var data = Curve.prototype.toJSON.call(this);
  23220. data.points = [];
  23221. for (var i = 0, l = this.points.length; i < l; i++) {
  23222. var point = this.points[i];
  23223. data.points.push(point.toArray());
  23224. }
  23225. data.closed = this.closed;
  23226. data.curveType = this.curveType;
  23227. data.tension = this.tension;
  23228. return data;
  23229. };
  23230. CatmullRomCurve3.prototype.fromJSON = function (json) {
  23231. Curve.prototype.fromJSON.call(this, json);
  23232. this.points = [];
  23233. for (var i = 0, l = json.points.length; i < l; i++) {
  23234. var point = json.points[i];
  23235. this.points.push(new Vector3().fromArray(point));
  23236. }
  23237. this.closed = json.closed;
  23238. this.curveType = json.curveType;
  23239. this.tension = json.tension;
  23240. return this;
  23241. };
  23242. /**
  23243. * @author zz85 / http://www.lab4games.net/zz85/blog
  23244. *
  23245. * Bezier Curves formulas obtained from
  23246. * http://en.wikipedia.org/wiki/Bézier_curve
  23247. */
  23248. function CatmullRom(t, p0, p1, p2, p3) {
  23249. var v0 = (p2 - p0) * 0.5;
  23250. var v1 = (p3 - p1) * 0.5;
  23251. var t2 = t * t;
  23252. var t3 = t * t2;
  23253. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  23254. } //
  23255. function QuadraticBezierP0(t, p) {
  23256. var k = 1 - t;
  23257. return k * k * p;
  23258. }
  23259. function QuadraticBezierP1(t, p) {
  23260. return 2 * (1 - t) * t * p;
  23261. }
  23262. function QuadraticBezierP2(t, p) {
  23263. return t * t * p;
  23264. }
  23265. function QuadraticBezier(t, p0, p1, p2) {
  23266. return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
  23267. } //
  23268. function CubicBezierP0(t, p) {
  23269. var k = 1 - t;
  23270. return k * k * k * p;
  23271. }
  23272. function CubicBezierP1(t, p) {
  23273. var k = 1 - t;
  23274. return 3 * k * k * t * p;
  23275. }
  23276. function CubicBezierP2(t, p) {
  23277. return 3 * (1 - t) * t * t * p;
  23278. }
  23279. function CubicBezierP3(t, p) {
  23280. return t * t * t * p;
  23281. }
  23282. function CubicBezier(t, p0, p1, p2, p3) {
  23283. return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
  23284. }
  23285. function CubicBezierCurve(v0, v1, v2, v3) {
  23286. Curve.call(this);
  23287. this.type = 'CubicBezierCurve';
  23288. this.v0 = v0 || new Vector2();
  23289. this.v1 = v1 || new Vector2();
  23290. this.v2 = v2 || new Vector2();
  23291. this.v3 = v3 || new Vector2();
  23292. }
  23293. CubicBezierCurve.prototype = Object.create(Curve.prototype);
  23294. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  23295. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  23296. CubicBezierCurve.prototype.getPoint = function (t, optionalTarget) {
  23297. var point = optionalTarget || new Vector2();
  23298. var v0 = this.v0,
  23299. v1 = this.v1,
  23300. v2 = this.v2,
  23301. v3 = this.v3;
  23302. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
  23303. return point;
  23304. };
  23305. CubicBezierCurve.prototype.copy = function (source) {
  23306. Curve.prototype.copy.call(this, source);
  23307. this.v0.copy(source.v0);
  23308. this.v1.copy(source.v1);
  23309. this.v2.copy(source.v2);
  23310. this.v3.copy(source.v3);
  23311. return this;
  23312. };
  23313. CubicBezierCurve.prototype.toJSON = function () {
  23314. var data = Curve.prototype.toJSON.call(this);
  23315. data.v0 = this.v0.toArray();
  23316. data.v1 = this.v1.toArray();
  23317. data.v2 = this.v2.toArray();
  23318. data.v3 = this.v3.toArray();
  23319. return data;
  23320. };
  23321. CubicBezierCurve.prototype.fromJSON = function (json) {
  23322. Curve.prototype.fromJSON.call(this, json);
  23323. this.v0.fromArray(json.v0);
  23324. this.v1.fromArray(json.v1);
  23325. this.v2.fromArray(json.v2);
  23326. this.v3.fromArray(json.v3);
  23327. return this;
  23328. };
  23329. function CubicBezierCurve3(v0, v1, v2, v3) {
  23330. Curve.call(this);
  23331. this.type = 'CubicBezierCurve3';
  23332. this.v0 = v0 || new Vector3();
  23333. this.v1 = v1 || new Vector3();
  23334. this.v2 = v2 || new Vector3();
  23335. this.v3 = v3 || new Vector3();
  23336. }
  23337. CubicBezierCurve3.prototype = Object.create(Curve.prototype);
  23338. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  23339. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  23340. CubicBezierCurve3.prototype.getPoint = function (t, optionalTarget) {
  23341. var point = optionalTarget || new Vector3();
  23342. var v0 = this.v0,
  23343. v1 = this.v1,
  23344. v2 = this.v2,
  23345. v3 = this.v3;
  23346. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y), CubicBezier(t, v0.z, v1.z, v2.z, v3.z));
  23347. return point;
  23348. };
  23349. CubicBezierCurve3.prototype.copy = function (source) {
  23350. Curve.prototype.copy.call(this, source);
  23351. this.v0.copy(source.v0);
  23352. this.v1.copy(source.v1);
  23353. this.v2.copy(source.v2);
  23354. this.v3.copy(source.v3);
  23355. return this;
  23356. };
  23357. CubicBezierCurve3.prototype.toJSON = function () {
  23358. var data = Curve.prototype.toJSON.call(this);
  23359. data.v0 = this.v0.toArray();
  23360. data.v1 = this.v1.toArray();
  23361. data.v2 = this.v2.toArray();
  23362. data.v3 = this.v3.toArray();
  23363. return data;
  23364. };
  23365. CubicBezierCurve3.prototype.fromJSON = function (json) {
  23366. Curve.prototype.fromJSON.call(this, json);
  23367. this.v0.fromArray(json.v0);
  23368. this.v1.fromArray(json.v1);
  23369. this.v2.fromArray(json.v2);
  23370. this.v3.fromArray(json.v3);
  23371. return this;
  23372. };
  23373. function LineCurve(v1, v2) {
  23374. Curve.call(this);
  23375. this.type = 'LineCurve';
  23376. this.v1 = v1 || new Vector2();
  23377. this.v2 = v2 || new Vector2();
  23378. }
  23379. LineCurve.prototype = Object.create(Curve.prototype);
  23380. LineCurve.prototype.constructor = LineCurve;
  23381. LineCurve.prototype.isLineCurve = true;
  23382. LineCurve.prototype.getPoint = function (t, optionalTarget) {
  23383. var point = optionalTarget || new Vector2();
  23384. if (t === 1) {
  23385. point.copy(this.v2);
  23386. } else {
  23387. point.copy(this.v2).sub(this.v1);
  23388. point.multiplyScalar(t).add(this.v1);
  23389. }
  23390. return point;
  23391. }; // Line curve is linear, so we can overwrite default getPointAt
  23392. LineCurve.prototype.getPointAt = function (u, optionalTarget) {
  23393. return this.getPoint(u, optionalTarget);
  23394. };
  23395. LineCurve.prototype.getTangent = function ()
  23396. /* t */
  23397. {
  23398. var tangent = this.v2.clone().sub(this.v1);
  23399. return tangent.normalize();
  23400. };
  23401. LineCurve.prototype.copy = function (source) {
  23402. Curve.prototype.copy.call(this, source);
  23403. this.v1.copy(source.v1);
  23404. this.v2.copy(source.v2);
  23405. return this;
  23406. };
  23407. LineCurve.prototype.toJSON = function () {
  23408. var data = Curve.prototype.toJSON.call(this);
  23409. data.v1 = this.v1.toArray();
  23410. data.v2 = this.v2.toArray();
  23411. return data;
  23412. };
  23413. LineCurve.prototype.fromJSON = function (json) {
  23414. Curve.prototype.fromJSON.call(this, json);
  23415. this.v1.fromArray(json.v1);
  23416. this.v2.fromArray(json.v2);
  23417. return this;
  23418. };
  23419. function LineCurve3(v1, v2) {
  23420. Curve.call(this);
  23421. this.type = 'LineCurve3';
  23422. this.v1 = v1 || new Vector3();
  23423. this.v2 = v2 || new Vector3();
  23424. }
  23425. LineCurve3.prototype = Object.create(Curve.prototype);
  23426. LineCurve3.prototype.constructor = LineCurve3;
  23427. LineCurve3.prototype.isLineCurve3 = true;
  23428. LineCurve3.prototype.getPoint = function (t, optionalTarget) {
  23429. var point = optionalTarget || new Vector3();
  23430. if (t === 1) {
  23431. point.copy(this.v2);
  23432. } else {
  23433. point.copy(this.v2).sub(this.v1);
  23434. point.multiplyScalar(t).add(this.v1);
  23435. }
  23436. return point;
  23437. }; // Line curve is linear, so we can overwrite default getPointAt
  23438. LineCurve3.prototype.getPointAt = function (u, optionalTarget) {
  23439. return this.getPoint(u, optionalTarget);
  23440. };
  23441. LineCurve3.prototype.copy = function (source) {
  23442. Curve.prototype.copy.call(this, source);
  23443. this.v1.copy(source.v1);
  23444. this.v2.copy(source.v2);
  23445. return this;
  23446. };
  23447. LineCurve3.prototype.toJSON = function () {
  23448. var data = Curve.prototype.toJSON.call(this);
  23449. data.v1 = this.v1.toArray();
  23450. data.v2 = this.v2.toArray();
  23451. return data;
  23452. };
  23453. LineCurve3.prototype.fromJSON = function (json) {
  23454. Curve.prototype.fromJSON.call(this, json);
  23455. this.v1.fromArray(json.v1);
  23456. this.v2.fromArray(json.v2);
  23457. return this;
  23458. };
  23459. function QuadraticBezierCurve(v0, v1, v2) {
  23460. Curve.call(this);
  23461. this.type = 'QuadraticBezierCurve';
  23462. this.v0 = v0 || new Vector2();
  23463. this.v1 = v1 || new Vector2();
  23464. this.v2 = v2 || new Vector2();
  23465. }
  23466. QuadraticBezierCurve.prototype = Object.create(Curve.prototype);
  23467. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  23468. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  23469. QuadraticBezierCurve.prototype.getPoint = function (t, optionalTarget) {
  23470. var point = optionalTarget || new Vector2();
  23471. var v0 = this.v0,
  23472. v1 = this.v1,
  23473. v2 = this.v2;
  23474. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
  23475. return point;
  23476. };
  23477. QuadraticBezierCurve.prototype.copy = function (source) {
  23478. Curve.prototype.copy.call(this, source);
  23479. this.v0.copy(source.v0);
  23480. this.v1.copy(source.v1);
  23481. this.v2.copy(source.v2);
  23482. return this;
  23483. };
  23484. QuadraticBezierCurve.prototype.toJSON = function () {
  23485. var data = Curve.prototype.toJSON.call(this);
  23486. data.v0 = this.v0.toArray();
  23487. data.v1 = this.v1.toArray();
  23488. data.v2 = this.v2.toArray();
  23489. return data;
  23490. };
  23491. QuadraticBezierCurve.prototype.fromJSON = function (json) {
  23492. Curve.prototype.fromJSON.call(this, json);
  23493. this.v0.fromArray(json.v0);
  23494. this.v1.fromArray(json.v1);
  23495. this.v2.fromArray(json.v2);
  23496. return this;
  23497. };
  23498. function QuadraticBezierCurve3(v0, v1, v2) {
  23499. Curve.call(this);
  23500. this.type = 'QuadraticBezierCurve3';
  23501. this.v0 = v0 || new Vector3();
  23502. this.v1 = v1 || new Vector3();
  23503. this.v2 = v2 || new Vector3();
  23504. }
  23505. QuadraticBezierCurve3.prototype = Object.create(Curve.prototype);
  23506. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  23507. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  23508. QuadraticBezierCurve3.prototype.getPoint = function (t, optionalTarget) {
  23509. var point = optionalTarget || new Vector3();
  23510. var v0 = this.v0,
  23511. v1 = this.v1,
  23512. v2 = this.v2;
  23513. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y), QuadraticBezier(t, v0.z, v1.z, v2.z));
  23514. return point;
  23515. };
  23516. QuadraticBezierCurve3.prototype.copy = function (source) {
  23517. Curve.prototype.copy.call(this, source);
  23518. this.v0.copy(source.v0);
  23519. this.v1.copy(source.v1);
  23520. this.v2.copy(source.v2);
  23521. return this;
  23522. };
  23523. QuadraticBezierCurve3.prototype.toJSON = function () {
  23524. var data = Curve.prototype.toJSON.call(this);
  23525. data.v0 = this.v0.toArray();
  23526. data.v1 = this.v1.toArray();
  23527. data.v2 = this.v2.toArray();
  23528. return data;
  23529. };
  23530. QuadraticBezierCurve3.prototype.fromJSON = function (json) {
  23531. Curve.prototype.fromJSON.call(this, json);
  23532. this.v0.fromArray(json.v0);
  23533. this.v1.fromArray(json.v1);
  23534. this.v2.fromArray(json.v2);
  23535. return this;
  23536. };
  23537. function SplineCurve(points
  23538. /* array of Vector2 */
  23539. ) {
  23540. Curve.call(this);
  23541. this.type = 'SplineCurve';
  23542. this.points = points || [];
  23543. }
  23544. SplineCurve.prototype = Object.create(Curve.prototype);
  23545. SplineCurve.prototype.constructor = SplineCurve;
  23546. SplineCurve.prototype.isSplineCurve = true;
  23547. SplineCurve.prototype.getPoint = function (t, optionalTarget) {
  23548. var point = optionalTarget || new Vector2();
  23549. var points = this.points;
  23550. var p = (points.length - 1) * t;
  23551. var intPoint = Math.floor(p);
  23552. var weight = p - intPoint;
  23553. var p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
  23554. var p1 = points[intPoint];
  23555. var p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
  23556. var p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
  23557. point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
  23558. return point;
  23559. };
  23560. SplineCurve.prototype.copy = function (source) {
  23561. Curve.prototype.copy.call(this, source);
  23562. this.points = [];
  23563. for (var i = 0, l = source.points.length; i < l; i++) {
  23564. var point = source.points[i];
  23565. this.points.push(point.clone());
  23566. }
  23567. return this;
  23568. };
  23569. SplineCurve.prototype.toJSON = function () {
  23570. var data = Curve.prototype.toJSON.call(this);
  23571. data.points = [];
  23572. for (var i = 0, l = this.points.length; i < l; i++) {
  23573. var point = this.points[i];
  23574. data.points.push(point.toArray());
  23575. }
  23576. return data;
  23577. };
  23578. SplineCurve.prototype.fromJSON = function (json) {
  23579. Curve.prototype.fromJSON.call(this, json);
  23580. this.points = [];
  23581. for (var i = 0, l = json.points.length; i < l; i++) {
  23582. var point = json.points[i];
  23583. this.points.push(new Vector2().fromArray(point));
  23584. }
  23585. return this;
  23586. };
  23587. var Curves =
  23588. /*#__PURE__*/
  23589. Object.freeze({
  23590. ArcCurve: ArcCurve,
  23591. CatmullRomCurve3: CatmullRomCurve3,
  23592. CubicBezierCurve: CubicBezierCurve,
  23593. CubicBezierCurve3: CubicBezierCurve3,
  23594. EllipseCurve: EllipseCurve,
  23595. LineCurve: LineCurve,
  23596. LineCurve3: LineCurve3,
  23597. QuadraticBezierCurve: QuadraticBezierCurve,
  23598. QuadraticBezierCurve3: QuadraticBezierCurve3,
  23599. SplineCurve: SplineCurve
  23600. });
  23601. /**
  23602. * @author zz85 / http://www.lab4games.net/zz85/blog
  23603. *
  23604. **/
  23605. /**************************************************************
  23606. * Curved Path - a curve path is simply a array of connected
  23607. * curves, but retains the api of a curve
  23608. **************************************************************/
  23609. function CurvePath() {
  23610. Curve.call(this);
  23611. this.type = 'CurvePath';
  23612. this.curves = [];
  23613. this.autoClose = false; // Automatically closes the path
  23614. }
  23615. CurvePath.prototype = Object.assign(Object.create(Curve.prototype), {
  23616. constructor: CurvePath,
  23617. add: function (curve) {
  23618. this.curves.push(curve);
  23619. },
  23620. closePath: function () {
  23621. // Add a line curve if start and end of lines are not connected
  23622. var startPoint = this.curves[0].getPoint(0);
  23623. var endPoint = this.curves[this.curves.length - 1].getPoint(1);
  23624. if (!startPoint.equals(endPoint)) {
  23625. this.curves.push(new LineCurve(endPoint, startPoint));
  23626. }
  23627. },
  23628. // To get accurate point with reference to
  23629. // entire path distance at time t,
  23630. // following has to be done:
  23631. // 1. Length of each sub path have to be known
  23632. // 2. Locate and identify type of curve
  23633. // 3. Get t for the curve
  23634. // 4. Return curve.getPointAt(t')
  23635. getPoint: function (t) {
  23636. var d = t * this.getLength();
  23637. var curveLengths = this.getCurveLengths();
  23638. var i = 0; // To think about boundaries points.
  23639. while (i < curveLengths.length) {
  23640. if (curveLengths[i] >= d) {
  23641. var diff = curveLengths[i] - d;
  23642. var curve = this.curves[i];
  23643. var segmentLength = curve.getLength();
  23644. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  23645. return curve.getPointAt(u);
  23646. }
  23647. i++;
  23648. }
  23649. return null; // loop where sum != 0, sum > d , sum+1 <d
  23650. },
  23651. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  23652. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  23653. // getPoint() depends on getLength
  23654. getLength: function () {
  23655. var lens = this.getCurveLengths();
  23656. return lens[lens.length - 1];
  23657. },
  23658. // cacheLengths must be recalculated.
  23659. updateArcLengths: function () {
  23660. this.needsUpdate = true;
  23661. this.cacheLengths = null;
  23662. this.getCurveLengths();
  23663. },
  23664. // Compute lengths and cache them
  23665. // We cannot overwrite getLengths() because UtoT mapping uses it.
  23666. getCurveLengths: function () {
  23667. // We use cache values if curves and cache array are same length
  23668. if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
  23669. return this.cacheLengths;
  23670. } // Get length of sub-curve
  23671. // Push sums into cached array
  23672. var lengths = [],
  23673. sums = 0;
  23674. for (var i = 0, l = this.curves.length; i < l; i++) {
  23675. sums += this.curves[i].getLength();
  23676. lengths.push(sums);
  23677. }
  23678. this.cacheLengths = lengths;
  23679. return lengths;
  23680. },
  23681. getSpacedPoints: function (divisions) {
  23682. if (divisions === undefined) divisions = 40;
  23683. var points = [];
  23684. for (var i = 0; i <= divisions; i++) {
  23685. points.push(this.getPoint(i / divisions));
  23686. }
  23687. if (this.autoClose) {
  23688. points.push(points[0]);
  23689. }
  23690. return points;
  23691. },
  23692. getPoints: function (divisions) {
  23693. divisions = divisions || 12;
  23694. var points = [],
  23695. last;
  23696. for (var i = 0, curves = this.curves; i < curves.length; i++) {
  23697. var curve = curves[i];
  23698. var resolution = curve && curve.isEllipseCurve ? divisions * 2 : curve && (curve.isLineCurve || curve.isLineCurve3) ? 1 : curve && curve.isSplineCurve ? divisions * curve.points.length : divisions;
  23699. var pts = curve.getPoints(resolution);
  23700. for (var j = 0; j < pts.length; j++) {
  23701. var point = pts[j];
  23702. if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
  23703. points.push(point);
  23704. last = point;
  23705. }
  23706. }
  23707. if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
  23708. points.push(points[0]);
  23709. }
  23710. return points;
  23711. },
  23712. copy: function (source) {
  23713. Curve.prototype.copy.call(this, source);
  23714. this.curves = [];
  23715. for (var i = 0, l = source.curves.length; i < l; i++) {
  23716. var curve = source.curves[i];
  23717. this.curves.push(curve.clone());
  23718. }
  23719. this.autoClose = source.autoClose;
  23720. return this;
  23721. },
  23722. toJSON: function () {
  23723. var data = Curve.prototype.toJSON.call(this);
  23724. data.autoClose = this.autoClose;
  23725. data.curves = [];
  23726. for (var i = 0, l = this.curves.length; i < l; i++) {
  23727. var curve = this.curves[i];
  23728. data.curves.push(curve.toJSON());
  23729. }
  23730. return data;
  23731. },
  23732. fromJSON: function (json) {
  23733. Curve.prototype.fromJSON.call(this, json);
  23734. this.autoClose = json.autoClose;
  23735. this.curves = [];
  23736. for (var i = 0, l = json.curves.length; i < l; i++) {
  23737. var curve = json.curves[i];
  23738. this.curves.push(new Curves[curve.type]().fromJSON(curve));
  23739. }
  23740. return this;
  23741. }
  23742. });
  23743. /**
  23744. * @author zz85 / http://www.lab4games.net/zz85/blog
  23745. * Creates free form 2d path using series of points, lines or curves.
  23746. **/
  23747. function Path(points) {
  23748. CurvePath.call(this);
  23749. this.type = 'Path';
  23750. this.currentPoint = new Vector2();
  23751. if (points) {
  23752. this.setFromPoints(points);
  23753. }
  23754. }
  23755. Path.prototype = Object.assign(Object.create(CurvePath.prototype), {
  23756. constructor: Path,
  23757. setFromPoints: function (points) {
  23758. this.moveTo(points[0].x, points[0].y);
  23759. for (var i = 1, l = points.length; i < l; i++) {
  23760. this.lineTo(points[i].x, points[i].y);
  23761. }
  23762. },
  23763. moveTo: function (x, y) {
  23764. this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
  23765. },
  23766. lineTo: function (x, y) {
  23767. var curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
  23768. this.curves.push(curve);
  23769. this.currentPoint.set(x, y);
  23770. },
  23771. quadraticCurveTo: function (aCPx, aCPy, aX, aY) {
  23772. var curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
  23773. this.curves.push(curve);
  23774. this.currentPoint.set(aX, aY);
  23775. },
  23776. bezierCurveTo: function (aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  23777. var curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
  23778. this.curves.push(curve);
  23779. this.currentPoint.set(aX, aY);
  23780. },
  23781. splineThru: function (pts
  23782. /*Array of Vector*/
  23783. ) {
  23784. var npts = [this.currentPoint.clone()].concat(pts);
  23785. var curve = new SplineCurve(npts);
  23786. this.curves.push(curve);
  23787. this.currentPoint.copy(pts[pts.length - 1]);
  23788. },
  23789. arc: function (aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  23790. var x0 = this.currentPoint.x;
  23791. var y0 = this.currentPoint.y;
  23792. this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
  23793. },
  23794. absarc: function (aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  23795. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  23796. },
  23797. ellipse: function (aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  23798. var x0 = this.currentPoint.x;
  23799. var y0 = this.currentPoint.y;
  23800. this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  23801. },
  23802. absellipse: function (aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  23803. var curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  23804. if (this.curves.length > 0) {
  23805. // if a previous curve is present, attempt to join
  23806. var firstPoint = curve.getPoint(0);
  23807. if (!firstPoint.equals(this.currentPoint)) {
  23808. this.lineTo(firstPoint.x, firstPoint.y);
  23809. }
  23810. }
  23811. this.curves.push(curve);
  23812. var lastPoint = curve.getPoint(1);
  23813. this.currentPoint.copy(lastPoint);
  23814. },
  23815. copy: function (source) {
  23816. CurvePath.prototype.copy.call(this, source);
  23817. this.currentPoint.copy(source.currentPoint);
  23818. return this;
  23819. },
  23820. toJSON: function () {
  23821. var data = CurvePath.prototype.toJSON.call(this);
  23822. data.currentPoint = this.currentPoint.toArray();
  23823. return data;
  23824. },
  23825. fromJSON: function (json) {
  23826. CurvePath.prototype.fromJSON.call(this, json);
  23827. this.currentPoint.fromArray(json.currentPoint);
  23828. return this;
  23829. }
  23830. });
  23831. /**
  23832. * @author zz85 / http://www.lab4games.net/zz85/blog
  23833. * Defines a 2d shape plane using paths.
  23834. **/
  23835. // STEP 1 Create a path.
  23836. // STEP 2 Turn path into shape.
  23837. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  23838. // STEP 3a - Extract points from each shape, turn to vertices
  23839. // STEP 3b - Triangulate each shape, add faces.
  23840. function Shape(points) {
  23841. Path.call(this, points);
  23842. this.uuid = _Math.generateUUID();
  23843. this.type = 'Shape';
  23844. this.holes = [];
  23845. }
  23846. Shape.prototype = Object.assign(Object.create(Path.prototype), {
  23847. constructor: Shape,
  23848. getPointsHoles: function (divisions) {
  23849. var holesPts = [];
  23850. for (var i = 0, l = this.holes.length; i < l; i++) {
  23851. holesPts[i] = this.holes[i].getPoints(divisions);
  23852. }
  23853. return holesPts;
  23854. },
  23855. // get points of shape and holes (keypoints based on segments parameter)
  23856. extractPoints: function (divisions) {
  23857. return {
  23858. shape: this.getPoints(divisions),
  23859. holes: this.getPointsHoles(divisions)
  23860. };
  23861. },
  23862. copy: function (source) {
  23863. Path.prototype.copy.call(this, source);
  23864. this.holes = [];
  23865. for (var i = 0, l = source.holes.length; i < l; i++) {
  23866. var hole = source.holes[i];
  23867. this.holes.push(hole.clone());
  23868. }
  23869. return this;
  23870. },
  23871. toJSON: function () {
  23872. var data = Path.prototype.toJSON.call(this);
  23873. data.uuid = this.uuid;
  23874. data.holes = [];
  23875. for (var i = 0, l = this.holes.length; i < l; i++) {
  23876. var hole = this.holes[i];
  23877. data.holes.push(hole.toJSON());
  23878. }
  23879. return data;
  23880. },
  23881. fromJSON: function (json) {
  23882. Path.prototype.fromJSON.call(this, json);
  23883. this.uuid = json.uuid;
  23884. this.holes = [];
  23885. for (var i = 0, l = json.holes.length; i < l; i++) {
  23886. var hole = json.holes[i];
  23887. this.holes.push(new Path().fromJSON(hole));
  23888. }
  23889. return this;
  23890. }
  23891. });
  23892. /**
  23893. * @author mrdoob / http://mrdoob.com/
  23894. * @author alteredq / http://alteredqualia.com/
  23895. */
  23896. function Light(color, intensity) {
  23897. Object3D.call(this);
  23898. this.type = 'Light';
  23899. this.color = new Color(color);
  23900. this.intensity = intensity !== undefined ? intensity : 1;
  23901. this.receiveShadow = undefined;
  23902. }
  23903. Light.prototype = Object.assign(Object.create(Object3D.prototype), {
  23904. constructor: Light,
  23905. isLight: true,
  23906. copy: function (source) {
  23907. Object3D.prototype.copy.call(this, source);
  23908. this.color.copy(source.color);
  23909. this.intensity = source.intensity;
  23910. return this;
  23911. },
  23912. toJSON: function (meta) {
  23913. var data = Object3D.prototype.toJSON.call(this, meta);
  23914. data.object.color = this.color.getHex();
  23915. data.object.intensity = this.intensity;
  23916. if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
  23917. if (this.distance !== undefined) data.object.distance = this.distance;
  23918. if (this.angle !== undefined) data.object.angle = this.angle;
  23919. if (this.decay !== undefined) data.object.decay = this.decay;
  23920. if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
  23921. if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
  23922. return data;
  23923. }
  23924. });
  23925. /**
  23926. * @author alteredq / http://alteredqualia.com/
  23927. */
  23928. function HemisphereLight(skyColor, groundColor, intensity) {
  23929. Light.call(this, skyColor, intensity);
  23930. this.type = 'HemisphereLight';
  23931. this.castShadow = undefined;
  23932. this.position.copy(Object3D.DefaultUp);
  23933. this.updateMatrix();
  23934. this.groundColor = new Color(groundColor);
  23935. }
  23936. HemisphereLight.prototype = Object.assign(Object.create(Light.prototype), {
  23937. constructor: HemisphereLight,
  23938. isHemisphereLight: true,
  23939. copy: function (source) {
  23940. Light.prototype.copy.call(this, source);
  23941. this.groundColor.copy(source.groundColor);
  23942. return this;
  23943. }
  23944. });
  23945. /**
  23946. * @author mrdoob / http://mrdoob.com/
  23947. */
  23948. function LightShadow(camera) {
  23949. this.camera = camera;
  23950. this.bias = 0;
  23951. this.radius = 1;
  23952. this.mapSize = new Vector2(512, 512);
  23953. this.map = null;
  23954. this.mapPass = null;
  23955. this.matrix = new Matrix4();
  23956. this._frustum = new Frustum();
  23957. this._frameExtents = new Vector2(1, 1);
  23958. this._viewportCount = 1;
  23959. this._viewports = [new Vector4(0, 0, 1, 1)];
  23960. }
  23961. Object.assign(LightShadow.prototype, {
  23962. _projScreenMatrix: new Matrix4(),
  23963. _lightPositionWorld: new Vector3(),
  23964. _lookTarget: new Vector3(),
  23965. getViewportCount: function () {
  23966. return this._viewportCount;
  23967. },
  23968. getFrustum: function () {
  23969. return this._frustum;
  23970. },
  23971. updateMatrices: function (light) {
  23972. var shadowCamera = this.camera,
  23973. shadowMatrix = this.matrix,
  23974. projScreenMatrix = this._projScreenMatrix,
  23975. lookTarget = this._lookTarget,
  23976. lightPositionWorld = this._lightPositionWorld;
  23977. lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  23978. shadowCamera.position.copy(lightPositionWorld);
  23979. lookTarget.setFromMatrixPosition(light.target.matrixWorld);
  23980. shadowCamera.lookAt(lookTarget);
  23981. shadowCamera.updateMatrixWorld();
  23982. projScreenMatrix.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
  23983. this._frustum.setFromMatrix(projScreenMatrix);
  23984. shadowMatrix.set(0.5, 0.0, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0);
  23985. shadowMatrix.multiply(shadowCamera.projectionMatrix);
  23986. shadowMatrix.multiply(shadowCamera.matrixWorldInverse);
  23987. },
  23988. getViewport: function (viewportIndex) {
  23989. return this._viewports[viewportIndex];
  23990. },
  23991. getFrameExtents: function () {
  23992. return this._frameExtents;
  23993. },
  23994. copy: function (source) {
  23995. this.camera = source.camera.clone();
  23996. this.bias = source.bias;
  23997. this.radius = source.radius;
  23998. this.mapSize.copy(source.mapSize);
  23999. return this;
  24000. },
  24001. clone: function () {
  24002. return new this.constructor().copy(this);
  24003. },
  24004. toJSON: function () {
  24005. var object = {};
  24006. if (this.bias !== 0) object.bias = this.bias;
  24007. if (this.radius !== 1) object.radius = this.radius;
  24008. if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
  24009. object.camera = this.camera.toJSON(false).object;
  24010. delete object.camera.matrix;
  24011. return object;
  24012. }
  24013. });
  24014. /**
  24015. * @author mrdoob / http://mrdoob.com/
  24016. */
  24017. function SpotLightShadow() {
  24018. LightShadow.call(this, new PerspectiveCamera(50, 1, 0.5, 500));
  24019. }
  24020. SpotLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  24021. constructor: SpotLightShadow,
  24022. isSpotLightShadow: true,
  24023. updateMatrices: function (light, viewCamera, viewportIndex) {
  24024. var camera = this.camera;
  24025. var fov = _Math.RAD2DEG * 2 * light.angle;
  24026. var aspect = this.mapSize.width / this.mapSize.height;
  24027. var far = light.distance || camera.far;
  24028. if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
  24029. camera.fov = fov;
  24030. camera.aspect = aspect;
  24031. camera.far = far;
  24032. camera.updateProjectionMatrix();
  24033. }
  24034. LightShadow.prototype.updateMatrices.call(this, light, viewCamera, viewportIndex);
  24035. }
  24036. });
  24037. /**
  24038. * @author alteredq / http://alteredqualia.com/
  24039. */
  24040. function SpotLight(color, intensity, distance, angle, penumbra, decay) {
  24041. Light.call(this, color, intensity);
  24042. this.type = 'SpotLight';
  24043. this.position.copy(Object3D.DefaultUp);
  24044. this.updateMatrix();
  24045. this.target = new Object3D();
  24046. Object.defineProperty(this, 'power', {
  24047. get: function () {
  24048. // intensity = power per solid angle.
  24049. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24050. return this.intensity * Math.PI;
  24051. },
  24052. set: function (power) {
  24053. // intensity = power per solid angle.
  24054. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24055. this.intensity = power / Math.PI;
  24056. }
  24057. });
  24058. this.distance = distance !== undefined ? distance : 0;
  24059. this.angle = angle !== undefined ? angle : Math.PI / 3;
  24060. this.penumbra = penumbra !== undefined ? penumbra : 0;
  24061. this.decay = decay !== undefined ? decay : 1; // for physically correct lights, should be 2.
  24062. this.shadow = new SpotLightShadow();
  24063. }
  24064. SpotLight.prototype = Object.assign(Object.create(Light.prototype), {
  24065. constructor: SpotLight,
  24066. isSpotLight: true,
  24067. copy: function (source) {
  24068. Light.prototype.copy.call(this, source);
  24069. this.distance = source.distance;
  24070. this.angle = source.angle;
  24071. this.penumbra = source.penumbra;
  24072. this.decay = source.decay;
  24073. this.target = source.target.clone();
  24074. this.shadow = source.shadow.clone();
  24075. return this;
  24076. }
  24077. });
  24078. function PointLightShadow() {
  24079. LightShadow.call(this, new PerspectiveCamera(90, 1, 0.5, 500));
  24080. this._frameExtents = new Vector2(4, 2);
  24081. this._viewportCount = 6;
  24082. this._viewports = [// These viewports map a cube-map onto a 2D texture with the
  24083. // following orientation:
  24084. //
  24085. // xzXZ
  24086. // y Y
  24087. //
  24088. // X - Positive x direction
  24089. // x - Negative x direction
  24090. // Y - Positive y direction
  24091. // y - Negative y direction
  24092. // Z - Positive z direction
  24093. // z - Negative z direction
  24094. // positive X
  24095. new Vector4(2, 1, 1, 1), // negative X
  24096. new Vector4(0, 1, 1, 1), // positive Z
  24097. new Vector4(3, 1, 1, 1), // negative Z
  24098. new Vector4(1, 1, 1, 1), // positive Y
  24099. new Vector4(3, 0, 1, 1), // negative Y
  24100. new Vector4(1, 0, 1, 1)];
  24101. this._cubeDirections = [new Vector3(1, 0, 0), new Vector3(-1, 0, 0), new Vector3(0, 0, 1), new Vector3(0, 0, -1), new Vector3(0, 1, 0), new Vector3(0, -1, 0)];
  24102. this._cubeUps = [new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 0, 1), new Vector3(0, 0, -1)];
  24103. }
  24104. PointLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  24105. constructor: PointLightShadow,
  24106. isPointLightShadow: true,
  24107. updateMatrices: function (light, viewCamera, viewportIndex) {
  24108. var camera = this.camera,
  24109. shadowMatrix = this.matrix,
  24110. lightPositionWorld = this._lightPositionWorld,
  24111. lookTarget = this._lookTarget,
  24112. projScreenMatrix = this._projScreenMatrix;
  24113. lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  24114. camera.position.copy(lightPositionWorld);
  24115. lookTarget.copy(camera.position);
  24116. lookTarget.add(this._cubeDirections[viewportIndex]);
  24117. camera.up.copy(this._cubeUps[viewportIndex]);
  24118. camera.lookAt(lookTarget);
  24119. camera.updateMatrixWorld();
  24120. shadowMatrix.makeTranslation(-lightPositionWorld.x, -lightPositionWorld.y, -lightPositionWorld.z);
  24121. projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  24122. this._frustum.setFromMatrix(projScreenMatrix);
  24123. }
  24124. });
  24125. /**
  24126. * @author mrdoob / http://mrdoob.com/
  24127. */
  24128. function PointLight(color, intensity, distance, decay) {
  24129. Light.call(this, color, intensity);
  24130. this.type = 'PointLight';
  24131. Object.defineProperty(this, 'power', {
  24132. get: function () {
  24133. // intensity = power per solid angle.
  24134. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24135. return this.intensity * 4 * Math.PI;
  24136. },
  24137. set: function (power) {
  24138. // intensity = power per solid angle.
  24139. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24140. this.intensity = power / (4 * Math.PI);
  24141. }
  24142. });
  24143. this.distance = distance !== undefined ? distance : 0;
  24144. this.decay = decay !== undefined ? decay : 1; // for physically correct lights, should be 2.
  24145. this.shadow = new PointLightShadow();
  24146. }
  24147. PointLight.prototype = Object.assign(Object.create(Light.prototype), {
  24148. constructor: PointLight,
  24149. isPointLight: true,
  24150. copy: function (source) {
  24151. Light.prototype.copy.call(this, source);
  24152. this.distance = source.distance;
  24153. this.decay = source.decay;
  24154. this.shadow = source.shadow.clone();
  24155. return this;
  24156. }
  24157. });
  24158. /**
  24159. * @author alteredq / http://alteredqualia.com/
  24160. * @author arose / http://github.com/arose
  24161. */
  24162. function OrthographicCamera(left, right, top, bottom, near, far) {
  24163. Camera.call(this);
  24164. this.type = 'OrthographicCamera';
  24165. this.zoom = 1;
  24166. this.view = null;
  24167. this.left = left !== undefined ? left : -1;
  24168. this.right = right !== undefined ? right : 1;
  24169. this.top = top !== undefined ? top : 1;
  24170. this.bottom = bottom !== undefined ? bottom : -1;
  24171. this.near = near !== undefined ? near : 0.1;
  24172. this.far = far !== undefined ? far : 2000;
  24173. this.updateProjectionMatrix();
  24174. }
  24175. OrthographicCamera.prototype = Object.assign(Object.create(Camera.prototype), {
  24176. constructor: OrthographicCamera,
  24177. isOrthographicCamera: true,
  24178. copy: function (source, recursive) {
  24179. Camera.prototype.copy.call(this, source, recursive);
  24180. this.left = source.left;
  24181. this.right = source.right;
  24182. this.top = source.top;
  24183. this.bottom = source.bottom;
  24184. this.near = source.near;
  24185. this.far = source.far;
  24186. this.zoom = source.zoom;
  24187. this.view = source.view === null ? null : Object.assign({}, source.view);
  24188. return this;
  24189. },
  24190. setViewOffset: function (fullWidth, fullHeight, x, y, width, height) {
  24191. if (this.view === null) {
  24192. this.view = {
  24193. enabled: true,
  24194. fullWidth: 1,
  24195. fullHeight: 1,
  24196. offsetX: 0,
  24197. offsetY: 0,
  24198. width: 1,
  24199. height: 1
  24200. };
  24201. }
  24202. this.view.enabled = true;
  24203. this.view.fullWidth = fullWidth;
  24204. this.view.fullHeight = fullHeight;
  24205. this.view.offsetX = x;
  24206. this.view.offsetY = y;
  24207. this.view.width = width;
  24208. this.view.height = height;
  24209. this.updateProjectionMatrix();
  24210. },
  24211. clearViewOffset: function () {
  24212. if (this.view !== null) {
  24213. this.view.enabled = false;
  24214. }
  24215. this.updateProjectionMatrix();
  24216. },
  24217. updateProjectionMatrix: function () {
  24218. var dx = (this.right - this.left) / (2 * this.zoom);
  24219. var dy = (this.top - this.bottom) / (2 * this.zoom);
  24220. var cx = (this.right + this.left) / 2;
  24221. var cy = (this.top + this.bottom) / 2;
  24222. var left = cx - dx;
  24223. var right = cx + dx;
  24224. var top = cy + dy;
  24225. var bottom = cy - dy;
  24226. if (this.view !== null && this.view.enabled) {
  24227. var zoomW = this.zoom / (this.view.width / this.view.fullWidth);
  24228. var zoomH = this.zoom / (this.view.height / this.view.fullHeight);
  24229. var scaleW = (this.right - this.left) / this.view.width;
  24230. var scaleH = (this.top - this.bottom) / this.view.height;
  24231. left += scaleW * (this.view.offsetX / zoomW);
  24232. right = left + scaleW * (this.view.width / zoomW);
  24233. top -= scaleH * (this.view.offsetY / zoomH);
  24234. bottom = top - scaleH * (this.view.height / zoomH);
  24235. }
  24236. this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
  24237. this.projectionMatrixInverse.getInverse(this.projectionMatrix);
  24238. },
  24239. toJSON: function (meta) {
  24240. var data = Object3D.prototype.toJSON.call(this, meta);
  24241. data.object.zoom = this.zoom;
  24242. data.object.left = this.left;
  24243. data.object.right = this.right;
  24244. data.object.top = this.top;
  24245. data.object.bottom = this.bottom;
  24246. data.object.near = this.near;
  24247. data.object.far = this.far;
  24248. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  24249. return data;
  24250. }
  24251. });
  24252. /**
  24253. * @author mrdoob / http://mrdoob.com/
  24254. */
  24255. function DirectionalLightShadow() {
  24256. LightShadow.call(this, new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
  24257. }
  24258. DirectionalLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  24259. constructor: DirectionalLightShadow,
  24260. isDirectionalLightShadow: true,
  24261. updateMatrices: function (light, viewCamera, viewportIndex) {
  24262. LightShadow.prototype.updateMatrices.call(this, light, viewCamera, viewportIndex);
  24263. }
  24264. });
  24265. /**
  24266. * @author mrdoob / http://mrdoob.com/
  24267. * @author alteredq / http://alteredqualia.com/
  24268. */
  24269. function DirectionalLight(color, intensity) {
  24270. Light.call(this, color, intensity);
  24271. this.type = 'DirectionalLight';
  24272. this.position.copy(Object3D.DefaultUp);
  24273. this.updateMatrix();
  24274. this.target = new Object3D();
  24275. this.shadow = new DirectionalLightShadow();
  24276. }
  24277. DirectionalLight.prototype = Object.assign(Object.create(Light.prototype), {
  24278. constructor: DirectionalLight,
  24279. isDirectionalLight: true,
  24280. copy: function (source) {
  24281. Light.prototype.copy.call(this, source);
  24282. this.target = source.target.clone();
  24283. this.shadow = source.shadow.clone();
  24284. return this;
  24285. }
  24286. });
  24287. /**
  24288. * @author mrdoob / http://mrdoob.com/
  24289. */
  24290. function AmbientLight(color, intensity) {
  24291. Light.call(this, color, intensity);
  24292. this.type = 'AmbientLight';
  24293. this.castShadow = undefined;
  24294. }
  24295. AmbientLight.prototype = Object.assign(Object.create(Light.prototype), {
  24296. constructor: AmbientLight,
  24297. isAmbientLight: true
  24298. });
  24299. /**
  24300. * @author abelnation / http://github.com/abelnation
  24301. */
  24302. function RectAreaLight(color, intensity, width, height) {
  24303. Light.call(this, color, intensity);
  24304. this.type = 'RectAreaLight';
  24305. this.width = width !== undefined ? width : 10;
  24306. this.height = height !== undefined ? height : 10;
  24307. }
  24308. RectAreaLight.prototype = Object.assign(Object.create(Light.prototype), {
  24309. constructor: RectAreaLight,
  24310. isRectAreaLight: true,
  24311. copy: function (source) {
  24312. Light.prototype.copy.call(this, source);
  24313. this.width = source.width;
  24314. this.height = source.height;
  24315. return this;
  24316. },
  24317. toJSON: function (meta) {
  24318. var data = Light.prototype.toJSON.call(this, meta);
  24319. data.object.width = this.width;
  24320. data.object.height = this.height;
  24321. return data;
  24322. }
  24323. });
  24324. /**
  24325. * @author mrdoob / http://mrdoob.com/
  24326. */
  24327. function MaterialLoader(manager) {
  24328. Loader.call(this, manager);
  24329. this.textures = {};
  24330. }
  24331. MaterialLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  24332. constructor: MaterialLoader,
  24333. load: function (url, onLoad, onProgress, onError) {
  24334. var scope = this;
  24335. var loader = new FileLoader(scope.manager);
  24336. loader.setPath(scope.path);
  24337. loader.load(url, function (text) {
  24338. onLoad(scope.parse(JSON.parse(text)));
  24339. }, onProgress, onError);
  24340. },
  24341. parse: function (json) {
  24342. var textures = this.textures;
  24343. function getTexture(name) {
  24344. if (textures[name] === undefined) {
  24345. console.warn('THREE.MaterialLoader: Undefined texture', name);
  24346. }
  24347. return textures[name];
  24348. }
  24349. var material = new Materials[json.type]();
  24350. if (json.uuid !== undefined) material.uuid = json.uuid;
  24351. if (json.name !== undefined) material.name = json.name;
  24352. if (json.color !== undefined) material.color.setHex(json.color);
  24353. if (json.roughness !== undefined) material.roughness = json.roughness;
  24354. if (json.metalness !== undefined) material.metalness = json.metalness;
  24355. if (json.sheen !== undefined) material.sheen = new Color().setHex(json.sheen);
  24356. if (json.emissive !== undefined) material.emissive.setHex(json.emissive);
  24357. if (json.specular !== undefined) material.specular.setHex(json.specular);
  24358. if (json.shininess !== undefined) material.shininess = json.shininess;
  24359. if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
  24360. if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
  24361. if (json.vertexColors !== undefined) material.vertexColors = json.vertexColors;
  24362. if (json.fog !== undefined) material.fog = json.fog;
  24363. if (json.flatShading !== undefined) material.flatShading = json.flatShading;
  24364. if (json.blending !== undefined) material.blending = json.blending;
  24365. if (json.combine !== undefined) material.combine = json.combine;
  24366. if (json.side !== undefined) material.side = json.side;
  24367. if (json.opacity !== undefined) material.opacity = json.opacity;
  24368. if (json.transparent !== undefined) material.transparent = json.transparent;
  24369. if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
  24370. if (json.depthTest !== undefined) material.depthTest = json.depthTest;
  24371. if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
  24372. if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
  24373. if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
  24374. if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
  24375. if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
  24376. if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
  24377. if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
  24378. if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
  24379. if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
  24380. if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
  24381. if (json.wireframe !== undefined) material.wireframe = json.wireframe;
  24382. if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
  24383. if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
  24384. if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
  24385. if (json.rotation !== undefined) material.rotation = json.rotation;
  24386. if (json.linewidth !== 1) material.linewidth = json.linewidth;
  24387. if (json.dashSize !== undefined) material.dashSize = json.dashSize;
  24388. if (json.gapSize !== undefined) material.gapSize = json.gapSize;
  24389. if (json.scale !== undefined) material.scale = json.scale;
  24390. if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
  24391. if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
  24392. if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
  24393. if (json.skinning !== undefined) material.skinning = json.skinning;
  24394. if (json.morphTargets !== undefined) material.morphTargets = json.morphTargets;
  24395. if (json.morphNormals !== undefined) material.morphNormals = json.morphNormals;
  24396. if (json.dithering !== undefined) material.dithering = json.dithering;
  24397. if (json.visible !== undefined) material.visible = json.visible;
  24398. if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
  24399. if (json.userData !== undefined) material.userData = json.userData; // Shader Material
  24400. if (json.uniforms !== undefined) {
  24401. for (var name in json.uniforms) {
  24402. var uniform = json.uniforms[name];
  24403. material.uniforms[name] = {};
  24404. switch (uniform.type) {
  24405. case 't':
  24406. material.uniforms[name].value = getTexture(uniform.value);
  24407. break;
  24408. case 'c':
  24409. material.uniforms[name].value = new Color().setHex(uniform.value);
  24410. break;
  24411. case 'v2':
  24412. material.uniforms[name].value = new Vector2().fromArray(uniform.value);
  24413. break;
  24414. case 'v3':
  24415. material.uniforms[name].value = new Vector3().fromArray(uniform.value);
  24416. break;
  24417. case 'v4':
  24418. material.uniforms[name].value = new Vector4().fromArray(uniform.value);
  24419. break;
  24420. case 'm3':
  24421. material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
  24422. case 'm4':
  24423. material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
  24424. break;
  24425. default:
  24426. material.uniforms[name].value = uniform.value;
  24427. }
  24428. }
  24429. }
  24430. if (json.defines !== undefined) material.defines = json.defines;
  24431. if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
  24432. if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
  24433. if (json.extensions !== undefined) {
  24434. for (var key in json.extensions) {
  24435. material.extensions[key] = json.extensions[key];
  24436. }
  24437. } // Deprecated
  24438. if (json.shading !== undefined) material.flatShading = json.shading === 1; // THREE.FlatShading
  24439. // for PointsMaterial
  24440. if (json.size !== undefined) material.size = json.size;
  24441. if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
  24442. if (json.map !== undefined) material.map = getTexture(json.map);
  24443. if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
  24444. if (json.alphaMap !== undefined) {
  24445. material.alphaMap = getTexture(json.alphaMap);
  24446. material.transparent = true;
  24447. }
  24448. if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
  24449. if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
  24450. if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
  24451. if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
  24452. if (json.normalScale !== undefined) {
  24453. var normalScale = json.normalScale;
  24454. if (Array.isArray(normalScale) === false) {
  24455. // Blender exporter used to export a scalar. See #7459
  24456. normalScale = [normalScale, normalScale];
  24457. }
  24458. material.normalScale = new Vector2().fromArray(normalScale);
  24459. }
  24460. if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
  24461. if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
  24462. if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
  24463. if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
  24464. if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
  24465. if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
  24466. if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
  24467. if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
  24468. if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
  24469. if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
  24470. if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
  24471. if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
  24472. if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
  24473. if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
  24474. if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
  24475. if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
  24476. if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
  24477. if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
  24478. if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
  24479. return material;
  24480. },
  24481. setTextures: function (value) {
  24482. this.textures = value;
  24483. return this;
  24484. }
  24485. });
  24486. /**
  24487. * @author Don McCurdy / https://www.donmccurdy.com
  24488. */
  24489. var LoaderUtils = {
  24490. decodeText: function (array) {
  24491. if (typeof TextDecoder !== 'undefined') {
  24492. return new TextDecoder().decode(array);
  24493. } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  24494. // throws a "maximum call stack size exceeded" error for large arrays.
  24495. var s = '';
  24496. for (var i = 0, il = array.length; i < il; i++) {
  24497. // Implicitly assumes little-endian.
  24498. s += String.fromCharCode(array[i]);
  24499. }
  24500. try {
  24501. // merges multi-byte utf-8 characters.
  24502. return decodeURIComponent(escape(s));
  24503. } catch (e) {
  24504. // see #16358
  24505. return s;
  24506. }
  24507. },
  24508. extractUrlBase: function (url) {
  24509. var index = url.lastIndexOf('/');
  24510. if (index === -1) return './';
  24511. return url.substr(0, index + 1);
  24512. }
  24513. };
  24514. /**
  24515. * @author benaadams / https://twitter.com/ben_a_adams
  24516. */
  24517. exports.LoaderUtils = LoaderUtils;
  24518. function InstancedBufferGeometry() {
  24519. BufferGeometry.call(this);
  24520. this.type = 'InstancedBufferGeometry';
  24521. this.maxInstancedCount = undefined;
  24522. }
  24523. InstancedBufferGeometry.prototype = Object.assign(Object.create(BufferGeometry.prototype), {
  24524. constructor: InstancedBufferGeometry,
  24525. isInstancedBufferGeometry: true,
  24526. copy: function (source) {
  24527. BufferGeometry.prototype.copy.call(this, source);
  24528. this.maxInstancedCount = source.maxInstancedCount;
  24529. return this;
  24530. },
  24531. clone: function () {
  24532. return new this.constructor().copy(this);
  24533. },
  24534. toJSON: function () {
  24535. var data = BufferGeometry.prototype.toJSON.call(this);
  24536. data.maxInstancedCount = this.maxInstancedCount;
  24537. data.isInstancedBufferGeometry = true;
  24538. return data;
  24539. }
  24540. });
  24541. /**
  24542. * @author benaadams / https://twitter.com/ben_a_adams
  24543. */
  24544. function InstancedBufferAttribute(array, itemSize, normalized, meshPerAttribute) {
  24545. if (typeof normalized === 'number') {
  24546. meshPerAttribute = normalized;
  24547. normalized = false;
  24548. console.error('THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.');
  24549. }
  24550. BufferAttribute.call(this, array, itemSize, normalized);
  24551. this.meshPerAttribute = meshPerAttribute || 1;
  24552. }
  24553. InstancedBufferAttribute.prototype = Object.assign(Object.create(BufferAttribute.prototype), {
  24554. constructor: InstancedBufferAttribute,
  24555. isInstancedBufferAttribute: true,
  24556. copy: function (source) {
  24557. BufferAttribute.prototype.copy.call(this, source);
  24558. this.meshPerAttribute = source.meshPerAttribute;
  24559. return this;
  24560. },
  24561. toJSON: function () {
  24562. var data = BufferAttribute.prototype.toJSON.call(this);
  24563. data.meshPerAttribute = this.meshPerAttribute;
  24564. data.isInstancedBufferAttribute = true;
  24565. return data;
  24566. }
  24567. });
  24568. /**
  24569. * @author mrdoob / http://mrdoob.com/
  24570. */
  24571. function BufferGeometryLoader(manager) {
  24572. Loader.call(this, manager);
  24573. }
  24574. BufferGeometryLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  24575. constructor: BufferGeometryLoader,
  24576. load: function (url, onLoad, onProgress, onError) {
  24577. var scope = this;
  24578. var loader = new FileLoader(scope.manager);
  24579. loader.setPath(scope.path);
  24580. loader.load(url, function (text) {
  24581. onLoad(scope.parse(JSON.parse(text)));
  24582. }, onProgress, onError);
  24583. },
  24584. parse: function (json) {
  24585. var geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  24586. var index = json.data.index;
  24587. if (index !== undefined) {
  24588. var typedArray = new TYPED_ARRAYS[index.type](index.array);
  24589. geometry.setIndex(new BufferAttribute(typedArray, 1));
  24590. }
  24591. var attributes = json.data.attributes;
  24592. for (var key in attributes) {
  24593. var attribute = attributes[key];
  24594. var typedArray = new TYPED_ARRAYS[attribute.type](attribute.array);
  24595. var bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  24596. var bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized);
  24597. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  24598. geometry.addAttribute(key, bufferAttribute);
  24599. }
  24600. var morphAttributes = json.data.morphAttributes;
  24601. if (morphAttributes) {
  24602. for (var key in morphAttributes) {
  24603. var attributeArray = morphAttributes[key];
  24604. var array = [];
  24605. for (var i = 0, il = attributeArray.length; i < il; i++) {
  24606. var attribute = attributeArray[i];
  24607. var typedArray = new TYPED_ARRAYS[attribute.type](attribute.array);
  24608. var bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized);
  24609. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  24610. array.push(bufferAttribute);
  24611. }
  24612. geometry.morphAttributes[key] = array;
  24613. }
  24614. }
  24615. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  24616. if (groups !== undefined) {
  24617. for (var i = 0, n = groups.length; i !== n; ++i) {
  24618. var group = groups[i];
  24619. geometry.addGroup(group.start, group.count, group.materialIndex);
  24620. }
  24621. }
  24622. var boundingSphere = json.data.boundingSphere;
  24623. if (boundingSphere !== undefined) {
  24624. var center = new Vector3();
  24625. if (boundingSphere.center !== undefined) {
  24626. center.fromArray(boundingSphere.center);
  24627. }
  24628. geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
  24629. }
  24630. if (json.name) geometry.name = json.name;
  24631. if (json.userData) geometry.userData = json.userData;
  24632. return geometry;
  24633. }
  24634. });
  24635. var TYPED_ARRAYS = {
  24636. Int8Array: Int8Array,
  24637. Uint8Array: Uint8Array,
  24638. // Workaround for IE11 pre KB2929437. See #11440
  24639. Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
  24640. Int16Array: Int16Array,
  24641. Uint16Array: Uint16Array,
  24642. Int32Array: Int32Array,
  24643. Uint32Array: Uint32Array,
  24644. Float32Array: Float32Array,
  24645. Float64Array: Float64Array
  24646. };
  24647. /**
  24648. * @author mrdoob / http://mrdoob.com/
  24649. */
  24650. function ObjectLoader(manager) {
  24651. Loader.call(this, manager);
  24652. }
  24653. ObjectLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  24654. constructor: ObjectLoader,
  24655. load: function (url, onLoad, onProgress, onError) {
  24656. var scope = this;
  24657. var path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  24658. this.resourcePath = this.resourcePath || path;
  24659. var loader = new FileLoader(scope.manager);
  24660. loader.setPath(this.path);
  24661. loader.load(url, function (text) {
  24662. var json = null;
  24663. try {
  24664. json = JSON.parse(text);
  24665. } catch (error) {
  24666. if (onError !== undefined) onError(error);
  24667. console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
  24668. return;
  24669. }
  24670. var metadata = json.metadata;
  24671. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  24672. console.error('THREE.ObjectLoader: Can\'t load ' + url);
  24673. return;
  24674. }
  24675. scope.parse(json, onLoad);
  24676. }, onProgress, onError);
  24677. },
  24678. parse: function (json, onLoad) {
  24679. var shapes = this.parseShape(json.shapes);
  24680. var geometries = this.parseGeometries(json.geometries, shapes);
  24681. var images = this.parseImages(json.images, function () {
  24682. if (onLoad !== undefined) onLoad(object);
  24683. });
  24684. var textures = this.parseTextures(json.textures, images);
  24685. var materials = this.parseMaterials(json.materials, textures);
  24686. var object = this.parseObject(json.object, geometries, materials);
  24687. if (json.animations) {
  24688. object.animations = this.parseAnimations(json.animations);
  24689. }
  24690. if (json.images === undefined || json.images.length === 0) {
  24691. if (onLoad !== undefined) onLoad(object);
  24692. }
  24693. return object;
  24694. },
  24695. parseShape: function (json) {
  24696. var shapes = {};
  24697. if (json !== undefined) {
  24698. for (var i = 0, l = json.length; i < l; i++) {
  24699. var shape = new Shape().fromJSON(json[i]);
  24700. shapes[shape.uuid] = shape;
  24701. }
  24702. }
  24703. return shapes;
  24704. },
  24705. parseGeometries: function (json, shapes) {
  24706. var geometries = {};
  24707. if (json !== undefined) {
  24708. var bufferGeometryLoader = new BufferGeometryLoader();
  24709. for (var i = 0, l = json.length; i < l; i++) {
  24710. var geometry;
  24711. var data = json[i];
  24712. switch (data.type) {
  24713. case 'PlaneGeometry':
  24714. case 'PlaneBufferGeometry':
  24715. geometry = new Geometries[data.type](data.width, data.height, data.widthSegments, data.heightSegments);
  24716. break;
  24717. case 'BoxGeometry':
  24718. case 'BoxBufferGeometry':
  24719. case 'CubeGeometry':
  24720. // backwards compatible
  24721. geometry = new Geometries[data.type](data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  24722. break;
  24723. case 'CircleGeometry':
  24724. case 'CircleBufferGeometry':
  24725. geometry = new Geometries[data.type](data.radius, data.segments, data.thetaStart, data.thetaLength);
  24726. break;
  24727. case 'CylinderGeometry':
  24728. case 'CylinderBufferGeometry':
  24729. geometry = new Geometries[data.type](data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  24730. break;
  24731. case 'ConeGeometry':
  24732. case 'ConeBufferGeometry':
  24733. geometry = new Geometries[data.type](data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  24734. break;
  24735. case 'SphereGeometry':
  24736. case 'SphereBufferGeometry':
  24737. geometry = new Geometries[data.type](data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
  24738. break;
  24739. case 'DodecahedronGeometry':
  24740. case 'DodecahedronBufferGeometry':
  24741. case 'IcosahedronGeometry':
  24742. case 'IcosahedronBufferGeometry':
  24743. case 'OctahedronGeometry':
  24744. case 'OctahedronBufferGeometry':
  24745. case 'TetrahedronGeometry':
  24746. case 'TetrahedronBufferGeometry':
  24747. geometry = new Geometries[data.type](data.radius, data.detail);
  24748. break;
  24749. case 'RingGeometry':
  24750. case 'RingBufferGeometry':
  24751. geometry = new Geometries[data.type](data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
  24752. break;
  24753. case 'TorusGeometry':
  24754. case 'TorusBufferGeometry':
  24755. geometry = new Geometries[data.type](data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
  24756. break;
  24757. case 'TorusKnotGeometry':
  24758. case 'TorusKnotBufferGeometry':
  24759. geometry = new Geometries[data.type](data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
  24760. break;
  24761. case 'TubeGeometry':
  24762. case 'TubeBufferGeometry':
  24763. // This only works for built-in curves (e.g. CatmullRomCurve3).
  24764. // User defined curves or instances of CurvePath will not be deserialized.
  24765. geometry = new Geometries[data.type](new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
  24766. break;
  24767. case 'LatheGeometry':
  24768. case 'LatheBufferGeometry':
  24769. geometry = new Geometries[data.type](data.points, data.segments, data.phiStart, data.phiLength);
  24770. break;
  24771. case 'PolyhedronGeometry':
  24772. case 'PolyhedronBufferGeometry':
  24773. geometry = new Geometries[data.type](data.vertices, data.indices, data.radius, data.details);
  24774. break;
  24775. case 'ShapeGeometry':
  24776. case 'ShapeBufferGeometry':
  24777. var geometryShapes = [];
  24778. for (var j = 0, jl = data.shapes.length; j < jl; j++) {
  24779. var shape = shapes[data.shapes[j]];
  24780. geometryShapes.push(shape);
  24781. }
  24782. geometry = new Geometries[data.type](geometryShapes, data.curveSegments);
  24783. break;
  24784. case 'ExtrudeGeometry':
  24785. case 'ExtrudeBufferGeometry':
  24786. var geometryShapes = [];
  24787. for (var j = 0, jl = data.shapes.length; j < jl; j++) {
  24788. var shape = shapes[data.shapes[j]];
  24789. geometryShapes.push(shape);
  24790. }
  24791. var extrudePath = data.options.extrudePath;
  24792. if (extrudePath !== undefined) {
  24793. data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
  24794. }
  24795. geometry = new Geometries[data.type](geometryShapes, data.options);
  24796. break;
  24797. case 'BufferGeometry':
  24798. case 'InstancedBufferGeometry':
  24799. geometry = bufferGeometryLoader.parse(data);
  24800. break;
  24801. case 'Geometry':
  24802. if ('THREE' in window && 'LegacyJSONLoader' in THREE) {
  24803. var geometryLoader = new THREE.LegacyJSONLoader();
  24804. geometry = geometryLoader.parse(data, this.resourcePath).geometry;
  24805. } else {
  24806. console.error('THREE.ObjectLoader: You have to import LegacyJSONLoader in order load geometry data of type "Geometry".');
  24807. }
  24808. break;
  24809. default:
  24810. console.warn('THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"');
  24811. continue;
  24812. }
  24813. geometry.uuid = data.uuid;
  24814. if (data.name !== undefined) geometry.name = data.name;
  24815. if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
  24816. geometries[data.uuid] = geometry;
  24817. }
  24818. }
  24819. return geometries;
  24820. },
  24821. parseMaterials: function (json, textures) {
  24822. var cache = {}; // MultiMaterial
  24823. var materials = {};
  24824. if (json !== undefined) {
  24825. var loader = new MaterialLoader();
  24826. loader.setTextures(textures);
  24827. for (var i = 0, l = json.length; i < l; i++) {
  24828. var data = json[i];
  24829. if (data.type === 'MultiMaterial') {
  24830. // Deprecated
  24831. var array = [];
  24832. for (var j = 0; j < data.materials.length; j++) {
  24833. var material = data.materials[j];
  24834. if (cache[material.uuid] === undefined) {
  24835. cache[material.uuid] = loader.parse(material);
  24836. }
  24837. array.push(cache[material.uuid]);
  24838. }
  24839. materials[data.uuid] = array;
  24840. } else {
  24841. if (cache[data.uuid] === undefined) {
  24842. cache[data.uuid] = loader.parse(data);
  24843. }
  24844. materials[data.uuid] = cache[data.uuid];
  24845. }
  24846. }
  24847. }
  24848. return materials;
  24849. },
  24850. parseAnimations: function (json) {
  24851. var animations = [];
  24852. for (var i = 0; i < json.length; i++) {
  24853. var data = json[i];
  24854. var clip = AnimationClip.parse(data);
  24855. if (data.uuid !== undefined) clip.uuid = data.uuid;
  24856. animations.push(clip);
  24857. }
  24858. return animations;
  24859. },
  24860. parseImages: function (json, onLoad) {
  24861. var scope = this;
  24862. var images = {};
  24863. function loadImage(url) {
  24864. scope.manager.itemStart(url);
  24865. return loader.load(url, function () {
  24866. scope.manager.itemEnd(url);
  24867. }, undefined, function () {
  24868. scope.manager.itemError(url);
  24869. scope.manager.itemEnd(url);
  24870. });
  24871. }
  24872. if (json !== undefined && json.length > 0) {
  24873. var manager = new LoadingManager(onLoad);
  24874. var loader = new ImageLoader(manager);
  24875. loader.setCrossOrigin(this.crossOrigin);
  24876. for (var i = 0, il = json.length; i < il; i++) {
  24877. var image = json[i];
  24878. var url = image.url;
  24879. if (Array.isArray(url)) {
  24880. // load array of images e.g CubeTexture
  24881. images[image.uuid] = [];
  24882. for (var j = 0, jl = url.length; j < jl; j++) {
  24883. var currentUrl = url[j];
  24884. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(currentUrl) ? currentUrl : scope.resourcePath + currentUrl;
  24885. images[image.uuid].push(loadImage(path));
  24886. }
  24887. } else {
  24888. // load single image
  24889. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(image.url) ? image.url : scope.resourcePath + image.url;
  24890. images[image.uuid] = loadImage(path);
  24891. }
  24892. }
  24893. }
  24894. return images;
  24895. },
  24896. parseTextures: function (json, images) {
  24897. function parseConstant(value, type) {
  24898. if (typeof value === 'number') return value;
  24899. console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
  24900. return type[value];
  24901. }
  24902. var textures = {};
  24903. if (json !== undefined) {
  24904. for (var i = 0, l = json.length; i < l; i++) {
  24905. var data = json[i];
  24906. if (data.image === undefined) {
  24907. console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
  24908. }
  24909. if (images[data.image] === undefined) {
  24910. console.warn('THREE.ObjectLoader: Undefined image', data.image);
  24911. }
  24912. var texture;
  24913. if (Array.isArray(images[data.image])) {
  24914. texture = new CubeTexture(images[data.image]);
  24915. } else {
  24916. texture = new Texture(images[data.image]);
  24917. }
  24918. texture.needsUpdate = true;
  24919. texture.uuid = data.uuid;
  24920. if (data.name !== undefined) texture.name = data.name;
  24921. if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
  24922. if (data.offset !== undefined) texture.offset.fromArray(data.offset);
  24923. if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
  24924. if (data.center !== undefined) texture.center.fromArray(data.center);
  24925. if (data.rotation !== undefined) texture.rotation = data.rotation;
  24926. if (data.wrap !== undefined) {
  24927. texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
  24928. texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
  24929. }
  24930. if (data.format !== undefined) texture.format = data.format;
  24931. if (data.type !== undefined) texture.type = data.type;
  24932. if (data.encoding !== undefined) texture.encoding = data.encoding;
  24933. if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
  24934. if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
  24935. if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
  24936. if (data.flipY !== undefined) texture.flipY = data.flipY;
  24937. if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
  24938. if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
  24939. textures[data.uuid] = texture;
  24940. }
  24941. }
  24942. return textures;
  24943. },
  24944. parseObject: function (data, geometries, materials) {
  24945. var object;
  24946. function getGeometry(name) {
  24947. if (geometries[name] === undefined) {
  24948. console.warn('THREE.ObjectLoader: Undefined geometry', name);
  24949. }
  24950. return geometries[name];
  24951. }
  24952. function getMaterial(name) {
  24953. if (name === undefined) return undefined;
  24954. if (Array.isArray(name)) {
  24955. var array = [];
  24956. for (var i = 0, l = name.length; i < l; i++) {
  24957. var uuid = name[i];
  24958. if (materials[uuid] === undefined) {
  24959. console.warn('THREE.ObjectLoader: Undefined material', uuid);
  24960. }
  24961. array.push(materials[uuid]);
  24962. }
  24963. return array;
  24964. }
  24965. if (materials[name] === undefined) {
  24966. console.warn('THREE.ObjectLoader: Undefined material', name);
  24967. }
  24968. return materials[name];
  24969. }
  24970. switch (data.type) {
  24971. case 'Scene':
  24972. object = new Scene();
  24973. if (data.background !== undefined) {
  24974. if (Number.isInteger(data.background)) {
  24975. object.background = new Color(data.background);
  24976. }
  24977. }
  24978. if (data.fog !== undefined) {
  24979. if (data.fog.type === 'Fog') {
  24980. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  24981. } else if (data.fog.type === 'FogExp2') {
  24982. object.fog = new FogExp2(data.fog.color, data.fog.density);
  24983. }
  24984. }
  24985. break;
  24986. case 'PerspectiveCamera':
  24987. object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
  24988. if (data.focus !== undefined) object.focus = data.focus;
  24989. if (data.zoom !== undefined) object.zoom = data.zoom;
  24990. if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
  24991. if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
  24992. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24993. break;
  24994. case 'OrthographicCamera':
  24995. object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
  24996. if (data.zoom !== undefined) object.zoom = data.zoom;
  24997. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24998. break;
  24999. case 'AmbientLight':
  25000. object = new AmbientLight(data.color, data.intensity);
  25001. break;
  25002. case 'DirectionalLight':
  25003. object = new DirectionalLight(data.color, data.intensity);
  25004. break;
  25005. case 'PointLight':
  25006. object = new PointLight(data.color, data.intensity, data.distance, data.decay);
  25007. break;
  25008. case 'RectAreaLight':
  25009. object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
  25010. break;
  25011. case 'SpotLight':
  25012. object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
  25013. break;
  25014. case 'HemisphereLight':
  25015. object = new HemisphereLight(data.color, data.groundColor, data.intensity);
  25016. break;
  25017. case 'SkinnedMesh':
  25018. console.warn('THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.');
  25019. case 'Mesh':
  25020. var geometry = getGeometry(data.geometry);
  25021. var material = getMaterial(data.material);
  25022. if (geometry.bones && geometry.bones.length > 0) {
  25023. object = new SkinnedMesh(geometry, material);
  25024. } else {
  25025. object = new Mesh(geometry, material);
  25026. }
  25027. if (data.drawMode !== undefined) object.setDrawMode(data.drawMode);
  25028. break;
  25029. case 'LOD':
  25030. object = new LOD();
  25031. break;
  25032. case 'Line':
  25033. object = new Line(getGeometry(data.geometry), getMaterial(data.material), data.mode);
  25034. break;
  25035. case 'LineLoop':
  25036. object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
  25037. break;
  25038. case 'LineSegments':
  25039. object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
  25040. break;
  25041. case 'PointCloud':
  25042. case 'Points':
  25043. object = new Points(getGeometry(data.geometry), getMaterial(data.material));
  25044. break;
  25045. case 'Sprite':
  25046. object = new Sprite(getMaterial(data.material));
  25047. break;
  25048. case 'Group':
  25049. object = new Group();
  25050. break;
  25051. default:
  25052. object = new Object3D();
  25053. }
  25054. object.uuid = data.uuid;
  25055. if (data.name !== undefined) object.name = data.name;
  25056. if (data.matrix !== undefined) {
  25057. object.matrix.fromArray(data.matrix);
  25058. if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
  25059. if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
  25060. } else {
  25061. if (data.position !== undefined) object.position.fromArray(data.position);
  25062. if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
  25063. if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
  25064. if (data.scale !== undefined) object.scale.fromArray(data.scale);
  25065. }
  25066. if (data.castShadow !== undefined) object.castShadow = data.castShadow;
  25067. if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
  25068. if (data.shadow) {
  25069. if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
  25070. if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
  25071. if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
  25072. if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
  25073. }
  25074. if (data.visible !== undefined) object.visible = data.visible;
  25075. if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
  25076. if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
  25077. if (data.userData !== undefined) object.userData = data.userData;
  25078. if (data.layers !== undefined) object.layers.mask = data.layers;
  25079. if (data.children !== undefined) {
  25080. var children = data.children;
  25081. for (var i = 0; i < children.length; i++) {
  25082. object.add(this.parseObject(children[i], geometries, materials));
  25083. }
  25084. }
  25085. if (data.type === 'LOD') {
  25086. var levels = data.levels;
  25087. for (var l = 0; l < levels.length; l++) {
  25088. var level = levels[l];
  25089. var child = object.getObjectByProperty('uuid', level.object);
  25090. if (child !== undefined) {
  25091. object.addLevel(child, level.distance);
  25092. }
  25093. }
  25094. }
  25095. return object;
  25096. }
  25097. });
  25098. var TEXTURE_MAPPING = {
  25099. UVMapping: UVMapping,
  25100. CubeReflectionMapping: CubeReflectionMapping,
  25101. CubeRefractionMapping: CubeRefractionMapping,
  25102. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  25103. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  25104. SphericalReflectionMapping: SphericalReflectionMapping,
  25105. CubeUVReflectionMapping: CubeUVReflectionMapping,
  25106. CubeUVRefractionMapping: CubeUVRefractionMapping
  25107. };
  25108. var TEXTURE_WRAPPING = {
  25109. RepeatWrapping: RepeatWrapping,
  25110. ClampToEdgeWrapping: ClampToEdgeWrapping,
  25111. MirroredRepeatWrapping: MirroredRepeatWrapping
  25112. };
  25113. var TEXTURE_FILTER = {
  25114. NearestFilter: NearestFilter,
  25115. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  25116. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  25117. LinearFilter: LinearFilter,
  25118. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  25119. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  25120. };
  25121. /**
  25122. * @author thespite / http://clicktorelease.com/
  25123. */
  25124. function ImageBitmapLoader(manager) {
  25125. if (typeof createImageBitmap === 'undefined') {
  25126. console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
  25127. }
  25128. if (typeof fetch === 'undefined') {
  25129. console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
  25130. }
  25131. Loader.call(this, manager);
  25132. this.options = undefined;
  25133. }
  25134. ImageBitmapLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  25135. constructor: ImageBitmapLoader,
  25136. setOptions: function setOptions(options) {
  25137. this.options = options;
  25138. return this;
  25139. },
  25140. load: function (url, onLoad, onProgress, onError) {
  25141. if (url === undefined) url = '';
  25142. if (this.path !== undefined) url = this.path + url;
  25143. url = this.manager.resolveURL(url);
  25144. var scope = this;
  25145. var cached = Cache.get(url);
  25146. if (cached !== undefined) {
  25147. scope.manager.itemStart(url);
  25148. setTimeout(function () {
  25149. if (onLoad) onLoad(cached);
  25150. scope.manager.itemEnd(url);
  25151. }, 0);
  25152. return cached;
  25153. }
  25154. fetch(url).then(function (res) {
  25155. return res.blob();
  25156. }).then(function (blob) {
  25157. if (scope.options === undefined) {
  25158. // Workaround for FireFox. It causes an error if you pass options.
  25159. return createImageBitmap(blob);
  25160. } else {
  25161. return createImageBitmap(blob, scope.options);
  25162. }
  25163. }).then(function (imageBitmap) {
  25164. Cache.add(url, imageBitmap);
  25165. if (onLoad) onLoad(imageBitmap);
  25166. scope.manager.itemEnd(url);
  25167. }).catch(function (e) {
  25168. if (onError) onError(e);
  25169. scope.manager.itemError(url);
  25170. scope.manager.itemEnd(url);
  25171. });
  25172. scope.manager.itemStart(url);
  25173. }
  25174. });
  25175. /**
  25176. * @author zz85 / http://www.lab4games.net/zz85/blog
  25177. * minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
  25178. **/
  25179. function ShapePath() {
  25180. this.type = 'ShapePath';
  25181. this.color = new Color();
  25182. this.subPaths = [];
  25183. this.currentPath = null;
  25184. }
  25185. Object.assign(ShapePath.prototype, {
  25186. moveTo: function (x, y) {
  25187. this.currentPath = new Path();
  25188. this.subPaths.push(this.currentPath);
  25189. this.currentPath.moveTo(x, y);
  25190. },
  25191. lineTo: function (x, y) {
  25192. this.currentPath.lineTo(x, y);
  25193. },
  25194. quadraticCurveTo: function (aCPx, aCPy, aX, aY) {
  25195. this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
  25196. },
  25197. bezierCurveTo: function (aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  25198. this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
  25199. },
  25200. splineThru: function (pts) {
  25201. this.currentPath.splineThru(pts);
  25202. },
  25203. toShapes: function (isCCW, noHoles) {
  25204. function toShapesNoHoles(inSubpaths) {
  25205. var shapes = [];
  25206. for (var i = 0, l = inSubpaths.length; i < l; i++) {
  25207. var tmpPath = inSubpaths[i];
  25208. var tmpShape = new Shape();
  25209. tmpShape.curves = tmpPath.curves;
  25210. shapes.push(tmpShape);
  25211. }
  25212. return shapes;
  25213. }
  25214. function isPointInsidePolygon(inPt, inPolygon) {
  25215. var polyLen = inPolygon.length; // inPt on polygon contour => immediate success or
  25216. // toggling of inside/outside at every single! intersection point of an edge
  25217. // with the horizontal line through inPt, left of inPt
  25218. // not counting lowerY endpoints of edges and whole edges on that line
  25219. var inside = false;
  25220. for (var p = polyLen - 1, q = 0; q < polyLen; p = q++) {
  25221. var edgeLowPt = inPolygon[p];
  25222. var edgeHighPt = inPolygon[q];
  25223. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  25224. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  25225. if (Math.abs(edgeDy) > Number.EPSILON) {
  25226. // not parallel
  25227. if (edgeDy < 0) {
  25228. edgeLowPt = inPolygon[q];
  25229. edgeDx = -edgeDx;
  25230. edgeHighPt = inPolygon[p];
  25231. edgeDy = -edgeDy;
  25232. }
  25233. if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
  25234. if (inPt.y === edgeLowPt.y) {
  25235. if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
  25236. // continue; // no intersection or edgeLowPt => doesn't count !!!
  25237. } else {
  25238. var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  25239. if (perpEdge === 0) return true; // inPt is on contour ?
  25240. if (perpEdge < 0) continue;
  25241. inside = !inside; // true intersection left of inPt
  25242. }
  25243. } else {
  25244. // parallel or collinear
  25245. if (inPt.y !== edgeLowPt.y) continue; // parallel
  25246. // edge lies on the same horizontal line as inPt
  25247. if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
  25248. // continue;
  25249. }
  25250. }
  25251. return inside;
  25252. }
  25253. var isClockWise = ShapeUtils.isClockWise;
  25254. var subPaths = this.subPaths;
  25255. if (subPaths.length === 0) return [];
  25256. if (noHoles === true) return toShapesNoHoles(subPaths);
  25257. var solid,
  25258. tmpPath,
  25259. tmpShape,
  25260. shapes = [];
  25261. if (subPaths.length === 1) {
  25262. tmpPath = subPaths[0];
  25263. tmpShape = new Shape();
  25264. tmpShape.curves = tmpPath.curves;
  25265. shapes.push(tmpShape);
  25266. return shapes;
  25267. }
  25268. var holesFirst = !isClockWise(subPaths[0].getPoints());
  25269. holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);
  25270. var betterShapeHoles = [];
  25271. var newShapes = [];
  25272. var newShapeHoles = [];
  25273. var mainIdx = 0;
  25274. var tmpPoints;
  25275. newShapes[mainIdx] = undefined;
  25276. newShapeHoles[mainIdx] = [];
  25277. for (var i = 0, l = subPaths.length; i < l; i++) {
  25278. tmpPath = subPaths[i];
  25279. tmpPoints = tmpPath.getPoints();
  25280. solid = isClockWise(tmpPoints);
  25281. solid = isCCW ? !solid : solid;
  25282. if (solid) {
  25283. if (!holesFirst && newShapes[mainIdx]) mainIdx++;
  25284. newShapes[mainIdx] = {
  25285. s: new Shape(),
  25286. p: tmpPoints
  25287. };
  25288. newShapes[mainIdx].s.curves = tmpPath.curves;
  25289. if (holesFirst) mainIdx++;
  25290. newShapeHoles[mainIdx] = []; //console.log('cw', i);
  25291. } else {
  25292. newShapeHoles[mainIdx].push({
  25293. h: tmpPath,
  25294. p: tmpPoints[0]
  25295. }); //console.log('ccw', i);
  25296. }
  25297. } // only Holes? -> probably all Shapes with wrong orientation
  25298. if (!newShapes[0]) return toShapesNoHoles(subPaths);
  25299. if (newShapes.length > 1) {
  25300. var ambiguous = false;
  25301. var toChange = [];
  25302. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  25303. betterShapeHoles[sIdx] = [];
  25304. }
  25305. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  25306. var sho = newShapeHoles[sIdx];
  25307. for (var hIdx = 0; hIdx < sho.length; hIdx++) {
  25308. var ho = sho[hIdx];
  25309. var hole_unassigned = true;
  25310. for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
  25311. if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
  25312. if (sIdx !== s2Idx) toChange.push({
  25313. froms: sIdx,
  25314. tos: s2Idx,
  25315. hole: hIdx
  25316. });
  25317. if (hole_unassigned) {
  25318. hole_unassigned = false;
  25319. betterShapeHoles[s2Idx].push(ho);
  25320. } else {
  25321. ambiguous = true;
  25322. }
  25323. }
  25324. }
  25325. if (hole_unassigned) {
  25326. betterShapeHoles[sIdx].push(ho);
  25327. }
  25328. }
  25329. } // console.log("ambiguous: ", ambiguous);
  25330. if (toChange.length > 0) {
  25331. // console.log("to change: ", toChange);
  25332. if (!ambiguous) newShapeHoles = betterShapeHoles;
  25333. }
  25334. }
  25335. var tmpHoles;
  25336. for (var i = 0, il = newShapes.length; i < il; i++) {
  25337. tmpShape = newShapes[i].s;
  25338. shapes.push(tmpShape);
  25339. tmpHoles = newShapeHoles[i];
  25340. for (var j = 0, jl = tmpHoles.length; j < jl; j++) {
  25341. tmpShape.holes.push(tmpHoles[j].h);
  25342. }
  25343. } //console.log("shape", shapes);
  25344. return shapes;
  25345. }
  25346. });
  25347. /**
  25348. * @author zz85 / http://www.lab4games.net/zz85/blog
  25349. * @author mrdoob / http://mrdoob.com/
  25350. */
  25351. function Font(data) {
  25352. this.type = 'Font';
  25353. this.data = data;
  25354. }
  25355. Object.assign(Font.prototype, {
  25356. isFont: true,
  25357. generateShapes: function (text, size) {
  25358. if (size === undefined) size = 100;
  25359. var shapes = [];
  25360. var paths = createPaths(text, size, this.data);
  25361. for (var p = 0, pl = paths.length; p < pl; p++) {
  25362. Array.prototype.push.apply(shapes, paths[p].toShapes());
  25363. }
  25364. return shapes;
  25365. }
  25366. });
  25367. function createPaths(text, size, data) {
  25368. var chars = Array.from ? Array.from(text) : String(text).split(''); // see #13988
  25369. var scale = size / data.resolution;
  25370. var line_height = (data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness) * scale;
  25371. var paths = [];
  25372. var offsetX = 0,
  25373. offsetY = 0;
  25374. for (var i = 0; i < chars.length; i++) {
  25375. var char = chars[i];
  25376. if (char === '\n') {
  25377. offsetX = 0;
  25378. offsetY -= line_height;
  25379. } else {
  25380. var ret = createPath(char, scale, offsetX, offsetY, data);
  25381. offsetX += ret.offsetX;
  25382. paths.push(ret.path);
  25383. }
  25384. }
  25385. return paths;
  25386. }
  25387. function createPath(char, scale, offsetX, offsetY, data) {
  25388. var glyph = data.glyphs[char] || data.glyphs['?'];
  25389. if (!glyph) {
  25390. console.error('THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.');
  25391. return;
  25392. }
  25393. var path = new ShapePath();
  25394. var x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  25395. if (glyph.o) {
  25396. var outline = glyph._cachedOutline || (glyph._cachedOutline = glyph.o.split(' '));
  25397. for (var i = 0, l = outline.length; i < l;) {
  25398. var action = outline[i++];
  25399. switch (action) {
  25400. case 'm':
  25401. // moveTo
  25402. x = outline[i++] * scale + offsetX;
  25403. y = outline[i++] * scale + offsetY;
  25404. path.moveTo(x, y);
  25405. break;
  25406. case 'l':
  25407. // lineTo
  25408. x = outline[i++] * scale + offsetX;
  25409. y = outline[i++] * scale + offsetY;
  25410. path.lineTo(x, y);
  25411. break;
  25412. case 'q':
  25413. // quadraticCurveTo
  25414. cpx = outline[i++] * scale + offsetX;
  25415. cpy = outline[i++] * scale + offsetY;
  25416. cpx1 = outline[i++] * scale + offsetX;
  25417. cpy1 = outline[i++] * scale + offsetY;
  25418. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  25419. break;
  25420. case 'b':
  25421. // bezierCurveTo
  25422. cpx = outline[i++] * scale + offsetX;
  25423. cpy = outline[i++] * scale + offsetY;
  25424. cpx1 = outline[i++] * scale + offsetX;
  25425. cpy1 = outline[i++] * scale + offsetY;
  25426. cpx2 = outline[i++] * scale + offsetX;
  25427. cpy2 = outline[i++] * scale + offsetY;
  25428. path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy);
  25429. break;
  25430. }
  25431. }
  25432. }
  25433. return {
  25434. offsetX: glyph.ha * scale,
  25435. path: path
  25436. };
  25437. }
  25438. /**
  25439. * @author mrdoob / http://mrdoob.com/
  25440. */
  25441. function FontLoader(manager) {
  25442. Loader.call(this, manager);
  25443. }
  25444. FontLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  25445. constructor: FontLoader,
  25446. load: function (url, onLoad, onProgress, onError) {
  25447. var scope = this;
  25448. var loader = new FileLoader(this.manager);
  25449. loader.setPath(this.path);
  25450. loader.load(url, function (text) {
  25451. var json;
  25452. try {
  25453. json = JSON.parse(text);
  25454. } catch (e) {
  25455. console.warn('THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.');
  25456. json = JSON.parse(text.substring(65, text.length - 2));
  25457. }
  25458. var font = scope.parse(json);
  25459. if (onLoad) onLoad(font);
  25460. }, onProgress, onError);
  25461. },
  25462. parse: function (json) {
  25463. return new Font(json);
  25464. }
  25465. });
  25466. /**
  25467. * @author mrdoob / http://mrdoob.com/
  25468. */
  25469. var _context;
  25470. var AudioContext = {
  25471. getContext: function () {
  25472. if (_context === undefined) {
  25473. _context = new (window.AudioContext || window.webkitAudioContext)();
  25474. }
  25475. return _context;
  25476. },
  25477. setContext: function (value) {
  25478. _context = value;
  25479. }
  25480. };
  25481. /**
  25482. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  25483. */
  25484. exports.AudioContext = AudioContext;
  25485. function AudioLoader(manager) {
  25486. Loader.call(this, manager);
  25487. }
  25488. AudioLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  25489. constructor: AudioLoader,
  25490. load: function (url, onLoad, onProgress, onError) {
  25491. var loader = new FileLoader(this.manager);
  25492. loader.setResponseType('arraybuffer');
  25493. loader.setPath(this.path);
  25494. loader.load(url, function (buffer) {
  25495. // Create a copy of the buffer. The `decodeAudioData` method
  25496. // detaches the buffer when complete, preventing reuse.
  25497. var bufferCopy = buffer.slice(0);
  25498. var context = AudioContext.getContext();
  25499. context.decodeAudioData(bufferCopy, function (audioBuffer) {
  25500. onLoad(audioBuffer);
  25501. });
  25502. }, onProgress, onError);
  25503. }
  25504. });
  25505. /**
  25506. * @author bhouston / http://clara.io
  25507. * @author WestLangley / http://github.com/WestLangley
  25508. *
  25509. * Primary reference:
  25510. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  25511. *
  25512. * Secondary reference:
  25513. * https://www.ppsloan.org/publications/StupidSH36.pdf
  25514. */
  25515. // 3-band SH defined by 9 coefficients
  25516. function SphericalHarmonics3() {
  25517. this.coefficients = [];
  25518. for (var i = 0; i < 9; i++) {
  25519. this.coefficients.push(new Vector3());
  25520. }
  25521. }
  25522. Object.assign(SphericalHarmonics3.prototype, {
  25523. isSphericalHarmonics3: true,
  25524. set: function (coefficients) {
  25525. for (var i = 0; i < 9; i++) {
  25526. this.coefficients[i].copy(coefficients[i]);
  25527. }
  25528. return this;
  25529. },
  25530. zero: function () {
  25531. for (var i = 0; i < 9; i++) {
  25532. this.coefficients[i].set(0, 0, 0);
  25533. }
  25534. return this;
  25535. },
  25536. // get the radiance in the direction of the normal
  25537. // target is a Vector3
  25538. getAt: function (normal, target) {
  25539. // normal is assumed to be unit length
  25540. var x = normal.x,
  25541. y = normal.y,
  25542. z = normal.z;
  25543. var coeff = this.coefficients; // band 0
  25544. target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
  25545. target.addScale(coeff[1], 0.488603 * y);
  25546. target.addScale(coeff[2], 0.488603 * z);
  25547. target.addScale(coeff[3], 0.488603 * x); // band 2
  25548. target.addScale(coeff[4], 1.092548 * (x * y));
  25549. target.addScale(coeff[5], 1.092548 * (y * z));
  25550. target.addScale(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
  25551. target.addScale(coeff[7], 1.092548 * (x * z));
  25552. target.addScale(coeff[8], 0.546274 * (x * x - y * y));
  25553. return target;
  25554. },
  25555. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  25556. // target is a Vector3
  25557. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  25558. getIrradianceAt: function (normal, target) {
  25559. // normal is assumed to be unit length
  25560. var x = normal.x,
  25561. y = normal.y,
  25562. z = normal.z;
  25563. var coeff = this.coefficients; // band 0
  25564. target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
  25565. // band 1
  25566. target.addScale(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
  25567. target.addScale(coeff[2], 2.0 * 0.511664 * z);
  25568. target.addScale(coeff[3], 2.0 * 0.511664 * x); // band 2
  25569. target.addScale(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
  25570. target.addScale(coeff[5], 2.0 * 0.429043 * y * z);
  25571. target.addScale(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
  25572. target.addScale(coeff[7], 2.0 * 0.429043 * x * z);
  25573. target.addScale(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
  25574. return target;
  25575. },
  25576. add: function (sh) {
  25577. for (var i = 0; i < 9; i++) {
  25578. this.coefficients[i].add(sh.coefficients[i]);
  25579. }
  25580. return this;
  25581. },
  25582. scale: function (s) {
  25583. for (var i = 0; i < 9; i++) {
  25584. this.coefficients[i].multiplyScalar(s);
  25585. }
  25586. return this;
  25587. },
  25588. lerp: function (sh, alpha) {
  25589. for (var i = 0; i < 9; i++) {
  25590. this.coefficients[i].lerp(sh.coefficients[i], alpha);
  25591. }
  25592. return this;
  25593. },
  25594. equals: function (sh) {
  25595. for (var i = 0; i < 9; i++) {
  25596. if (!this.coefficients[i].equals(sh.coefficients[i])) {
  25597. return false;
  25598. }
  25599. }
  25600. return true;
  25601. },
  25602. copy: function (sh) {
  25603. return this.set(sh.coefficients);
  25604. },
  25605. clone: function () {
  25606. return new this.constructor().copy(this);
  25607. },
  25608. fromArray: function (array, offset) {
  25609. if (offset === undefined) offset = 0;
  25610. var coefficients = this.coefficients;
  25611. for (var i = 0; i < 9; i++) {
  25612. coefficients[i].fromArray(array, offset + i * 3);
  25613. }
  25614. return this;
  25615. },
  25616. toArray: function (array, offset) {
  25617. if (array === undefined) array = [];
  25618. if (offset === undefined) offset = 0;
  25619. var coefficients = this.coefficients;
  25620. for (var i = 0; i < 9; i++) {
  25621. coefficients[i].toArray(array, offset + i * 3);
  25622. }
  25623. return array;
  25624. }
  25625. });
  25626. Object.assign(SphericalHarmonics3, {
  25627. // evaluate the basis functions
  25628. // shBasis is an Array[ 9 ]
  25629. getBasisAt: function (normal, shBasis) {
  25630. // normal is assumed to be unit length
  25631. var x = normal.x,
  25632. y = normal.y,
  25633. z = normal.z; // band 0
  25634. shBasis[0] = 0.282095; // band 1
  25635. shBasis[1] = 0.488603 * y;
  25636. shBasis[2] = 0.488603 * z;
  25637. shBasis[3] = 0.488603 * x; // band 2
  25638. shBasis[4] = 1.092548 * x * y;
  25639. shBasis[5] = 1.092548 * y * z;
  25640. shBasis[6] = 0.315392 * (3 * z * z - 1);
  25641. shBasis[7] = 1.092548 * x * z;
  25642. shBasis[8] = 0.546274 * (x * x - y * y);
  25643. }
  25644. });
  25645. /**
  25646. * @author WestLangley / http://github.com/WestLangley
  25647. *
  25648. * A LightProbe is a source of indirect-diffuse light
  25649. */
  25650. function LightProbe(sh, intensity) {
  25651. Light.call(this, undefined, intensity);
  25652. this.sh = sh !== undefined ? sh : new SphericalHarmonics3();
  25653. }
  25654. LightProbe.prototype = Object.assign(Object.create(Light.prototype), {
  25655. constructor: LightProbe,
  25656. isLightProbe: true,
  25657. copy: function (source) {
  25658. Light.prototype.copy.call(this, source);
  25659. this.sh.copy(source.sh);
  25660. this.intensity = source.intensity;
  25661. return this;
  25662. },
  25663. toJSON: function (meta) {
  25664. var data = Light.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  25665. return data;
  25666. }
  25667. });
  25668. /**
  25669. * @author WestLangley / http://github.com/WestLangley
  25670. */
  25671. function HemisphereLightProbe(skyColor, groundColor, intensity) {
  25672. LightProbe.call(this, undefined, intensity);
  25673. var color1 = new Color().set(skyColor);
  25674. var color2 = new Color().set(groundColor);
  25675. var sky = new Vector3(color1.r, color1.g, color1.b);
  25676. var ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  25677. var c0 = Math.sqrt(Math.PI);
  25678. var c1 = c0 * Math.sqrt(0.75);
  25679. this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
  25680. this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
  25681. }
  25682. HemisphereLightProbe.prototype = Object.assign(Object.create(LightProbe.prototype), {
  25683. constructor: HemisphereLightProbe,
  25684. isHemisphereLightProbe: true,
  25685. copy: function (source) {
  25686. // modifying colors not currently supported
  25687. LightProbe.prototype.copy.call(this, source);
  25688. return this;
  25689. },
  25690. toJSON: function (meta) {
  25691. var data = LightProbe.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  25692. return data;
  25693. }
  25694. });
  25695. /**
  25696. * @author WestLangley / http://github.com/WestLangley
  25697. */
  25698. function AmbientLightProbe(color, intensity) {
  25699. LightProbe.call(this, undefined, intensity);
  25700. var color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  25701. this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
  25702. }
  25703. AmbientLightProbe.prototype = Object.assign(Object.create(LightProbe.prototype), {
  25704. constructor: AmbientLightProbe,
  25705. isAmbientLightProbe: true,
  25706. copy: function (source) {
  25707. // modifying color not currently supported
  25708. LightProbe.prototype.copy.call(this, source);
  25709. return this;
  25710. },
  25711. toJSON: function (meta) {
  25712. var data = LightProbe.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  25713. return data;
  25714. }
  25715. });
  25716. var _eyeRight = new Matrix4();
  25717. var _eyeLeft = new Matrix4();
  25718. /**
  25719. * @author mrdoob / http://mrdoob.com/
  25720. */
  25721. function StereoCamera() {
  25722. this.type = 'StereoCamera';
  25723. this.aspect = 1;
  25724. this.eyeSep = 0.064;
  25725. this.cameraL = new PerspectiveCamera();
  25726. this.cameraL.layers.enable(1);
  25727. this.cameraL.matrixAutoUpdate = false;
  25728. this.cameraR = new PerspectiveCamera();
  25729. this.cameraR.layers.enable(2);
  25730. this.cameraR.matrixAutoUpdate = false;
  25731. this._cache = {
  25732. focus: null,
  25733. fov: null,
  25734. aspect: null,
  25735. near: null,
  25736. far: null,
  25737. zoom: null,
  25738. eyeSep: null
  25739. };
  25740. }
  25741. Object.assign(StereoCamera.prototype, {
  25742. update: function (camera) {
  25743. var cache = this._cache;
  25744. var needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov || cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near || cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  25745. if (needsUpdate) {
  25746. cache.focus = camera.focus;
  25747. cache.fov = camera.fov;
  25748. cache.aspect = camera.aspect * this.aspect;
  25749. cache.near = camera.near;
  25750. cache.far = camera.far;
  25751. cache.zoom = camera.zoom;
  25752. cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on
  25753. // http://paulbourke.net/stereographics/stereorender/
  25754. var projectionMatrix = camera.projectionMatrix.clone();
  25755. var eyeSepHalf = cache.eyeSep / 2;
  25756. var eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  25757. var ymax = cache.near * Math.tan(_Math.DEG2RAD * cache.fov * 0.5) / cache.zoom;
  25758. var xmin, xmax; // translate xOffset
  25759. _eyeLeft.elements[12] = -eyeSepHalf;
  25760. _eyeRight.elements[12] = eyeSepHalf; // for left eye
  25761. xmin = -ymax * cache.aspect + eyeSepOnProjection;
  25762. xmax = ymax * cache.aspect + eyeSepOnProjection;
  25763. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  25764. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  25765. this.cameraL.projectionMatrix.copy(projectionMatrix); // for right eye
  25766. xmin = -ymax * cache.aspect - eyeSepOnProjection;
  25767. xmax = ymax * cache.aspect - eyeSepOnProjection;
  25768. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  25769. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  25770. this.cameraR.projectionMatrix.copy(projectionMatrix);
  25771. }
  25772. this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
  25773. this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  25774. }
  25775. });
  25776. /**
  25777. * @author alteredq / http://alteredqualia.com/
  25778. */
  25779. function Clock(autoStart) {
  25780. this.autoStart = autoStart !== undefined ? autoStart : true;
  25781. this.startTime = 0;
  25782. this.oldTime = 0;
  25783. this.elapsedTime = 0;
  25784. this.running = false;
  25785. }
  25786. Object.assign(Clock.prototype, {
  25787. start: function () {
  25788. this.startTime = (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
  25789. this.oldTime = this.startTime;
  25790. this.elapsedTime = 0;
  25791. this.running = true;
  25792. },
  25793. stop: function () {
  25794. this.getElapsedTime();
  25795. this.running = false;
  25796. this.autoStart = false;
  25797. },
  25798. getElapsedTime: function () {
  25799. this.getDelta();
  25800. return this.elapsedTime;
  25801. },
  25802. getDelta: function () {
  25803. var diff = 0;
  25804. if (this.autoStart && !this.running) {
  25805. this.start();
  25806. return 0;
  25807. }
  25808. if (this.running) {
  25809. var newTime = (typeof performance === 'undefined' ? Date : performance).now();
  25810. diff = (newTime - this.oldTime) / 1000;
  25811. this.oldTime = newTime;
  25812. this.elapsedTime += diff;
  25813. }
  25814. return diff;
  25815. }
  25816. });
  25817. /**
  25818. * @author mrdoob / http://mrdoob.com/
  25819. */
  25820. var _position$2 = new Vector3();
  25821. var _quaternion$3 = new Quaternion();
  25822. var _scale$1 = new Vector3();
  25823. var _orientation = new Vector3();
  25824. function AudioListener() {
  25825. Object3D.call(this);
  25826. this.type = 'AudioListener';
  25827. this.context = AudioContext.getContext();
  25828. this.gain = this.context.createGain();
  25829. this.gain.connect(this.context.destination);
  25830. this.filter = null;
  25831. this.timeDelta = 0; // private
  25832. this._clock = new Clock();
  25833. }
  25834. AudioListener.prototype = Object.assign(Object.create(Object3D.prototype), {
  25835. constructor: AudioListener,
  25836. getInput: function () {
  25837. return this.gain;
  25838. },
  25839. removeFilter: function () {
  25840. if (this.filter !== null) {
  25841. this.gain.disconnect(this.filter);
  25842. this.filter.disconnect(this.context.destination);
  25843. this.gain.connect(this.context.destination);
  25844. this.filter = null;
  25845. }
  25846. return this;
  25847. },
  25848. getFilter: function () {
  25849. return this.filter;
  25850. },
  25851. setFilter: function (value) {
  25852. if (this.filter !== null) {
  25853. this.gain.disconnect(this.filter);
  25854. this.filter.disconnect(this.context.destination);
  25855. } else {
  25856. this.gain.disconnect(this.context.destination);
  25857. }
  25858. this.filter = value;
  25859. this.gain.connect(this.filter);
  25860. this.filter.connect(this.context.destination);
  25861. return this;
  25862. },
  25863. getMasterVolume: function () {
  25864. return this.gain.gain.value;
  25865. },
  25866. setMasterVolume: function (value) {
  25867. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  25868. return this;
  25869. },
  25870. updateMatrixWorld: function (force) {
  25871. Object3D.prototype.updateMatrixWorld.call(this, force);
  25872. var listener = this.context.listener;
  25873. var up = this.up;
  25874. this.timeDelta = this._clock.getDelta();
  25875. this.matrixWorld.decompose(_position$2, _quaternion$3, _scale$1);
  25876. _orientation.set(0, 0, -1).applyQuaternion(_quaternion$3);
  25877. if (listener.positionX) {
  25878. // code path for Chrome (see #14393)
  25879. var endTime = this.context.currentTime + this.timeDelta;
  25880. listener.positionX.linearRampToValueAtTime(_position$2.x, endTime);
  25881. listener.positionY.linearRampToValueAtTime(_position$2.y, endTime);
  25882. listener.positionZ.linearRampToValueAtTime(_position$2.z, endTime);
  25883. listener.forwardX.linearRampToValueAtTime(_orientation.x, endTime);
  25884. listener.forwardY.linearRampToValueAtTime(_orientation.y, endTime);
  25885. listener.forwardZ.linearRampToValueAtTime(_orientation.z, endTime);
  25886. listener.upX.linearRampToValueAtTime(up.x, endTime);
  25887. listener.upY.linearRampToValueAtTime(up.y, endTime);
  25888. listener.upZ.linearRampToValueAtTime(up.z, endTime);
  25889. } else {
  25890. listener.setPosition(_position$2.x, _position$2.y, _position$2.z);
  25891. listener.setOrientation(_orientation.x, _orientation.y, _orientation.z, up.x, up.y, up.z);
  25892. }
  25893. }
  25894. });
  25895. /**
  25896. * @author mrdoob / http://mrdoob.com/
  25897. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  25898. */
  25899. function Audio(listener) {
  25900. Object3D.call(this);
  25901. this.type = 'Audio';
  25902. this.listener = listener;
  25903. this.context = listener.context;
  25904. this.gain = this.context.createGain();
  25905. this.gain.connect(listener.getInput());
  25906. this.autoplay = false;
  25907. this.buffer = null;
  25908. this.detune = 0;
  25909. this.loop = false;
  25910. this.startTime = 0;
  25911. this.offset = 0;
  25912. this.duration = undefined;
  25913. this.playbackRate = 1;
  25914. this.isPlaying = false;
  25915. this.hasPlaybackControl = true;
  25916. this.sourceType = 'empty';
  25917. this.filters = [];
  25918. }
  25919. Audio.prototype = Object.assign(Object.create(Object3D.prototype), {
  25920. constructor: Audio,
  25921. getOutput: function () {
  25922. return this.gain;
  25923. },
  25924. setNodeSource: function (audioNode) {
  25925. this.hasPlaybackControl = false;
  25926. this.sourceType = 'audioNode';
  25927. this.source = audioNode;
  25928. this.connect();
  25929. return this;
  25930. },
  25931. setMediaElementSource: function (mediaElement) {
  25932. this.hasPlaybackControl = false;
  25933. this.sourceType = 'mediaNode';
  25934. this.source = this.context.createMediaElementSource(mediaElement);
  25935. this.connect();
  25936. return this;
  25937. },
  25938. setMediaStreamSource: function (mediaStream) {
  25939. this.hasPlaybackControl = false;
  25940. this.sourceType = 'mediaStreamNode';
  25941. this.source = this.context.createMediaStreamSource(mediaStream);
  25942. this.connect();
  25943. return this;
  25944. },
  25945. setBuffer: function (audioBuffer) {
  25946. this.buffer = audioBuffer;
  25947. this.sourceType = 'buffer';
  25948. if (this.autoplay) this.play();
  25949. return this;
  25950. },
  25951. play: function () {
  25952. if (this.isPlaying === true) {
  25953. console.warn('THREE.Audio: Audio is already playing.');
  25954. return;
  25955. }
  25956. if (this.hasPlaybackControl === false) {
  25957. console.warn('THREE.Audio: this Audio has no playback control.');
  25958. return;
  25959. }
  25960. var source = this.context.createBufferSource();
  25961. source.buffer = this.buffer;
  25962. source.loop = this.loop;
  25963. source.onended = this.onEnded.bind(this);
  25964. this.startTime = this.context.currentTime;
  25965. source.start(this.startTime, this.offset, this.duration);
  25966. this.isPlaying = true;
  25967. this.source = source;
  25968. this.setDetune(this.detune);
  25969. this.setPlaybackRate(this.playbackRate);
  25970. return this.connect();
  25971. },
  25972. pause: function () {
  25973. if (this.hasPlaybackControl === false) {
  25974. console.warn('THREE.Audio: this Audio has no playback control.');
  25975. return;
  25976. }
  25977. if (this.isPlaying === true) {
  25978. this.source.stop();
  25979. this.source.onended = null;
  25980. this.offset += (this.context.currentTime - this.startTime) * this.playbackRate;
  25981. this.isPlaying = false;
  25982. }
  25983. return this;
  25984. },
  25985. stop: function () {
  25986. if (this.hasPlaybackControl === false) {
  25987. console.warn('THREE.Audio: this Audio has no playback control.');
  25988. return;
  25989. }
  25990. this.source.stop();
  25991. this.source.onended = null;
  25992. this.offset = 0;
  25993. this.isPlaying = false;
  25994. return this;
  25995. },
  25996. connect: function () {
  25997. if (this.filters.length > 0) {
  25998. this.source.connect(this.filters[0]);
  25999. for (var i = 1, l = this.filters.length; i < l; i++) {
  26000. this.filters[i - 1].connect(this.filters[i]);
  26001. }
  26002. this.filters[this.filters.length - 1].connect(this.getOutput());
  26003. } else {
  26004. this.source.connect(this.getOutput());
  26005. }
  26006. return this;
  26007. },
  26008. disconnect: function () {
  26009. if (this.filters.length > 0) {
  26010. this.source.disconnect(this.filters[0]);
  26011. for (var i = 1, l = this.filters.length; i < l; i++) {
  26012. this.filters[i - 1].disconnect(this.filters[i]);
  26013. }
  26014. this.filters[this.filters.length - 1].disconnect(this.getOutput());
  26015. } else {
  26016. this.source.disconnect(this.getOutput());
  26017. }
  26018. return this;
  26019. },
  26020. getFilters: function () {
  26021. return this.filters;
  26022. },
  26023. setFilters: function (value) {
  26024. if (!value) value = [];
  26025. if (this.isPlaying === true) {
  26026. this.disconnect();
  26027. this.filters = value;
  26028. this.connect();
  26029. } else {
  26030. this.filters = value;
  26031. }
  26032. return this;
  26033. },
  26034. setDetune: function (value) {
  26035. this.detune = value;
  26036. if (this.source.detune === undefined) return; // only set detune when available
  26037. if (this.isPlaying === true) {
  26038. this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
  26039. }
  26040. return this;
  26041. },
  26042. getDetune: function () {
  26043. return this.detune;
  26044. },
  26045. getFilter: function () {
  26046. return this.getFilters()[0];
  26047. },
  26048. setFilter: function (filter) {
  26049. return this.setFilters(filter ? [filter] : []);
  26050. },
  26051. setPlaybackRate: function (value) {
  26052. if (this.hasPlaybackControl === false) {
  26053. console.warn('THREE.Audio: this Audio has no playback control.');
  26054. return;
  26055. }
  26056. this.playbackRate = value;
  26057. if (this.isPlaying === true) {
  26058. this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
  26059. }
  26060. return this;
  26061. },
  26062. getPlaybackRate: function () {
  26063. return this.playbackRate;
  26064. },
  26065. onEnded: function () {
  26066. this.isPlaying = false;
  26067. },
  26068. getLoop: function () {
  26069. if (this.hasPlaybackControl === false) {
  26070. console.warn('THREE.Audio: this Audio has no playback control.');
  26071. return false;
  26072. }
  26073. return this.loop;
  26074. },
  26075. setLoop: function (value) {
  26076. if (this.hasPlaybackControl === false) {
  26077. console.warn('THREE.Audio: this Audio has no playback control.');
  26078. return;
  26079. }
  26080. this.loop = value;
  26081. if (this.isPlaying === true) {
  26082. this.source.loop = this.loop;
  26083. }
  26084. return this;
  26085. },
  26086. getVolume: function () {
  26087. return this.gain.gain.value;
  26088. },
  26089. setVolume: function (value) {
  26090. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  26091. return this;
  26092. }
  26093. });
  26094. /**
  26095. * @author mrdoob / http://mrdoob.com/
  26096. */
  26097. var _position$3 = new Vector3();
  26098. var _quaternion$4 = new Quaternion();
  26099. var _scale$2 = new Vector3();
  26100. var _orientation$1 = new Vector3();
  26101. function PositionalAudio(listener) {
  26102. Audio.call(this, listener);
  26103. this.panner = this.context.createPanner();
  26104. this.panner.panningModel = 'HRTF';
  26105. this.panner.connect(this.gain);
  26106. }
  26107. PositionalAudio.prototype = Object.assign(Object.create(Audio.prototype), {
  26108. constructor: PositionalAudio,
  26109. getOutput: function () {
  26110. return this.panner;
  26111. },
  26112. getRefDistance: function () {
  26113. return this.panner.refDistance;
  26114. },
  26115. setRefDistance: function (value) {
  26116. this.panner.refDistance = value;
  26117. return this;
  26118. },
  26119. getRolloffFactor: function () {
  26120. return this.panner.rolloffFactor;
  26121. },
  26122. setRolloffFactor: function (value) {
  26123. this.panner.rolloffFactor = value;
  26124. return this;
  26125. },
  26126. getDistanceModel: function () {
  26127. return this.panner.distanceModel;
  26128. },
  26129. setDistanceModel: function (value) {
  26130. this.panner.distanceModel = value;
  26131. return this;
  26132. },
  26133. getMaxDistance: function () {
  26134. return this.panner.maxDistance;
  26135. },
  26136. setMaxDistance: function (value) {
  26137. this.panner.maxDistance = value;
  26138. return this;
  26139. },
  26140. setDirectionalCone: function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  26141. this.panner.coneInnerAngle = coneInnerAngle;
  26142. this.panner.coneOuterAngle = coneOuterAngle;
  26143. this.panner.coneOuterGain = coneOuterGain;
  26144. return this;
  26145. },
  26146. updateMatrixWorld: function (force) {
  26147. Object3D.prototype.updateMatrixWorld.call(this, force);
  26148. if (this.hasPlaybackControl === true && this.isPlaying === false) return;
  26149. this.matrixWorld.decompose(_position$3, _quaternion$4, _scale$2);
  26150. _orientation$1.set(0, 0, 1).applyQuaternion(_quaternion$4);
  26151. var panner = this.panner;
  26152. if (panner.positionX) {
  26153. // code path for Chrome and Firefox (see #14393)
  26154. var endTime = this.context.currentTime + this.listener.timeDelta;
  26155. panner.positionX.linearRampToValueAtTime(_position$3.x, endTime);
  26156. panner.positionY.linearRampToValueAtTime(_position$3.y, endTime);
  26157. panner.positionZ.linearRampToValueAtTime(_position$3.z, endTime);
  26158. panner.orientationX.linearRampToValueAtTime(_orientation$1.x, endTime);
  26159. panner.orientationY.linearRampToValueAtTime(_orientation$1.y, endTime);
  26160. panner.orientationZ.linearRampToValueAtTime(_orientation$1.z, endTime);
  26161. } else {
  26162. panner.setPosition(_position$3.x, _position$3.y, _position$3.z);
  26163. panner.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z);
  26164. }
  26165. }
  26166. });
  26167. /**
  26168. * @author mrdoob / http://mrdoob.com/
  26169. */
  26170. function AudioAnalyser(audio, fftSize) {
  26171. this.analyser = audio.context.createAnalyser();
  26172. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  26173. this.data = new Uint8Array(this.analyser.frequencyBinCount);
  26174. audio.getOutput().connect(this.analyser);
  26175. }
  26176. Object.assign(AudioAnalyser.prototype, {
  26177. getFrequencyData: function () {
  26178. this.analyser.getByteFrequencyData(this.data);
  26179. return this.data;
  26180. },
  26181. getAverageFrequency: function () {
  26182. var value = 0,
  26183. data = this.getFrequencyData();
  26184. for (var i = 0; i < data.length; i++) {
  26185. value += data[i];
  26186. }
  26187. return value / data.length;
  26188. }
  26189. });
  26190. /**
  26191. *
  26192. * Buffered scene graph property that allows weighted accumulation.
  26193. *
  26194. *
  26195. * @author Ben Houston / http://clara.io/
  26196. * @author David Sarno / http://lighthaus.us/
  26197. * @author tschw
  26198. */
  26199. function PropertyMixer(binding, typeName, valueSize) {
  26200. this.binding = binding;
  26201. this.valueSize = valueSize;
  26202. var bufferType = Float64Array,
  26203. mixFunction;
  26204. switch (typeName) {
  26205. case 'quaternion':
  26206. mixFunction = this._slerp;
  26207. break;
  26208. case 'string':
  26209. case 'bool':
  26210. bufferType = Array;
  26211. mixFunction = this._select;
  26212. break;
  26213. default:
  26214. mixFunction = this._lerp;
  26215. }
  26216. this.buffer = new bufferType(valueSize * 4); // layout: [ incoming | accu0 | accu1 | orig ]
  26217. //
  26218. // interpolators can use .buffer as their .result
  26219. // the data then goes to 'incoming'
  26220. //
  26221. // 'accu0' and 'accu1' are used frame-interleaved for
  26222. // the cumulative result and are compared to detect
  26223. // changes
  26224. //
  26225. // 'orig' stores the original state of the property
  26226. this._mixBufferRegion = mixFunction;
  26227. this.cumulativeWeight = 0;
  26228. this.useCount = 0;
  26229. this.referenceCount = 0;
  26230. }
  26231. Object.assign(PropertyMixer.prototype, {
  26232. // accumulate data in the 'incoming' region into 'accu<i>'
  26233. accumulate: function (accuIndex, weight) {
  26234. // note: happily accumulating nothing when weight = 0, the caller knows
  26235. // the weight and shouldn't have made the call in the first place
  26236. var buffer = this.buffer,
  26237. stride = this.valueSize,
  26238. offset = accuIndex * stride + stride,
  26239. currentWeight = this.cumulativeWeight;
  26240. if (currentWeight === 0) {
  26241. // accuN := incoming * weight
  26242. for (var i = 0; i !== stride; ++i) {
  26243. buffer[offset + i] = buffer[i];
  26244. }
  26245. currentWeight = weight;
  26246. } else {
  26247. // accuN := accuN + incoming * weight
  26248. currentWeight += weight;
  26249. var mix = weight / currentWeight;
  26250. this._mixBufferRegion(buffer, offset, 0, mix, stride);
  26251. }
  26252. this.cumulativeWeight = currentWeight;
  26253. },
  26254. // apply the state of 'accu<i>' to the binding when accus differ
  26255. apply: function (accuIndex) {
  26256. var stride = this.valueSize,
  26257. buffer = this.buffer,
  26258. offset = accuIndex * stride + stride,
  26259. weight = this.cumulativeWeight,
  26260. binding = this.binding;
  26261. this.cumulativeWeight = 0;
  26262. if (weight < 1) {
  26263. // accuN := accuN + original * ( 1 - cumulativeWeight )
  26264. var originalValueOffset = stride * 3;
  26265. this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
  26266. }
  26267. for (var i = stride, e = stride + stride; i !== e; ++i) {
  26268. if (buffer[i] !== buffer[i + stride]) {
  26269. // value has changed -> update scene graph
  26270. binding.setValue(buffer, offset);
  26271. break;
  26272. }
  26273. }
  26274. },
  26275. // remember the state of the bound property and copy it to both accus
  26276. saveOriginalState: function () {
  26277. var binding = this.binding;
  26278. var buffer = this.buffer,
  26279. stride = this.valueSize,
  26280. originalValueOffset = stride * 3;
  26281. binding.getValue(buffer, originalValueOffset); // accu[0..1] := orig -- initially detect changes against the original
  26282. for (var i = stride, e = originalValueOffset; i !== e; ++i) {
  26283. buffer[i] = buffer[originalValueOffset + i % stride];
  26284. }
  26285. this.cumulativeWeight = 0;
  26286. },
  26287. // apply the state previously taken via 'saveOriginalState' to the binding
  26288. restoreOriginalState: function () {
  26289. var originalValueOffset = this.valueSize * 3;
  26290. this.binding.setValue(this.buffer, originalValueOffset);
  26291. },
  26292. // mix functions
  26293. _select: function (buffer, dstOffset, srcOffset, t, stride) {
  26294. if (t >= 0.5) {
  26295. for (var i = 0; i !== stride; ++i) {
  26296. buffer[dstOffset + i] = buffer[srcOffset + i];
  26297. }
  26298. }
  26299. },
  26300. _slerp: function (buffer, dstOffset, srcOffset, t) {
  26301. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
  26302. },
  26303. _lerp: function (buffer, dstOffset, srcOffset, t, stride) {
  26304. var s = 1 - t;
  26305. for (var i = 0; i !== stride; ++i) {
  26306. var j = dstOffset + i;
  26307. buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
  26308. }
  26309. }
  26310. });
  26311. /**
  26312. *
  26313. * A reference to a real property in the scene graph.
  26314. *
  26315. *
  26316. * @author Ben Houston / http://clara.io/
  26317. * @author David Sarno / http://lighthaus.us/
  26318. * @author tschw
  26319. */
  26320. // Characters [].:/ are reserved for track binding syntax.
  26321. var _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  26322. var _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
  26323. // only latin characters, and the unicode \p{L} is not yet supported. So
  26324. // instead, we exclude reserved characters and match everything else.
  26325. var _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  26326. var _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
  26327. // be matched to parse the rest of the track name.
  26328. var _directoryRe = /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  26329. var _nodeRe = /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
  26330. // characters. Accessor may contain any character except closing bracket.
  26331. var _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
  26332. // contain any non-bracket characters.
  26333. var _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
  26334. var _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
  26335. var _supportedObjectNames = ['material', 'materials', 'bones'];
  26336. function Composite(targetGroup, path, optionalParsedPath) {
  26337. var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
  26338. this._targetGroup = targetGroup;
  26339. this._bindings = targetGroup.subscribe_(path, parsedPath);
  26340. }
  26341. Object.assign(Composite.prototype, {
  26342. getValue: function (array, offset) {
  26343. this.bind(); // bind all binding
  26344. var firstValidIndex = this._targetGroup.nCachedObjects_,
  26345. binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
  26346. if (binding !== undefined) binding.getValue(array, offset);
  26347. },
  26348. setValue: function (array, offset) {
  26349. var bindings = this._bindings;
  26350. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  26351. bindings[i].setValue(array, offset);
  26352. }
  26353. },
  26354. bind: function () {
  26355. var bindings = this._bindings;
  26356. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  26357. bindings[i].bind();
  26358. }
  26359. },
  26360. unbind: function () {
  26361. var bindings = this._bindings;
  26362. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  26363. bindings[i].unbind();
  26364. }
  26365. }
  26366. });
  26367. function PropertyBinding(rootNode, path, parsedPath) {
  26368. this.path = path;
  26369. this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
  26370. this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
  26371. this.rootNode = rootNode;
  26372. }
  26373. Object.assign(PropertyBinding, {
  26374. Composite: Composite,
  26375. create: function (root, path, parsedPath) {
  26376. if (!(root && root.isAnimationObjectGroup)) {
  26377. return new PropertyBinding(root, path, parsedPath);
  26378. } else {
  26379. return new PropertyBinding.Composite(root, path, parsedPath);
  26380. }
  26381. },
  26382. /**
  26383. * Replaces spaces with underscores and removes unsupported characters from
  26384. * node names, to ensure compatibility with parseTrackName().
  26385. *
  26386. * @param {string} name Node name to be sanitized.
  26387. * @return {string}
  26388. */
  26389. sanitizeNodeName: function (name) {
  26390. return name.replace(/\s/g, '_').replace(_reservedRe, '');
  26391. },
  26392. parseTrackName: function (trackName) {
  26393. var matches = _trackRe.exec(trackName);
  26394. if (!matches) {
  26395. throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
  26396. }
  26397. var results = {
  26398. // directoryName: matches[ 1 ], // (tschw) currently unused
  26399. nodeName: matches[2],
  26400. objectName: matches[3],
  26401. objectIndex: matches[4],
  26402. propertyName: matches[5],
  26403. // required
  26404. propertyIndex: matches[6]
  26405. };
  26406. var lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
  26407. if (lastDot !== undefined && lastDot !== -1) {
  26408. var objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against a whitelist. Otherwise, there
  26409. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  26410. // 'bar' could be the objectName, or part of a nodeName (which can
  26411. // include '.' characters).
  26412. if (_supportedObjectNames.indexOf(objectName) !== -1) {
  26413. results.nodeName = results.nodeName.substring(0, lastDot);
  26414. results.objectName = objectName;
  26415. }
  26416. }
  26417. if (results.propertyName === null || results.propertyName.length === 0) {
  26418. throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
  26419. }
  26420. return results;
  26421. },
  26422. findNode: function (root, nodeName) {
  26423. if (!nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
  26424. return root;
  26425. } // search into skeleton bones.
  26426. if (root.skeleton) {
  26427. var bone = root.skeleton.getBoneByName(nodeName);
  26428. if (bone !== undefined) {
  26429. return bone;
  26430. }
  26431. } // search into node subtree.
  26432. if (root.children) {
  26433. var searchNodeSubtree = function (children) {
  26434. for (var i = 0; i < children.length; i++) {
  26435. var childNode = children[i];
  26436. if (childNode.name === nodeName || childNode.uuid === nodeName) {
  26437. return childNode;
  26438. }
  26439. var result = searchNodeSubtree(childNode.children);
  26440. if (result) return result;
  26441. }
  26442. return null;
  26443. };
  26444. var subTreeNode = searchNodeSubtree(root.children);
  26445. if (subTreeNode) {
  26446. return subTreeNode;
  26447. }
  26448. }
  26449. return null;
  26450. }
  26451. });
  26452. Object.assign(PropertyBinding.prototype, {
  26453. // prototype, continued
  26454. // these are used to "bind" a nonexistent property
  26455. _getValue_unavailable: function () {},
  26456. _setValue_unavailable: function () {},
  26457. BindingType: {
  26458. Direct: 0,
  26459. EntireArray: 1,
  26460. ArrayElement: 2,
  26461. HasFromToArray: 3
  26462. },
  26463. Versioning: {
  26464. None: 0,
  26465. NeedsUpdate: 1,
  26466. MatrixWorldNeedsUpdate: 2
  26467. },
  26468. GetterByBindingType: [function getValue_direct(buffer, offset) {
  26469. buffer[offset] = this.node[this.propertyName];
  26470. }, function getValue_array(buffer, offset) {
  26471. var source = this.resolvedProperty;
  26472. for (var i = 0, n = source.length; i !== n; ++i) {
  26473. buffer[offset++] = source[i];
  26474. }
  26475. }, function getValue_arrayElement(buffer, offset) {
  26476. buffer[offset] = this.resolvedProperty[this.propertyIndex];
  26477. }, function getValue_toArray(buffer, offset) {
  26478. this.resolvedProperty.toArray(buffer, offset);
  26479. }],
  26480. SetterByBindingTypeAndVersioning: [[// Direct
  26481. function setValue_direct(buffer, offset) {
  26482. this.targetObject[this.propertyName] = buffer[offset];
  26483. }, function setValue_direct_setNeedsUpdate(buffer, offset) {
  26484. this.targetObject[this.propertyName] = buffer[offset];
  26485. this.targetObject.needsUpdate = true;
  26486. }, function setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
  26487. this.targetObject[this.propertyName] = buffer[offset];
  26488. this.targetObject.matrixWorldNeedsUpdate = true;
  26489. }], [// EntireArray
  26490. function setValue_array(buffer, offset) {
  26491. var dest = this.resolvedProperty;
  26492. for (var i = 0, n = dest.length; i !== n; ++i) {
  26493. dest[i] = buffer[offset++];
  26494. }
  26495. }, function setValue_array_setNeedsUpdate(buffer, offset) {
  26496. var dest = this.resolvedProperty;
  26497. for (var i = 0, n = dest.length; i !== n; ++i) {
  26498. dest[i] = buffer[offset++];
  26499. }
  26500. this.targetObject.needsUpdate = true;
  26501. }, function setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
  26502. var dest = this.resolvedProperty;
  26503. for (var i = 0, n = dest.length; i !== n; ++i) {
  26504. dest[i] = buffer[offset++];
  26505. }
  26506. this.targetObject.matrixWorldNeedsUpdate = true;
  26507. }], [// ArrayElement
  26508. function setValue_arrayElement(buffer, offset) {
  26509. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  26510. }, function setValue_arrayElement_setNeedsUpdate(buffer, offset) {
  26511. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  26512. this.targetObject.needsUpdate = true;
  26513. }, function setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
  26514. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  26515. this.targetObject.matrixWorldNeedsUpdate = true;
  26516. }], [// HasToFromArray
  26517. function setValue_fromArray(buffer, offset) {
  26518. this.resolvedProperty.fromArray(buffer, offset);
  26519. }, function setValue_fromArray_setNeedsUpdate(buffer, offset) {
  26520. this.resolvedProperty.fromArray(buffer, offset);
  26521. this.targetObject.needsUpdate = true;
  26522. }, function setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
  26523. this.resolvedProperty.fromArray(buffer, offset);
  26524. this.targetObject.matrixWorldNeedsUpdate = true;
  26525. }]],
  26526. getValue: function getValue_unbound(targetArray, offset) {
  26527. this.bind();
  26528. this.getValue(targetArray, offset); // Note: This class uses a State pattern on a per-method basis:
  26529. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  26530. // prototype version of these methods with one that represents
  26531. // the bound state. When the property is not found, the methods
  26532. // become no-ops.
  26533. },
  26534. setValue: function getValue_unbound(sourceArray, offset) {
  26535. this.bind();
  26536. this.setValue(sourceArray, offset);
  26537. },
  26538. // create getter / setter pair for a property in the scene graph
  26539. bind: function () {
  26540. var targetObject = this.node,
  26541. parsedPath = this.parsedPath,
  26542. objectName = parsedPath.objectName,
  26543. propertyName = parsedPath.propertyName,
  26544. propertyIndex = parsedPath.propertyIndex;
  26545. if (!targetObject) {
  26546. targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
  26547. this.node = targetObject;
  26548. } // set fail state so we can just 'return' on error
  26549. this.getValue = this._getValue_unavailable;
  26550. this.setValue = this._setValue_unavailable; // ensure there is a value node
  26551. if (!targetObject) {
  26552. console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
  26553. return;
  26554. }
  26555. if (objectName) {
  26556. var objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
  26557. switch (objectName) {
  26558. case 'materials':
  26559. if (!targetObject.material) {
  26560. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  26561. return;
  26562. }
  26563. if (!targetObject.material.materials) {
  26564. console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
  26565. return;
  26566. }
  26567. targetObject = targetObject.material.materials;
  26568. break;
  26569. case 'bones':
  26570. if (!targetObject.skeleton) {
  26571. console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
  26572. return;
  26573. } // potential future optimization: skip this if propertyIndex is already an integer
  26574. // and convert the integer string to a true integer.
  26575. targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
  26576. for (var i = 0; i < targetObject.length; i++) {
  26577. if (targetObject[i].name === objectIndex) {
  26578. objectIndex = i;
  26579. break;
  26580. }
  26581. }
  26582. break;
  26583. default:
  26584. if (targetObject[objectName] === undefined) {
  26585. console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
  26586. return;
  26587. }
  26588. targetObject = targetObject[objectName];
  26589. }
  26590. if (objectIndex !== undefined) {
  26591. if (targetObject[objectIndex] === undefined) {
  26592. console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
  26593. return;
  26594. }
  26595. targetObject = targetObject[objectIndex];
  26596. }
  26597. } // resolve property
  26598. var nodeProperty = targetObject[propertyName];
  26599. if (nodeProperty === undefined) {
  26600. var nodeName = parsedPath.nodeName;
  26601. console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
  26602. return;
  26603. } // determine versioning scheme
  26604. var versioning = this.Versioning.None;
  26605. this.targetObject = targetObject;
  26606. if (targetObject.needsUpdate !== undefined) {
  26607. // material
  26608. versioning = this.Versioning.NeedsUpdate;
  26609. } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
  26610. // node transform
  26611. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  26612. } // determine how the property gets bound
  26613. var bindingType = this.BindingType.Direct;
  26614. if (propertyIndex !== undefined) {
  26615. // access a sub element of the property array (only primitives are supported right now)
  26616. if (propertyName === "morphTargetInfluences") {
  26617. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  26618. // support resolving morphTarget names into indices.
  26619. if (!targetObject.geometry) {
  26620. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
  26621. return;
  26622. }
  26623. if (targetObject.geometry.isBufferGeometry) {
  26624. if (!targetObject.geometry.morphAttributes) {
  26625. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
  26626. return;
  26627. }
  26628. for (var i = 0; i < this.node.geometry.morphAttributes.position.length; i++) {
  26629. if (targetObject.geometry.morphAttributes.position[i].name === propertyIndex) {
  26630. propertyIndex = i;
  26631. break;
  26632. }
  26633. }
  26634. } else {
  26635. if (!targetObject.geometry.morphTargets) {
  26636. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphTargets.', this);
  26637. return;
  26638. }
  26639. for (var i = 0; i < this.node.geometry.morphTargets.length; i++) {
  26640. if (targetObject.geometry.morphTargets[i].name === propertyIndex) {
  26641. propertyIndex = i;
  26642. break;
  26643. }
  26644. }
  26645. }
  26646. }
  26647. bindingType = this.BindingType.ArrayElement;
  26648. this.resolvedProperty = nodeProperty;
  26649. this.propertyIndex = propertyIndex;
  26650. } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
  26651. // must use copy for Object3D.Euler/Quaternion
  26652. bindingType = this.BindingType.HasFromToArray;
  26653. this.resolvedProperty = nodeProperty;
  26654. } else if (Array.isArray(nodeProperty)) {
  26655. bindingType = this.BindingType.EntireArray;
  26656. this.resolvedProperty = nodeProperty;
  26657. } else {
  26658. this.propertyName = propertyName;
  26659. } // select getter / setter
  26660. this.getValue = this.GetterByBindingType[bindingType];
  26661. this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  26662. },
  26663. unbind: function () {
  26664. this.node = null; // back to the prototype version of getValue / setValue
  26665. // note: avoiding to mutate the shape of 'this' via 'delete'
  26666. this.getValue = this._getValue_unbound;
  26667. this.setValue = this._setValue_unbound;
  26668. }
  26669. }); //!\ DECLARE ALIAS AFTER assign prototype !
  26670. Object.assign(PropertyBinding.prototype, {
  26671. // initial state of these methods that calls 'bind'
  26672. _getValue_unbound: PropertyBinding.prototype.getValue,
  26673. _setValue_unbound: PropertyBinding.prototype.setValue
  26674. });
  26675. /**
  26676. *
  26677. * A group of objects that receives a shared animation state.
  26678. *
  26679. * Usage:
  26680. *
  26681. * - Add objects you would otherwise pass as 'root' to the
  26682. * constructor or the .clipAction method of AnimationMixer.
  26683. *
  26684. * - Instead pass this object as 'root'.
  26685. *
  26686. * - You can also add and remove objects later when the mixer
  26687. * is running.
  26688. *
  26689. * Note:
  26690. *
  26691. * Objects of this class appear as one object to the mixer,
  26692. * so cache control of the individual objects must be done
  26693. * on the group.
  26694. *
  26695. * Limitation:
  26696. *
  26697. * - The animated properties must be compatible among the
  26698. * all objects in the group.
  26699. *
  26700. * - A single property can either be controlled through a
  26701. * target group or directly, but not both.
  26702. *
  26703. * @author tschw
  26704. */
  26705. function AnimationObjectGroup() {
  26706. this.uuid = _Math.generateUUID(); // cached objects followed by the active ones
  26707. this._objects = Array.prototype.slice.call(arguments);
  26708. this.nCachedObjects_ = 0; // threshold
  26709. // note: read by PropertyBinding.Composite
  26710. var indices = {};
  26711. this._indicesByUUID = indices; // for bookkeeping
  26712. for (var i = 0, n = arguments.length; i !== n; ++i) {
  26713. indices[arguments[i].uuid] = i;
  26714. }
  26715. this._paths = []; // inside: string
  26716. this._parsedPaths = []; // inside: { we don't care, here }
  26717. this._bindings = []; // inside: Array< PropertyBinding >
  26718. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  26719. var scope = this;
  26720. this.stats = {
  26721. objects: {
  26722. get total() {
  26723. return scope._objects.length;
  26724. },
  26725. get inUse() {
  26726. return this.total - scope.nCachedObjects_;
  26727. }
  26728. },
  26729. get bindingsPerObject() {
  26730. return scope._bindings.length;
  26731. }
  26732. };
  26733. }
  26734. Object.assign(AnimationObjectGroup.prototype, {
  26735. isAnimationObjectGroup: true,
  26736. add: function () {
  26737. var objects = this._objects,
  26738. nObjects = objects.length,
  26739. nCachedObjects = this.nCachedObjects_,
  26740. indicesByUUID = this._indicesByUUID,
  26741. paths = this._paths,
  26742. parsedPaths = this._parsedPaths,
  26743. bindings = this._bindings,
  26744. nBindings = bindings.length,
  26745. knownObject = undefined;
  26746. for (var i = 0, n = arguments.length; i !== n; ++i) {
  26747. var object = arguments[i],
  26748. uuid = object.uuid,
  26749. index = indicesByUUID[uuid];
  26750. if (index === undefined) {
  26751. // unknown object -> add it to the ACTIVE region
  26752. index = nObjects++;
  26753. indicesByUUID[uuid] = index;
  26754. objects.push(object); // accounting is done, now do the same for all bindings
  26755. for (var j = 0, m = nBindings; j !== m; ++j) {
  26756. bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
  26757. }
  26758. } else if (index < nCachedObjects) {
  26759. knownObject = objects[index]; // move existing object to the ACTIVE region
  26760. var firstActiveIndex = --nCachedObjects,
  26761. lastCachedObject = objects[firstActiveIndex];
  26762. indicesByUUID[lastCachedObject.uuid] = index;
  26763. objects[index] = lastCachedObject;
  26764. indicesByUUID[uuid] = firstActiveIndex;
  26765. objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
  26766. for (var j = 0, m = nBindings; j !== m; ++j) {
  26767. var bindingsForPath = bindings[j],
  26768. lastCached = bindingsForPath[firstActiveIndex],
  26769. binding = bindingsForPath[index];
  26770. bindingsForPath[index] = lastCached;
  26771. if (binding === undefined) {
  26772. // since we do not bother to create new bindings
  26773. // for objects that are cached, the binding may
  26774. // or may not exist
  26775. binding = new PropertyBinding(object, paths[j], parsedPaths[j]);
  26776. }
  26777. bindingsForPath[firstActiveIndex] = binding;
  26778. }
  26779. } else if (objects[index] !== knownObject) {
  26780. console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
  26781. } // else the object is already where we want it to be
  26782. } // for arguments
  26783. this.nCachedObjects_ = nCachedObjects;
  26784. },
  26785. remove: function () {
  26786. var objects = this._objects,
  26787. nCachedObjects = this.nCachedObjects_,
  26788. indicesByUUID = this._indicesByUUID,
  26789. bindings = this._bindings,
  26790. nBindings = bindings.length;
  26791. for (var i = 0, n = arguments.length; i !== n; ++i) {
  26792. var object = arguments[i],
  26793. uuid = object.uuid,
  26794. index = indicesByUUID[uuid];
  26795. if (index !== undefined && index >= nCachedObjects) {
  26796. // move existing object into the CACHED region
  26797. var lastCachedIndex = nCachedObjects++,
  26798. firstActiveObject = objects[lastCachedIndex];
  26799. indicesByUUID[firstActiveObject.uuid] = index;
  26800. objects[index] = firstActiveObject;
  26801. indicesByUUID[uuid] = lastCachedIndex;
  26802. objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
  26803. for (var j = 0, m = nBindings; j !== m; ++j) {
  26804. var bindingsForPath = bindings[j],
  26805. firstActive = bindingsForPath[lastCachedIndex],
  26806. binding = bindingsForPath[index];
  26807. bindingsForPath[index] = firstActive;
  26808. bindingsForPath[lastCachedIndex] = binding;
  26809. }
  26810. }
  26811. } // for arguments
  26812. this.nCachedObjects_ = nCachedObjects;
  26813. },
  26814. // remove & forget
  26815. uncache: function () {
  26816. var objects = this._objects,
  26817. nObjects = objects.length,
  26818. nCachedObjects = this.nCachedObjects_,
  26819. indicesByUUID = this._indicesByUUID,
  26820. bindings = this._bindings,
  26821. nBindings = bindings.length;
  26822. for (var i = 0, n = arguments.length; i !== n; ++i) {
  26823. var object = arguments[i],
  26824. uuid = object.uuid,
  26825. index = indicesByUUID[uuid];
  26826. if (index !== undefined) {
  26827. delete indicesByUUID[uuid];
  26828. if (index < nCachedObjects) {
  26829. // object is cached, shrink the CACHED region
  26830. var firstActiveIndex = --nCachedObjects,
  26831. lastCachedObject = objects[firstActiveIndex],
  26832. lastIndex = --nObjects,
  26833. lastObject = objects[lastIndex]; // last cached object takes this object's place
  26834. indicesByUUID[lastCachedObject.uuid] = index;
  26835. objects[index] = lastCachedObject; // last object goes to the activated slot and pop
  26836. indicesByUUID[lastObject.uuid] = firstActiveIndex;
  26837. objects[firstActiveIndex] = lastObject;
  26838. objects.pop(); // accounting is done, now do the same for all bindings
  26839. for (var j = 0, m = nBindings; j !== m; ++j) {
  26840. var bindingsForPath = bindings[j],
  26841. lastCached = bindingsForPath[firstActiveIndex],
  26842. last = bindingsForPath[lastIndex];
  26843. bindingsForPath[index] = lastCached;
  26844. bindingsForPath[firstActiveIndex] = last;
  26845. bindingsForPath.pop();
  26846. }
  26847. } else {
  26848. // object is active, just swap with the last and pop
  26849. var lastIndex = --nObjects,
  26850. lastObject = objects[lastIndex];
  26851. indicesByUUID[lastObject.uuid] = index;
  26852. objects[index] = lastObject;
  26853. objects.pop(); // accounting is done, now do the same for all bindings
  26854. for (var j = 0, m = nBindings; j !== m; ++j) {
  26855. var bindingsForPath = bindings[j];
  26856. bindingsForPath[index] = bindingsForPath[lastIndex];
  26857. bindingsForPath.pop();
  26858. }
  26859. } // cached or active
  26860. } // if object is known
  26861. } // for arguments
  26862. this.nCachedObjects_ = nCachedObjects;
  26863. },
  26864. // Internal interface used by befriended PropertyBinding.Composite:
  26865. subscribe_: function (path, parsedPath) {
  26866. // returns an array of bindings for the given path that is changed
  26867. // according to the contained objects in the group
  26868. var indicesByPath = this._bindingsIndicesByPath,
  26869. index = indicesByPath[path],
  26870. bindings = this._bindings;
  26871. if (index !== undefined) return bindings[index];
  26872. var paths = this._paths,
  26873. parsedPaths = this._parsedPaths,
  26874. objects = this._objects,
  26875. nObjects = objects.length,
  26876. nCachedObjects = this.nCachedObjects_,
  26877. bindingsForPath = new Array(nObjects);
  26878. index = bindings.length;
  26879. indicesByPath[path] = index;
  26880. paths.push(path);
  26881. parsedPaths.push(parsedPath);
  26882. bindings.push(bindingsForPath);
  26883. for (var i = nCachedObjects, n = objects.length; i !== n; ++i) {
  26884. var object = objects[i];
  26885. bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
  26886. }
  26887. return bindingsForPath;
  26888. },
  26889. unsubscribe_: function (path) {
  26890. // tells the group to forget about a property path and no longer
  26891. // update the array previously obtained with 'subscribe_'
  26892. var indicesByPath = this._bindingsIndicesByPath,
  26893. index = indicesByPath[path];
  26894. if (index !== undefined) {
  26895. var paths = this._paths,
  26896. parsedPaths = this._parsedPaths,
  26897. bindings = this._bindings,
  26898. lastBindingsIndex = bindings.length - 1,
  26899. lastBindings = bindings[lastBindingsIndex],
  26900. lastBindingsPath = path[lastBindingsIndex];
  26901. indicesByPath[lastBindingsPath] = index;
  26902. bindings[index] = lastBindings;
  26903. bindings.pop();
  26904. parsedPaths[index] = parsedPaths[lastBindingsIndex];
  26905. parsedPaths.pop();
  26906. paths[index] = paths[lastBindingsIndex];
  26907. paths.pop();
  26908. }
  26909. }
  26910. });
  26911. /**
  26912. *
  26913. * Action provided by AnimationMixer for scheduling clip playback on specific
  26914. * objects.
  26915. *
  26916. * @author Ben Houston / http://clara.io/
  26917. * @author David Sarno / http://lighthaus.us/
  26918. * @author tschw
  26919. *
  26920. */
  26921. function AnimationAction(mixer, clip, localRoot) {
  26922. this._mixer = mixer;
  26923. this._clip = clip;
  26924. this._localRoot = localRoot || null;
  26925. var tracks = clip.tracks,
  26926. nTracks = tracks.length,
  26927. interpolants = new Array(nTracks);
  26928. var interpolantSettings = {
  26929. endingStart: ZeroCurvatureEnding,
  26930. endingEnd: ZeroCurvatureEnding
  26931. };
  26932. for (var i = 0; i !== nTracks; ++i) {
  26933. var interpolant = tracks[i].createInterpolant(null);
  26934. interpolants[i] = interpolant;
  26935. interpolant.settings = interpolantSettings;
  26936. }
  26937. this._interpolantSettings = interpolantSettings;
  26938. this._interpolants = interpolants; // bound by the mixer
  26939. // inside: PropertyMixer (managed by the mixer)
  26940. this._propertyBindings = new Array(nTracks);
  26941. this._cacheIndex = null; // for the memory manager
  26942. this._byClipCacheIndex = null; // for the memory manager
  26943. this._timeScaleInterpolant = null;
  26944. this._weightInterpolant = null;
  26945. this.loop = LoopRepeat;
  26946. this._loopCount = -1; // global mixer time when the action is to be started
  26947. // it's set back to 'null' upon start of the action
  26948. this._startTime = null; // scaled local time of the action
  26949. // gets clamped or wrapped to 0..clip.duration according to loop
  26950. this.time = 0;
  26951. this.timeScale = 1;
  26952. this._effectiveTimeScale = 1;
  26953. this.weight = 1;
  26954. this._effectiveWeight = 1;
  26955. this.repetitions = Infinity; // no. of repetitions when looping
  26956. this.paused = false; // true -> zero effective time scale
  26957. this.enabled = true; // false -> zero effective weight
  26958. this.clampWhenFinished = false; // keep feeding the last frame?
  26959. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  26960. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  26961. }
  26962. Object.assign(AnimationAction.prototype, {
  26963. // State & Scheduling
  26964. play: function () {
  26965. this._mixer._activateAction(this);
  26966. return this;
  26967. },
  26968. stop: function () {
  26969. this._mixer._deactivateAction(this);
  26970. return this.reset();
  26971. },
  26972. reset: function () {
  26973. this.paused = false;
  26974. this.enabled = true;
  26975. this.time = 0; // restart clip
  26976. this._loopCount = -1; // forget previous loops
  26977. this._startTime = null; // forget scheduling
  26978. return this.stopFading().stopWarping();
  26979. },
  26980. isRunning: function () {
  26981. return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  26982. },
  26983. // return true when play has been called
  26984. isScheduled: function () {
  26985. return this._mixer._isActiveAction(this);
  26986. },
  26987. startAt: function (time) {
  26988. this._startTime = time;
  26989. return this;
  26990. },
  26991. setLoop: function (mode, repetitions) {
  26992. this.loop = mode;
  26993. this.repetitions = repetitions;
  26994. return this;
  26995. },
  26996. // Weight
  26997. // set the weight stopping any scheduled fading
  26998. // although .enabled = false yields an effective weight of zero, this
  26999. // method does *not* change .enabled, because it would be confusing
  27000. setEffectiveWeight: function (weight) {
  27001. this.weight = weight; // note: same logic as when updated at runtime
  27002. this._effectiveWeight = this.enabled ? weight : 0;
  27003. return this.stopFading();
  27004. },
  27005. // return the weight considering fading and .enabled
  27006. getEffectiveWeight: function () {
  27007. return this._effectiveWeight;
  27008. },
  27009. fadeIn: function (duration) {
  27010. return this._scheduleFading(duration, 0, 1);
  27011. },
  27012. fadeOut: function (duration) {
  27013. return this._scheduleFading(duration, 1, 0);
  27014. },
  27015. crossFadeFrom: function (fadeOutAction, duration, warp) {
  27016. fadeOutAction.fadeOut(duration);
  27017. this.fadeIn(duration);
  27018. if (warp) {
  27019. var fadeInDuration = this._clip.duration,
  27020. fadeOutDuration = fadeOutAction._clip.duration,
  27021. startEndRatio = fadeOutDuration / fadeInDuration,
  27022. endStartRatio = fadeInDuration / fadeOutDuration;
  27023. fadeOutAction.warp(1.0, startEndRatio, duration);
  27024. this.warp(endStartRatio, 1.0, duration);
  27025. }
  27026. return this;
  27027. },
  27028. crossFadeTo: function (fadeInAction, duration, warp) {
  27029. return fadeInAction.crossFadeFrom(this, duration, warp);
  27030. },
  27031. stopFading: function () {
  27032. var weightInterpolant = this._weightInterpolant;
  27033. if (weightInterpolant !== null) {
  27034. this._weightInterpolant = null;
  27035. this._mixer._takeBackControlInterpolant(weightInterpolant);
  27036. }
  27037. return this;
  27038. },
  27039. // Time Scale Control
  27040. // set the time scale stopping any scheduled warping
  27041. // although .paused = true yields an effective time scale of zero, this
  27042. // method does *not* change .paused, because it would be confusing
  27043. setEffectiveTimeScale: function (timeScale) {
  27044. this.timeScale = timeScale;
  27045. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  27046. return this.stopWarping();
  27047. },
  27048. // return the time scale considering warping and .paused
  27049. getEffectiveTimeScale: function () {
  27050. return this._effectiveTimeScale;
  27051. },
  27052. setDuration: function (duration) {
  27053. this.timeScale = this._clip.duration / duration;
  27054. return this.stopWarping();
  27055. },
  27056. syncWith: function (action) {
  27057. this.time = action.time;
  27058. this.timeScale = action.timeScale;
  27059. return this.stopWarping();
  27060. },
  27061. halt: function (duration) {
  27062. return this.warp(this._effectiveTimeScale, 0, duration);
  27063. },
  27064. warp: function (startTimeScale, endTimeScale, duration) {
  27065. var mixer = this._mixer,
  27066. now = mixer.time,
  27067. interpolant = this._timeScaleInterpolant,
  27068. timeScale = this.timeScale;
  27069. if (interpolant === null) {
  27070. interpolant = mixer._lendControlInterpolant();
  27071. this._timeScaleInterpolant = interpolant;
  27072. }
  27073. var times = interpolant.parameterPositions,
  27074. values = interpolant.sampleValues;
  27075. times[0] = now;
  27076. times[1] = now + duration;
  27077. values[0] = startTimeScale / timeScale;
  27078. values[1] = endTimeScale / timeScale;
  27079. return this;
  27080. },
  27081. stopWarping: function () {
  27082. var timeScaleInterpolant = this._timeScaleInterpolant;
  27083. if (timeScaleInterpolant !== null) {
  27084. this._timeScaleInterpolant = null;
  27085. this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
  27086. }
  27087. return this;
  27088. },
  27089. // Object Accessors
  27090. getMixer: function () {
  27091. return this._mixer;
  27092. },
  27093. getClip: function () {
  27094. return this._clip;
  27095. },
  27096. getRoot: function () {
  27097. return this._localRoot || this._mixer._root;
  27098. },
  27099. // Interna
  27100. _update: function (time, deltaTime, timeDirection, accuIndex) {
  27101. // called by the mixer
  27102. if (!this.enabled) {
  27103. // call ._updateWeight() to update ._effectiveWeight
  27104. this._updateWeight(time);
  27105. return;
  27106. }
  27107. var startTime = this._startTime;
  27108. if (startTime !== null) {
  27109. // check for scheduled start of action
  27110. var timeRunning = (time - startTime) * timeDirection;
  27111. if (timeRunning < 0 || timeDirection === 0) {
  27112. return; // yet to come / don't decide when delta = 0
  27113. } // start
  27114. this._startTime = null; // unschedule
  27115. deltaTime = timeDirection * timeRunning;
  27116. } // apply time scale and advance time
  27117. deltaTime *= this._updateTimeScale(time);
  27118. var clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
  27119. // an effective weight of 0
  27120. var weight = this._updateWeight(time);
  27121. if (weight > 0) {
  27122. var interpolants = this._interpolants;
  27123. var propertyMixers = this._propertyBindings;
  27124. for (var j = 0, m = interpolants.length; j !== m; ++j) {
  27125. interpolants[j].evaluate(clipTime);
  27126. propertyMixers[j].accumulate(accuIndex, weight);
  27127. }
  27128. }
  27129. },
  27130. _updateWeight: function (time) {
  27131. var weight = 0;
  27132. if (this.enabled) {
  27133. weight = this.weight;
  27134. var interpolant = this._weightInterpolant;
  27135. if (interpolant !== null) {
  27136. var interpolantValue = interpolant.evaluate(time)[0];
  27137. weight *= interpolantValue;
  27138. if (time > interpolant.parameterPositions[1]) {
  27139. this.stopFading();
  27140. if (interpolantValue === 0) {
  27141. // faded out, disable
  27142. this.enabled = false;
  27143. }
  27144. }
  27145. }
  27146. }
  27147. this._effectiveWeight = weight;
  27148. return weight;
  27149. },
  27150. _updateTimeScale: function (time) {
  27151. var timeScale = 0;
  27152. if (!this.paused) {
  27153. timeScale = this.timeScale;
  27154. var interpolant = this._timeScaleInterpolant;
  27155. if (interpolant !== null) {
  27156. var interpolantValue = interpolant.evaluate(time)[0];
  27157. timeScale *= interpolantValue;
  27158. if (time > interpolant.parameterPositions[1]) {
  27159. this.stopWarping();
  27160. if (timeScale === 0) {
  27161. // motion has halted, pause
  27162. this.paused = true;
  27163. } else {
  27164. // warp done - apply final time scale
  27165. this.timeScale = timeScale;
  27166. }
  27167. }
  27168. }
  27169. }
  27170. this._effectiveTimeScale = timeScale;
  27171. return timeScale;
  27172. },
  27173. _updateTime: function (deltaTime) {
  27174. var time = this.time + deltaTime;
  27175. var duration = this._clip.duration;
  27176. var loop = this.loop;
  27177. var loopCount = this._loopCount;
  27178. var pingPong = loop === LoopPingPong;
  27179. if (deltaTime === 0) {
  27180. if (loopCount === -1) return time;
  27181. return pingPong && (loopCount & 1) === 1 ? duration - time : time;
  27182. }
  27183. if (loop === LoopOnce) {
  27184. if (loopCount === -1) {
  27185. // just started
  27186. this._loopCount = 0;
  27187. this._setEndings(true, true, false);
  27188. }
  27189. handle_stop: {
  27190. if (time >= duration) {
  27191. time = duration;
  27192. } else if (time < 0) {
  27193. time = 0;
  27194. } else {
  27195. this.time = time;
  27196. break handle_stop;
  27197. }
  27198. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  27199. this.time = time;
  27200. this._mixer.dispatchEvent({
  27201. type: 'finished',
  27202. action: this,
  27203. direction: deltaTime < 0 ? -1 : 1
  27204. });
  27205. }
  27206. } else {
  27207. // repetitive Repeat or PingPong
  27208. if (loopCount === -1) {
  27209. // just started
  27210. if (deltaTime >= 0) {
  27211. loopCount = 0;
  27212. this._setEndings(true, this.repetitions === 0, pingPong);
  27213. } else {
  27214. // when looping in reverse direction, the initial
  27215. // transition through zero counts as a repetition,
  27216. // so leave loopCount at -1
  27217. this._setEndings(this.repetitions === 0, true, pingPong);
  27218. }
  27219. }
  27220. if (time >= duration || time < 0) {
  27221. // wrap around
  27222. var loopDelta = Math.floor(time / duration); // signed
  27223. time -= duration * loopDelta;
  27224. loopCount += Math.abs(loopDelta);
  27225. var pending = this.repetitions - loopCount;
  27226. if (pending <= 0) {
  27227. // have to stop (switch state, clamp time, fire event)
  27228. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  27229. time = deltaTime > 0 ? duration : 0;
  27230. this.time = time;
  27231. this._mixer.dispatchEvent({
  27232. type: 'finished',
  27233. action: this,
  27234. direction: deltaTime > 0 ? 1 : -1
  27235. });
  27236. } else {
  27237. // keep running
  27238. if (pending === 1) {
  27239. // entering the last round
  27240. var atStart = deltaTime < 0;
  27241. this._setEndings(atStart, !atStart, pingPong);
  27242. } else {
  27243. this._setEndings(false, false, pingPong);
  27244. }
  27245. this._loopCount = loopCount;
  27246. this.time = time;
  27247. this._mixer.dispatchEvent({
  27248. type: 'loop',
  27249. action: this,
  27250. loopDelta: loopDelta
  27251. });
  27252. }
  27253. } else {
  27254. this.time = time;
  27255. }
  27256. if (pingPong && (loopCount & 1) === 1) {
  27257. // invert time for the "pong round"
  27258. return duration - time;
  27259. }
  27260. }
  27261. return time;
  27262. },
  27263. _setEndings: function (atStart, atEnd, pingPong) {
  27264. var settings = this._interpolantSettings;
  27265. if (pingPong) {
  27266. settings.endingStart = ZeroSlopeEnding;
  27267. settings.endingEnd = ZeroSlopeEnding;
  27268. } else {
  27269. // assuming for LoopOnce atStart == atEnd == true
  27270. if (atStart) {
  27271. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27272. } else {
  27273. settings.endingStart = WrapAroundEnding;
  27274. }
  27275. if (atEnd) {
  27276. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27277. } else {
  27278. settings.endingEnd = WrapAroundEnding;
  27279. }
  27280. }
  27281. },
  27282. _scheduleFading: function (duration, weightNow, weightThen) {
  27283. var mixer = this._mixer,
  27284. now = mixer.time,
  27285. interpolant = this._weightInterpolant;
  27286. if (interpolant === null) {
  27287. interpolant = mixer._lendControlInterpolant();
  27288. this._weightInterpolant = interpolant;
  27289. }
  27290. var times = interpolant.parameterPositions,
  27291. values = interpolant.sampleValues;
  27292. times[0] = now;
  27293. values[0] = weightNow;
  27294. times[1] = now + duration;
  27295. values[1] = weightThen;
  27296. return this;
  27297. }
  27298. });
  27299. /**
  27300. *
  27301. * Player for AnimationClips.
  27302. *
  27303. *
  27304. * @author Ben Houston / http://clara.io/
  27305. * @author David Sarno / http://lighthaus.us/
  27306. * @author tschw
  27307. */
  27308. function AnimationMixer(root) {
  27309. this._root = root;
  27310. this._initMemoryManager();
  27311. this._accuIndex = 0;
  27312. this.time = 0;
  27313. this.timeScale = 1.0;
  27314. }
  27315. AnimationMixer.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  27316. constructor: AnimationMixer,
  27317. _bindAction: function (action, prototypeAction) {
  27318. var root = action._localRoot || this._root,
  27319. tracks = action._clip.tracks,
  27320. nTracks = tracks.length,
  27321. bindings = action._propertyBindings,
  27322. interpolants = action._interpolants,
  27323. rootUuid = root.uuid,
  27324. bindingsByRoot = this._bindingsByRootAndName,
  27325. bindingsByName = bindingsByRoot[rootUuid];
  27326. if (bindingsByName === undefined) {
  27327. bindingsByName = {};
  27328. bindingsByRoot[rootUuid] = bindingsByName;
  27329. }
  27330. for (var i = 0; i !== nTracks; ++i) {
  27331. var track = tracks[i],
  27332. trackName = track.name,
  27333. binding = bindingsByName[trackName];
  27334. if (binding !== undefined) {
  27335. bindings[i] = binding;
  27336. } else {
  27337. binding = bindings[i];
  27338. if (binding !== undefined) {
  27339. // existing binding, make sure the cache knows
  27340. if (binding._cacheIndex === null) {
  27341. ++binding.referenceCount;
  27342. this._addInactiveBinding(binding, rootUuid, trackName);
  27343. }
  27344. continue;
  27345. }
  27346. var path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
  27347. binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
  27348. ++binding.referenceCount;
  27349. this._addInactiveBinding(binding, rootUuid, trackName);
  27350. bindings[i] = binding;
  27351. }
  27352. interpolants[i].resultBuffer = binding.buffer;
  27353. }
  27354. },
  27355. _activateAction: function (action) {
  27356. if (!this._isActiveAction(action)) {
  27357. if (action._cacheIndex === null) {
  27358. // this action has been forgotten by the cache, but the user
  27359. // appears to be still using it -> rebind
  27360. var rootUuid = (action._localRoot || this._root).uuid,
  27361. clipUuid = action._clip.uuid,
  27362. actionsForClip = this._actionsByClip[clipUuid];
  27363. this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
  27364. this._addInactiveAction(action, clipUuid, rootUuid);
  27365. }
  27366. var bindings = action._propertyBindings; // increment reference counts / sort out state
  27367. for (var i = 0, n = bindings.length; i !== n; ++i) {
  27368. var binding = bindings[i];
  27369. if (binding.useCount++ === 0) {
  27370. this._lendBinding(binding);
  27371. binding.saveOriginalState();
  27372. }
  27373. }
  27374. this._lendAction(action);
  27375. }
  27376. },
  27377. _deactivateAction: function (action) {
  27378. if (this._isActiveAction(action)) {
  27379. var bindings = action._propertyBindings; // decrement reference counts / sort out state
  27380. for (var i = 0, n = bindings.length; i !== n; ++i) {
  27381. var binding = bindings[i];
  27382. if (--binding.useCount === 0) {
  27383. binding.restoreOriginalState();
  27384. this._takeBackBinding(binding);
  27385. }
  27386. }
  27387. this._takeBackAction(action);
  27388. }
  27389. },
  27390. // Memory manager
  27391. _initMemoryManager: function () {
  27392. this._actions = []; // 'nActiveActions' followed by inactive ones
  27393. this._nActiveActions = 0;
  27394. this._actionsByClip = {}; // inside:
  27395. // {
  27396. // knownActions: Array< AnimationAction > - used as prototypes
  27397. // actionByRoot: AnimationAction - lookup
  27398. // }
  27399. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  27400. this._nActiveBindings = 0;
  27401. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  27402. this._controlInterpolants = []; // same game as above
  27403. this._nActiveControlInterpolants = 0;
  27404. var scope = this;
  27405. this.stats = {
  27406. actions: {
  27407. get total() {
  27408. return scope._actions.length;
  27409. },
  27410. get inUse() {
  27411. return scope._nActiveActions;
  27412. }
  27413. },
  27414. bindings: {
  27415. get total() {
  27416. return scope._bindings.length;
  27417. },
  27418. get inUse() {
  27419. return scope._nActiveBindings;
  27420. }
  27421. },
  27422. controlInterpolants: {
  27423. get total() {
  27424. return scope._controlInterpolants.length;
  27425. },
  27426. get inUse() {
  27427. return scope._nActiveControlInterpolants;
  27428. }
  27429. }
  27430. };
  27431. },
  27432. // Memory management for AnimationAction objects
  27433. _isActiveAction: function (action) {
  27434. var index = action._cacheIndex;
  27435. return index !== null && index < this._nActiveActions;
  27436. },
  27437. _addInactiveAction: function (action, clipUuid, rootUuid) {
  27438. var actions = this._actions,
  27439. actionsByClip = this._actionsByClip,
  27440. actionsForClip = actionsByClip[clipUuid];
  27441. if (actionsForClip === undefined) {
  27442. actionsForClip = {
  27443. knownActions: [action],
  27444. actionByRoot: {}
  27445. };
  27446. action._byClipCacheIndex = 0;
  27447. actionsByClip[clipUuid] = actionsForClip;
  27448. } else {
  27449. var knownActions = actionsForClip.knownActions;
  27450. action._byClipCacheIndex = knownActions.length;
  27451. knownActions.push(action);
  27452. }
  27453. action._cacheIndex = actions.length;
  27454. actions.push(action);
  27455. actionsForClip.actionByRoot[rootUuid] = action;
  27456. },
  27457. _removeInactiveAction: function (action) {
  27458. var actions = this._actions,
  27459. lastInactiveAction = actions[actions.length - 1],
  27460. cacheIndex = action._cacheIndex;
  27461. lastInactiveAction._cacheIndex = cacheIndex;
  27462. actions[cacheIndex] = lastInactiveAction;
  27463. actions.pop();
  27464. action._cacheIndex = null;
  27465. var clipUuid = action._clip.uuid,
  27466. actionsByClip = this._actionsByClip,
  27467. actionsForClip = actionsByClip[clipUuid],
  27468. knownActionsForClip = actionsForClip.knownActions,
  27469. lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
  27470. byClipCacheIndex = action._byClipCacheIndex;
  27471. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  27472. knownActionsForClip[byClipCacheIndex] = lastKnownAction;
  27473. knownActionsForClip.pop();
  27474. action._byClipCacheIndex = null;
  27475. var actionByRoot = actionsForClip.actionByRoot,
  27476. rootUuid = (action._localRoot || this._root).uuid;
  27477. delete actionByRoot[rootUuid];
  27478. if (knownActionsForClip.length === 0) {
  27479. delete actionsByClip[clipUuid];
  27480. }
  27481. this._removeInactiveBindingsForAction(action);
  27482. },
  27483. _removeInactiveBindingsForAction: function (action) {
  27484. var bindings = action._propertyBindings;
  27485. for (var i = 0, n = bindings.length; i !== n; ++i) {
  27486. var binding = bindings[i];
  27487. if (--binding.referenceCount === 0) {
  27488. this._removeInactiveBinding(binding);
  27489. }
  27490. }
  27491. },
  27492. _lendAction: function (action) {
  27493. // [ active actions | inactive actions ]
  27494. // [ active actions >| inactive actions ]
  27495. // s a
  27496. // <-swap->
  27497. // a s
  27498. var actions = this._actions,
  27499. prevIndex = action._cacheIndex,
  27500. lastActiveIndex = this._nActiveActions++,
  27501. firstInactiveAction = actions[lastActiveIndex];
  27502. action._cacheIndex = lastActiveIndex;
  27503. actions[lastActiveIndex] = action;
  27504. firstInactiveAction._cacheIndex = prevIndex;
  27505. actions[prevIndex] = firstInactiveAction;
  27506. },
  27507. _takeBackAction: function (action) {
  27508. // [ active actions | inactive actions ]
  27509. // [ active actions |< inactive actions ]
  27510. // a s
  27511. // <-swap->
  27512. // s a
  27513. var actions = this._actions,
  27514. prevIndex = action._cacheIndex,
  27515. firstInactiveIndex = --this._nActiveActions,
  27516. lastActiveAction = actions[firstInactiveIndex];
  27517. action._cacheIndex = firstInactiveIndex;
  27518. actions[firstInactiveIndex] = action;
  27519. lastActiveAction._cacheIndex = prevIndex;
  27520. actions[prevIndex] = lastActiveAction;
  27521. },
  27522. // Memory management for PropertyMixer objects
  27523. _addInactiveBinding: function (binding, rootUuid, trackName) {
  27524. var bindingsByRoot = this._bindingsByRootAndName,
  27525. bindingByName = bindingsByRoot[rootUuid],
  27526. bindings = this._bindings;
  27527. if (bindingByName === undefined) {
  27528. bindingByName = {};
  27529. bindingsByRoot[rootUuid] = bindingByName;
  27530. }
  27531. bindingByName[trackName] = binding;
  27532. binding._cacheIndex = bindings.length;
  27533. bindings.push(binding);
  27534. },
  27535. _removeInactiveBinding: function (binding) {
  27536. var bindings = this._bindings,
  27537. propBinding = binding.binding,
  27538. rootUuid = propBinding.rootNode.uuid,
  27539. trackName = propBinding.path,
  27540. bindingsByRoot = this._bindingsByRootAndName,
  27541. bindingByName = bindingsByRoot[rootUuid],
  27542. lastInactiveBinding = bindings[bindings.length - 1],
  27543. cacheIndex = binding._cacheIndex;
  27544. lastInactiveBinding._cacheIndex = cacheIndex;
  27545. bindings[cacheIndex] = lastInactiveBinding;
  27546. bindings.pop();
  27547. delete bindingByName[trackName];
  27548. if (Object.keys(bindingByName).length === 0) {
  27549. delete bindingsByRoot[rootUuid];
  27550. }
  27551. },
  27552. _lendBinding: function (binding) {
  27553. var bindings = this._bindings,
  27554. prevIndex = binding._cacheIndex,
  27555. lastActiveIndex = this._nActiveBindings++,
  27556. firstInactiveBinding = bindings[lastActiveIndex];
  27557. binding._cacheIndex = lastActiveIndex;
  27558. bindings[lastActiveIndex] = binding;
  27559. firstInactiveBinding._cacheIndex = prevIndex;
  27560. bindings[prevIndex] = firstInactiveBinding;
  27561. },
  27562. _takeBackBinding: function (binding) {
  27563. var bindings = this._bindings,
  27564. prevIndex = binding._cacheIndex,
  27565. firstInactiveIndex = --this._nActiveBindings,
  27566. lastActiveBinding = bindings[firstInactiveIndex];
  27567. binding._cacheIndex = firstInactiveIndex;
  27568. bindings[firstInactiveIndex] = binding;
  27569. lastActiveBinding._cacheIndex = prevIndex;
  27570. bindings[prevIndex] = lastActiveBinding;
  27571. },
  27572. // Memory management of Interpolants for weight and time scale
  27573. _lendControlInterpolant: function () {
  27574. var interpolants = this._controlInterpolants,
  27575. lastActiveIndex = this._nActiveControlInterpolants++,
  27576. interpolant = interpolants[lastActiveIndex];
  27577. if (interpolant === undefined) {
  27578. interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, this._controlInterpolantsResultBuffer);
  27579. interpolant.__cacheIndex = lastActiveIndex;
  27580. interpolants[lastActiveIndex] = interpolant;
  27581. }
  27582. return interpolant;
  27583. },
  27584. _takeBackControlInterpolant: function (interpolant) {
  27585. var interpolants = this._controlInterpolants,
  27586. prevIndex = interpolant.__cacheIndex,
  27587. firstInactiveIndex = --this._nActiveControlInterpolants,
  27588. lastActiveInterpolant = interpolants[firstInactiveIndex];
  27589. interpolant.__cacheIndex = firstInactiveIndex;
  27590. interpolants[firstInactiveIndex] = interpolant;
  27591. lastActiveInterpolant.__cacheIndex = prevIndex;
  27592. interpolants[prevIndex] = lastActiveInterpolant;
  27593. },
  27594. _controlInterpolantsResultBuffer: new Float32Array(1),
  27595. // return an action for a clip optionally using a custom root target
  27596. // object (this method allocates a lot of dynamic memory in case a
  27597. // previously unknown clip/root combination is specified)
  27598. clipAction: function (clip, optionalRoot) {
  27599. var root = optionalRoot || this._root,
  27600. rootUuid = root.uuid,
  27601. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  27602. clipUuid = clipObject !== null ? clipObject.uuid : clip,
  27603. actionsForClip = this._actionsByClip[clipUuid],
  27604. prototypeAction = null;
  27605. if (actionsForClip !== undefined) {
  27606. var existingAction = actionsForClip.actionByRoot[rootUuid];
  27607. if (existingAction !== undefined) {
  27608. return existingAction;
  27609. } // we know the clip, so we don't have to parse all
  27610. // the bindings again but can just copy
  27611. prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
  27612. if (clipObject === null) clipObject = prototypeAction._clip;
  27613. } // clip must be known when specified via string
  27614. if (clipObject === null) return null; // allocate all resources required to run it
  27615. var newAction = new AnimationAction(this, clipObject, optionalRoot);
  27616. this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
  27617. this._addInactiveAction(newAction, clipUuid, rootUuid);
  27618. return newAction;
  27619. },
  27620. // get an existing action
  27621. existingAction: function (clip, optionalRoot) {
  27622. var root = optionalRoot || this._root,
  27623. rootUuid = root.uuid,
  27624. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  27625. clipUuid = clipObject ? clipObject.uuid : clip,
  27626. actionsForClip = this._actionsByClip[clipUuid];
  27627. if (actionsForClip !== undefined) {
  27628. return actionsForClip.actionByRoot[rootUuid] || null;
  27629. }
  27630. return null;
  27631. },
  27632. // deactivates all previously scheduled actions
  27633. stopAllAction: function () {
  27634. var actions = this._actions,
  27635. nActions = this._nActiveActions,
  27636. bindings = this._bindings,
  27637. nBindings = this._nActiveBindings;
  27638. this._nActiveActions = 0;
  27639. this._nActiveBindings = 0;
  27640. for (var i = 0; i !== nActions; ++i) {
  27641. actions[i].reset();
  27642. }
  27643. for (var i = 0; i !== nBindings; ++i) {
  27644. bindings[i].useCount = 0;
  27645. }
  27646. return this;
  27647. },
  27648. // advance the time and update apply the animation
  27649. update: function (deltaTime) {
  27650. deltaTime *= this.timeScale;
  27651. var actions = this._actions,
  27652. nActions = this._nActiveActions,
  27653. time = this.time += deltaTime,
  27654. timeDirection = Math.sign(deltaTime),
  27655. accuIndex = this._accuIndex ^= 1; // run active actions
  27656. for (var i = 0; i !== nActions; ++i) {
  27657. var action = actions[i];
  27658. action._update(time, deltaTime, timeDirection, accuIndex);
  27659. } // update scene graph
  27660. var bindings = this._bindings,
  27661. nBindings = this._nActiveBindings;
  27662. for (var i = 0; i !== nBindings; ++i) {
  27663. bindings[i].apply(accuIndex);
  27664. }
  27665. return this;
  27666. },
  27667. // Allows you to seek to a specific time in an animation.
  27668. setTime: function (timeInSeconds) {
  27669. this.time = 0; // Zero out time attribute for AnimationMixer object;
  27670. for (var i = 0; i < this._actions.length; i++) {
  27671. this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  27672. }
  27673. return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
  27674. },
  27675. // return this mixer's root target object
  27676. getRoot: function () {
  27677. return this._root;
  27678. },
  27679. // free all resources specific to a particular clip
  27680. uncacheClip: function (clip) {
  27681. var actions = this._actions,
  27682. clipUuid = clip.uuid,
  27683. actionsByClip = this._actionsByClip,
  27684. actionsForClip = actionsByClip[clipUuid];
  27685. if (actionsForClip !== undefined) {
  27686. // note: just calling _removeInactiveAction would mess up the
  27687. // iteration state and also require updating the state we can
  27688. // just throw away
  27689. var actionsToRemove = actionsForClip.knownActions;
  27690. for (var i = 0, n = actionsToRemove.length; i !== n; ++i) {
  27691. var action = actionsToRemove[i];
  27692. this._deactivateAction(action);
  27693. var cacheIndex = action._cacheIndex,
  27694. lastInactiveAction = actions[actions.length - 1];
  27695. action._cacheIndex = null;
  27696. action._byClipCacheIndex = null;
  27697. lastInactiveAction._cacheIndex = cacheIndex;
  27698. actions[cacheIndex] = lastInactiveAction;
  27699. actions.pop();
  27700. this._removeInactiveBindingsForAction(action);
  27701. }
  27702. delete actionsByClip[clipUuid];
  27703. }
  27704. },
  27705. // free all resources specific to a particular root target object
  27706. uncacheRoot: function (root) {
  27707. var rootUuid = root.uuid,
  27708. actionsByClip = this._actionsByClip;
  27709. for (var clipUuid in actionsByClip) {
  27710. var actionByRoot = actionsByClip[clipUuid].actionByRoot,
  27711. action = actionByRoot[rootUuid];
  27712. if (action !== undefined) {
  27713. this._deactivateAction(action);
  27714. this._removeInactiveAction(action);
  27715. }
  27716. }
  27717. var bindingsByRoot = this._bindingsByRootAndName,
  27718. bindingByName = bindingsByRoot[rootUuid];
  27719. if (bindingByName !== undefined) {
  27720. for (var trackName in bindingByName) {
  27721. var binding = bindingByName[trackName];
  27722. binding.restoreOriginalState();
  27723. this._removeInactiveBinding(binding);
  27724. }
  27725. }
  27726. },
  27727. // remove a targeted clip from the cache
  27728. uncacheAction: function (clip, optionalRoot) {
  27729. var action = this.existingAction(clip, optionalRoot);
  27730. if (action !== null) {
  27731. this._deactivateAction(action);
  27732. this._removeInactiveAction(action);
  27733. }
  27734. }
  27735. });
  27736. /**
  27737. * @author mrdoob / http://mrdoob.com/
  27738. */
  27739. function Uniform(value) {
  27740. if (typeof value === 'string') {
  27741. console.warn('THREE.Uniform: Type parameter is no longer needed.');
  27742. value = arguments[1];
  27743. }
  27744. this.value = value;
  27745. }
  27746. Uniform.prototype.clone = function () {
  27747. return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
  27748. };
  27749. /**
  27750. * @author benaadams / https://twitter.com/ben_a_adams
  27751. */
  27752. function InstancedInterleavedBuffer(array, stride, meshPerAttribute) {
  27753. InterleavedBuffer.call(this, array, stride);
  27754. this.meshPerAttribute = meshPerAttribute || 1;
  27755. }
  27756. InstancedInterleavedBuffer.prototype = Object.assign(Object.create(InterleavedBuffer.prototype), {
  27757. constructor: InstancedInterleavedBuffer,
  27758. isInstancedInterleavedBuffer: true,
  27759. copy: function (source) {
  27760. InterleavedBuffer.prototype.copy.call(this, source);
  27761. this.meshPerAttribute = source.meshPerAttribute;
  27762. return this;
  27763. }
  27764. });
  27765. /**
  27766. * @author mrdoob / http://mrdoob.com/
  27767. * @author bhouston / http://clara.io/
  27768. * @author stephomi / http://stephaneginier.com/
  27769. */
  27770. function Raycaster(origin, direction, near, far) {
  27771. this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
  27772. this.near = near || 0;
  27773. this.far = far || Infinity;
  27774. this.camera = null;
  27775. this.params = {
  27776. Mesh: {},
  27777. Line: {},
  27778. LOD: {},
  27779. Points: {
  27780. threshold: 1
  27781. },
  27782. Sprite: {}
  27783. };
  27784. Object.defineProperties(this.params, {
  27785. PointCloud: {
  27786. get: function () {
  27787. console.warn('THREE.Raycaster: params.PointCloud has been renamed to params.Points.');
  27788. return this.Points;
  27789. }
  27790. }
  27791. });
  27792. }
  27793. function ascSort(a, b) {
  27794. return a.distance - b.distance;
  27795. }
  27796. function intersectObject(object, raycaster, intersects, recursive) {
  27797. if (object.visible === false) return;
  27798. object.raycast(raycaster, intersects);
  27799. if (recursive === true) {
  27800. var children = object.children;
  27801. for (var i = 0, l = children.length; i < l; i++) {
  27802. intersectObject(children[i], raycaster, intersects, true);
  27803. }
  27804. }
  27805. }
  27806. Object.assign(Raycaster.prototype, {
  27807. linePrecision: 1,
  27808. set: function (origin, direction) {
  27809. // direction is assumed to be normalized (for accurate distance calculations)
  27810. this.ray.set(origin, direction);
  27811. },
  27812. setFromCamera: function (coords, camera) {
  27813. if (camera && camera.isPerspectiveCamera) {
  27814. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  27815. this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  27816. this.camera = camera;
  27817. } else if (camera && camera.isOrthographicCamera) {
  27818. this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  27819. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  27820. this.camera = camera;
  27821. } else {
  27822. console.error('THREE.Raycaster: Unsupported camera type.');
  27823. }
  27824. },
  27825. intersectObject: function (object, recursive, optionalTarget) {
  27826. var intersects = optionalTarget || [];
  27827. intersectObject(object, this, intersects, recursive);
  27828. intersects.sort(ascSort);
  27829. return intersects;
  27830. },
  27831. intersectObjects: function (objects, recursive, optionalTarget) {
  27832. var intersects = optionalTarget || [];
  27833. if (Array.isArray(objects) === false) {
  27834. console.warn('THREE.Raycaster.intersectObjects: objects is not an Array.');
  27835. return intersects;
  27836. }
  27837. for (var i = 0, l = objects.length; i < l; i++) {
  27838. intersectObject(objects[i], this, intersects, recursive);
  27839. }
  27840. intersects.sort(ascSort);
  27841. return intersects;
  27842. }
  27843. });
  27844. /**
  27845. * @author bhouston / http://clara.io
  27846. * @author WestLangley / http://github.com/WestLangley
  27847. *
  27848. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  27849. *
  27850. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  27851. * The azimuthal angle (theta) is measured from the positive z-axiz.
  27852. */
  27853. function Spherical(radius, phi, theta) {
  27854. this.radius = radius !== undefined ? radius : 1.0;
  27855. this.phi = phi !== undefined ? phi : 0; // polar angle
  27856. this.theta = theta !== undefined ? theta : 0; // azimuthal angle
  27857. return this;
  27858. }
  27859. Object.assign(Spherical.prototype, {
  27860. set: function (radius, phi, theta) {
  27861. this.radius = radius;
  27862. this.phi = phi;
  27863. this.theta = theta;
  27864. return this;
  27865. },
  27866. clone: function () {
  27867. return new this.constructor().copy(this);
  27868. },
  27869. copy: function (other) {
  27870. this.radius = other.radius;
  27871. this.phi = other.phi;
  27872. this.theta = other.theta;
  27873. return this;
  27874. },
  27875. // restrict phi to be betwee EPS and PI-EPS
  27876. makeSafe: function () {
  27877. var EPS = 0.000001;
  27878. this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
  27879. return this;
  27880. },
  27881. setFromVector3: function (v) {
  27882. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27883. },
  27884. setFromCartesianCoords: function (x, y, z) {
  27885. this.radius = Math.sqrt(x * x + y * y + z * z);
  27886. if (this.radius === 0) {
  27887. this.theta = 0;
  27888. this.phi = 0;
  27889. } else {
  27890. this.theta = Math.atan2(x, z);
  27891. this.phi = Math.acos(_Math.clamp(y / this.radius, -1, 1));
  27892. }
  27893. return this;
  27894. }
  27895. });
  27896. /**
  27897. * @author Mugen87 / https://github.com/Mugen87
  27898. *
  27899. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  27900. *
  27901. */
  27902. function Cylindrical(radius, theta, y) {
  27903. this.radius = radius !== undefined ? radius : 1.0; // distance from the origin to a point in the x-z plane
  27904. this.theta = theta !== undefined ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  27905. this.y = y !== undefined ? y : 0; // height above the x-z plane
  27906. return this;
  27907. }
  27908. Object.assign(Cylindrical.prototype, {
  27909. set: function (radius, theta, y) {
  27910. this.radius = radius;
  27911. this.theta = theta;
  27912. this.y = y;
  27913. return this;
  27914. },
  27915. clone: function () {
  27916. return new this.constructor().copy(this);
  27917. },
  27918. copy: function (other) {
  27919. this.radius = other.radius;
  27920. this.theta = other.theta;
  27921. this.y = other.y;
  27922. return this;
  27923. },
  27924. setFromVector3: function (v) {
  27925. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27926. },
  27927. setFromCartesianCoords: function (x, y, z) {
  27928. this.radius = Math.sqrt(x * x + z * z);
  27929. this.theta = Math.atan2(x, z);
  27930. this.y = y;
  27931. return this;
  27932. }
  27933. });
  27934. /**
  27935. * @author bhouston / http://clara.io
  27936. */
  27937. var _vector$6 = new Vector2();
  27938. function Box2(min, max) {
  27939. this.min = min !== undefined ? min : new Vector2(+Infinity, +Infinity);
  27940. this.max = max !== undefined ? max : new Vector2(-Infinity, -Infinity);
  27941. }
  27942. Object.assign(Box2.prototype, {
  27943. set: function (min, max) {
  27944. this.min.copy(min);
  27945. this.max.copy(max);
  27946. return this;
  27947. },
  27948. setFromPoints: function (points) {
  27949. this.makeEmpty();
  27950. for (var i = 0, il = points.length; i < il; i++) {
  27951. this.expandByPoint(points[i]);
  27952. }
  27953. return this;
  27954. },
  27955. setFromCenterAndSize: function (center, size) {
  27956. var halfSize = _vector$6.copy(size).multiplyScalar(0.5);
  27957. this.min.copy(center).sub(halfSize);
  27958. this.max.copy(center).add(halfSize);
  27959. return this;
  27960. },
  27961. clone: function () {
  27962. return new this.constructor().copy(this);
  27963. },
  27964. copy: function (box) {
  27965. this.min.copy(box.min);
  27966. this.max.copy(box.max);
  27967. return this;
  27968. },
  27969. makeEmpty: function () {
  27970. this.min.x = this.min.y = +Infinity;
  27971. this.max.x = this.max.y = -Infinity;
  27972. return this;
  27973. },
  27974. isEmpty: function () {
  27975. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  27976. return this.max.x < this.min.x || this.max.y < this.min.y;
  27977. },
  27978. getCenter: function (target) {
  27979. if (target === undefined) {
  27980. console.warn('THREE.Box2: .getCenter() target is now required');
  27981. target = new Vector2();
  27982. }
  27983. return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  27984. },
  27985. getSize: function (target) {
  27986. if (target === undefined) {
  27987. console.warn('THREE.Box2: .getSize() target is now required');
  27988. target = new Vector2();
  27989. }
  27990. return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  27991. },
  27992. expandByPoint: function (point) {
  27993. this.min.min(point);
  27994. this.max.max(point);
  27995. return this;
  27996. },
  27997. expandByVector: function (vector) {
  27998. this.min.sub(vector);
  27999. this.max.add(vector);
  28000. return this;
  28001. },
  28002. expandByScalar: function (scalar) {
  28003. this.min.addScalar(-scalar);
  28004. this.max.addScalar(scalar);
  28005. return this;
  28006. },
  28007. containsPoint: function (point) {
  28008. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
  28009. },
  28010. containsBox: function (box) {
  28011. return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y;
  28012. },
  28013. getParameter: function (point, target) {
  28014. // This can potentially have a divide by zero if the box
  28015. // has a size dimension of 0.
  28016. if (target === undefined) {
  28017. console.warn('THREE.Box2: .getParameter() target is now required');
  28018. target = new Vector2();
  28019. }
  28020. return target.set((point.x - this.min.x) / (this.max.x - this.min.x), (point.y - this.min.y) / (this.max.y - this.min.y));
  28021. },
  28022. intersectsBox: function (box) {
  28023. // using 4 splitting planes to rule out intersections
  28024. return box.max.x < this.min.x || box.min.x > this.max.x || box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  28025. },
  28026. clampPoint: function (point, target) {
  28027. if (target === undefined) {
  28028. console.warn('THREE.Box2: .clampPoint() target is now required');
  28029. target = new Vector2();
  28030. }
  28031. return target.copy(point).clamp(this.min, this.max);
  28032. },
  28033. distanceToPoint: function (point) {
  28034. var clampedPoint = _vector$6.copy(point).clamp(this.min, this.max);
  28035. return clampedPoint.sub(point).length();
  28036. },
  28037. intersect: function (box) {
  28038. this.min.max(box.min);
  28039. this.max.min(box.max);
  28040. return this;
  28041. },
  28042. union: function (box) {
  28043. this.min.min(box.min);
  28044. this.max.max(box.max);
  28045. return this;
  28046. },
  28047. translate: function (offset) {
  28048. this.min.add(offset);
  28049. this.max.add(offset);
  28050. return this;
  28051. },
  28052. equals: function (box) {
  28053. return box.min.equals(this.min) && box.max.equals(this.max);
  28054. }
  28055. });
  28056. /**
  28057. * @author bhouston / http://clara.io
  28058. */
  28059. var _startP = new Vector3();
  28060. var _startEnd = new Vector3();
  28061. function Line3(start, end) {
  28062. this.start = start !== undefined ? start : new Vector3();
  28063. this.end = end !== undefined ? end : new Vector3();
  28064. }
  28065. Object.assign(Line3.prototype, {
  28066. set: function (start, end) {
  28067. this.start.copy(start);
  28068. this.end.copy(end);
  28069. return this;
  28070. },
  28071. clone: function () {
  28072. return new this.constructor().copy(this);
  28073. },
  28074. copy: function (line) {
  28075. this.start.copy(line.start);
  28076. this.end.copy(line.end);
  28077. return this;
  28078. },
  28079. getCenter: function (target) {
  28080. if (target === undefined) {
  28081. console.warn('THREE.Line3: .getCenter() target is now required');
  28082. target = new Vector3();
  28083. }
  28084. return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  28085. },
  28086. delta: function (target) {
  28087. if (target === undefined) {
  28088. console.warn('THREE.Line3: .delta() target is now required');
  28089. target = new Vector3();
  28090. }
  28091. return target.subVectors(this.end, this.start);
  28092. },
  28093. distanceSq: function () {
  28094. return this.start.distanceToSquared(this.end);
  28095. },
  28096. distance: function () {
  28097. return this.start.distanceTo(this.end);
  28098. },
  28099. at: function (t, target) {
  28100. if (target === undefined) {
  28101. console.warn('THREE.Line3: .at() target is now required');
  28102. target = new Vector3();
  28103. }
  28104. return this.delta(target).multiplyScalar(t).add(this.start);
  28105. },
  28106. closestPointToPointParameter: function (point, clampToLine) {
  28107. _startP.subVectors(point, this.start);
  28108. _startEnd.subVectors(this.end, this.start);
  28109. var startEnd2 = _startEnd.dot(_startEnd);
  28110. var startEnd_startP = _startEnd.dot(_startP);
  28111. var t = startEnd_startP / startEnd2;
  28112. if (clampToLine) {
  28113. t = _Math.clamp(t, 0, 1);
  28114. }
  28115. return t;
  28116. },
  28117. closestPointToPoint: function (point, clampToLine, target) {
  28118. var t = this.closestPointToPointParameter(point, clampToLine);
  28119. if (target === undefined) {
  28120. console.warn('THREE.Line3: .closestPointToPoint() target is now required');
  28121. target = new Vector3();
  28122. }
  28123. return this.delta(target).multiplyScalar(t).add(this.start);
  28124. },
  28125. applyMatrix4: function (matrix) {
  28126. this.start.applyMatrix4(matrix);
  28127. this.end.applyMatrix4(matrix);
  28128. return this;
  28129. },
  28130. equals: function (line) {
  28131. return line.start.equals(this.start) && line.end.equals(this.end);
  28132. }
  28133. });
  28134. /**
  28135. * @author alteredq / http://alteredqualia.com/
  28136. */
  28137. function ImmediateRenderObject(material) {
  28138. Object3D.call(this);
  28139. this.material = material;
  28140. this.render = function ()
  28141. /* renderCallback */
  28142. {};
  28143. }
  28144. ImmediateRenderObject.prototype = Object.create(Object3D.prototype);
  28145. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  28146. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  28147. /**
  28148. * @author mrdoob / http://mrdoob.com/
  28149. * @author WestLangley / http://github.com/WestLangley
  28150. */
  28151. var _v1$5 = new Vector3();
  28152. var _v2$3 = new Vector3();
  28153. var _normalMatrix$1 = new Matrix3();
  28154. var _keys = ['a', 'b', 'c'];
  28155. function VertexNormalsHelper(object, size, hex, linewidth) {
  28156. this.object = object;
  28157. this.size = size !== undefined ? size : 1;
  28158. var color = hex !== undefined ? hex : 0xff0000;
  28159. var width = linewidth !== undefined ? linewidth : 1; //
  28160. var nNormals = 0;
  28161. var objGeometry = this.object.geometry;
  28162. if (objGeometry && objGeometry.isGeometry) {
  28163. nNormals = objGeometry.faces.length * 3;
  28164. } else if (objGeometry && objGeometry.isBufferGeometry) {
  28165. nNormals = objGeometry.attributes.normal.count;
  28166. } //
  28167. var geometry = new BufferGeometry();
  28168. var positions = new Float32BufferAttribute(nNormals * 2 * 3, 3);
  28169. geometry.addAttribute('position', positions);
  28170. LineSegments.call(this, geometry, new LineBasicMaterial({
  28171. color: color,
  28172. linewidth: width
  28173. })); //
  28174. this.matrixAutoUpdate = false;
  28175. this.update();
  28176. }
  28177. VertexNormalsHelper.prototype = Object.create(LineSegments.prototype);
  28178. VertexNormalsHelper.prototype.constructor = VertexNormalsHelper;
  28179. VertexNormalsHelper.prototype.update = function () {
  28180. this.object.updateMatrixWorld(true);
  28181. _normalMatrix$1.getNormalMatrix(this.object.matrixWorld);
  28182. var matrixWorld = this.object.matrixWorld;
  28183. var position = this.geometry.attributes.position; //
  28184. var objGeometry = this.object.geometry;
  28185. if (objGeometry && objGeometry.isGeometry) {
  28186. var vertices = objGeometry.vertices;
  28187. var faces = objGeometry.faces;
  28188. var idx = 0;
  28189. for (var i = 0, l = faces.length; i < l; i++) {
  28190. var face = faces[i];
  28191. for (var j = 0, jl = face.vertexNormals.length; j < jl; j++) {
  28192. var vertex = vertices[face[_keys[j]]];
  28193. var normal = face.vertexNormals[j];
  28194. _v1$5.copy(vertex).applyMatrix4(matrixWorld);
  28195. _v2$3.copy(normal).applyMatrix3(_normalMatrix$1).normalize().multiplyScalar(this.size).add(_v1$5);
  28196. position.setXYZ(idx, _v1$5.x, _v1$5.y, _v1$5.z);
  28197. idx = idx + 1;
  28198. position.setXYZ(idx, _v2$3.x, _v2$3.y, _v2$3.z);
  28199. idx = idx + 1;
  28200. }
  28201. }
  28202. } else if (objGeometry && objGeometry.isBufferGeometry) {
  28203. var objPos = objGeometry.attributes.position;
  28204. var objNorm = objGeometry.attributes.normal;
  28205. var idx = 0; // for simplicity, ignore index and drawcalls, and render every normal
  28206. for (var j = 0, jl = objPos.count; j < jl; j++) {
  28207. _v1$5.set(objPos.getX(j), objPos.getY(j), objPos.getZ(j)).applyMatrix4(matrixWorld);
  28208. _v2$3.set(objNorm.getX(j), objNorm.getY(j), objNorm.getZ(j));
  28209. _v2$3.applyMatrix3(_normalMatrix$1).normalize().multiplyScalar(this.size).add(_v1$5);
  28210. position.setXYZ(idx, _v1$5.x, _v1$5.y, _v1$5.z);
  28211. idx = idx + 1;
  28212. position.setXYZ(idx, _v2$3.x, _v2$3.y, _v2$3.z);
  28213. idx = idx + 1;
  28214. }
  28215. }
  28216. position.needsUpdate = true;
  28217. };
  28218. /**
  28219. * @author alteredq / http://alteredqualia.com/
  28220. * @author mrdoob / http://mrdoob.com/
  28221. * @author WestLangley / http://github.com/WestLangley
  28222. */
  28223. var _vector$7 = new Vector3();
  28224. function SpotLightHelper(light, color) {
  28225. Object3D.call(this);
  28226. this.light = light;
  28227. this.light.updateMatrixWorld();
  28228. this.matrix = light.matrixWorld;
  28229. this.matrixAutoUpdate = false;
  28230. this.color = color;
  28231. var geometry = new BufferGeometry();
  28232. var positions = [0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, -1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, -1, 1];
  28233. for (var i = 0, j = 1, l = 32; i < l; i++, j++) {
  28234. var p1 = i / l * Math.PI * 2;
  28235. var p2 = j / l * Math.PI * 2;
  28236. positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
  28237. }
  28238. geometry.addAttribute('position', new Float32BufferAttribute(positions, 3));
  28239. var material = new LineBasicMaterial({
  28240. fog: false
  28241. });
  28242. this.cone = new LineSegments(geometry, material);
  28243. this.add(this.cone);
  28244. this.update();
  28245. }
  28246. SpotLightHelper.prototype = Object.create(Object3D.prototype);
  28247. SpotLightHelper.prototype.constructor = SpotLightHelper;
  28248. SpotLightHelper.prototype.dispose = function () {
  28249. this.cone.geometry.dispose();
  28250. this.cone.material.dispose();
  28251. };
  28252. SpotLightHelper.prototype.update = function () {
  28253. this.light.updateMatrixWorld();
  28254. var coneLength = this.light.distance ? this.light.distance : 1000;
  28255. var coneWidth = coneLength * Math.tan(this.light.angle);
  28256. this.cone.scale.set(coneWidth, coneWidth, coneLength);
  28257. _vector$7.setFromMatrixPosition(this.light.target.matrixWorld);
  28258. this.cone.lookAt(_vector$7);
  28259. if (this.color !== undefined) {
  28260. this.cone.material.color.set(this.color);
  28261. } else {
  28262. this.cone.material.color.copy(this.light.color);
  28263. }
  28264. };
  28265. /**
  28266. * @author Sean Griffin / http://twitter.com/sgrif
  28267. * @author Michael Guerrero / http://realitymeltdown.com
  28268. * @author mrdoob / http://mrdoob.com/
  28269. * @author ikerr / http://verold.com
  28270. * @author Mugen87 / https://github.com/Mugen87
  28271. */
  28272. var _vector$8 = new Vector3();
  28273. var _boneMatrix = new Matrix4();
  28274. var _matrixWorldInv = new Matrix4();
  28275. function getBoneList(object) {
  28276. var boneList = [];
  28277. if (object && object.isBone) {
  28278. boneList.push(object);
  28279. }
  28280. for (var i = 0; i < object.children.length; i++) {
  28281. boneList.push.apply(boneList, getBoneList(object.children[i]));
  28282. }
  28283. return boneList;
  28284. }
  28285. function SkeletonHelper(object) {
  28286. var bones = getBoneList(object);
  28287. var geometry = new BufferGeometry();
  28288. var vertices = [];
  28289. var colors = [];
  28290. var color1 = new Color(0, 0, 1);
  28291. var color2 = new Color(0, 1, 0);
  28292. for (var i = 0; i < bones.length; i++) {
  28293. var bone = bones[i];
  28294. if (bone.parent && bone.parent.isBone) {
  28295. vertices.push(0, 0, 0);
  28296. vertices.push(0, 0, 0);
  28297. colors.push(color1.r, color1.g, color1.b);
  28298. colors.push(color2.r, color2.g, color2.b);
  28299. }
  28300. }
  28301. geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  28302. geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));
  28303. var material = new LineBasicMaterial({
  28304. vertexColors: VertexColors,
  28305. depthTest: false,
  28306. depthWrite: false,
  28307. transparent: true
  28308. });
  28309. LineSegments.call(this, geometry, material);
  28310. this.root = object;
  28311. this.bones = bones;
  28312. this.matrix = object.matrixWorld;
  28313. this.matrixAutoUpdate = false;
  28314. }
  28315. SkeletonHelper.prototype = Object.create(LineSegments.prototype);
  28316. SkeletonHelper.prototype.constructor = SkeletonHelper;
  28317. SkeletonHelper.prototype.updateMatrixWorld = function (force) {
  28318. var bones = this.bones;
  28319. var geometry = this.geometry;
  28320. var position = geometry.getAttribute('position');
  28321. _matrixWorldInv.getInverse(this.root.matrixWorld);
  28322. for (var i = 0, j = 0; i < bones.length; i++) {
  28323. var bone = bones[i];
  28324. if (bone.parent && bone.parent.isBone) {
  28325. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
  28326. _vector$8.setFromMatrixPosition(_boneMatrix);
  28327. position.setXYZ(j, _vector$8.x, _vector$8.y, _vector$8.z);
  28328. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
  28329. _vector$8.setFromMatrixPosition(_boneMatrix);
  28330. position.setXYZ(j + 1, _vector$8.x, _vector$8.y, _vector$8.z);
  28331. j += 2;
  28332. }
  28333. }
  28334. geometry.getAttribute('position').needsUpdate = true;
  28335. Object3D.prototype.updateMatrixWorld.call(this, force);
  28336. };
  28337. /**
  28338. * @author alteredq / http://alteredqualia.com/
  28339. * @author mrdoob / http://mrdoob.com/
  28340. */
  28341. function PointLightHelper(light, sphereSize, color) {
  28342. this.light = light;
  28343. this.light.updateMatrixWorld();
  28344. this.color = color;
  28345. var geometry = new SphereBufferGeometry(sphereSize, 4, 2);
  28346. var material = new MeshBasicMaterial({
  28347. wireframe: true,
  28348. fog: false
  28349. });
  28350. Mesh.call(this, geometry, material);
  28351. this.matrix = this.light.matrixWorld;
  28352. this.matrixAutoUpdate = false;
  28353. this.update();
  28354. /*
  28355. var distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  28356. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  28357. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  28358. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  28359. var d = light.distance;
  28360. if ( d === 0.0 ) {
  28361. this.lightDistance.visible = false;
  28362. } else {
  28363. this.lightDistance.scale.set( d, d, d );
  28364. }
  28365. this.add( this.lightDistance );
  28366. */
  28367. }
  28368. PointLightHelper.prototype = Object.create(Mesh.prototype);
  28369. PointLightHelper.prototype.constructor = PointLightHelper;
  28370. PointLightHelper.prototype.dispose = function () {
  28371. this.geometry.dispose();
  28372. this.material.dispose();
  28373. };
  28374. PointLightHelper.prototype.update = function () {
  28375. if (this.color !== undefined) {
  28376. this.material.color.set(this.color);
  28377. } else {
  28378. this.material.color.copy(this.light.color);
  28379. }
  28380. /*
  28381. var d = this.light.distance;
  28382. if ( d === 0.0 ) {
  28383. this.lightDistance.visible = false;
  28384. } else {
  28385. this.lightDistance.visible = true;
  28386. this.lightDistance.scale.set( d, d, d );
  28387. }
  28388. */
  28389. };
  28390. /**
  28391. * @author abelnation / http://github.com/abelnation
  28392. * @author Mugen87 / http://github.com/Mugen87
  28393. * @author WestLangley / http://github.com/WestLangley
  28394. *
  28395. * This helper must be added as a child of the light
  28396. */
  28397. function RectAreaLightHelper(light, color) {
  28398. this.type = 'RectAreaLightHelper';
  28399. this.light = light;
  28400. this.color = color; // optional hardwired color for the helper
  28401. var positions = [1, 1, 0, -1, 1, 0, -1, -1, 0, 1, -1, 0, 1, 1, 0];
  28402. var geometry = new BufferGeometry();
  28403. geometry.addAttribute('position', new Float32BufferAttribute(positions, 3));
  28404. geometry.computeBoundingSphere();
  28405. var material = new LineBasicMaterial({
  28406. fog: false
  28407. });
  28408. Line.call(this, geometry, material); //
  28409. var positions2 = [1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0];
  28410. var geometry2 = new BufferGeometry();
  28411. geometry2.addAttribute('position', new Float32BufferAttribute(positions2, 3));
  28412. geometry2.computeBoundingSphere();
  28413. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  28414. side: BackSide,
  28415. fog: false
  28416. })));
  28417. this.update();
  28418. }
  28419. RectAreaLightHelper.prototype = Object.create(Line.prototype);
  28420. RectAreaLightHelper.prototype.constructor = RectAreaLightHelper;
  28421. RectAreaLightHelper.prototype.update = function () {
  28422. this.scale.set(0.5 * this.light.width, 0.5 * this.light.height, 1);
  28423. if (this.color !== undefined) {
  28424. this.material.color.set(this.color);
  28425. this.children[0].material.color.set(this.color);
  28426. } else {
  28427. this.material.color.copy(this.light.color).multiplyScalar(this.light.intensity); // prevent hue shift
  28428. var c = this.material.color;
  28429. var max = Math.max(c.r, c.g, c.b);
  28430. if (max > 1) c.multiplyScalar(1 / max);
  28431. this.children[0].material.color.copy(this.material.color);
  28432. }
  28433. };
  28434. RectAreaLightHelper.prototype.dispose = function () {
  28435. this.geometry.dispose();
  28436. this.material.dispose();
  28437. this.children[0].geometry.dispose();
  28438. this.children[0].material.dispose();
  28439. };
  28440. /**
  28441. * @author alteredq / http://alteredqualia.com/
  28442. * @author mrdoob / http://mrdoob.com/
  28443. * @author Mugen87 / https://github.com/Mugen87
  28444. */
  28445. var _vector$9 = new Vector3();
  28446. var _color1 = new Color();
  28447. var _color2 = new Color();
  28448. function HemisphereLightHelper(light, size, color) {
  28449. Object3D.call(this);
  28450. this.light = light;
  28451. this.light.updateMatrixWorld();
  28452. this.matrix = light.matrixWorld;
  28453. this.matrixAutoUpdate = false;
  28454. this.color = color;
  28455. var geometry = new OctahedronBufferGeometry(size);
  28456. geometry.rotateY(Math.PI * 0.5);
  28457. this.material = new MeshBasicMaterial({
  28458. wireframe: true,
  28459. fog: false
  28460. });
  28461. if (this.color === undefined) this.material.vertexColors = VertexColors;
  28462. var position = geometry.getAttribute('position');
  28463. var colors = new Float32Array(position.count * 3);
  28464. geometry.addAttribute('color', new BufferAttribute(colors, 3));
  28465. this.add(new Mesh(geometry, this.material));
  28466. this.update();
  28467. }
  28468. HemisphereLightHelper.prototype = Object.create(Object3D.prototype);
  28469. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  28470. HemisphereLightHelper.prototype.dispose = function () {
  28471. this.children[0].geometry.dispose();
  28472. this.children[0].material.dispose();
  28473. };
  28474. HemisphereLightHelper.prototype.update = function () {
  28475. var mesh = this.children[0];
  28476. if (this.color !== undefined) {
  28477. this.material.color.set(this.color);
  28478. } else {
  28479. var colors = mesh.geometry.getAttribute('color');
  28480. _color1.copy(this.light.color);
  28481. _color2.copy(this.light.groundColor);
  28482. for (var i = 0, l = colors.count; i < l; i++) {
  28483. var color = i < l / 2 ? _color1 : _color2;
  28484. colors.setXYZ(i, color.r, color.g, color.b);
  28485. }
  28486. colors.needsUpdate = true;
  28487. }
  28488. mesh.lookAt(_vector$9.setFromMatrixPosition(this.light.matrixWorld).negate());
  28489. };
  28490. /**
  28491. * @author WestLangley / http://github.com/WestLangley
  28492. */
  28493. function LightProbeHelper(lightProbe, size) {
  28494. this.lightProbe = lightProbe;
  28495. this.size = size;
  28496. var defines = {};
  28497. defines['GAMMA_OUTPUT'] = ""; // material
  28498. var material = new ShaderMaterial({
  28499. defines: defines,
  28500. uniforms: {
  28501. sh: {
  28502. value: this.lightProbe.sh.coefficients
  28503. },
  28504. // by reference
  28505. intensity: {
  28506. value: this.lightProbe.intensity
  28507. }
  28508. },
  28509. vertexShader: ['varying vec3 vNormal;', 'void main() {', ' vNormal = normalize( normalMatrix * normal );', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'),
  28510. fragmentShader: ['#define RECIPROCAL_PI 0.318309886', 'vec3 inverseTransformDirection( in vec3 normal, in mat4 matrix ) {', ' // matrix is assumed to be orthogonal', ' return normalize( ( vec4( normal, 0.0 ) * matrix ).xyz );', '}', 'vec3 linearToOutput( in vec3 a ) {', ' #ifdef GAMMA_OUTPUT', ' return pow( a, vec3( 1.0 / float( GAMMA_FACTOR ) ) );', ' #else', ' return a;', ' #endif', '}', '// source: https://graphics.stanford.edu/papers/envmap/envmap.pdf', 'vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {', ' // normal is assumed to have unit length', ' float x = normal.x, y = normal.y, z = normal.z;', ' // band 0', ' vec3 result = shCoefficients[ 0 ] * 0.886227;', ' // band 1', ' result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;', ' result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;', ' result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;', ' // band 2', ' result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;', ' result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;', ' result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );', ' result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;', ' result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );', ' return result;', '}', 'uniform vec3 sh[ 9 ]; // sh coefficients', 'uniform float intensity; // light probe intensity', 'varying vec3 vNormal;', 'void main() {', ' vec3 normal = normalize( vNormal );', ' vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );', ' vec3 irradiance = shGetIrradianceAt( worldNormal, sh );', ' vec3 outgoingLight = RECIPROCAL_PI * irradiance * intensity;', ' outgoingLight = linearToOutput( outgoingLight );', ' gl_FragColor = vec4( outgoingLight, 1.0 );', '}'].join('\n')
  28511. });
  28512. var geometry = new SphereBufferGeometry(1, 32, 16);
  28513. Mesh.call(this, geometry, material);
  28514. this.onBeforeRender();
  28515. }
  28516. LightProbeHelper.prototype = Object.create(Mesh.prototype);
  28517. LightProbeHelper.prototype.constructor = LightProbeHelper;
  28518. LightProbeHelper.prototype.dispose = function () {
  28519. this.geometry.dispose();
  28520. this.material.dispose();
  28521. };
  28522. LightProbeHelper.prototype.onBeforeRender = function () {
  28523. this.position.copy(this.lightProbe.position);
  28524. this.scale.set(1, 1, 1).multiplyScalar(this.size);
  28525. this.material.uniforms.intensity.value = this.lightProbe.intensity;
  28526. };
  28527. /**
  28528. * @author mrdoob / http://mrdoob.com/
  28529. */
  28530. function GridHelper(size, divisions, color1, color2) {
  28531. size = size || 10;
  28532. divisions = divisions || 10;
  28533. color1 = new Color(color1 !== undefined ? color1 : 0x444444);
  28534. color2 = new Color(color2 !== undefined ? color2 : 0x888888);
  28535. var center = divisions / 2;
  28536. var step = size / divisions;
  28537. var halfSize = size / 2;
  28538. var vertices = [],
  28539. colors = [];
  28540. for (var i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
  28541. vertices.push(-halfSize, 0, k, halfSize, 0, k);
  28542. vertices.push(k, 0, -halfSize, k, 0, halfSize);
  28543. var color = i === center ? color1 : color2;
  28544. color.toArray(colors, j);
  28545. j += 3;
  28546. color.toArray(colors, j);
  28547. j += 3;
  28548. color.toArray(colors, j);
  28549. j += 3;
  28550. color.toArray(colors, j);
  28551. j += 3;
  28552. }
  28553. var geometry = new BufferGeometry();
  28554. geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  28555. geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));
  28556. var material = new LineBasicMaterial({
  28557. vertexColors: VertexColors
  28558. });
  28559. LineSegments.call(this, geometry, material);
  28560. }
  28561. GridHelper.prototype = Object.assign(Object.create(LineSegments.prototype), {
  28562. constructor: GridHelper,
  28563. copy: function (source) {
  28564. LineSegments.prototype.copy.call(this, source);
  28565. this.geometry.copy(source.geometry);
  28566. this.material.copy(source.material);
  28567. return this;
  28568. },
  28569. clone: function () {
  28570. return new this.constructor().copy(this);
  28571. }
  28572. });
  28573. /**
  28574. * @author mrdoob / http://mrdoob.com/
  28575. * @author Mugen87 / http://github.com/Mugen87
  28576. * @author Hectate / http://www.github.com/Hectate
  28577. */
  28578. function PolarGridHelper(radius, radials, circles, divisions, color1, color2) {
  28579. radius = radius || 10;
  28580. radials = radials || 16;
  28581. circles = circles || 8;
  28582. divisions = divisions || 64;
  28583. color1 = new Color(color1 !== undefined ? color1 : 0x444444);
  28584. color2 = new Color(color2 !== undefined ? color2 : 0x888888);
  28585. var vertices = [];
  28586. var colors = [];
  28587. var x, z;
  28588. var v, i, j, r, color; // create the radials
  28589. for (i = 0; i <= radials; i++) {
  28590. v = i / radials * (Math.PI * 2);
  28591. x = Math.sin(v) * radius;
  28592. z = Math.cos(v) * radius;
  28593. vertices.push(0, 0, 0);
  28594. vertices.push(x, 0, z);
  28595. color = i & 1 ? color1 : color2;
  28596. colors.push(color.r, color.g, color.b);
  28597. colors.push(color.r, color.g, color.b);
  28598. } // create the circles
  28599. for (i = 0; i <= circles; i++) {
  28600. color = i & 1 ? color1 : color2;
  28601. r = radius - radius / circles * i;
  28602. for (j = 0; j < divisions; j++) {
  28603. // first vertex
  28604. v = j / divisions * (Math.PI * 2);
  28605. x = Math.sin(v) * r;
  28606. z = Math.cos(v) * r;
  28607. vertices.push(x, 0, z);
  28608. colors.push(color.r, color.g, color.b); // second vertex
  28609. v = (j + 1) / divisions * (Math.PI * 2);
  28610. x = Math.sin(v) * r;
  28611. z = Math.cos(v) * r;
  28612. vertices.push(x, 0, z);
  28613. colors.push(color.r, color.g, color.b);
  28614. }
  28615. }
  28616. var geometry = new BufferGeometry();
  28617. geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  28618. geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));
  28619. var material = new LineBasicMaterial({
  28620. vertexColors: VertexColors
  28621. });
  28622. LineSegments.call(this, geometry, material);
  28623. }
  28624. PolarGridHelper.prototype = Object.create(LineSegments.prototype);
  28625. PolarGridHelper.prototype.constructor = PolarGridHelper;
  28626. /**
  28627. * @author Mugen87 / http://github.com/Mugen87
  28628. */
  28629. function PositionalAudioHelper(audio, range, divisionsInnerAngle, divisionsOuterAngle) {
  28630. this.audio = audio;
  28631. this.range = range || 1;
  28632. this.divisionsInnerAngle = divisionsInnerAngle || 16;
  28633. this.divisionsOuterAngle = divisionsOuterAngle || 2;
  28634. var geometry = new BufferGeometry();
  28635. var divisions = this.divisionsInnerAngle + this.divisionsOuterAngle * 2;
  28636. var positions = new Float32Array((divisions * 3 + 3) * 3);
  28637. geometry.addAttribute('position', new BufferAttribute(positions, 3));
  28638. var materialInnerAngle = new LineBasicMaterial({
  28639. color: 0x00ff00
  28640. });
  28641. var materialOuterAngle = new LineBasicMaterial({
  28642. color: 0xffff00
  28643. });
  28644. Line.call(this, geometry, [materialOuterAngle, materialInnerAngle]);
  28645. this.update();
  28646. }
  28647. PositionalAudioHelper.prototype = Object.create(Line.prototype);
  28648. PositionalAudioHelper.prototype.constructor = PositionalAudioHelper;
  28649. PositionalAudioHelper.prototype.update = function () {
  28650. var audio = this.audio;
  28651. var range = this.range;
  28652. var divisionsInnerAngle = this.divisionsInnerAngle;
  28653. var divisionsOuterAngle = this.divisionsOuterAngle;
  28654. var coneInnerAngle = _Math.degToRad(audio.panner.coneInnerAngle);
  28655. var coneOuterAngle = _Math.degToRad(audio.panner.coneOuterAngle);
  28656. var halfConeInnerAngle = coneInnerAngle / 2;
  28657. var halfConeOuterAngle = coneOuterAngle / 2;
  28658. var start = 0;
  28659. var count = 0;
  28660. var i, stride;
  28661. var geometry = this.geometry;
  28662. var positionAttribute = geometry.attributes.position;
  28663. geometry.clearGroups(); //
  28664. function generateSegment(from, to, divisions, materialIndex) {
  28665. var step = (to - from) / divisions;
  28666. positionAttribute.setXYZ(start, 0, 0, 0);
  28667. count++;
  28668. for (i = from; i < to; i += step) {
  28669. stride = start + count;
  28670. positionAttribute.setXYZ(stride, Math.sin(i) * range, 0, Math.cos(i) * range);
  28671. positionAttribute.setXYZ(stride + 1, Math.sin(Math.min(i + step, to)) * range, 0, Math.cos(Math.min(i + step, to)) * range);
  28672. positionAttribute.setXYZ(stride + 2, 0, 0, 0);
  28673. count += 3;
  28674. }
  28675. geometry.addGroup(start, count, materialIndex);
  28676. start += count;
  28677. count = 0;
  28678. } //
  28679. generateSegment(-halfConeOuterAngle, -halfConeInnerAngle, divisionsOuterAngle, 0);
  28680. generateSegment(-halfConeInnerAngle, halfConeInnerAngle, divisionsInnerAngle, 1);
  28681. generateSegment(halfConeInnerAngle, halfConeOuterAngle, divisionsOuterAngle, 0); //
  28682. positionAttribute.needsUpdate = true;
  28683. if (coneInnerAngle === coneOuterAngle) this.material[0].visible = false;
  28684. };
  28685. PositionalAudioHelper.prototype.dispose = function () {
  28686. this.geometry.dispose();
  28687. this.material[0].dispose();
  28688. this.material[1].dispose();
  28689. };
  28690. /**
  28691. * @author mrdoob / http://mrdoob.com/
  28692. * @author WestLangley / http://github.com/WestLangley
  28693. */
  28694. var _v1$6 = new Vector3();
  28695. var _v2$4 = new Vector3();
  28696. var _normalMatrix$2 = new Matrix3();
  28697. function FaceNormalsHelper(object, size, hex, linewidth) {
  28698. // FaceNormalsHelper only supports THREE.Geometry
  28699. this.object = object;
  28700. this.size = size !== undefined ? size : 1;
  28701. var color = hex !== undefined ? hex : 0xffff00;
  28702. var width = linewidth !== undefined ? linewidth : 1; //
  28703. var nNormals = 0;
  28704. var objGeometry = this.object.geometry;
  28705. if (objGeometry && objGeometry.isGeometry) {
  28706. nNormals = objGeometry.faces.length;
  28707. } else {
  28708. console.warn('THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.');
  28709. } //
  28710. var geometry = new BufferGeometry();
  28711. var positions = new Float32BufferAttribute(nNormals * 2 * 3, 3);
  28712. geometry.addAttribute('position', positions);
  28713. LineSegments.call(this, geometry, new LineBasicMaterial({
  28714. color: color,
  28715. linewidth: width
  28716. })); //
  28717. this.matrixAutoUpdate = false;
  28718. this.update();
  28719. }
  28720. FaceNormalsHelper.prototype = Object.create(LineSegments.prototype);
  28721. FaceNormalsHelper.prototype.constructor = FaceNormalsHelper;
  28722. FaceNormalsHelper.prototype.update = function () {
  28723. this.object.updateMatrixWorld(true);
  28724. _normalMatrix$2.getNormalMatrix(this.object.matrixWorld);
  28725. var matrixWorld = this.object.matrixWorld;
  28726. var position = this.geometry.attributes.position; //
  28727. var objGeometry = this.object.geometry;
  28728. var vertices = objGeometry.vertices;
  28729. var faces = objGeometry.faces;
  28730. var idx = 0;
  28731. for (var i = 0, l = faces.length; i < l; i++) {
  28732. var face = faces[i];
  28733. var normal = face.normal;
  28734. _v1$6.copy(vertices[face.a]).add(vertices[face.b]).add(vertices[face.c]).divideScalar(3).applyMatrix4(matrixWorld);
  28735. _v2$4.copy(normal).applyMatrix3(_normalMatrix$2).normalize().multiplyScalar(this.size).add(_v1$6);
  28736. position.setXYZ(idx, _v1$6.x, _v1$6.y, _v1$6.z);
  28737. idx = idx + 1;
  28738. position.setXYZ(idx, _v2$4.x, _v2$4.y, _v2$4.z);
  28739. idx = idx + 1;
  28740. }
  28741. position.needsUpdate = true;
  28742. };
  28743. /**
  28744. * @author alteredq / http://alteredqualia.com/
  28745. * @author mrdoob / http://mrdoob.com/
  28746. * @author WestLangley / http://github.com/WestLangley
  28747. */
  28748. var _v1$7 = new Vector3();
  28749. var _v2$5 = new Vector3();
  28750. var _v3$1 = new Vector3();
  28751. function DirectionalLightHelper(light, size, color) {
  28752. Object3D.call(this);
  28753. this.light = light;
  28754. this.light.updateMatrixWorld();
  28755. this.matrix = light.matrixWorld;
  28756. this.matrixAutoUpdate = false;
  28757. this.color = color;
  28758. if (size === undefined) size = 1;
  28759. var geometry = new BufferGeometry();
  28760. geometry.addAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
  28761. var material = new LineBasicMaterial({
  28762. fog: false
  28763. });
  28764. this.lightPlane = new Line(geometry, material);
  28765. this.add(this.lightPlane);
  28766. geometry = new BufferGeometry();
  28767. geometry.addAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
  28768. this.targetLine = new Line(geometry, material);
  28769. this.add(this.targetLine);
  28770. this.update();
  28771. }
  28772. DirectionalLightHelper.prototype = Object.create(Object3D.prototype);
  28773. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  28774. DirectionalLightHelper.prototype.dispose = function () {
  28775. this.lightPlane.geometry.dispose();
  28776. this.lightPlane.material.dispose();
  28777. this.targetLine.geometry.dispose();
  28778. this.targetLine.material.dispose();
  28779. };
  28780. DirectionalLightHelper.prototype.update = function () {
  28781. _v1$7.setFromMatrixPosition(this.light.matrixWorld);
  28782. _v2$5.setFromMatrixPosition(this.light.target.matrixWorld);
  28783. _v3$1.subVectors(_v2$5, _v1$7);
  28784. this.lightPlane.lookAt(_v2$5);
  28785. if (this.color !== undefined) {
  28786. this.lightPlane.material.color.set(this.color);
  28787. this.targetLine.material.color.set(this.color);
  28788. } else {
  28789. this.lightPlane.material.color.copy(this.light.color);
  28790. this.targetLine.material.color.copy(this.light.color);
  28791. }
  28792. this.targetLine.lookAt(_v2$5);
  28793. this.targetLine.scale.z = _v3$1.length();
  28794. };
  28795. /**
  28796. * @author alteredq / http://alteredqualia.com/
  28797. * @author Mugen87 / https://github.com/Mugen87
  28798. *
  28799. * - shows frustum, line of sight and up of the camera
  28800. * - suitable for fast updates
  28801. * - based on frustum visualization in lightgl.js shadowmap example
  28802. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  28803. */
  28804. var _vector$a = new Vector3();
  28805. var _camera = new Camera();
  28806. function CameraHelper(camera) {
  28807. var geometry = new BufferGeometry();
  28808. var material = new LineBasicMaterial({
  28809. color: 0xffffff,
  28810. vertexColors: FaceColors
  28811. });
  28812. var vertices = [];
  28813. var colors = [];
  28814. var pointMap = {}; // colors
  28815. var colorFrustum = new Color(0xffaa00);
  28816. var colorCone = new Color(0xff0000);
  28817. var colorUp = new Color(0x00aaff);
  28818. var colorTarget = new Color(0xffffff);
  28819. var colorCross = new Color(0x333333); // near
  28820. addLine('n1', 'n2', colorFrustum);
  28821. addLine('n2', 'n4', colorFrustum);
  28822. addLine('n4', 'n3', colorFrustum);
  28823. addLine('n3', 'n1', colorFrustum); // far
  28824. addLine('f1', 'f2', colorFrustum);
  28825. addLine('f2', 'f4', colorFrustum);
  28826. addLine('f4', 'f3', colorFrustum);
  28827. addLine('f3', 'f1', colorFrustum); // sides
  28828. addLine('n1', 'f1', colorFrustum);
  28829. addLine('n2', 'f2', colorFrustum);
  28830. addLine('n3', 'f3', colorFrustum);
  28831. addLine('n4', 'f4', colorFrustum); // cone
  28832. addLine('p', 'n1', colorCone);
  28833. addLine('p', 'n2', colorCone);
  28834. addLine('p', 'n3', colorCone);
  28835. addLine('p', 'n4', colorCone); // up
  28836. addLine('u1', 'u2', colorUp);
  28837. addLine('u2', 'u3', colorUp);
  28838. addLine('u3', 'u1', colorUp); // target
  28839. addLine('c', 't', colorTarget);
  28840. addLine('p', 'c', colorCross); // cross
  28841. addLine('cn1', 'cn2', colorCross);
  28842. addLine('cn3', 'cn4', colorCross);
  28843. addLine('cf1', 'cf2', colorCross);
  28844. addLine('cf3', 'cf4', colorCross);
  28845. function addLine(a, b, color) {
  28846. addPoint(a, color);
  28847. addPoint(b, color);
  28848. }
  28849. function addPoint(id, color) {
  28850. vertices.push(0, 0, 0);
  28851. colors.push(color.r, color.g, color.b);
  28852. if (pointMap[id] === undefined) {
  28853. pointMap[id] = [];
  28854. }
  28855. pointMap[id].push(vertices.length / 3 - 1);
  28856. }
  28857. geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  28858. geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));
  28859. LineSegments.call(this, geometry, material);
  28860. this.camera = camera;
  28861. if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix();
  28862. this.matrix = camera.matrixWorld;
  28863. this.matrixAutoUpdate = false;
  28864. this.pointMap = pointMap;
  28865. this.update();
  28866. }
  28867. CameraHelper.prototype = Object.create(LineSegments.prototype);
  28868. CameraHelper.prototype.constructor = CameraHelper;
  28869. CameraHelper.prototype.update = function () {
  28870. var geometry = this.geometry;
  28871. var pointMap = this.pointMap;
  28872. var w = 1,
  28873. h = 1; // we need just camera projection matrix inverse
  28874. // world matrix must be identity
  28875. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
  28876. setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
  28877. setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
  28878. setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
  28879. setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
  28880. setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
  28881. setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
  28882. setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
  28883. setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
  28884. setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
  28885. setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
  28886. setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
  28887. setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
  28888. setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
  28889. setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
  28890. setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
  28891. setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
  28892. setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
  28893. setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
  28894. setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
  28895. setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
  28896. setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
  28897. geometry.getAttribute('position').needsUpdate = true;
  28898. };
  28899. function setPoint(point, pointMap, geometry, camera, x, y, z) {
  28900. _vector$a.set(x, y, z).unproject(camera);
  28901. var points = pointMap[point];
  28902. if (points !== undefined) {
  28903. var position = geometry.getAttribute('position');
  28904. for (var i = 0, l = points.length; i < l; i++) {
  28905. position.setXYZ(points[i], _vector$a.x, _vector$a.y, _vector$a.z);
  28906. }
  28907. }
  28908. }
  28909. /**
  28910. * @author mrdoob / http://mrdoob.com/
  28911. * @author Mugen87 / http://github.com/Mugen87
  28912. */
  28913. var _box$2 = new Box3();
  28914. function BoxHelper(object, color) {
  28915. this.object = object;
  28916. if (color === undefined) color = 0xffff00;
  28917. 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]);
  28918. var positions = new Float32Array(8 * 3);
  28919. var geometry = new BufferGeometry();
  28920. geometry.setIndex(new BufferAttribute(indices, 1));
  28921. geometry.addAttribute('position', new BufferAttribute(positions, 3));
  28922. LineSegments.call(this, geometry, new LineBasicMaterial({
  28923. color: color
  28924. }));
  28925. this.matrixAutoUpdate = false;
  28926. this.update();
  28927. }
  28928. BoxHelper.prototype = Object.create(LineSegments.prototype);
  28929. BoxHelper.prototype.constructor = BoxHelper;
  28930. BoxHelper.prototype.update = function (object) {
  28931. if (object !== undefined) {
  28932. console.warn('THREE.BoxHelper: .update() has no longer arguments.');
  28933. }
  28934. if (this.object !== undefined) {
  28935. _box$2.setFromObject(this.object);
  28936. }
  28937. if (_box$2.isEmpty()) return;
  28938. var min = _box$2.min;
  28939. var max = _box$2.max;
  28940. /*
  28941. 5____4
  28942. 1/___0/|
  28943. | 6__|_7
  28944. 2/___3/
  28945. 0: max.x, max.y, max.z
  28946. 1: min.x, max.y, max.z
  28947. 2: min.x, min.y, max.z
  28948. 3: max.x, min.y, max.z
  28949. 4: max.x, max.y, min.z
  28950. 5: min.x, max.y, min.z
  28951. 6: min.x, min.y, min.z
  28952. 7: max.x, min.y, min.z
  28953. */
  28954. var position = this.geometry.attributes.position;
  28955. var array = position.array;
  28956. array[0] = max.x;
  28957. array[1] = max.y;
  28958. array[2] = max.z;
  28959. array[3] = min.x;
  28960. array[4] = max.y;
  28961. array[5] = max.z;
  28962. array[6] = min.x;
  28963. array[7] = min.y;
  28964. array[8] = max.z;
  28965. array[9] = max.x;
  28966. array[10] = min.y;
  28967. array[11] = max.z;
  28968. array[12] = max.x;
  28969. array[13] = max.y;
  28970. array[14] = min.z;
  28971. array[15] = min.x;
  28972. array[16] = max.y;
  28973. array[17] = min.z;
  28974. array[18] = min.x;
  28975. array[19] = min.y;
  28976. array[20] = min.z;
  28977. array[21] = max.x;
  28978. array[22] = min.y;
  28979. array[23] = min.z;
  28980. position.needsUpdate = true;
  28981. this.geometry.computeBoundingSphere();
  28982. };
  28983. BoxHelper.prototype.setFromObject = function (object) {
  28984. this.object = object;
  28985. this.update();
  28986. return this;
  28987. };
  28988. BoxHelper.prototype.copy = function (source) {
  28989. LineSegments.prototype.copy.call(this, source);
  28990. this.object = source.object;
  28991. return this;
  28992. };
  28993. BoxHelper.prototype.clone = function () {
  28994. return new this.constructor().copy(this);
  28995. };
  28996. /**
  28997. * @author WestLangley / http://github.com/WestLangley
  28998. */
  28999. function Box3Helper(box, color) {
  29000. this.type = 'Box3Helper';
  29001. this.box = box;
  29002. color = color || 0xffff00;
  29003. 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]);
  29004. var positions = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, 1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1];
  29005. var geometry = new BufferGeometry();
  29006. geometry.setIndex(new BufferAttribute(indices, 1));
  29007. geometry.addAttribute('position', new Float32BufferAttribute(positions, 3));
  29008. LineSegments.call(this, geometry, new LineBasicMaterial({
  29009. color: color
  29010. }));
  29011. this.geometry.computeBoundingSphere();
  29012. }
  29013. Box3Helper.prototype = Object.create(LineSegments.prototype);
  29014. Box3Helper.prototype.constructor = Box3Helper;
  29015. Box3Helper.prototype.updateMatrixWorld = function (force) {
  29016. var box = this.box;
  29017. if (box.isEmpty()) return;
  29018. box.getCenter(this.position);
  29019. box.getSize(this.scale);
  29020. this.scale.multiplyScalar(0.5);
  29021. Object3D.prototype.updateMatrixWorld.call(this, force);
  29022. };
  29023. /**
  29024. * @author WestLangley / http://github.com/WestLangley
  29025. */
  29026. function PlaneHelper(plane, size, hex) {
  29027. this.type = 'PlaneHelper';
  29028. this.plane = plane;
  29029. this.size = size === undefined ? 1 : size;
  29030. var color = hex !== undefined ? hex : 0xffff00;
  29031. var positions = [1, -1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0];
  29032. var geometry = new BufferGeometry();
  29033. geometry.addAttribute('position', new Float32BufferAttribute(positions, 3));
  29034. geometry.computeBoundingSphere();
  29035. Line.call(this, geometry, new LineBasicMaterial({
  29036. color: color
  29037. })); //
  29038. var positions2 = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1];
  29039. var geometry2 = new BufferGeometry();
  29040. geometry2.addAttribute('position', new Float32BufferAttribute(positions2, 3));
  29041. geometry2.computeBoundingSphere();
  29042. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  29043. color: color,
  29044. opacity: 0.2,
  29045. transparent: true,
  29046. depthWrite: false
  29047. })));
  29048. }
  29049. PlaneHelper.prototype = Object.create(Line.prototype);
  29050. PlaneHelper.prototype.constructor = PlaneHelper;
  29051. PlaneHelper.prototype.updateMatrixWorld = function (force) {
  29052. var scale = -this.plane.constant;
  29053. if (Math.abs(scale) < 1e-8) scale = 1e-8; // sign does not matter
  29054. this.scale.set(0.5 * this.size, 0.5 * this.size, scale);
  29055. this.children[0].material.side = scale < 0 ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  29056. this.lookAt(this.plane.normal);
  29057. Object3D.prototype.updateMatrixWorld.call(this, force);
  29058. };
  29059. /**
  29060. * @author WestLangley / http://github.com/WestLangley
  29061. * @author zz85 / http://github.com/zz85
  29062. * @author bhouston / http://clara.io
  29063. *
  29064. * Creates an arrow for visualizing directions
  29065. *
  29066. * Parameters:
  29067. * dir - Vector3
  29068. * origin - Vector3
  29069. * length - Number
  29070. * color - color in hex value
  29071. * headLength - Number
  29072. * headWidth - Number
  29073. */
  29074. var _axis = new Vector3();
  29075. var _lineGeometry, _coneGeometry;
  29076. function ArrowHelper(dir, origin, length, color, headLength, headWidth) {
  29077. // dir is assumed to be normalized
  29078. Object3D.call(this);
  29079. if (dir === undefined) dir = new Vector3(0, 0, 1);
  29080. if (origin === undefined) origin = new Vector3(0, 0, 0);
  29081. if (length === undefined) length = 1;
  29082. if (color === undefined) color = 0xffff00;
  29083. if (headLength === undefined) headLength = 0.2 * length;
  29084. if (headWidth === undefined) headWidth = 0.2 * headLength;
  29085. if (_lineGeometry === undefined) {
  29086. _lineGeometry = new BufferGeometry();
  29087. _lineGeometry.addAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
  29088. _coneGeometry = new CylinderBufferGeometry(0, 0.5, 1, 5, 1);
  29089. _coneGeometry.translate(0, -0.5, 0);
  29090. }
  29091. this.position.copy(origin);
  29092. this.line = new Line(_lineGeometry, new LineBasicMaterial({
  29093. color: color
  29094. }));
  29095. this.line.matrixAutoUpdate = false;
  29096. this.add(this.line);
  29097. this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
  29098. color: color
  29099. }));
  29100. this.cone.matrixAutoUpdate = false;
  29101. this.add(this.cone);
  29102. this.setDirection(dir);
  29103. this.setLength(length, headLength, headWidth);
  29104. }
  29105. ArrowHelper.prototype = Object.create(Object3D.prototype);
  29106. ArrowHelper.prototype.constructor = ArrowHelper;
  29107. ArrowHelper.prototype.setDirection = function (dir) {
  29108. // dir is assumed to be normalized
  29109. if (dir.y > 0.99999) {
  29110. this.quaternion.set(0, 0, 0, 1);
  29111. } else if (dir.y < -0.99999) {
  29112. this.quaternion.set(1, 0, 0, 0);
  29113. } else {
  29114. _axis.set(dir.z, 0, -dir.x).normalize();
  29115. var radians = Math.acos(dir.y);
  29116. this.quaternion.setFromAxisAngle(_axis, radians);
  29117. }
  29118. };
  29119. ArrowHelper.prototype.setLength = function (length, headLength, headWidth) {
  29120. if (headLength === undefined) headLength = 0.2 * length;
  29121. if (headWidth === undefined) headWidth = 0.2 * headLength;
  29122. this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
  29123. this.line.updateMatrix();
  29124. this.cone.scale.set(headWidth, headLength, headWidth);
  29125. this.cone.position.y = length;
  29126. this.cone.updateMatrix();
  29127. };
  29128. ArrowHelper.prototype.setColor = function (color) {
  29129. this.line.material.color.set(color);
  29130. this.cone.material.color.set(color);
  29131. };
  29132. ArrowHelper.prototype.copy = function (source) {
  29133. Object3D.prototype.copy.call(this, source, false);
  29134. this.line.copy(source.line);
  29135. this.cone.copy(source.cone);
  29136. return this;
  29137. };
  29138. ArrowHelper.prototype.clone = function () {
  29139. return new this.constructor().copy(this);
  29140. };
  29141. /**
  29142. * @author sroucheray / http://sroucheray.org/
  29143. * @author mrdoob / http://mrdoob.com/
  29144. */
  29145. function AxesHelper(size) {
  29146. size = size || 1;
  29147. var vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
  29148. var colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
  29149. var geometry = new BufferGeometry();
  29150. geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  29151. geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));
  29152. var material = new LineBasicMaterial({
  29153. vertexColors: VertexColors
  29154. });
  29155. LineSegments.call(this, geometry, material);
  29156. }
  29157. AxesHelper.prototype = Object.create(LineSegments.prototype);
  29158. AxesHelper.prototype.constructor = AxesHelper;
  29159. /**
  29160. * @author mrdoob / http://mrdoob.com/
  29161. */
  29162. function Face4(a, b, c, d, normal, color, materialIndex) {
  29163. console.warn('THREE.Face4 has been removed. A THREE.Face3 will be created instead.');
  29164. return new Face3(a, b, c, normal, color, materialIndex);
  29165. }
  29166. var LineStrip = 0;
  29167. exports.LineStrip = LineStrip;
  29168. var LinePieces = 1;
  29169. exports.LinePieces = LinePieces;
  29170. function MeshFaceMaterial(materials) {
  29171. console.warn('THREE.MeshFaceMaterial has been removed. Use an Array instead.');
  29172. return materials;
  29173. }
  29174. function MultiMaterial(materials) {
  29175. if (materials === undefined) materials = [];
  29176. console.warn('THREE.MultiMaterial has been removed. Use an Array instead.');
  29177. materials.isMultiMaterial = true;
  29178. materials.materials = materials;
  29179. materials.clone = function () {
  29180. return materials.slice();
  29181. };
  29182. return materials;
  29183. }
  29184. function PointCloud(geometry, material) {
  29185. console.warn('THREE.PointCloud has been renamed to THREE.Points.');
  29186. return new Points(geometry, material);
  29187. }
  29188. function Particle(material) {
  29189. console.warn('THREE.Particle has been renamed to THREE.Sprite.');
  29190. return new Sprite(material);
  29191. }
  29192. function ParticleSystem(geometry, material) {
  29193. console.warn('THREE.ParticleSystem has been renamed to THREE.Points.');
  29194. return new Points(geometry, material);
  29195. }
  29196. function PointCloudMaterial(parameters) {
  29197. console.warn('THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.');
  29198. return new PointsMaterial(parameters);
  29199. }
  29200. function ParticleBasicMaterial(parameters) {
  29201. console.warn('THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.');
  29202. return new PointsMaterial(parameters);
  29203. }
  29204. function ParticleSystemMaterial(parameters) {
  29205. console.warn('THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.');
  29206. return new PointsMaterial(parameters);
  29207. }
  29208. function Vertex(x, y, z) {
  29209. console.warn('THREE.Vertex has been removed. Use THREE.Vector3 instead.');
  29210. return new Vector3(x, y, z);
  29211. } //
  29212. function DynamicBufferAttribute(array, itemSize) {
  29213. console.warn('THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.');
  29214. return new BufferAttribute(array, itemSize).setDynamic(true);
  29215. }
  29216. function Int8Attribute(array, itemSize) {
  29217. console.warn('THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.');
  29218. return new Int8BufferAttribute(array, itemSize);
  29219. }
  29220. function Uint8Attribute(array, itemSize) {
  29221. console.warn('THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.');
  29222. return new Uint8BufferAttribute(array, itemSize);
  29223. }
  29224. function Uint8ClampedAttribute(array, itemSize) {
  29225. console.warn('THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.');
  29226. return new Uint8ClampedBufferAttribute(array, itemSize);
  29227. }
  29228. function Int16Attribute(array, itemSize) {
  29229. console.warn('THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.');
  29230. return new Int16BufferAttribute(array, itemSize);
  29231. }
  29232. function Uint16Attribute(array, itemSize) {
  29233. console.warn('THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.');
  29234. return new Uint16BufferAttribute(array, itemSize);
  29235. }
  29236. function Int32Attribute(array, itemSize) {
  29237. console.warn('THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.');
  29238. return new Int32BufferAttribute(array, itemSize);
  29239. }
  29240. function Uint32Attribute(array, itemSize) {
  29241. console.warn('THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.');
  29242. return new Uint32BufferAttribute(array, itemSize);
  29243. }
  29244. function Float32Attribute(array, itemSize) {
  29245. console.warn('THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.');
  29246. return new Float32BufferAttribute(array, itemSize);
  29247. }
  29248. function Float64Attribute(array, itemSize) {
  29249. console.warn('THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.');
  29250. return new Float64BufferAttribute(array, itemSize);
  29251. } //
  29252. Curve.create = function (construct, getPoint) {
  29253. console.log('THREE.Curve.create() has been deprecated');
  29254. construct.prototype = Object.create(Curve.prototype);
  29255. construct.prototype.constructor = construct;
  29256. construct.prototype.getPoint = getPoint;
  29257. return construct;
  29258. }; //
  29259. Object.assign(CurvePath.prototype, {
  29260. createPointsGeometry: function (divisions) {
  29261. console.warn('THREE.CurvePath: .createPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.'); // generate geometry from path points (for Line or Points objects)
  29262. var pts = this.getPoints(divisions);
  29263. return this.createGeometry(pts);
  29264. },
  29265. createSpacedPointsGeometry: function (divisions) {
  29266. console.warn('THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.'); // generate geometry from equidistant sampling along the path
  29267. var pts = this.getSpacedPoints(divisions);
  29268. return this.createGeometry(pts);
  29269. },
  29270. createGeometry: function (points) {
  29271. console.warn('THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.');
  29272. var geometry = new Geometry();
  29273. for (var i = 0, l = points.length; i < l; i++) {
  29274. var point = points[i];
  29275. geometry.vertices.push(new Vector3(point.x, point.y, point.z || 0));
  29276. }
  29277. return geometry;
  29278. }
  29279. }); //
  29280. Object.assign(Path.prototype, {
  29281. fromPoints: function (points) {
  29282. console.warn('THREE.Path: .fromPoints() has been renamed to .setFromPoints().');
  29283. this.setFromPoints(points);
  29284. }
  29285. }); //
  29286. function ClosedSplineCurve3(points) {
  29287. console.warn('THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');
  29288. CatmullRomCurve3.call(this, points);
  29289. this.type = 'catmullrom';
  29290. this.closed = true;
  29291. }
  29292. ClosedSplineCurve3.prototype = Object.create(CatmullRomCurve3.prototype); //
  29293. function SplineCurve3(points) {
  29294. console.warn('THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');
  29295. CatmullRomCurve3.call(this, points);
  29296. this.type = 'catmullrom';
  29297. }
  29298. SplineCurve3.prototype = Object.create(CatmullRomCurve3.prototype); //
  29299. function Spline(points) {
  29300. console.warn('THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.');
  29301. CatmullRomCurve3.call(this, points);
  29302. this.type = 'catmullrom';
  29303. }
  29304. Spline.prototype = Object.create(CatmullRomCurve3.prototype);
  29305. Object.assign(Spline.prototype, {
  29306. initFromArray: function ()
  29307. /* a */
  29308. {
  29309. console.error('THREE.Spline: .initFromArray() has been removed.');
  29310. },
  29311. getControlPointsArray: function ()
  29312. /* optionalTarget */
  29313. {
  29314. console.error('THREE.Spline: .getControlPointsArray() has been removed.');
  29315. },
  29316. reparametrizeByArcLength: function ()
  29317. /* samplingCoef */
  29318. {
  29319. console.error('THREE.Spline: .reparametrizeByArcLength() has been removed.');
  29320. }
  29321. }); //
  29322. function AxisHelper(size) {
  29323. console.warn('THREE.AxisHelper has been renamed to THREE.AxesHelper.');
  29324. return new AxesHelper(size);
  29325. }
  29326. function BoundingBoxHelper(object, color) {
  29327. console.warn('THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.');
  29328. return new BoxHelper(object, color);
  29329. }
  29330. function EdgesHelper(object, hex) {
  29331. console.warn('THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.');
  29332. return new LineSegments(new EdgesGeometry(object.geometry), new LineBasicMaterial({
  29333. color: hex !== undefined ? hex : 0xffffff
  29334. }));
  29335. }
  29336. GridHelper.prototype.setColors = function () {
  29337. console.error('THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.');
  29338. };
  29339. SkeletonHelper.prototype.update = function () {
  29340. console.error('THREE.SkeletonHelper: update() no longer needs to be called.');
  29341. };
  29342. function WireframeHelper(object, hex) {
  29343. console.warn('THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.');
  29344. return new LineSegments(new WireframeGeometry(object.geometry), new LineBasicMaterial({
  29345. color: hex !== undefined ? hex : 0xffffff
  29346. }));
  29347. } //
  29348. Object.assign(Loader.prototype, {
  29349. extractUrlBase: function (url) {
  29350. console.warn('THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.');
  29351. return LoaderUtils.extractUrlBase(url);
  29352. }
  29353. });
  29354. Loader.Handlers = {
  29355. add: function ()
  29356. /* regex, loader */
  29357. {
  29358. console.error('THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.');
  29359. },
  29360. get: function ()
  29361. /* file */
  29362. {
  29363. console.error('THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.');
  29364. }
  29365. };
  29366. function XHRLoader(manager) {
  29367. console.warn('THREE.XHRLoader has been renamed to THREE.FileLoader.');
  29368. return new FileLoader(manager);
  29369. }
  29370. function BinaryTextureLoader(manager) {
  29371. console.warn('THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.');
  29372. return new DataTextureLoader(manager);
  29373. }
  29374. Object.assign(ObjectLoader.prototype, {
  29375. setTexturePath: function (value) {
  29376. console.warn('THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().');
  29377. return this.setResourcePath(value);
  29378. }
  29379. }); //
  29380. Object.assign(Box2.prototype, {
  29381. center: function (optionalTarget) {
  29382. console.warn('THREE.Box2: .center() has been renamed to .getCenter().');
  29383. return this.getCenter(optionalTarget);
  29384. },
  29385. empty: function () {
  29386. console.warn('THREE.Box2: .empty() has been renamed to .isEmpty().');
  29387. return this.isEmpty();
  29388. },
  29389. isIntersectionBox: function (box) {
  29390. console.warn('THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().');
  29391. return this.intersectsBox(box);
  29392. },
  29393. size: function (optionalTarget) {
  29394. console.warn('THREE.Box2: .size() has been renamed to .getSize().');
  29395. return this.getSize(optionalTarget);
  29396. }
  29397. });
  29398. Object.assign(Box3.prototype, {
  29399. center: function (optionalTarget) {
  29400. console.warn('THREE.Box3: .center() has been renamed to .getCenter().');
  29401. return this.getCenter(optionalTarget);
  29402. },
  29403. empty: function () {
  29404. console.warn('THREE.Box3: .empty() has been renamed to .isEmpty().');
  29405. return this.isEmpty();
  29406. },
  29407. isIntersectionBox: function (box) {
  29408. console.warn('THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().');
  29409. return this.intersectsBox(box);
  29410. },
  29411. isIntersectionSphere: function (sphere) {
  29412. console.warn('THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  29413. return this.intersectsSphere(sphere);
  29414. },
  29415. size: function (optionalTarget) {
  29416. console.warn('THREE.Box3: .size() has been renamed to .getSize().');
  29417. return this.getSize(optionalTarget);
  29418. }
  29419. });
  29420. Line3.prototype.center = function (optionalTarget) {
  29421. console.warn('THREE.Line3: .center() has been renamed to .getCenter().');
  29422. return this.getCenter(optionalTarget);
  29423. };
  29424. Object.assign(_Math, {
  29425. random16: function () {
  29426. console.warn('THREE.Math: .random16() has been deprecated. Use Math.random() instead.');
  29427. return Math.random();
  29428. },
  29429. nearestPowerOfTwo: function (value) {
  29430. console.warn('THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().');
  29431. return _Math.floorPowerOfTwo(value);
  29432. },
  29433. nextPowerOfTwo: function (value) {
  29434. console.warn('THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().');
  29435. return _Math.ceilPowerOfTwo(value);
  29436. }
  29437. });
  29438. Object.assign(Matrix3.prototype, {
  29439. flattenToArrayOffset: function (array, offset) {
  29440. console.warn("THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");
  29441. return this.toArray(array, offset);
  29442. },
  29443. multiplyVector3: function (vector) {
  29444. console.warn('THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.');
  29445. return vector.applyMatrix3(this);
  29446. },
  29447. multiplyVector3Array: function ()
  29448. /* a */
  29449. {
  29450. console.error('THREE.Matrix3: .multiplyVector3Array() has been removed.');
  29451. },
  29452. applyToBuffer: function (buffer
  29453. /*, offset, length */
  29454. ) {
  29455. console.warn('THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.');
  29456. return this.applyToBufferAttribute(buffer);
  29457. },
  29458. applyToVector3Array: function ()
  29459. /* array, offset, length */
  29460. {
  29461. console.error('THREE.Matrix3: .applyToVector3Array() has been removed.');
  29462. }
  29463. });
  29464. Object.assign(Matrix4.prototype, {
  29465. extractPosition: function (m) {
  29466. console.warn('THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().');
  29467. return this.copyPosition(m);
  29468. },
  29469. flattenToArrayOffset: function (array, offset) {
  29470. console.warn("THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");
  29471. return this.toArray(array, offset);
  29472. },
  29473. getPosition: function () {
  29474. console.warn('THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.');
  29475. return new Vector3().setFromMatrixColumn(this, 3);
  29476. },
  29477. setRotationFromQuaternion: function (q) {
  29478. console.warn('THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().');
  29479. return this.makeRotationFromQuaternion(q);
  29480. },
  29481. multiplyToArray: function () {
  29482. console.warn('THREE.Matrix4: .multiplyToArray() has been removed.');
  29483. },
  29484. multiplyVector3: function (vector) {
  29485. console.warn('THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  29486. return vector.applyMatrix4(this);
  29487. },
  29488. multiplyVector4: function (vector) {
  29489. console.warn('THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  29490. return vector.applyMatrix4(this);
  29491. },
  29492. multiplyVector3Array: function ()
  29493. /* a */
  29494. {
  29495. console.error('THREE.Matrix4: .multiplyVector3Array() has been removed.');
  29496. },
  29497. rotateAxis: function (v) {
  29498. console.warn('THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.');
  29499. v.transformDirection(this);
  29500. },
  29501. crossVector: function (vector) {
  29502. console.warn('THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  29503. return vector.applyMatrix4(this);
  29504. },
  29505. translate: function () {
  29506. console.error('THREE.Matrix4: .translate() has been removed.');
  29507. },
  29508. rotateX: function () {
  29509. console.error('THREE.Matrix4: .rotateX() has been removed.');
  29510. },
  29511. rotateY: function () {
  29512. console.error('THREE.Matrix4: .rotateY() has been removed.');
  29513. },
  29514. rotateZ: function () {
  29515. console.error('THREE.Matrix4: .rotateZ() has been removed.');
  29516. },
  29517. rotateByAxis: function () {
  29518. console.error('THREE.Matrix4: .rotateByAxis() has been removed.');
  29519. },
  29520. applyToBuffer: function (buffer
  29521. /*, offset, length */
  29522. ) {
  29523. console.warn('THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.');
  29524. return this.applyToBufferAttribute(buffer);
  29525. },
  29526. applyToVector3Array: function ()
  29527. /* array, offset, length */
  29528. {
  29529. console.error('THREE.Matrix4: .applyToVector3Array() has been removed.');
  29530. },
  29531. makeFrustum: function (left, right, bottom, top, near, far) {
  29532. console.warn('THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.');
  29533. return this.makePerspective(left, right, top, bottom, near, far);
  29534. }
  29535. });
  29536. Plane.prototype.isIntersectionLine = function (line) {
  29537. console.warn('THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().');
  29538. return this.intersectsLine(line);
  29539. };
  29540. Quaternion.prototype.multiplyVector3 = function (vector) {
  29541. console.warn('THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.');
  29542. return vector.applyQuaternion(this);
  29543. };
  29544. Object.assign(Ray.prototype, {
  29545. isIntersectionBox: function (box) {
  29546. console.warn('THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().');
  29547. return this.intersectsBox(box);
  29548. },
  29549. isIntersectionPlane: function (plane) {
  29550. console.warn('THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().');
  29551. return this.intersectsPlane(plane);
  29552. },
  29553. isIntersectionSphere: function (sphere) {
  29554. console.warn('THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  29555. return this.intersectsSphere(sphere);
  29556. }
  29557. });
  29558. Object.assign(Triangle.prototype, {
  29559. area: function () {
  29560. console.warn('THREE.Triangle: .area() has been renamed to .getArea().');
  29561. return this.getArea();
  29562. },
  29563. barycoordFromPoint: function (point, target) {
  29564. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  29565. return this.getBarycoord(point, target);
  29566. },
  29567. midpoint: function (target) {
  29568. console.warn('THREE.Triangle: .midpoint() has been renamed to .getMidpoint().');
  29569. return this.getMidpoint(target);
  29570. },
  29571. normal: function (target) {
  29572. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  29573. return this.getNormal(target);
  29574. },
  29575. plane: function (target) {
  29576. console.warn('THREE.Triangle: .plane() has been renamed to .getPlane().');
  29577. return this.getPlane(target);
  29578. }
  29579. });
  29580. Object.assign(Triangle, {
  29581. barycoordFromPoint: function (point, a, b, c, target) {
  29582. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  29583. return Triangle.getBarycoord(point, a, b, c, target);
  29584. },
  29585. normal: function (a, b, c, target) {
  29586. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  29587. return Triangle.getNormal(a, b, c, target);
  29588. }
  29589. });
  29590. Object.assign(Shape.prototype, {
  29591. extractAllPoints: function (divisions) {
  29592. console.warn('THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.');
  29593. return this.extractPoints(divisions);
  29594. },
  29595. extrude: function (options) {
  29596. console.warn('THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.');
  29597. return new ExtrudeGeometry(this, options);
  29598. },
  29599. makeGeometry: function (options) {
  29600. console.warn('THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.');
  29601. return new ShapeGeometry(this, options);
  29602. }
  29603. });
  29604. Object.assign(Vector2.prototype, {
  29605. fromAttribute: function (attribute, index, offset) {
  29606. console.warn('THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().');
  29607. return this.fromBufferAttribute(attribute, index, offset);
  29608. },
  29609. distanceToManhattan: function (v) {
  29610. console.warn('THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  29611. return this.manhattanDistanceTo(v);
  29612. },
  29613. lengthManhattan: function () {
  29614. console.warn('THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().');
  29615. return this.manhattanLength();
  29616. }
  29617. });
  29618. Object.assign(Vector3.prototype, {
  29619. setEulerFromRotationMatrix: function () {
  29620. console.error('THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.');
  29621. },
  29622. setEulerFromQuaternion: function () {
  29623. console.error('THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.');
  29624. },
  29625. getPositionFromMatrix: function (m) {
  29626. console.warn('THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().');
  29627. return this.setFromMatrixPosition(m);
  29628. },
  29629. getScaleFromMatrix: function (m) {
  29630. console.warn('THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().');
  29631. return this.setFromMatrixScale(m);
  29632. },
  29633. getColumnFromMatrix: function (index, matrix) {
  29634. console.warn('THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().');
  29635. return this.setFromMatrixColumn(matrix, index);
  29636. },
  29637. applyProjection: function (m) {
  29638. console.warn('THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.');
  29639. return this.applyMatrix4(m);
  29640. },
  29641. fromAttribute: function (attribute, index, offset) {
  29642. console.warn('THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().');
  29643. return this.fromBufferAttribute(attribute, index, offset);
  29644. },
  29645. distanceToManhattan: function (v) {
  29646. console.warn('THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  29647. return this.manhattanDistanceTo(v);
  29648. },
  29649. lengthManhattan: function () {
  29650. console.warn('THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().');
  29651. return this.manhattanLength();
  29652. }
  29653. });
  29654. Object.assign(Vector4.prototype, {
  29655. fromAttribute: function (attribute, index, offset) {
  29656. console.warn('THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().');
  29657. return this.fromBufferAttribute(attribute, index, offset);
  29658. },
  29659. lengthManhattan: function () {
  29660. console.warn('THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().');
  29661. return this.manhattanLength();
  29662. }
  29663. }); //
  29664. Object.assign(Geometry.prototype, {
  29665. computeTangents: function () {
  29666. console.error('THREE.Geometry: .computeTangents() has been removed.');
  29667. },
  29668. computeLineDistances: function () {
  29669. console.error('THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.');
  29670. }
  29671. });
  29672. Object.assign(Object3D.prototype, {
  29673. getChildByName: function (name) {
  29674. console.warn('THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().');
  29675. return this.getObjectByName(name);
  29676. },
  29677. renderDepth: function () {
  29678. console.warn('THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.');
  29679. },
  29680. translate: function (distance, axis) {
  29681. console.warn('THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.');
  29682. return this.translateOnAxis(axis, distance);
  29683. },
  29684. getWorldRotation: function () {
  29685. console.error('THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.');
  29686. }
  29687. });
  29688. Object.defineProperties(Object3D.prototype, {
  29689. eulerOrder: {
  29690. get: function () {
  29691. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  29692. return this.rotation.order;
  29693. },
  29694. set: function (value) {
  29695. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  29696. this.rotation.order = value;
  29697. }
  29698. },
  29699. useQuaternion: {
  29700. get: function () {
  29701. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  29702. },
  29703. set: function () {
  29704. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  29705. }
  29706. }
  29707. });
  29708. Object.defineProperties(LOD.prototype, {
  29709. objects: {
  29710. get: function () {
  29711. console.warn('THREE.LOD: .objects has been renamed to .levels.');
  29712. return this.levels;
  29713. }
  29714. }
  29715. });
  29716. Object.defineProperty(Skeleton.prototype, 'useVertexTexture', {
  29717. get: function () {
  29718. console.warn('THREE.Skeleton: useVertexTexture has been removed.');
  29719. },
  29720. set: function () {
  29721. console.warn('THREE.Skeleton: useVertexTexture has been removed.');
  29722. }
  29723. });
  29724. SkinnedMesh.prototype.initBones = function () {
  29725. console.error('THREE.SkinnedMesh: initBones() has been removed.');
  29726. };
  29727. Object.defineProperty(Curve.prototype, '__arcLengthDivisions', {
  29728. get: function () {
  29729. console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');
  29730. return this.arcLengthDivisions;
  29731. },
  29732. set: function (value) {
  29733. console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');
  29734. this.arcLengthDivisions = value;
  29735. }
  29736. }); //
  29737. PerspectiveCamera.prototype.setLens = function (focalLength, filmGauge) {
  29738. console.warn("THREE.PerspectiveCamera.setLens is deprecated. " + "Use .setFocalLength and .filmGauge for a photographic setup.");
  29739. if (filmGauge !== undefined) this.filmGauge = filmGauge;
  29740. this.setFocalLength(focalLength);
  29741. }; //
  29742. Object.defineProperties(Light.prototype, {
  29743. onlyShadow: {
  29744. set: function () {
  29745. console.warn('THREE.Light: .onlyShadow has been removed.');
  29746. }
  29747. },
  29748. shadowCameraFov: {
  29749. set: function (value) {
  29750. console.warn('THREE.Light: .shadowCameraFov is now .shadow.camera.fov.');
  29751. this.shadow.camera.fov = value;
  29752. }
  29753. },
  29754. shadowCameraLeft: {
  29755. set: function (value) {
  29756. console.warn('THREE.Light: .shadowCameraLeft is now .shadow.camera.left.');
  29757. this.shadow.camera.left = value;
  29758. }
  29759. },
  29760. shadowCameraRight: {
  29761. set: function (value) {
  29762. console.warn('THREE.Light: .shadowCameraRight is now .shadow.camera.right.');
  29763. this.shadow.camera.right = value;
  29764. }
  29765. },
  29766. shadowCameraTop: {
  29767. set: function (value) {
  29768. console.warn('THREE.Light: .shadowCameraTop is now .shadow.camera.top.');
  29769. this.shadow.camera.top = value;
  29770. }
  29771. },
  29772. shadowCameraBottom: {
  29773. set: function (value) {
  29774. console.warn('THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.');
  29775. this.shadow.camera.bottom = value;
  29776. }
  29777. },
  29778. shadowCameraNear: {
  29779. set: function (value) {
  29780. console.warn('THREE.Light: .shadowCameraNear is now .shadow.camera.near.');
  29781. this.shadow.camera.near = value;
  29782. }
  29783. },
  29784. shadowCameraFar: {
  29785. set: function (value) {
  29786. console.warn('THREE.Light: .shadowCameraFar is now .shadow.camera.far.');
  29787. this.shadow.camera.far = value;
  29788. }
  29789. },
  29790. shadowCameraVisible: {
  29791. set: function () {
  29792. console.warn('THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.');
  29793. }
  29794. },
  29795. shadowBias: {
  29796. set: function (value) {
  29797. console.warn('THREE.Light: .shadowBias is now .shadow.bias.');
  29798. this.shadow.bias = value;
  29799. }
  29800. },
  29801. shadowDarkness: {
  29802. set: function () {
  29803. console.warn('THREE.Light: .shadowDarkness has been removed.');
  29804. }
  29805. },
  29806. shadowMapWidth: {
  29807. set: function (value) {
  29808. console.warn('THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.');
  29809. this.shadow.mapSize.width = value;
  29810. }
  29811. },
  29812. shadowMapHeight: {
  29813. set: function (value) {
  29814. console.warn('THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.');
  29815. this.shadow.mapSize.height = value;
  29816. }
  29817. }
  29818. }); //
  29819. Object.defineProperties(BufferAttribute.prototype, {
  29820. length: {
  29821. get: function () {
  29822. console.warn('THREE.BufferAttribute: .length has been deprecated. Use .count instead.');
  29823. return this.array.length;
  29824. }
  29825. }
  29826. });
  29827. Object.assign(BufferAttribute.prototype, {
  29828. copyIndicesArray: function ()
  29829. /* indices */
  29830. {
  29831. console.error('THREE.BufferAttribute: .copyIndicesArray() has been removed.');
  29832. },
  29833. setArray: function (array) {
  29834. console.warn('THREE.BufferAttribute: .setArray has been deprecated. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  29835. this.count = array !== undefined ? array.length / this.itemSize : 0;
  29836. this.array = array;
  29837. return this;
  29838. }
  29839. });
  29840. Object.assign(BufferGeometry.prototype, {
  29841. addIndex: function (index) {
  29842. console.warn('THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().');
  29843. this.setIndex(index);
  29844. },
  29845. addDrawCall: function (start, count, indexOffset) {
  29846. if (indexOffset !== undefined) {
  29847. console.warn('THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.');
  29848. }
  29849. console.warn('THREE.BufferGeometry: .addDrawCall() is now .addGroup().');
  29850. this.addGroup(start, count);
  29851. },
  29852. clearDrawCalls: function () {
  29853. console.warn('THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().');
  29854. this.clearGroups();
  29855. },
  29856. computeTangents: function () {
  29857. console.warn('THREE.BufferGeometry: .computeTangents() has been removed.');
  29858. },
  29859. computeOffsets: function () {
  29860. console.warn('THREE.BufferGeometry: .computeOffsets() has been removed.');
  29861. }
  29862. });
  29863. Object.defineProperties(BufferGeometry.prototype, {
  29864. drawcalls: {
  29865. get: function () {
  29866. console.error('THREE.BufferGeometry: .drawcalls has been renamed to .groups.');
  29867. return this.groups;
  29868. }
  29869. },
  29870. offsets: {
  29871. get: function () {
  29872. console.warn('THREE.BufferGeometry: .offsets has been renamed to .groups.');
  29873. return this.groups;
  29874. }
  29875. }
  29876. });
  29877. Object.assign(InterleavedBuffer.prototype, {
  29878. setArray: function (array) {
  29879. console.warn('THREE.InterleavedBuffer: .setArray has been deprecated. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  29880. this.count = array !== undefined ? array.length / this.stride : 0;
  29881. this.array = array;
  29882. return this;
  29883. }
  29884. }); //
  29885. Object.assign(ExtrudeBufferGeometry.prototype, {
  29886. getArrays: function () {
  29887. console.error('THREE.ExtrudeBufferGeometry: .getArrays() has been removed.');
  29888. },
  29889. addShapeList: function () {
  29890. console.error('THREE.ExtrudeBufferGeometry: .addShapeList() has been removed.');
  29891. },
  29892. addShape: function () {
  29893. console.error('THREE.ExtrudeBufferGeometry: .addShape() has been removed.');
  29894. }
  29895. }); //
  29896. Object.defineProperties(Uniform.prototype, {
  29897. dynamic: {
  29898. set: function () {
  29899. console.warn('THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.');
  29900. }
  29901. },
  29902. onUpdate: {
  29903. value: function () {
  29904. console.warn('THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.');
  29905. return this;
  29906. }
  29907. }
  29908. }); //
  29909. Object.defineProperties(Material.prototype, {
  29910. wrapAround: {
  29911. get: function () {
  29912. console.warn('THREE.Material: .wrapAround has been removed.');
  29913. },
  29914. set: function () {
  29915. console.warn('THREE.Material: .wrapAround has been removed.');
  29916. }
  29917. },
  29918. overdraw: {
  29919. get: function () {
  29920. console.warn('THREE.Material: .overdraw has been removed.');
  29921. },
  29922. set: function () {
  29923. console.warn('THREE.Material: .overdraw has been removed.');
  29924. }
  29925. },
  29926. wrapRGB: {
  29927. get: function () {
  29928. console.warn('THREE.Material: .wrapRGB has been removed.');
  29929. return new Color();
  29930. }
  29931. },
  29932. shading: {
  29933. get: function () {
  29934. console.error('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  29935. },
  29936. set: function (value) {
  29937. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  29938. this.flatShading = value === FlatShading;
  29939. }
  29940. },
  29941. stencilMask: {
  29942. get: function () {
  29943. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  29944. return this.stencilFuncMask;
  29945. },
  29946. set: function (value) {
  29947. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  29948. this.stencilFuncMask = value;
  29949. }
  29950. }
  29951. });
  29952. Object.defineProperties(MeshPhongMaterial.prototype, {
  29953. metal: {
  29954. get: function () {
  29955. console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.');
  29956. return false;
  29957. },
  29958. set: function () {
  29959. console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead');
  29960. }
  29961. }
  29962. });
  29963. Object.defineProperties(ShaderMaterial.prototype, {
  29964. derivatives: {
  29965. get: function () {
  29966. console.warn('THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  29967. return this.extensions.derivatives;
  29968. },
  29969. set: function (value) {
  29970. console.warn('THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  29971. this.extensions.derivatives = value;
  29972. }
  29973. }
  29974. }); //
  29975. Object.assign(WebGLRenderer.prototype, {
  29976. clearTarget: function (renderTarget, color, depth, stencil) {
  29977. console.warn('THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.');
  29978. this.setRenderTarget(renderTarget);
  29979. this.clear(color, depth, stencil);
  29980. },
  29981. animate: function (callback) {
  29982. console.warn('THREE.WebGLRenderer: .animate() is now .setAnimationLoop().');
  29983. this.setAnimationLoop(callback);
  29984. },
  29985. getCurrentRenderTarget: function () {
  29986. console.warn('THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().');
  29987. return this.getRenderTarget();
  29988. },
  29989. getMaxAnisotropy: function () {
  29990. console.warn('THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().');
  29991. return this.capabilities.getMaxAnisotropy();
  29992. },
  29993. getPrecision: function () {
  29994. console.warn('THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.');
  29995. return this.capabilities.precision;
  29996. },
  29997. resetGLState: function () {
  29998. console.warn('THREE.WebGLRenderer: .resetGLState() is now .state.reset().');
  29999. return this.state.reset();
  30000. },
  30001. supportsFloatTextures: function () {
  30002. console.warn('THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).');
  30003. return this.extensions.get('OES_texture_float');
  30004. },
  30005. supportsHalfFloatTextures: function () {
  30006. console.warn('THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).');
  30007. return this.extensions.get('OES_texture_half_float');
  30008. },
  30009. supportsStandardDerivatives: function () {
  30010. console.warn('THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).');
  30011. return this.extensions.get('OES_standard_derivatives');
  30012. },
  30013. supportsCompressedTextureS3TC: function () {
  30014. console.warn('THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).');
  30015. return this.extensions.get('WEBGL_compressed_texture_s3tc');
  30016. },
  30017. supportsCompressedTexturePVRTC: function () {
  30018. console.warn('THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).');
  30019. return this.extensions.get('WEBGL_compressed_texture_pvrtc');
  30020. },
  30021. supportsBlendMinMax: function () {
  30022. console.warn('THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).');
  30023. return this.extensions.get('EXT_blend_minmax');
  30024. },
  30025. supportsVertexTextures: function () {
  30026. console.warn('THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.');
  30027. return this.capabilities.vertexTextures;
  30028. },
  30029. supportsInstancedArrays: function () {
  30030. console.warn('THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).');
  30031. return this.extensions.get('ANGLE_instanced_arrays');
  30032. },
  30033. enableScissorTest: function (boolean) {
  30034. console.warn('THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().');
  30035. this.setScissorTest(boolean);
  30036. },
  30037. initMaterial: function () {
  30038. console.warn('THREE.WebGLRenderer: .initMaterial() has been removed.');
  30039. },
  30040. addPrePlugin: function () {
  30041. console.warn('THREE.WebGLRenderer: .addPrePlugin() has been removed.');
  30042. },
  30043. addPostPlugin: function () {
  30044. console.warn('THREE.WebGLRenderer: .addPostPlugin() has been removed.');
  30045. },
  30046. updateShadowMap: function () {
  30047. console.warn('THREE.WebGLRenderer: .updateShadowMap() has been removed.');
  30048. },
  30049. setFaceCulling: function () {
  30050. console.warn('THREE.WebGLRenderer: .setFaceCulling() has been removed.');
  30051. },
  30052. allocTextureUnit: function () {
  30053. console.warn('THREE.WebGLRenderer: .allocTextureUnit() has been removed.');
  30054. },
  30055. setTexture: function () {
  30056. console.warn('THREE.WebGLRenderer: .setTexture() has been removed.');
  30057. },
  30058. setTexture2D: function () {
  30059. console.warn('THREE.WebGLRenderer: .setTexture2D() has been removed.');
  30060. },
  30061. setTextureCube: function () {
  30062. console.warn('THREE.WebGLRenderer: .setTextureCube() has been removed.');
  30063. },
  30064. getActiveMipMapLevel: function () {
  30065. console.warn('THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().');
  30066. return this.getActiveMipmapLevel();
  30067. }
  30068. });
  30069. Object.defineProperties(WebGLRenderer.prototype, {
  30070. shadowMapEnabled: {
  30071. get: function () {
  30072. return this.shadowMap.enabled;
  30073. },
  30074. set: function (value) {
  30075. console.warn('THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.');
  30076. this.shadowMap.enabled = value;
  30077. }
  30078. },
  30079. shadowMapType: {
  30080. get: function () {
  30081. return this.shadowMap.type;
  30082. },
  30083. set: function (value) {
  30084. console.warn('THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.');
  30085. this.shadowMap.type = value;
  30086. }
  30087. },
  30088. shadowMapCullFace: {
  30089. get: function () {
  30090. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  30091. return undefined;
  30092. },
  30093. set: function ()
  30094. /* value */
  30095. {
  30096. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  30097. }
  30098. },
  30099. context: {
  30100. get: function () {
  30101. console.warn('THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.');
  30102. return this.getContext();
  30103. }
  30104. }
  30105. });
  30106. Object.defineProperties(WebGLShadowMap.prototype, {
  30107. cullFace: {
  30108. get: function () {
  30109. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  30110. return undefined;
  30111. },
  30112. set: function ()
  30113. /* cullFace */
  30114. {
  30115. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  30116. }
  30117. },
  30118. renderReverseSided: {
  30119. get: function () {
  30120. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  30121. return undefined;
  30122. },
  30123. set: function () {
  30124. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  30125. }
  30126. },
  30127. renderSingleSided: {
  30128. get: function () {
  30129. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  30130. return undefined;
  30131. },
  30132. set: function () {
  30133. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  30134. }
  30135. }
  30136. }); //
  30137. Object.defineProperties(WebGLRenderTargetCube.prototype, {
  30138. activeCubeFace: {
  30139. set: function ()
  30140. /* value */
  30141. {
  30142. console.warn('THREE.WebGLRenderTargetCube: .activeCubeFace has been removed. It is now the second parameter of WebGLRenderer.setRenderTarget().');
  30143. }
  30144. },
  30145. activeMipMapLevel: {
  30146. set: function ()
  30147. /* value */
  30148. {
  30149. console.warn('THREE.WebGLRenderTargetCube: .activeMipMapLevel has been removed. It is now the third parameter of WebGLRenderer.setRenderTarget().');
  30150. }
  30151. }
  30152. }); //
  30153. Object.defineProperties(WebGLRenderTarget.prototype, {
  30154. wrapS: {
  30155. get: function () {
  30156. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  30157. return this.texture.wrapS;
  30158. },
  30159. set: function (value) {
  30160. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  30161. this.texture.wrapS = value;
  30162. }
  30163. },
  30164. wrapT: {
  30165. get: function () {
  30166. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  30167. return this.texture.wrapT;
  30168. },
  30169. set: function (value) {
  30170. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  30171. this.texture.wrapT = value;
  30172. }
  30173. },
  30174. magFilter: {
  30175. get: function () {
  30176. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  30177. return this.texture.magFilter;
  30178. },
  30179. set: function (value) {
  30180. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  30181. this.texture.magFilter = value;
  30182. }
  30183. },
  30184. minFilter: {
  30185. get: function () {
  30186. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  30187. return this.texture.minFilter;
  30188. },
  30189. set: function (value) {
  30190. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  30191. this.texture.minFilter = value;
  30192. }
  30193. },
  30194. anisotropy: {
  30195. get: function () {
  30196. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  30197. return this.texture.anisotropy;
  30198. },
  30199. set: function (value) {
  30200. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  30201. this.texture.anisotropy = value;
  30202. }
  30203. },
  30204. offset: {
  30205. get: function () {
  30206. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  30207. return this.texture.offset;
  30208. },
  30209. set: function (value) {
  30210. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  30211. this.texture.offset = value;
  30212. }
  30213. },
  30214. repeat: {
  30215. get: function () {
  30216. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  30217. return this.texture.repeat;
  30218. },
  30219. set: function (value) {
  30220. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  30221. this.texture.repeat = value;
  30222. }
  30223. },
  30224. format: {
  30225. get: function () {
  30226. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  30227. return this.texture.format;
  30228. },
  30229. set: function (value) {
  30230. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  30231. this.texture.format = value;
  30232. }
  30233. },
  30234. type: {
  30235. get: function () {
  30236. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  30237. return this.texture.type;
  30238. },
  30239. set: function (value) {
  30240. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  30241. this.texture.type = value;
  30242. }
  30243. },
  30244. generateMipmaps: {
  30245. get: function () {
  30246. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  30247. return this.texture.generateMipmaps;
  30248. },
  30249. set: function (value) {
  30250. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  30251. this.texture.generateMipmaps = value;
  30252. }
  30253. }
  30254. }); //
  30255. Object.defineProperties(WebVRManager.prototype, {
  30256. standing: {
  30257. set: function ()
  30258. /* value */
  30259. {
  30260. console.warn('THREE.WebVRManager: .standing has been removed.');
  30261. }
  30262. },
  30263. userHeight: {
  30264. set: function ()
  30265. /* value */
  30266. {
  30267. console.warn('THREE.WebVRManager: .userHeight has been removed.');
  30268. }
  30269. }
  30270. }); //
  30271. Audio.prototype.load = function (file) {
  30272. console.warn('THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.');
  30273. var scope = this;
  30274. var audioLoader = new AudioLoader();
  30275. audioLoader.load(file, function (buffer) {
  30276. scope.setBuffer(buffer);
  30277. });
  30278. return this;
  30279. };
  30280. AudioAnalyser.prototype.getData = function () {
  30281. console.warn('THREE.AudioAnalyser: .getData() is now .getFrequencyData().');
  30282. return this.getFrequencyData();
  30283. }; //
  30284. CubeCamera.prototype.updateCubeMap = function (renderer, scene) {
  30285. console.warn('THREE.CubeCamera: .updateCubeMap() is now .update().');
  30286. return this.update(renderer, scene);
  30287. }; //
  30288. var GeometryUtils = {
  30289. merge: function (geometry1, geometry2, materialIndexOffset) {
  30290. console.warn('THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.');
  30291. var matrix;
  30292. if (geometry2.isMesh) {
  30293. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  30294. matrix = geometry2.matrix;
  30295. geometry2 = geometry2.geometry;
  30296. }
  30297. geometry1.merge(geometry2, matrix, materialIndexOffset);
  30298. },
  30299. center: function (geometry) {
  30300. console.warn('THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.');
  30301. return geometry.center();
  30302. }
  30303. };
  30304. exports.GeometryUtils = GeometryUtils;
  30305. ImageUtils.crossOrigin = undefined;
  30306. ImageUtils.loadTexture = function (url, mapping, onLoad, onError) {
  30307. console.warn('THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.');
  30308. var loader = new TextureLoader();
  30309. loader.setCrossOrigin(this.crossOrigin);
  30310. var texture = loader.load(url, onLoad, undefined, onError);
  30311. if (mapping) texture.mapping = mapping;
  30312. return texture;
  30313. };
  30314. ImageUtils.loadTextureCube = function (urls, mapping, onLoad, onError) {
  30315. console.warn('THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.');
  30316. var loader = new CubeTextureLoader();
  30317. loader.setCrossOrigin(this.crossOrigin);
  30318. var texture = loader.load(urls, onLoad, undefined, onError);
  30319. if (mapping) texture.mapping = mapping;
  30320. return texture;
  30321. };
  30322. ImageUtils.loadCompressedTexture = function () {
  30323. console.error('THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.');
  30324. };
  30325. ImageUtils.loadCompressedTextureCube = function () {
  30326. console.error('THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.');
  30327. }; //
  30328. function CanvasRenderer() {
  30329. console.error('THREE.CanvasRenderer has been removed');
  30330. } //
  30331. function JSONLoader() {
  30332. console.error('THREE.JSONLoader has been removed.');
  30333. } //
  30334. var SceneUtils = {
  30335. createMultiMaterialObject: function ()
  30336. /* geometry, materials */
  30337. {
  30338. console.error('THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js');
  30339. },
  30340. detach: function ()
  30341. /* child, parent, scene */
  30342. {
  30343. console.error('THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js');
  30344. },
  30345. attach: function ()
  30346. /* child, scene, parent */
  30347. {
  30348. console.error('THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js');
  30349. }
  30350. }; //
  30351. exports.SceneUtils = SceneUtils;
  30352. function LensFlare() {
  30353. console.error('THREE.LensFlare has been moved to /examples/js/objects/Lensflare.js');
  30354. }
  30355. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  30356. /* eslint-disable no-undef */
  30357. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
  30358. detail: {
  30359. revision: REVISION
  30360. }
  30361. }));
  30362. /* eslint-enable no-undef */
  30363. }
  30364. },{}],"../node_modules/three/examples/jsm/loaders/GLTFLoader.js":[function(require,module,exports) {
  30365. "use strict";
  30366. Object.defineProperty(exports, "__esModule", {
  30367. value: true
  30368. });
  30369. exports.GLTFLoader = void 0;
  30370. var _threeModule = require("../../../build/three.module.js");
  30371. /**
  30372. * @author Rich Tibbett / https://github.com/richtr
  30373. * @author mrdoob / http://mrdoob.com/
  30374. * @author Tony Parisi / http://www.tonyparisi.com/
  30375. * @author Takahiro / https://github.com/takahirox
  30376. * @author Don McCurdy / https://www.donmccurdy.com
  30377. */
  30378. var GLTFLoader = function () {
  30379. function GLTFLoader(manager) {
  30380. _threeModule.Loader.call(this, manager);
  30381. this.dracoLoader = null;
  30382. this.ddsLoader = null;
  30383. }
  30384. GLTFLoader.prototype = Object.assign(Object.create(_threeModule.Loader.prototype), {
  30385. constructor: GLTFLoader,
  30386. load: function (url, onLoad, onProgress, onError) {
  30387. var scope = this;
  30388. var resourcePath;
  30389. if (this.resourcePath !== '') {
  30390. resourcePath = this.resourcePath;
  30391. } else if (this.path !== '') {
  30392. resourcePath = this.path;
  30393. } else {
  30394. resourcePath = _threeModule.LoaderUtils.extractUrlBase(url);
  30395. } // Tells the LoadingManager to track an extra item, which resolves after
  30396. // the model is fully loaded. This means the count of items loaded will
  30397. // be incorrect, but ensures manager.onLoad() does not fire early.
  30398. scope.manager.itemStart(url);
  30399. var _onError = function (e) {
  30400. if (onError) {
  30401. onError(e);
  30402. } else {
  30403. console.error(e);
  30404. }
  30405. scope.manager.itemError(url);
  30406. scope.manager.itemEnd(url);
  30407. };
  30408. var loader = new _threeModule.FileLoader(scope.manager);
  30409. loader.setPath(this.path);
  30410. loader.setResponseType('arraybuffer');
  30411. if (scope.crossOrigin === 'use-credentials') {
  30412. loader.setWithCredentials(true);
  30413. }
  30414. loader.load(url, function (data) {
  30415. try {
  30416. scope.parse(data, resourcePath, function (gltf) {
  30417. onLoad(gltf);
  30418. scope.manager.itemEnd(url);
  30419. }, _onError);
  30420. } catch (e) {
  30421. _onError(e);
  30422. }
  30423. }, onProgress, _onError);
  30424. },
  30425. setDRACOLoader: function (dracoLoader) {
  30426. this.dracoLoader = dracoLoader;
  30427. return this;
  30428. },
  30429. setDDSLoader: function (ddsLoader) {
  30430. this.ddsLoader = ddsLoader;
  30431. return this;
  30432. },
  30433. parse: function (data, path, onLoad, onError) {
  30434. var content;
  30435. var extensions = {};
  30436. if (typeof data === 'string') {
  30437. content = data;
  30438. } else {
  30439. var magic = _threeModule.LoaderUtils.decodeText(new Uint8Array(data, 0, 4));
  30440. if (magic === BINARY_EXTENSION_HEADER_MAGIC) {
  30441. try {
  30442. extensions[EXTENSIONS.KHR_BINARY_GLTF] = new GLTFBinaryExtension(data);
  30443. } catch (error) {
  30444. if (onError) onError(error);
  30445. return;
  30446. }
  30447. content = extensions[EXTENSIONS.KHR_BINARY_GLTF].content;
  30448. } else {
  30449. content = _threeModule.LoaderUtils.decodeText(new Uint8Array(data));
  30450. }
  30451. }
  30452. var json = JSON.parse(content);
  30453. if (json.asset === undefined || json.asset.version[0] < 2) {
  30454. if (onError) onError(new Error('THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported. Use LegacyGLTFLoader instead.'));
  30455. return;
  30456. }
  30457. if (json.extensionsUsed) {
  30458. for (var i = 0; i < json.extensionsUsed.length; ++i) {
  30459. var extensionName = json.extensionsUsed[i];
  30460. var extensionsRequired = json.extensionsRequired || [];
  30461. switch (extensionName) {
  30462. case EXTENSIONS.KHR_LIGHTS_PUNCTUAL:
  30463. extensions[extensionName] = new GLTFLightsExtension(json);
  30464. break;
  30465. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  30466. extensions[extensionName] = new GLTFMaterialsUnlitExtension();
  30467. break;
  30468. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  30469. extensions[extensionName] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  30470. break;
  30471. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  30472. extensions[extensionName] = new GLTFDracoMeshCompressionExtension(json, this.dracoLoader);
  30473. break;
  30474. case EXTENSIONS.MSFT_TEXTURE_DDS:
  30475. extensions[EXTENSIONS.MSFT_TEXTURE_DDS] = new GLTFTextureDDSExtension(this.ddsLoader);
  30476. break;
  30477. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  30478. extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM] = new GLTFTextureTransformExtension();
  30479. break;
  30480. default:
  30481. if (extensionsRequired.indexOf(extensionName) >= 0) {
  30482. console.warn('THREE.GLTFLoader: Unknown extension "' + extensionName + '".');
  30483. }
  30484. }
  30485. }
  30486. }
  30487. var parser = new GLTFParser(json, extensions, {
  30488. path: path || this.resourcePath || '',
  30489. crossOrigin: this.crossOrigin,
  30490. manager: this.manager
  30491. });
  30492. parser.parse(onLoad, onError);
  30493. }
  30494. });
  30495. /* GLTFREGISTRY */
  30496. function GLTFRegistry() {
  30497. var objects = {};
  30498. return {
  30499. get: function (key) {
  30500. return objects[key];
  30501. },
  30502. add: function (key, object) {
  30503. objects[key] = object;
  30504. },
  30505. remove: function (key) {
  30506. delete objects[key];
  30507. },
  30508. removeAll: function () {
  30509. objects = {};
  30510. }
  30511. };
  30512. }
  30513. /*********************************/
  30514. /********** EXTENSIONS ***********/
  30515. /*********************************/
  30516. var EXTENSIONS = {
  30517. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  30518. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  30519. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  30520. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  30521. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  30522. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  30523. MSFT_TEXTURE_DDS: 'MSFT_texture_dds'
  30524. };
  30525. /**
  30526. * DDS Texture Extension
  30527. *
  30528. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds
  30529. *
  30530. */
  30531. function GLTFTextureDDSExtension(ddsLoader) {
  30532. if (!ddsLoader) {
  30533. throw new Error('THREE.GLTFLoader: Attempting to load .dds texture without importing DDSLoader');
  30534. }
  30535. this.name = EXTENSIONS.MSFT_TEXTURE_DDS;
  30536. this.ddsLoader = ddsLoader;
  30537. }
  30538. /**
  30539. * Punctual Lights Extension
  30540. *
  30541. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  30542. */
  30543. function GLTFLightsExtension(json) {
  30544. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
  30545. var extension = json.extensions && json.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL] || {};
  30546. this.lightDefs = extension.lights || [];
  30547. }
  30548. GLTFLightsExtension.prototype.loadLight = function (lightIndex) {
  30549. var lightDef = this.lightDefs[lightIndex];
  30550. var lightNode;
  30551. var color = new _threeModule.Color(0xffffff);
  30552. if (lightDef.color !== undefined) color.fromArray(lightDef.color);
  30553. var range = lightDef.range !== undefined ? lightDef.range : 0;
  30554. switch (lightDef.type) {
  30555. case 'directional':
  30556. lightNode = new _threeModule.DirectionalLight(color);
  30557. lightNode.target.position.set(0, 0, -1);
  30558. lightNode.add(lightNode.target);
  30559. break;
  30560. case 'point':
  30561. lightNode = new _threeModule.PointLight(color);
  30562. lightNode.distance = range;
  30563. break;
  30564. case 'spot':
  30565. lightNode = new _threeModule.SpotLight(color);
  30566. lightNode.distance = range; // Handle spotlight properties.
  30567. lightDef.spot = lightDef.spot || {};
  30568. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  30569. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  30570. lightNode.angle = lightDef.spot.outerConeAngle;
  30571. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  30572. lightNode.target.position.set(0, 0, -1);
  30573. lightNode.add(lightNode.target);
  30574. break;
  30575. default:
  30576. throw new Error('THREE.GLTFLoader: Unexpected light type, "' + lightDef.type + '".');
  30577. } // Some lights (e.g. spot) default to a position other than the origin. Reset the position
  30578. // here, because node-level parsing will only override position if explicitly specified.
  30579. lightNode.position.set(0, 0, 0);
  30580. lightNode.decay = 2;
  30581. if (lightDef.intensity !== undefined) lightNode.intensity = lightDef.intensity;
  30582. lightNode.name = lightDef.name || 'light_' + lightIndex;
  30583. return Promise.resolve(lightNode);
  30584. };
  30585. /**
  30586. * Unlit Materials Extension
  30587. *
  30588. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
  30589. */
  30590. function GLTFMaterialsUnlitExtension() {
  30591. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  30592. }
  30593. GLTFMaterialsUnlitExtension.prototype.getMaterialType = function () {
  30594. return _threeModule.MeshBasicMaterial;
  30595. };
  30596. GLTFMaterialsUnlitExtension.prototype.extendParams = function (materialParams, materialDef, parser) {
  30597. var pending = [];
  30598. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  30599. materialParams.opacity = 1.0;
  30600. var metallicRoughness = materialDef.pbrMetallicRoughness;
  30601. if (metallicRoughness) {
  30602. if (Array.isArray(metallicRoughness.baseColorFactor)) {
  30603. var array = metallicRoughness.baseColorFactor;
  30604. materialParams.color.fromArray(array);
  30605. materialParams.opacity = array[3];
  30606. }
  30607. if (metallicRoughness.baseColorTexture !== undefined) {
  30608. pending.push(parser.assignTexture(materialParams, 'map', metallicRoughness.baseColorTexture));
  30609. }
  30610. }
  30611. return Promise.all(pending);
  30612. };
  30613. /* BINARY EXTENSION */
  30614. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  30615. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  30616. var BINARY_EXTENSION_CHUNK_TYPES = {
  30617. JSON: 0x4E4F534A,
  30618. BIN: 0x004E4942
  30619. };
  30620. function GLTFBinaryExtension(data) {
  30621. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  30622. this.content = null;
  30623. this.body = null;
  30624. var headerView = new DataView(data, 0, BINARY_EXTENSION_HEADER_LENGTH);
  30625. this.header = {
  30626. magic: _threeModule.LoaderUtils.decodeText(new Uint8Array(data.slice(0, 4))),
  30627. version: headerView.getUint32(4, true),
  30628. length: headerView.getUint32(8, true)
  30629. };
  30630. if (this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC) {
  30631. throw new Error('THREE.GLTFLoader: Unsupported glTF-Binary header.');
  30632. } else if (this.header.version < 2.0) {
  30633. throw new Error('THREE.GLTFLoader: Legacy binary file detected. Use LegacyGLTFLoader instead.');
  30634. }
  30635. var chunkView = new DataView(data, BINARY_EXTENSION_HEADER_LENGTH);
  30636. var chunkIndex = 0;
  30637. while (chunkIndex < chunkView.byteLength) {
  30638. var chunkLength = chunkView.getUint32(chunkIndex, true);
  30639. chunkIndex += 4;
  30640. var chunkType = chunkView.getUint32(chunkIndex, true);
  30641. chunkIndex += 4;
  30642. if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON) {
  30643. var contentArray = new Uint8Array(data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength);
  30644. this.content = _threeModule.LoaderUtils.decodeText(contentArray);
  30645. } else if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN) {
  30646. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  30647. this.body = data.slice(byteOffset, byteOffset + chunkLength);
  30648. } // Clients must ignore chunks with unknown types.
  30649. chunkIndex += chunkLength;
  30650. }
  30651. if (this.content === null) {
  30652. throw new Error('THREE.GLTFLoader: JSON content not found.');
  30653. }
  30654. }
  30655. /**
  30656. * DRACO Mesh Compression Extension
  30657. *
  30658. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  30659. */
  30660. function GLTFDracoMeshCompressionExtension(json, dracoLoader) {
  30661. if (!dracoLoader) {
  30662. throw new Error('THREE.GLTFLoader: No DRACOLoader instance provided.');
  30663. }
  30664. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  30665. this.json = json;
  30666. this.dracoLoader = dracoLoader;
  30667. }
  30668. GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function (primitive, parser) {
  30669. var json = this.json;
  30670. var dracoLoader = this.dracoLoader;
  30671. var bufferViewIndex = primitive.extensions[this.name].bufferView;
  30672. var gltfAttributeMap = primitive.extensions[this.name].attributes;
  30673. var threeAttributeMap = {};
  30674. var attributeNormalizedMap = {};
  30675. var attributeTypeMap = {};
  30676. for (var attributeName in gltfAttributeMap) {
  30677. var threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase();
  30678. threeAttributeMap[threeAttributeName] = gltfAttributeMap[attributeName];
  30679. }
  30680. for (attributeName in primitive.attributes) {
  30681. var threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase();
  30682. if (gltfAttributeMap[attributeName] !== undefined) {
  30683. var accessorDef = json.accessors[primitive.attributes[attributeName]];
  30684. var componentType = WEBGL_COMPONENT_TYPES[accessorDef.componentType];
  30685. attributeTypeMap[threeAttributeName] = componentType;
  30686. attributeNormalizedMap[threeAttributeName] = accessorDef.normalized === true;
  30687. }
  30688. }
  30689. return parser.getDependency('bufferView', bufferViewIndex).then(function (bufferView) {
  30690. return new Promise(function (resolve) {
  30691. dracoLoader.decodeDracoFile(bufferView, function (geometry) {
  30692. for (var attributeName in geometry.attributes) {
  30693. var attribute = geometry.attributes[attributeName];
  30694. var normalized = attributeNormalizedMap[attributeName];
  30695. if (normalized !== undefined) attribute.normalized = normalized;
  30696. }
  30697. resolve(geometry);
  30698. }, threeAttributeMap, attributeTypeMap);
  30699. });
  30700. });
  30701. };
  30702. /**
  30703. * Texture Transform Extension
  30704. *
  30705. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform
  30706. */
  30707. function GLTFTextureTransformExtension() {
  30708. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  30709. }
  30710. GLTFTextureTransformExtension.prototype.extendTexture = function (texture, transform) {
  30711. texture = texture.clone();
  30712. if (transform.offset !== undefined) {
  30713. texture.offset.fromArray(transform.offset);
  30714. }
  30715. if (transform.rotation !== undefined) {
  30716. texture.rotation = transform.rotation;
  30717. }
  30718. if (transform.scale !== undefined) {
  30719. texture.repeat.fromArray(transform.scale);
  30720. }
  30721. if (transform.texCoord !== undefined) {
  30722. console.warn('THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.');
  30723. }
  30724. texture.needsUpdate = true;
  30725. return texture;
  30726. };
  30727. /**
  30728. * Specular-Glossiness Extension
  30729. *
  30730. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  30731. */
  30732. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  30733. return {
  30734. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  30735. specularGlossinessParams: ['color', 'map', 'lightMap', 'lightMapIntensity', 'aoMap', 'aoMapIntensity', 'emissive', 'emissiveIntensity', 'emissiveMap', 'bumpMap', 'bumpScale', 'normalMap', 'displacementMap', 'displacementScale', 'displacementBias', 'specularMap', 'specular', 'glossinessMap', 'glossiness', 'alphaMap', 'envMap', 'envMapIntensity', 'refractionRatio'],
  30736. getMaterialType: function () {
  30737. return _threeModule.ShaderMaterial;
  30738. },
  30739. extendParams: function (materialParams, materialDef, parser) {
  30740. var pbrSpecularGlossiness = materialDef.extensions[this.name];
  30741. var shader = _threeModule.ShaderLib['standard'];
  30742. var uniforms = _threeModule.UniformsUtils.clone(shader.uniforms);
  30743. var specularMapParsFragmentChunk = ['#ifdef USE_SPECULARMAP', ' uniform sampler2D specularMap;', '#endif'].join('\n');
  30744. var glossinessMapParsFragmentChunk = ['#ifdef USE_GLOSSINESSMAP', ' uniform sampler2D glossinessMap;', '#endif'].join('\n');
  30745. var specularMapFragmentChunk = ['vec3 specularFactor = specular;', '#ifdef USE_SPECULARMAP', ' vec4 texelSpecular = texture2D( specularMap, vUv );', ' texelSpecular = sRGBToLinear( texelSpecular );', ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture', ' specularFactor *= texelSpecular.rgb;', '#endif'].join('\n');
  30746. var glossinessMapFragmentChunk = ['float glossinessFactor = glossiness;', '#ifdef USE_GLOSSINESSMAP', ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );', ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture', ' glossinessFactor *= texelGlossiness.a;', '#endif'].join('\n');
  30747. var lightPhysicalFragmentChunk = ['PhysicalMaterial material;', 'material.diffuseColor = diffuseColor.rgb;', 'material.specularRoughness = clamp( 1.0 - glossinessFactor, 0.04, 1.0 );', 'material.specularColor = specularFactor.rgb;'].join('\n');
  30748. var fragmentShader = shader.fragmentShader.replace('uniform float roughness;', 'uniform vec3 specular;').replace('uniform float metalness;', 'uniform float glossiness;').replace('#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk).replace('#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk).replace('#include <roughnessmap_fragment>', specularMapFragmentChunk).replace('#include <metalnessmap_fragment>', glossinessMapFragmentChunk).replace('#include <lights_physical_fragment>', lightPhysicalFragmentChunk);
  30749. delete uniforms.roughness;
  30750. delete uniforms.metalness;
  30751. delete uniforms.roughnessMap;
  30752. delete uniforms.metalnessMap;
  30753. uniforms.specular = {
  30754. value: new _threeModule.Color().setHex(0x111111)
  30755. };
  30756. uniforms.glossiness = {
  30757. value: 0.5
  30758. };
  30759. uniforms.specularMap = {
  30760. value: null
  30761. };
  30762. uniforms.glossinessMap = {
  30763. value: null
  30764. };
  30765. materialParams.vertexShader = shader.vertexShader;
  30766. materialParams.fragmentShader = fragmentShader;
  30767. materialParams.uniforms = uniforms;
  30768. materialParams.defines = {
  30769. 'STANDARD': ''
  30770. };
  30771. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  30772. materialParams.opacity = 1.0;
  30773. var pending = [];
  30774. if (Array.isArray(pbrSpecularGlossiness.diffuseFactor)) {
  30775. var array = pbrSpecularGlossiness.diffuseFactor;
  30776. materialParams.color.fromArray(array);
  30777. materialParams.opacity = array[3];
  30778. }
  30779. if (pbrSpecularGlossiness.diffuseTexture !== undefined) {
  30780. pending.push(parser.assignTexture(materialParams, 'map', pbrSpecularGlossiness.diffuseTexture));
  30781. }
  30782. materialParams.emissive = new _threeModule.Color(0.0, 0.0, 0.0);
  30783. materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  30784. materialParams.specular = new _threeModule.Color(1.0, 1.0, 1.0);
  30785. if (Array.isArray(pbrSpecularGlossiness.specularFactor)) {
  30786. materialParams.specular.fromArray(pbrSpecularGlossiness.specularFactor);
  30787. }
  30788. if (pbrSpecularGlossiness.specularGlossinessTexture !== undefined) {
  30789. var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
  30790. pending.push(parser.assignTexture(materialParams, 'glossinessMap', specGlossMapDef));
  30791. pending.push(parser.assignTexture(materialParams, 'specularMap', specGlossMapDef));
  30792. }
  30793. return Promise.all(pending);
  30794. },
  30795. createMaterial: function (params) {
  30796. // setup material properties based on MeshStandardMaterial for Specular-Glossiness
  30797. var material = new _threeModule.ShaderMaterial({
  30798. defines: params.defines,
  30799. vertexShader: params.vertexShader,
  30800. fragmentShader: params.fragmentShader,
  30801. uniforms: params.uniforms,
  30802. fog: true,
  30803. lights: true,
  30804. opacity: params.opacity,
  30805. transparent: params.transparent
  30806. });
  30807. material.isGLTFSpecularGlossinessMaterial = true;
  30808. material.color = params.color;
  30809. material.map = params.map === undefined ? null : params.map;
  30810. material.lightMap = null;
  30811. material.lightMapIntensity = 1.0;
  30812. material.aoMap = params.aoMap === undefined ? null : params.aoMap;
  30813. material.aoMapIntensity = 1.0;
  30814. material.emissive = params.emissive;
  30815. material.emissiveIntensity = 1.0;
  30816. material.emissiveMap = params.emissiveMap === undefined ? null : params.emissiveMap;
  30817. material.bumpMap = params.bumpMap === undefined ? null : params.bumpMap;
  30818. material.bumpScale = 1;
  30819. material.normalMap = params.normalMap === undefined ? null : params.normalMap;
  30820. if (params.normalScale) material.normalScale = params.normalScale;
  30821. material.displacementMap = null;
  30822. material.displacementScale = 1;
  30823. material.displacementBias = 0;
  30824. material.specularMap = params.specularMap === undefined ? null : params.specularMap;
  30825. material.specular = params.specular;
  30826. material.glossinessMap = params.glossinessMap === undefined ? null : params.glossinessMap;
  30827. material.glossiness = params.glossiness;
  30828. material.alphaMap = null;
  30829. material.envMap = params.envMap === undefined ? null : params.envMap;
  30830. material.envMapIntensity = 1.0;
  30831. material.refractionRatio = 0.98;
  30832. material.extensions.derivatives = true;
  30833. return material;
  30834. },
  30835. /**
  30836. * Clones a GLTFSpecularGlossinessMaterial instance. The ShaderMaterial.copy() method can
  30837. * copy only properties it knows about or inherits, and misses many properties that would
  30838. * normally be defined by MeshStandardMaterial.
  30839. *
  30840. * This method allows GLTFSpecularGlossinessMaterials to be cloned in the process of
  30841. * loading a glTF model, but cloning later (e.g. by the user) would require these changes
  30842. * AND also updating `.onBeforeRender` on the parent mesh.
  30843. *
  30844. * @param {ShaderMaterial} source
  30845. * @return {ShaderMaterial}
  30846. */
  30847. cloneMaterial: function (source) {
  30848. var target = source.clone();
  30849. target.isGLTFSpecularGlossinessMaterial = true;
  30850. var params = this.specularGlossinessParams;
  30851. for (var i = 0, il = params.length; i < il; i++) {
  30852. var value = source[params[i]];
  30853. target[params[i]] = value && value.isColor ? value.clone() : value;
  30854. }
  30855. return target;
  30856. },
  30857. // Here's based on refreshUniformsCommon() and refreshUniformsStandard() in WebGLRenderer.
  30858. refreshUniforms: function (renderer, scene, camera, geometry, material) {
  30859. if (material.isGLTFSpecularGlossinessMaterial !== true) {
  30860. return;
  30861. }
  30862. var uniforms = material.uniforms;
  30863. var defines = material.defines;
  30864. uniforms.opacity.value = material.opacity;
  30865. uniforms.diffuse.value.copy(material.color);
  30866. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  30867. uniforms.map.value = material.map;
  30868. uniforms.specularMap.value = material.specularMap;
  30869. uniforms.alphaMap.value = material.alphaMap;
  30870. uniforms.lightMap.value = material.lightMap;
  30871. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  30872. uniforms.aoMap.value = material.aoMap;
  30873. uniforms.aoMapIntensity.value = material.aoMapIntensity; // uv repeat and offset setting priorities
  30874. // 1. color map
  30875. // 2. specular map
  30876. // 3. normal map
  30877. // 4. bump map
  30878. // 5. alpha map
  30879. // 6. emissive map
  30880. var uvScaleMap;
  30881. if (material.map) {
  30882. uvScaleMap = material.map;
  30883. } else if (material.specularMap) {
  30884. uvScaleMap = material.specularMap;
  30885. } else if (material.displacementMap) {
  30886. uvScaleMap = material.displacementMap;
  30887. } else if (material.normalMap) {
  30888. uvScaleMap = material.normalMap;
  30889. } else if (material.bumpMap) {
  30890. uvScaleMap = material.bumpMap;
  30891. } else if (material.glossinessMap) {
  30892. uvScaleMap = material.glossinessMap;
  30893. } else if (material.alphaMap) {
  30894. uvScaleMap = material.alphaMap;
  30895. } else if (material.emissiveMap) {
  30896. uvScaleMap = material.emissiveMap;
  30897. }
  30898. if (uvScaleMap !== undefined) {
  30899. // backwards compatibility
  30900. if (uvScaleMap.isWebGLRenderTarget) {
  30901. uvScaleMap = uvScaleMap.texture;
  30902. }
  30903. if (uvScaleMap.matrixAutoUpdate === true) {
  30904. uvScaleMap.updateMatrix();
  30905. }
  30906. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  30907. }
  30908. if (material.envMap) {
  30909. uniforms.envMap.value = material.envMap;
  30910. uniforms.envMapIntensity.value = material.envMapIntensity; // don't flip CubeTexture envMaps, flip everything else:
  30911. // WebGLRenderTargetCube will be flipped for backwards compatibility
  30912. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  30913. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  30914. uniforms.flipEnvMap.value = material.envMap.isCubeTexture ? -1 : 1;
  30915. uniforms.reflectivity.value = material.reflectivity;
  30916. uniforms.refractionRatio.value = material.refractionRatio;
  30917. uniforms.maxMipLevel.value = renderer.properties.get(material.envMap).__maxMipLevel;
  30918. }
  30919. uniforms.specular.value.copy(material.specular);
  30920. uniforms.glossiness.value = material.glossiness;
  30921. uniforms.glossinessMap.value = material.glossinessMap;
  30922. uniforms.emissiveMap.value = material.emissiveMap;
  30923. uniforms.bumpMap.value = material.bumpMap;
  30924. uniforms.normalMap.value = material.normalMap;
  30925. uniforms.displacementMap.value = material.displacementMap;
  30926. uniforms.displacementScale.value = material.displacementScale;
  30927. uniforms.displacementBias.value = material.displacementBias;
  30928. if (uniforms.glossinessMap.value !== null && defines.USE_GLOSSINESSMAP === undefined) {
  30929. defines.USE_GLOSSINESSMAP = ''; // set USE_ROUGHNESSMAP to enable vUv
  30930. defines.USE_ROUGHNESSMAP = '';
  30931. }
  30932. if (uniforms.glossinessMap.value === null && defines.USE_GLOSSINESSMAP !== undefined) {
  30933. delete defines.USE_GLOSSINESSMAP;
  30934. delete defines.USE_ROUGHNESSMAP;
  30935. }
  30936. }
  30937. };
  30938. }
  30939. /*********************************/
  30940. /********** INTERPOLATION ********/
  30941. /*********************************/
  30942. // Spline Interpolation
  30943. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  30944. function GLTFCubicSplineInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  30945. _threeModule.Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  30946. }
  30947. GLTFCubicSplineInterpolant.prototype = Object.create(_threeModule.Interpolant.prototype);
  30948. GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant;
  30949. GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function (index) {
  30950. // Copies a sample value to the result buffer. See description of glTF
  30951. // CUBICSPLINE values layout in interpolate_() function below.
  30952. var result = this.resultBuffer,
  30953. values = this.sampleValues,
  30954. valueSize = this.valueSize,
  30955. offset = index * valueSize * 3 + valueSize;
  30956. for (var i = 0; i !== valueSize; i++) {
  30957. result[i] = values[offset + i];
  30958. }
  30959. return result;
  30960. };
  30961. GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  30962. GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  30963. GLTFCubicSplineInterpolant.prototype.interpolate_ = function (i1, t0, t, t1) {
  30964. var result = this.resultBuffer;
  30965. var values = this.sampleValues;
  30966. var stride = this.valueSize;
  30967. var stride2 = stride * 2;
  30968. var stride3 = stride * 3;
  30969. var td = t1 - t0;
  30970. var p = (t - t0) / td;
  30971. var pp = p * p;
  30972. var ppp = pp * p;
  30973. var offset1 = i1 * stride3;
  30974. var offset0 = offset1 - stride3;
  30975. var s2 = -2 * ppp + 3 * pp;
  30976. var s3 = ppp - pp;
  30977. var s0 = 1 - s2;
  30978. var s1 = s3 - pp + p; // Layout of keyframe output values for CUBICSPLINE animations:
  30979. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  30980. for (var i = 0; i !== stride; i++) {
  30981. var p0 = values[offset0 + i + stride]; // splineVertex_k
  30982. var m0 = values[offset0 + i + stride2] * td; // outTangent_k * (t_k+1 - t_k)
  30983. var p1 = values[offset1 + i + stride]; // splineVertex_k+1
  30984. var m1 = values[offset1 + i] * td; // inTangent_k+1 * (t_k+1 - t_k)
  30985. result[i] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  30986. }
  30987. return result;
  30988. };
  30989. /*********************************/
  30990. /********** INTERNALS ************/
  30991. /*********************************/
  30992. /* CONSTANTS */
  30993. var WEBGL_CONSTANTS = {
  30994. FLOAT: 5126,
  30995. //FLOAT_MAT2: 35674,
  30996. FLOAT_MAT3: 35675,
  30997. FLOAT_MAT4: 35676,
  30998. FLOAT_VEC2: 35664,
  30999. FLOAT_VEC3: 35665,
  31000. FLOAT_VEC4: 35666,
  31001. LINEAR: 9729,
  31002. REPEAT: 10497,
  31003. SAMPLER_2D: 35678,
  31004. POINTS: 0,
  31005. LINES: 1,
  31006. LINE_LOOP: 2,
  31007. LINE_STRIP: 3,
  31008. TRIANGLES: 4,
  31009. TRIANGLE_STRIP: 5,
  31010. TRIANGLE_FAN: 6,
  31011. UNSIGNED_BYTE: 5121,
  31012. UNSIGNED_SHORT: 5123
  31013. };
  31014. var WEBGL_COMPONENT_TYPES = {
  31015. 5120: Int8Array,
  31016. 5121: Uint8Array,
  31017. 5122: Int16Array,
  31018. 5123: Uint16Array,
  31019. 5125: Uint32Array,
  31020. 5126: Float32Array
  31021. };
  31022. var WEBGL_FILTERS = {
  31023. 9728: _threeModule.NearestFilter,
  31024. 9729: _threeModule.LinearFilter,
  31025. 9984: _threeModule.NearestMipmapNearestFilter,
  31026. 9985: _threeModule.LinearMipmapNearestFilter,
  31027. 9986: _threeModule.NearestMipmapLinearFilter,
  31028. 9987: _threeModule.LinearMipmapLinearFilter
  31029. };
  31030. var WEBGL_WRAPPINGS = {
  31031. 33071: _threeModule.ClampToEdgeWrapping,
  31032. 33648: _threeModule.MirroredRepeatWrapping,
  31033. 10497: _threeModule.RepeatWrapping
  31034. };
  31035. var WEBGL_TYPE_SIZES = {
  31036. 'SCALAR': 1,
  31037. 'VEC2': 2,
  31038. 'VEC3': 3,
  31039. 'VEC4': 4,
  31040. 'MAT2': 4,
  31041. 'MAT3': 9,
  31042. 'MAT4': 16
  31043. };
  31044. var ATTRIBUTES = {
  31045. POSITION: 'position',
  31046. NORMAL: 'normal',
  31047. TANGENT: 'tangent',
  31048. TEXCOORD_0: 'uv',
  31049. TEXCOORD_1: 'uv2',
  31050. COLOR_0: 'color',
  31051. WEIGHTS_0: 'skinWeight',
  31052. JOINTS_0: 'skinIndex'
  31053. };
  31054. var PATH_PROPERTIES = {
  31055. scale: 'scale',
  31056. translation: 'position',
  31057. rotation: 'quaternion',
  31058. weights: 'morphTargetInfluences'
  31059. };
  31060. var INTERPOLATION = {
  31061. CUBICSPLINE: undefined,
  31062. // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
  31063. // keyframe track will be initialized with a default interpolation type, then modified.
  31064. LINEAR: _threeModule.InterpolateLinear,
  31065. STEP: _threeModule.InterpolateDiscrete
  31066. };
  31067. var ALPHA_MODES = {
  31068. OPAQUE: 'OPAQUE',
  31069. MASK: 'MASK',
  31070. BLEND: 'BLEND'
  31071. };
  31072. var MIME_TYPE_FORMATS = {
  31073. 'image/png': _threeModule.RGBAFormat,
  31074. 'image/jpeg': _threeModule.RGBFormat
  31075. };
  31076. /* UTILITY FUNCTIONS */
  31077. function resolveURL(url, path) {
  31078. // Invalid URL
  31079. if (typeof url !== 'string' || url === '') return ''; // Host Relative URL
  31080. if (/^https?:\/\//i.test(path) && /^\//.test(url)) {
  31081. path = path.replace(/(^https?:\/\/[^\/]+).*/i, '$1');
  31082. } // Absolute URL http://,https://,//
  31083. if (/^(https?:)?\/\//i.test(url)) return url; // Data URI
  31084. if (/^data:.*,.*$/i.test(url)) return url; // Blob URL
  31085. if (/^blob:.*$/i.test(url)) return url; // Relative URL
  31086. return path + url;
  31087. }
  31088. var defaultMaterial;
  31089. /**
  31090. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  31091. */
  31092. function createDefaultMaterial() {
  31093. defaultMaterial = defaultMaterial || new _threeModule.MeshStandardMaterial({
  31094. color: 0xFFFFFF,
  31095. emissive: 0x000000,
  31096. metalness: 1,
  31097. roughness: 1,
  31098. transparent: false,
  31099. depthTest: true,
  31100. side: _threeModule.FrontSide
  31101. });
  31102. return defaultMaterial;
  31103. }
  31104. function addUnknownExtensionsToUserData(knownExtensions, object, objectDef) {
  31105. // Add unknown glTF extensions to an object's userData.
  31106. for (var name in objectDef.extensions) {
  31107. if (knownExtensions[name] === undefined) {
  31108. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  31109. object.userData.gltfExtensions[name] = objectDef.extensions[name];
  31110. }
  31111. }
  31112. }
  31113. /**
  31114. * @param {Object3D|Material|BufferGeometry} object
  31115. * @param {GLTF.definition} gltfDef
  31116. */
  31117. function assignExtrasToUserData(object, gltfDef) {
  31118. if (gltfDef.extras !== undefined) {
  31119. if (typeof gltfDef.extras === 'object') {
  31120. Object.assign(object.userData, gltfDef.extras);
  31121. } else {
  31122. console.warn('THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras);
  31123. }
  31124. }
  31125. }
  31126. /**
  31127. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  31128. *
  31129. * @param {BufferGeometry} geometry
  31130. * @param {Array<GLTF.Target>} targets
  31131. * @param {GLTFParser} parser
  31132. * @return {Promise<BufferGeometry>}
  31133. */
  31134. function addMorphTargets(geometry, targets, parser) {
  31135. var hasMorphPosition = false;
  31136. var hasMorphNormal = false;
  31137. for (var i = 0, il = targets.length; i < il; i++) {
  31138. var target = targets[i];
  31139. if (target.POSITION !== undefined) hasMorphPosition = true;
  31140. if (target.NORMAL !== undefined) hasMorphNormal = true;
  31141. if (hasMorphPosition && hasMorphNormal) break;
  31142. }
  31143. if (!hasMorphPosition && !hasMorphNormal) return Promise.resolve(geometry);
  31144. var pendingPositionAccessors = [];
  31145. var pendingNormalAccessors = [];
  31146. for (var i = 0, il = targets.length; i < il; i++) {
  31147. var target = targets[i];
  31148. if (hasMorphPosition) {
  31149. var pendingAccessor = target.POSITION !== undefined ? parser.getDependency('accessor', target.POSITION) : geometry.attributes.position;
  31150. pendingPositionAccessors.push(pendingAccessor);
  31151. }
  31152. if (hasMorphNormal) {
  31153. var pendingAccessor = target.NORMAL !== undefined ? parser.getDependency('accessor', target.NORMAL) : geometry.attributes.normal;
  31154. pendingNormalAccessors.push(pendingAccessor);
  31155. }
  31156. }
  31157. return Promise.all([Promise.all(pendingPositionAccessors), Promise.all(pendingNormalAccessors)]).then(function (accessors) {
  31158. var morphPositions = accessors[0];
  31159. var morphNormals = accessors[1]; // Clone morph target accessors before modifying them.
  31160. for (var i = 0, il = morphPositions.length; i < il; i++) {
  31161. if (geometry.attributes.position === morphPositions[i]) continue;
  31162. morphPositions[i] = cloneBufferAttribute(morphPositions[i]);
  31163. }
  31164. for (var i = 0, il = morphNormals.length; i < il; i++) {
  31165. if (geometry.attributes.normal === morphNormals[i]) continue;
  31166. morphNormals[i] = cloneBufferAttribute(morphNormals[i]);
  31167. }
  31168. for (var i = 0, il = targets.length; i < il; i++) {
  31169. var target = targets[i];
  31170. var attributeName = 'morphTarget' + i;
  31171. if (hasMorphPosition) {
  31172. // Three.js morph position is absolute value. The formula is
  31173. // basePosition
  31174. // + weight0 * ( morphPosition0 - basePosition )
  31175. // + weight1 * ( morphPosition1 - basePosition )
  31176. // ...
  31177. // while the glTF one is relative
  31178. // basePosition
  31179. // + weight0 * glTFmorphPosition0
  31180. // + weight1 * glTFmorphPosition1
  31181. // ...
  31182. // then we need to convert from relative to absolute here.
  31183. if (target.POSITION !== undefined) {
  31184. var positionAttribute = morphPositions[i];
  31185. positionAttribute.name = attributeName;
  31186. var position = geometry.attributes.position;
  31187. for (var j = 0, jl = positionAttribute.count; j < jl; j++) {
  31188. positionAttribute.setXYZ(j, positionAttribute.getX(j) + position.getX(j), positionAttribute.getY(j) + position.getY(j), positionAttribute.getZ(j) + position.getZ(j));
  31189. }
  31190. }
  31191. }
  31192. if (hasMorphNormal) {
  31193. // see target.POSITION's comment
  31194. if (target.NORMAL !== undefined) {
  31195. var normalAttribute = morphNormals[i];
  31196. normalAttribute.name = attributeName;
  31197. var normal = geometry.attributes.normal;
  31198. for (var j = 0, jl = normalAttribute.count; j < jl; j++) {
  31199. normalAttribute.setXYZ(j, normalAttribute.getX(j) + normal.getX(j), normalAttribute.getY(j) + normal.getY(j), normalAttribute.getZ(j) + normal.getZ(j));
  31200. }
  31201. }
  31202. }
  31203. }
  31204. if (hasMorphPosition) geometry.morphAttributes.position = morphPositions;
  31205. if (hasMorphNormal) geometry.morphAttributes.normal = morphNormals;
  31206. return geometry;
  31207. });
  31208. }
  31209. /**
  31210. * @param {Mesh} mesh
  31211. * @param {GLTF.Mesh} meshDef
  31212. */
  31213. function updateMorphTargets(mesh, meshDef) {
  31214. mesh.updateMorphTargets();
  31215. if (meshDef.weights !== undefined) {
  31216. for (var i = 0, il = meshDef.weights.length; i < il; i++) {
  31217. mesh.morphTargetInfluences[i] = meshDef.weights[i];
  31218. }
  31219. } // .extras has user-defined data, so check that .extras.targetNames is an array.
  31220. if (meshDef.extras && Array.isArray(meshDef.extras.targetNames)) {
  31221. var targetNames = meshDef.extras.targetNames;
  31222. if (mesh.morphTargetInfluences.length === targetNames.length) {
  31223. mesh.morphTargetDictionary = {};
  31224. for (var i = 0, il = targetNames.length; i < il; i++) {
  31225. mesh.morphTargetDictionary[targetNames[i]] = i;
  31226. }
  31227. } else {
  31228. console.warn('THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.');
  31229. }
  31230. }
  31231. }
  31232. function createPrimitiveKey(primitiveDef) {
  31233. var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION];
  31234. var geometryKey;
  31235. if (dracoExtension) {
  31236. geometryKey = 'draco:' + dracoExtension.bufferView + ':' + dracoExtension.indices + ':' + createAttributesKey(dracoExtension.attributes);
  31237. } else {
  31238. geometryKey = primitiveDef.indices + ':' + createAttributesKey(primitiveDef.attributes) + ':' + primitiveDef.mode;
  31239. }
  31240. return geometryKey;
  31241. }
  31242. function createAttributesKey(attributes) {
  31243. var attributesKey = '';
  31244. var keys = Object.keys(attributes).sort();
  31245. for (var i = 0, il = keys.length; i < il; i++) {
  31246. attributesKey += keys[i] + ':' + attributes[keys[i]] + ';';
  31247. }
  31248. return attributesKey;
  31249. }
  31250. function cloneBufferAttribute(attribute) {
  31251. if (attribute.isInterleavedBufferAttribute) {
  31252. var count = attribute.count;
  31253. var itemSize = attribute.itemSize;
  31254. var array = attribute.array.slice(0, count * itemSize);
  31255. for (var i = 0, j = 0; i < count; ++i) {
  31256. array[j++] = attribute.getX(i);
  31257. if (itemSize >= 2) array[j++] = attribute.getY(i);
  31258. if (itemSize >= 3) array[j++] = attribute.getZ(i);
  31259. if (itemSize >= 4) array[j++] = attribute.getW(i);
  31260. }
  31261. return new _threeModule.BufferAttribute(array, itemSize, attribute.normalized);
  31262. }
  31263. return attribute.clone();
  31264. }
  31265. /* GLTF PARSER */
  31266. function GLTFParser(json, extensions, options) {
  31267. this.json = json || {};
  31268. this.extensions = extensions || {};
  31269. this.options = options || {}; // loader object cache
  31270. this.cache = new GLTFRegistry(); // BufferGeometry caching
  31271. this.primitiveCache = {};
  31272. this.textureLoader = new _threeModule.TextureLoader(this.options.manager);
  31273. this.textureLoader.setCrossOrigin(this.options.crossOrigin);
  31274. this.fileLoader = new _threeModule.FileLoader(this.options.manager);
  31275. this.fileLoader.setResponseType('arraybuffer');
  31276. if (this.options.crossOrigin === 'use-credentials') {
  31277. this.fileLoader.setWithCredentials(true);
  31278. }
  31279. }
  31280. GLTFParser.prototype.parse = function (onLoad, onError) {
  31281. var parser = this;
  31282. var json = this.json;
  31283. var extensions = this.extensions; // Clear the loader cache
  31284. this.cache.removeAll(); // Mark the special nodes/meshes in json for efficient parse
  31285. this.markDefs();
  31286. Promise.all([this.getDependencies('scene'), this.getDependencies('animation'), this.getDependencies('camera')]).then(function (dependencies) {
  31287. var result = {
  31288. scene: dependencies[0][json.scene || 0],
  31289. scenes: dependencies[0],
  31290. animations: dependencies[1],
  31291. cameras: dependencies[2],
  31292. asset: json.asset,
  31293. parser: parser,
  31294. userData: {}
  31295. };
  31296. addUnknownExtensionsToUserData(extensions, result, json);
  31297. assignExtrasToUserData(result, json);
  31298. onLoad(result);
  31299. }).catch(onError);
  31300. };
  31301. /**
  31302. * Marks the special nodes/meshes in json for efficient parse.
  31303. */
  31304. GLTFParser.prototype.markDefs = function () {
  31305. var nodeDefs = this.json.nodes || [];
  31306. var skinDefs = this.json.skins || [];
  31307. var meshDefs = this.json.meshes || [];
  31308. var meshReferences = {};
  31309. var meshUses = {}; // Nothing in the node definition indicates whether it is a Bone or an
  31310. // Object3D. Use the skins' joint references to mark bones.
  31311. for (var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex++) {
  31312. var joints = skinDefs[skinIndex].joints;
  31313. for (var i = 0, il = joints.length; i < il; i++) {
  31314. nodeDefs[joints[i]].isBone = true;
  31315. }
  31316. } // Meshes can (and should) be reused by multiple nodes in a glTF asset. To
  31317. // avoid having more than one Mesh with the same name, count
  31318. // references and rename instances below.
  31319. //
  31320. // Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  31321. for (var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex++) {
  31322. var nodeDef = nodeDefs[nodeIndex];
  31323. if (nodeDef.mesh !== undefined) {
  31324. if (meshReferences[nodeDef.mesh] === undefined) {
  31325. meshReferences[nodeDef.mesh] = meshUses[nodeDef.mesh] = 0;
  31326. }
  31327. meshReferences[nodeDef.mesh]++; // Nothing in the mesh definition indicates whether it is
  31328. // a SkinnedMesh or Mesh. Use the node's mesh reference
  31329. // to mark SkinnedMesh if node has skin.
  31330. if (nodeDef.skin !== undefined) {
  31331. meshDefs[nodeDef.mesh].isSkinnedMesh = true;
  31332. }
  31333. }
  31334. }
  31335. this.json.meshReferences = meshReferences;
  31336. this.json.meshUses = meshUses;
  31337. };
  31338. /**
  31339. * Requests the specified dependency asynchronously, with caching.
  31340. * @param {string} type
  31341. * @param {number} index
  31342. * @return {Promise<Object3D|Material|THREE.Texture|AnimationClip|ArrayBuffer|Object>}
  31343. */
  31344. GLTFParser.prototype.getDependency = function (type, index) {
  31345. var cacheKey = type + ':' + index;
  31346. var dependency = this.cache.get(cacheKey);
  31347. if (!dependency) {
  31348. switch (type) {
  31349. case 'scene':
  31350. dependency = this.loadScene(index);
  31351. break;
  31352. case 'node':
  31353. dependency = this.loadNode(index);
  31354. break;
  31355. case 'mesh':
  31356. dependency = this.loadMesh(index);
  31357. break;
  31358. case 'accessor':
  31359. dependency = this.loadAccessor(index);
  31360. break;
  31361. case 'bufferView':
  31362. dependency = this.loadBufferView(index);
  31363. break;
  31364. case 'buffer':
  31365. dependency = this.loadBuffer(index);
  31366. break;
  31367. case 'material':
  31368. dependency = this.loadMaterial(index);
  31369. break;
  31370. case 'texture':
  31371. dependency = this.loadTexture(index);
  31372. break;
  31373. case 'skin':
  31374. dependency = this.loadSkin(index);
  31375. break;
  31376. case 'animation':
  31377. dependency = this.loadAnimation(index);
  31378. break;
  31379. case 'camera':
  31380. dependency = this.loadCamera(index);
  31381. break;
  31382. case 'light':
  31383. dependency = this.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].loadLight(index);
  31384. break;
  31385. default:
  31386. throw new Error('Unknown type: ' + type);
  31387. }
  31388. this.cache.add(cacheKey, dependency);
  31389. }
  31390. return dependency;
  31391. };
  31392. /**
  31393. * Requests all dependencies of the specified type asynchronously, with caching.
  31394. * @param {string} type
  31395. * @return {Promise<Array<Object>>}
  31396. */
  31397. GLTFParser.prototype.getDependencies = function (type) {
  31398. var dependencies = this.cache.get(type);
  31399. if (!dependencies) {
  31400. var parser = this;
  31401. var defs = this.json[type + (type === 'mesh' ? 'es' : 's')] || [];
  31402. dependencies = Promise.all(defs.map(function (def, index) {
  31403. return parser.getDependency(type, index);
  31404. }));
  31405. this.cache.add(type, dependencies);
  31406. }
  31407. return dependencies;
  31408. };
  31409. /**
  31410. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  31411. * @param {number} bufferIndex
  31412. * @return {Promise<ArrayBuffer>}
  31413. */
  31414. GLTFParser.prototype.loadBuffer = function (bufferIndex) {
  31415. var bufferDef = this.json.buffers[bufferIndex];
  31416. var loader = this.fileLoader;
  31417. if (bufferDef.type && bufferDef.type !== 'arraybuffer') {
  31418. throw new Error('THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.');
  31419. } // If present, GLB container is required to be the first buffer.
  31420. if (bufferDef.uri === undefined && bufferIndex === 0) {
  31421. return Promise.resolve(this.extensions[EXTENSIONS.KHR_BINARY_GLTF].body);
  31422. }
  31423. var options = this.options;
  31424. return new Promise(function (resolve, reject) {
  31425. loader.load(resolveURL(bufferDef.uri, options.path), resolve, undefined, function () {
  31426. reject(new Error('THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".'));
  31427. });
  31428. });
  31429. };
  31430. /**
  31431. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  31432. * @param {number} bufferViewIndex
  31433. * @return {Promise<ArrayBuffer>}
  31434. */
  31435. GLTFParser.prototype.loadBufferView = function (bufferViewIndex) {
  31436. var bufferViewDef = this.json.bufferViews[bufferViewIndex];
  31437. return this.getDependency('buffer', bufferViewDef.buffer).then(function (buffer) {
  31438. var byteLength = bufferViewDef.byteLength || 0;
  31439. var byteOffset = bufferViewDef.byteOffset || 0;
  31440. return buffer.slice(byteOffset, byteOffset + byteLength);
  31441. });
  31442. };
  31443. /**
  31444. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  31445. * @param {number} accessorIndex
  31446. * @return {Promise<BufferAttribute|InterleavedBufferAttribute>}
  31447. */
  31448. GLTFParser.prototype.loadAccessor = function (accessorIndex) {
  31449. var parser = this;
  31450. var json = this.json;
  31451. var accessorDef = this.json.accessors[accessorIndex];
  31452. if (accessorDef.bufferView === undefined && accessorDef.sparse === undefined) {
  31453. // Ignore empty accessors, which may be used to declare runtime
  31454. // information about attributes coming from another source (e.g. Draco
  31455. // compression extension).
  31456. return Promise.resolve(null);
  31457. }
  31458. var pendingBufferViews = [];
  31459. if (accessorDef.bufferView !== undefined) {
  31460. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.bufferView));
  31461. } else {
  31462. pendingBufferViews.push(null);
  31463. }
  31464. if (accessorDef.sparse !== undefined) {
  31465. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.sparse.indices.bufferView));
  31466. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.sparse.values.bufferView));
  31467. }
  31468. return Promise.all(pendingBufferViews).then(function (bufferViews) {
  31469. var bufferView = bufferViews[0];
  31470. var itemSize = WEBGL_TYPE_SIZES[accessorDef.type];
  31471. var TypedArray = WEBGL_COMPONENT_TYPES[accessorDef.componentType]; // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  31472. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  31473. var itemBytes = elementBytes * itemSize;
  31474. var byteOffset = accessorDef.byteOffset || 0;
  31475. var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[accessorDef.bufferView].byteStride : undefined;
  31476. var normalized = accessorDef.normalized === true;
  31477. var array, bufferAttribute; // The buffer is not interleaved if the stride is the item size in bytes.
  31478. if (byteStride && byteStride !== itemBytes) {
  31479. // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer
  31480. // This makes sure that IBA.count reflects accessor.count properly
  31481. var ibSlice = Math.floor(byteOffset / byteStride);
  31482. var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;
  31483. var ib = parser.cache.get(ibCacheKey);
  31484. if (!ib) {
  31485. array = new TypedArray(bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes); // Integer parameters to IB/IBA are in array elements, not bytes.
  31486. ib = new _threeModule.InterleavedBuffer(array, byteStride / elementBytes);
  31487. parser.cache.add(ibCacheKey, ib);
  31488. }
  31489. bufferAttribute = new _threeModule.InterleavedBufferAttribute(ib, itemSize, byteOffset % byteStride / elementBytes, normalized);
  31490. } else {
  31491. if (bufferView === null) {
  31492. array = new TypedArray(accessorDef.count * itemSize);
  31493. } else {
  31494. array = new TypedArray(bufferView, byteOffset, accessorDef.count * itemSize);
  31495. }
  31496. bufferAttribute = new _threeModule.BufferAttribute(array, itemSize, normalized);
  31497. } // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  31498. if (accessorDef.sparse !== undefined) {
  31499. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  31500. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[accessorDef.sparse.indices.componentType];
  31501. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  31502. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  31503. var sparseIndices = new TypedArrayIndices(bufferViews[1], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices);
  31504. var sparseValues = new TypedArray(bufferViews[2], byteOffsetValues, accessorDef.sparse.count * itemSize);
  31505. if (bufferView !== null) {
  31506. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  31507. bufferAttribute = new _threeModule.BufferAttribute(bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized);
  31508. }
  31509. for (var i = 0, il = sparseIndices.length; i < il; i++) {
  31510. var index = sparseIndices[i];
  31511. bufferAttribute.setX(index, sparseValues[i * itemSize]);
  31512. if (itemSize >= 2) bufferAttribute.setY(index, sparseValues[i * itemSize + 1]);
  31513. if (itemSize >= 3) bufferAttribute.setZ(index, sparseValues[i * itemSize + 2]);
  31514. if (itemSize >= 4) bufferAttribute.setW(index, sparseValues[i * itemSize + 3]);
  31515. if (itemSize >= 5) throw new Error('THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.');
  31516. }
  31517. }
  31518. return bufferAttribute;
  31519. });
  31520. };
  31521. /**
  31522. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  31523. * @param {number} textureIndex
  31524. * @return {Promise<THREE.Texture>}
  31525. */
  31526. GLTFParser.prototype.loadTexture = function (textureIndex) {
  31527. var parser = this;
  31528. var json = this.json;
  31529. var options = this.options;
  31530. var textureLoader = this.textureLoader;
  31531. var URL = window.URL || window.webkitURL;
  31532. var textureDef = json.textures[textureIndex];
  31533. var textureExtensions = textureDef.extensions || {};
  31534. var source;
  31535. if (textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS]) {
  31536. source = json.images[textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS].source];
  31537. } else {
  31538. source = json.images[textureDef.source];
  31539. }
  31540. var sourceURI = source.uri;
  31541. var isObjectURL = false;
  31542. if (source.bufferView !== undefined) {
  31543. // Load binary image data from bufferView, if provided.
  31544. sourceURI = parser.getDependency('bufferView', source.bufferView).then(function (bufferView) {
  31545. isObjectURL = true;
  31546. var blob = new Blob([bufferView], {
  31547. type: source.mimeType
  31548. });
  31549. sourceURI = URL.createObjectURL(blob);
  31550. return sourceURI;
  31551. });
  31552. }
  31553. return Promise.resolve(sourceURI).then(function (sourceURI) {
  31554. // Load Texture resource.
  31555. var loader = options.manager.getHandler(sourceURI);
  31556. if (!loader) {
  31557. loader = textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS] ? parser.extensions[EXTENSIONS.MSFT_TEXTURE_DDS].ddsLoader : textureLoader;
  31558. }
  31559. return new Promise(function (resolve, reject) {
  31560. loader.load(resolveURL(sourceURI, options.path), resolve, undefined, reject);
  31561. });
  31562. }).then(function (texture) {
  31563. // Clean up resources and configure Texture.
  31564. if (isObjectURL === true) {
  31565. URL.revokeObjectURL(sourceURI);
  31566. }
  31567. texture.flipY = false;
  31568. if (textureDef.name !== undefined) texture.name = textureDef.name; // Ignore unknown mime types, like DDS files.
  31569. if (source.mimeType in MIME_TYPE_FORMATS) {
  31570. texture.format = MIME_TYPE_FORMATS[source.mimeType];
  31571. }
  31572. var samplers = json.samplers || {};
  31573. var sampler = samplers[textureDef.sampler] || {};
  31574. texture.magFilter = WEBGL_FILTERS[sampler.magFilter] || _threeModule.LinearFilter;
  31575. texture.minFilter = WEBGL_FILTERS[sampler.minFilter] || _threeModule.LinearMipmapLinearFilter;
  31576. texture.wrapS = WEBGL_WRAPPINGS[sampler.wrapS] || _threeModule.RepeatWrapping;
  31577. texture.wrapT = WEBGL_WRAPPINGS[sampler.wrapT] || _threeModule.RepeatWrapping;
  31578. return texture;
  31579. });
  31580. };
  31581. /**
  31582. * Asynchronously assigns a texture to the given material parameters.
  31583. * @param {Object} materialParams
  31584. * @param {string} mapName
  31585. * @param {Object} mapDef
  31586. * @return {Promise}
  31587. */
  31588. GLTFParser.prototype.assignTexture = function (materialParams, mapName, mapDef) {
  31589. var parser = this;
  31590. return this.getDependency('texture', mapDef.index).then(function (texture) {
  31591. if (!texture.isCompressedTexture) {
  31592. switch (mapName) {
  31593. case 'aoMap':
  31594. case 'emissiveMap':
  31595. case 'metalnessMap':
  31596. case 'normalMap':
  31597. case 'roughnessMap':
  31598. texture.format = _threeModule.RGBFormat;
  31599. break;
  31600. }
  31601. }
  31602. if (parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM]) {
  31603. var transform = mapDef.extensions !== undefined ? mapDef.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM] : undefined;
  31604. if (transform) {
  31605. texture = parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM].extendTexture(texture, transform);
  31606. }
  31607. }
  31608. materialParams[mapName] = texture;
  31609. });
  31610. };
  31611. /**
  31612. * Assigns final material to a Mesh, Line, or Points instance. The instance
  31613. * already has a material (generated from the glTF material options alone)
  31614. * but reuse of the same glTF material may require multiple threejs materials
  31615. * to accomodate different primitive types, defines, etc. New materials will
  31616. * be created if necessary, and reused from a cache.
  31617. * @param {Object3D} mesh Mesh, Line, or Points instance.
  31618. */
  31619. GLTFParser.prototype.assignFinalMaterial = function (mesh) {
  31620. var geometry = mesh.geometry;
  31621. var material = mesh.material;
  31622. var extensions = this.extensions;
  31623. var useVertexTangents = geometry.attributes.tangent !== undefined;
  31624. var useVertexColors = geometry.attributes.color !== undefined;
  31625. var useFlatShading = geometry.attributes.normal === undefined;
  31626. var useSkinning = mesh.isSkinnedMesh === true;
  31627. var useMorphTargets = Object.keys(geometry.morphAttributes).length > 0;
  31628. var useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined;
  31629. if (mesh.isPoints) {
  31630. var cacheKey = 'PointsMaterial:' + material.uuid;
  31631. var pointsMaterial = this.cache.get(cacheKey);
  31632. if (!pointsMaterial) {
  31633. pointsMaterial = new _threeModule.PointsMaterial();
  31634. _threeModule.Material.prototype.copy.call(pointsMaterial, material);
  31635. pointsMaterial.color.copy(material.color);
  31636. pointsMaterial.map = material.map;
  31637. pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px
  31638. this.cache.add(cacheKey, pointsMaterial);
  31639. }
  31640. material = pointsMaterial;
  31641. } else if (mesh.isLine) {
  31642. var cacheKey = 'LineBasicMaterial:' + material.uuid;
  31643. var lineMaterial = this.cache.get(cacheKey);
  31644. if (!lineMaterial) {
  31645. lineMaterial = new _threeModule.LineBasicMaterial();
  31646. _threeModule.Material.prototype.copy.call(lineMaterial, material);
  31647. lineMaterial.color.copy(material.color);
  31648. this.cache.add(cacheKey, lineMaterial);
  31649. }
  31650. material = lineMaterial;
  31651. } // Clone the material if it will be modified
  31652. if (useVertexTangents || useVertexColors || useFlatShading || useSkinning || useMorphTargets) {
  31653. var cacheKey = 'ClonedMaterial:' + material.uuid + ':';
  31654. if (material.isGLTFSpecularGlossinessMaterial) cacheKey += 'specular-glossiness:';
  31655. if (useSkinning) cacheKey += 'skinning:';
  31656. if (useVertexTangents) cacheKey += 'vertex-tangents:';
  31657. if (useVertexColors) cacheKey += 'vertex-colors:';
  31658. if (useFlatShading) cacheKey += 'flat-shading:';
  31659. if (useMorphTargets) cacheKey += 'morph-targets:';
  31660. if (useMorphNormals) cacheKey += 'morph-normals:';
  31661. var cachedMaterial = this.cache.get(cacheKey);
  31662. if (!cachedMaterial) {
  31663. cachedMaterial = material.isGLTFSpecularGlossinessMaterial ? extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].cloneMaterial(material) : material.clone();
  31664. if (useSkinning) cachedMaterial.skinning = true;
  31665. if (useVertexTangents) cachedMaterial.vertexTangents = true;
  31666. if (useVertexColors) cachedMaterial.vertexColors = _threeModule.VertexColors;
  31667. if (useFlatShading) cachedMaterial.flatShading = true;
  31668. if (useMorphTargets) cachedMaterial.morphTargets = true;
  31669. if (useMorphNormals) cachedMaterial.morphNormals = true;
  31670. this.cache.add(cacheKey, cachedMaterial);
  31671. }
  31672. material = cachedMaterial;
  31673. } // workarounds for mesh and geometry
  31674. if (material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined) {
  31675. console.log('THREE.GLTFLoader: Duplicating UVs to support aoMap.');
  31676. geometry.addAttribute('uv2', new _threeModule.BufferAttribute(geometry.attributes.uv.array, 2));
  31677. }
  31678. if (material.isGLTFSpecularGlossinessMaterial) {
  31679. // for GLTFSpecularGlossinessMaterial(ShaderMaterial) uniforms runtime update
  31680. mesh.onBeforeRender = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].refreshUniforms;
  31681. }
  31682. mesh.material = material;
  31683. };
  31684. /**
  31685. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  31686. * @param {number} materialIndex
  31687. * @return {Promise<Material>}
  31688. */
  31689. GLTFParser.prototype.loadMaterial = function (materialIndex) {
  31690. var parser = this;
  31691. var json = this.json;
  31692. var extensions = this.extensions;
  31693. var materialDef = json.materials[materialIndex];
  31694. var materialType;
  31695. var materialParams = {};
  31696. var materialExtensions = materialDef.extensions || {};
  31697. var pending = [];
  31698. if (materialExtensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS]) {
  31699. var sgExtension = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS];
  31700. materialType = sgExtension.getMaterialType();
  31701. pending.push(sgExtension.extendParams(materialParams, materialDef, parser));
  31702. } else if (materialExtensions[EXTENSIONS.KHR_MATERIALS_UNLIT]) {
  31703. var kmuExtension = extensions[EXTENSIONS.KHR_MATERIALS_UNLIT];
  31704. materialType = kmuExtension.getMaterialType();
  31705. pending.push(kmuExtension.extendParams(materialParams, materialDef, parser));
  31706. } else {
  31707. // Specification:
  31708. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  31709. materialType = _threeModule.MeshStandardMaterial;
  31710. var metallicRoughness = materialDef.pbrMetallicRoughness || {};
  31711. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  31712. materialParams.opacity = 1.0;
  31713. if (Array.isArray(metallicRoughness.baseColorFactor)) {
  31714. var array = metallicRoughness.baseColorFactor;
  31715. materialParams.color.fromArray(array);
  31716. materialParams.opacity = array[3];
  31717. }
  31718. if (metallicRoughness.baseColorTexture !== undefined) {
  31719. pending.push(parser.assignTexture(materialParams, 'map', metallicRoughness.baseColorTexture));
  31720. }
  31721. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  31722. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  31723. if (metallicRoughness.metallicRoughnessTexture !== undefined) {
  31724. pending.push(parser.assignTexture(materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture));
  31725. pending.push(parser.assignTexture(materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture));
  31726. }
  31727. }
  31728. if (materialDef.doubleSided === true) {
  31729. materialParams.side = _threeModule.DoubleSide;
  31730. }
  31731. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  31732. if (alphaMode === ALPHA_MODES.BLEND) {
  31733. materialParams.transparent = true;
  31734. } else {
  31735. materialParams.transparent = false;
  31736. if (alphaMode === ALPHA_MODES.MASK) {
  31737. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  31738. }
  31739. }
  31740. if (materialDef.normalTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  31741. pending.push(parser.assignTexture(materialParams, 'normalMap', materialDef.normalTexture));
  31742. materialParams.normalScale = new _threeModule.Vector2(1, 1);
  31743. if (materialDef.normalTexture.scale !== undefined) {
  31744. materialParams.normalScale.set(materialDef.normalTexture.scale, materialDef.normalTexture.scale);
  31745. }
  31746. }
  31747. if (materialDef.occlusionTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  31748. pending.push(parser.assignTexture(materialParams, 'aoMap', materialDef.occlusionTexture));
  31749. if (materialDef.occlusionTexture.strength !== undefined) {
  31750. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  31751. }
  31752. }
  31753. if (materialDef.emissiveFactor !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  31754. materialParams.emissive = new _threeModule.Color().fromArray(materialDef.emissiveFactor);
  31755. }
  31756. if (materialDef.emissiveTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  31757. pending.push(parser.assignTexture(materialParams, 'emissiveMap', materialDef.emissiveTexture));
  31758. }
  31759. return Promise.all(pending).then(function () {
  31760. var material;
  31761. if (materialType === _threeModule.ShaderMaterial) {
  31762. material = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].createMaterial(materialParams);
  31763. } else {
  31764. material = new materialType(materialParams);
  31765. }
  31766. if (materialDef.name !== undefined) material.name = materialDef.name; // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding.
  31767. if (material.map) material.map.encoding = _threeModule.sRGBEncoding;
  31768. if (material.emissiveMap) material.emissiveMap.encoding = _threeModule.sRGBEncoding;
  31769. if (material.specularMap) material.specularMap.encoding = _threeModule.sRGBEncoding;
  31770. assignExtrasToUserData(material, materialDef);
  31771. if (materialDef.extensions) addUnknownExtensionsToUserData(extensions, material, materialDef);
  31772. return material;
  31773. });
  31774. };
  31775. /**
  31776. * @param {BufferGeometry} geometry
  31777. * @param {GLTF.Primitive} primitiveDef
  31778. * @param {GLTFParser} parser
  31779. * @return {Promise<BufferGeometry>}
  31780. */
  31781. function addPrimitiveAttributes(geometry, primitiveDef, parser) {
  31782. var attributes = primitiveDef.attributes;
  31783. var pending = [];
  31784. function assignAttributeAccessor(accessorIndex, attributeName) {
  31785. return parser.getDependency('accessor', accessorIndex).then(function (accessor) {
  31786. geometry.addAttribute(attributeName, accessor);
  31787. });
  31788. }
  31789. for (var gltfAttributeName in attributes) {
  31790. var threeAttributeName = ATTRIBUTES[gltfAttributeName] || gltfAttributeName.toLowerCase(); // Skip attributes already provided by e.g. Draco extension.
  31791. if (threeAttributeName in geometry.attributes) continue;
  31792. pending.push(assignAttributeAccessor(attributes[gltfAttributeName], threeAttributeName));
  31793. }
  31794. if (primitiveDef.indices !== undefined && !geometry.index) {
  31795. var accessor = parser.getDependency('accessor', primitiveDef.indices).then(function (accessor) {
  31796. geometry.setIndex(accessor);
  31797. });
  31798. pending.push(accessor);
  31799. }
  31800. assignExtrasToUserData(geometry, primitiveDef);
  31801. return Promise.all(pending).then(function () {
  31802. return primitiveDef.targets !== undefined ? addMorphTargets(geometry, primitiveDef.targets, parser) : geometry;
  31803. });
  31804. }
  31805. /**
  31806. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  31807. *
  31808. * Creates BufferGeometries from primitives.
  31809. *
  31810. * @param {Array<GLTF.Primitive>} primitives
  31811. * @return {Promise<Array<BufferGeometry>>}
  31812. */
  31813. GLTFParser.prototype.loadGeometries = function (primitives) {
  31814. var parser = this;
  31815. var extensions = this.extensions;
  31816. var cache = this.primitiveCache;
  31817. function createDracoPrimitive(primitive) {
  31818. return extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(primitive, parser).then(function (geometry) {
  31819. return addPrimitiveAttributes(geometry, primitive, parser);
  31820. });
  31821. }
  31822. var pending = [];
  31823. for (var i = 0, il = primitives.length; i < il; i++) {
  31824. var primitive = primitives[i];
  31825. var cacheKey = createPrimitiveKey(primitive); // See if we've already created this geometry
  31826. var cached = cache[cacheKey];
  31827. if (cached) {
  31828. // Use the cached geometry if it exists
  31829. pending.push(cached.promise);
  31830. } else {
  31831. var geometryPromise;
  31832. if (primitive.extensions && primitive.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION]) {
  31833. // Use DRACO geometry if available
  31834. geometryPromise = createDracoPrimitive(primitive);
  31835. } else {
  31836. // Otherwise create a new geometry
  31837. geometryPromise = addPrimitiveAttributes(new _threeModule.BufferGeometry(), primitive, parser);
  31838. } // Cache this geometry
  31839. cache[cacheKey] = {
  31840. primitive: primitive,
  31841. promise: geometryPromise
  31842. };
  31843. pending.push(geometryPromise);
  31844. }
  31845. }
  31846. return Promise.all(pending);
  31847. };
  31848. /**
  31849. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  31850. * @param {number} meshIndex
  31851. * @return {Promise<Group|Mesh|SkinnedMesh>}
  31852. */
  31853. GLTFParser.prototype.loadMesh = function (meshIndex) {
  31854. var parser = this;
  31855. var json = this.json;
  31856. var meshDef = json.meshes[meshIndex];
  31857. var primitives = meshDef.primitives;
  31858. var pending = [];
  31859. for (var i = 0, il = primitives.length; i < il; i++) {
  31860. var material = primitives[i].material === undefined ? createDefaultMaterial() : this.getDependency('material', primitives[i].material);
  31861. pending.push(material);
  31862. }
  31863. return Promise.all(pending).then(function (originalMaterials) {
  31864. return parser.loadGeometries(primitives).then(function (geometries) {
  31865. var meshes = [];
  31866. for (var i = 0, il = geometries.length; i < il; i++) {
  31867. var geometry = geometries[i];
  31868. var primitive = primitives[i]; // 1. create Mesh
  31869. var mesh;
  31870. var material = originalMaterials[i];
  31871. if (primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN || primitive.mode === undefined) {
  31872. // .isSkinnedMesh isn't in glTF spec. See .markDefs()
  31873. mesh = meshDef.isSkinnedMesh === true ? new _threeModule.SkinnedMesh(geometry, material) : new _threeModule.Mesh(geometry, material);
  31874. if (mesh.isSkinnedMesh === true && !mesh.geometry.attributes.skinWeight.normalized) {
  31875. // we normalize floating point skin weight array to fix malformed assets (see #15319)
  31876. // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs
  31877. mesh.normalizeSkinWeights();
  31878. }
  31879. if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP) {
  31880. mesh.drawMode = _threeModule.TriangleStripDrawMode;
  31881. } else if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN) {
  31882. mesh.drawMode = _threeModule.TriangleFanDrawMode;
  31883. }
  31884. } else if (primitive.mode === WEBGL_CONSTANTS.LINES) {
  31885. mesh = new _threeModule.LineSegments(geometry, material);
  31886. } else if (primitive.mode === WEBGL_CONSTANTS.LINE_STRIP) {
  31887. mesh = new _threeModule.Line(geometry, material);
  31888. } else if (primitive.mode === WEBGL_CONSTANTS.LINE_LOOP) {
  31889. mesh = new _threeModule.LineLoop(geometry, material);
  31890. } else if (primitive.mode === WEBGL_CONSTANTS.POINTS) {
  31891. mesh = new _threeModule.Points(geometry, material);
  31892. } else {
  31893. throw new Error('THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode);
  31894. }
  31895. if (Object.keys(mesh.geometry.morphAttributes).length > 0) {
  31896. updateMorphTargets(mesh, meshDef);
  31897. }
  31898. mesh.name = meshDef.name || 'mesh_' + meshIndex;
  31899. if (geometries.length > 1) mesh.name += '_' + i;
  31900. assignExtrasToUserData(mesh, meshDef);
  31901. parser.assignFinalMaterial(mesh);
  31902. meshes.push(mesh);
  31903. }
  31904. if (meshes.length === 1) {
  31905. return meshes[0];
  31906. }
  31907. var group = new _threeModule.Group();
  31908. for (var i = 0, il = meshes.length; i < il; i++) {
  31909. group.add(meshes[i]);
  31910. }
  31911. return group;
  31912. });
  31913. });
  31914. };
  31915. /**
  31916. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  31917. * @param {number} cameraIndex
  31918. * @return {Promise<THREE.Camera>}
  31919. */
  31920. GLTFParser.prototype.loadCamera = function (cameraIndex) {
  31921. var camera;
  31922. var cameraDef = this.json.cameras[cameraIndex];
  31923. var params = cameraDef[cameraDef.type];
  31924. if (!params) {
  31925. console.warn('THREE.GLTFLoader: Missing camera parameters.');
  31926. return;
  31927. }
  31928. if (cameraDef.type === 'perspective') {
  31929. camera = new _threeModule.PerspectiveCamera(_threeModule.Math.radToDeg(params.yfov), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6);
  31930. } else if (cameraDef.type === 'orthographic') {
  31931. camera = new _threeModule.OrthographicCamera(params.xmag / -2, params.xmag / 2, params.ymag / 2, params.ymag / -2, params.znear, params.zfar);
  31932. }
  31933. if (cameraDef.name !== undefined) camera.name = cameraDef.name;
  31934. assignExtrasToUserData(camera, cameraDef);
  31935. return Promise.resolve(camera);
  31936. };
  31937. /**
  31938. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  31939. * @param {number} skinIndex
  31940. * @return {Promise<Object>}
  31941. */
  31942. GLTFParser.prototype.loadSkin = function (skinIndex) {
  31943. var skinDef = this.json.skins[skinIndex];
  31944. var skinEntry = {
  31945. joints: skinDef.joints
  31946. };
  31947. if (skinDef.inverseBindMatrices === undefined) {
  31948. return Promise.resolve(skinEntry);
  31949. }
  31950. return this.getDependency('accessor', skinDef.inverseBindMatrices).then(function (accessor) {
  31951. skinEntry.inverseBindMatrices = accessor;
  31952. return skinEntry;
  31953. });
  31954. };
  31955. /**
  31956. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  31957. * @param {number} animationIndex
  31958. * @return {Promise<AnimationClip>}
  31959. */
  31960. GLTFParser.prototype.loadAnimation = function (animationIndex) {
  31961. var json = this.json;
  31962. var animationDef = json.animations[animationIndex];
  31963. var pendingNodes = [];
  31964. var pendingInputAccessors = [];
  31965. var pendingOutputAccessors = [];
  31966. var pendingSamplers = [];
  31967. var pendingTargets = [];
  31968. for (var i = 0, il = animationDef.channels.length; i < il; i++) {
  31969. var channel = animationDef.channels[i];
  31970. var sampler = animationDef.samplers[channel.sampler];
  31971. var target = channel.target;
  31972. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  31973. var input = animationDef.parameters !== undefined ? animationDef.parameters[sampler.input] : sampler.input;
  31974. var output = animationDef.parameters !== undefined ? animationDef.parameters[sampler.output] : sampler.output;
  31975. pendingNodes.push(this.getDependency('node', name));
  31976. pendingInputAccessors.push(this.getDependency('accessor', input));
  31977. pendingOutputAccessors.push(this.getDependency('accessor', output));
  31978. pendingSamplers.push(sampler);
  31979. pendingTargets.push(target);
  31980. }
  31981. return Promise.all([Promise.all(pendingNodes), Promise.all(pendingInputAccessors), Promise.all(pendingOutputAccessors), Promise.all(pendingSamplers), Promise.all(pendingTargets)]).then(function (dependencies) {
  31982. var nodes = dependencies[0];
  31983. var inputAccessors = dependencies[1];
  31984. var outputAccessors = dependencies[2];
  31985. var samplers = dependencies[3];
  31986. var targets = dependencies[4];
  31987. var tracks = [];
  31988. for (var i = 0, il = nodes.length; i < il; i++) {
  31989. var node = nodes[i];
  31990. var inputAccessor = inputAccessors[i];
  31991. var outputAccessor = outputAccessors[i];
  31992. var sampler = samplers[i];
  31993. var target = targets[i];
  31994. if (node === undefined) continue;
  31995. node.updateMatrix();
  31996. node.matrixAutoUpdate = true;
  31997. var TypedKeyframeTrack;
  31998. switch (PATH_PROPERTIES[target.path]) {
  31999. case PATH_PROPERTIES.weights:
  32000. TypedKeyframeTrack = _threeModule.NumberKeyframeTrack;
  32001. break;
  32002. case PATH_PROPERTIES.rotation:
  32003. TypedKeyframeTrack = _threeModule.QuaternionKeyframeTrack;
  32004. break;
  32005. case PATH_PROPERTIES.position:
  32006. case PATH_PROPERTIES.scale:
  32007. default:
  32008. TypedKeyframeTrack = _threeModule.VectorKeyframeTrack;
  32009. break;
  32010. }
  32011. var targetName = node.name ? node.name : node.uuid;
  32012. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[sampler.interpolation] : _threeModule.InterpolateLinear;
  32013. var targetNames = [];
  32014. if (PATH_PROPERTIES[target.path] === PATH_PROPERTIES.weights) {
  32015. // Node may be a Group (glTF mesh with several primitives) or a Mesh.
  32016. node.traverse(function (object) {
  32017. if (object.isMesh === true && object.morphTargetInfluences) {
  32018. targetNames.push(object.name ? object.name : object.uuid);
  32019. }
  32020. });
  32021. } else {
  32022. targetNames.push(targetName);
  32023. }
  32024. var outputArray = outputAccessor.array;
  32025. if (outputAccessor.normalized) {
  32026. var scale;
  32027. if (outputArray.constructor === Int8Array) {
  32028. scale = 1 / 127;
  32029. } else if (outputArray.constructor === Uint8Array) {
  32030. scale = 1 / 255;
  32031. } else if (outputArray.constructor == Int16Array) {
  32032. scale = 1 / 32767;
  32033. } else if (outputArray.constructor === Uint16Array) {
  32034. scale = 1 / 65535;
  32035. } else {
  32036. throw new Error('THREE.GLTFLoader: Unsupported output accessor component type.');
  32037. }
  32038. var scaled = new Float32Array(outputArray.length);
  32039. for (var j = 0, jl = outputArray.length; j < jl; j++) {
  32040. scaled[j] = outputArray[j] * scale;
  32041. }
  32042. outputArray = scaled;
  32043. }
  32044. for (var j = 0, jl = targetNames.length; j < jl; j++) {
  32045. var track = new TypedKeyframeTrack(targetNames[j] + '.' + PATH_PROPERTIES[target.path], inputAccessor.array, outputArray, interpolation); // Override interpolation with custom factory method.
  32046. if (sampler.interpolation === 'CUBICSPLINE') {
  32047. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline(result) {
  32048. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  32049. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  32050. // must be divided by three to get the interpolant's sampleSize argument.
  32051. return new GLTFCubicSplineInterpolant(this.times, this.values, this.getValueSize() / 3, result);
  32052. }; // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
  32053. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  32054. }
  32055. tracks.push(track);
  32056. }
  32057. }
  32058. var name = animationDef.name !== undefined ? animationDef.name : 'animation_' + animationIndex;
  32059. return new _threeModule.AnimationClip(name, undefined, tracks);
  32060. });
  32061. };
  32062. /**
  32063. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  32064. * @param {number} nodeIndex
  32065. * @return {Promise<Object3D>}
  32066. */
  32067. GLTFParser.prototype.loadNode = function (nodeIndex) {
  32068. var json = this.json;
  32069. var extensions = this.extensions;
  32070. var parser = this;
  32071. var meshReferences = json.meshReferences;
  32072. var meshUses = json.meshUses;
  32073. var nodeDef = json.nodes[nodeIndex];
  32074. return function () {
  32075. var pending = [];
  32076. if (nodeDef.mesh !== undefined) {
  32077. pending.push(parser.getDependency('mesh', nodeDef.mesh).then(function (mesh) {
  32078. var node;
  32079. if (meshReferences[nodeDef.mesh] > 1) {
  32080. var instanceNum = meshUses[nodeDef.mesh]++;
  32081. node = mesh.clone();
  32082. node.name += '_instance_' + instanceNum; // onBeforeRender copy for Specular-Glossiness
  32083. node.onBeforeRender = mesh.onBeforeRender;
  32084. for (var i = 0, il = node.children.length; i < il; i++) {
  32085. node.children[i].name += '_instance_' + instanceNum;
  32086. node.children[i].onBeforeRender = mesh.children[i].onBeforeRender;
  32087. }
  32088. } else {
  32089. node = mesh;
  32090. } // if weights are provided on the node, override weights on the mesh.
  32091. if (nodeDef.weights !== undefined) {
  32092. node.traverse(function (o) {
  32093. if (!o.isMesh) return;
  32094. for (var i = 0, il = nodeDef.weights.length; i < il; i++) {
  32095. o.morphTargetInfluences[i] = nodeDef.weights[i];
  32096. }
  32097. });
  32098. }
  32099. return node;
  32100. }));
  32101. }
  32102. if (nodeDef.camera !== undefined) {
  32103. pending.push(parser.getDependency('camera', nodeDef.camera));
  32104. }
  32105. if (nodeDef.extensions && nodeDef.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL] && nodeDef.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].light !== undefined) {
  32106. pending.push(parser.getDependency('light', nodeDef.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].light));
  32107. }
  32108. return Promise.all(pending);
  32109. }().then(function (objects) {
  32110. var node; // .isBone isn't in glTF spec. See .markDefs
  32111. if (nodeDef.isBone === true) {
  32112. node = new _threeModule.Bone();
  32113. } else if (objects.length > 1) {
  32114. node = new _threeModule.Group();
  32115. } else if (objects.length === 1) {
  32116. node = objects[0];
  32117. } else {
  32118. node = new _threeModule.Object3D();
  32119. }
  32120. if (node !== objects[0]) {
  32121. for (var i = 0, il = objects.length; i < il; i++) {
  32122. node.add(objects[i]);
  32123. }
  32124. }
  32125. if (nodeDef.name !== undefined) {
  32126. node.userData.name = nodeDef.name;
  32127. node.name = _threeModule.PropertyBinding.sanitizeNodeName(nodeDef.name);
  32128. }
  32129. assignExtrasToUserData(node, nodeDef);
  32130. if (nodeDef.extensions) addUnknownExtensionsToUserData(extensions, node, nodeDef);
  32131. if (nodeDef.matrix !== undefined) {
  32132. var matrix = new _threeModule.Matrix4();
  32133. matrix.fromArray(nodeDef.matrix);
  32134. node.applyMatrix(matrix);
  32135. } else {
  32136. if (nodeDef.translation !== undefined) {
  32137. node.position.fromArray(nodeDef.translation);
  32138. }
  32139. if (nodeDef.rotation !== undefined) {
  32140. node.quaternion.fromArray(nodeDef.rotation);
  32141. }
  32142. if (nodeDef.scale !== undefined) {
  32143. node.scale.fromArray(nodeDef.scale);
  32144. }
  32145. }
  32146. return node;
  32147. });
  32148. };
  32149. /**
  32150. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  32151. * @param {number} sceneIndex
  32152. * @return {Promise<Scene>}
  32153. */
  32154. GLTFParser.prototype.loadScene = function () {
  32155. // scene node hierachy builder
  32156. function buildNodeHierachy(nodeId, parentObject, json, parser) {
  32157. var nodeDef = json.nodes[nodeId];
  32158. return parser.getDependency('node', nodeId).then(function (node) {
  32159. if (nodeDef.skin === undefined) return node; // build skeleton here as well
  32160. var skinEntry;
  32161. return parser.getDependency('skin', nodeDef.skin).then(function (skin) {
  32162. skinEntry = skin;
  32163. var pendingJoints = [];
  32164. for (var i = 0, il = skinEntry.joints.length; i < il; i++) {
  32165. pendingJoints.push(parser.getDependency('node', skinEntry.joints[i]));
  32166. }
  32167. return Promise.all(pendingJoints);
  32168. }).then(function (jointNodes) {
  32169. node.traverse(function (mesh) {
  32170. if (!mesh.isMesh) return;
  32171. var bones = [];
  32172. var boneInverses = [];
  32173. for (var j = 0, jl = jointNodes.length; j < jl; j++) {
  32174. var jointNode = jointNodes[j];
  32175. if (jointNode) {
  32176. bones.push(jointNode);
  32177. var mat = new _threeModule.Matrix4();
  32178. if (skinEntry.inverseBindMatrices !== undefined) {
  32179. mat.fromArray(skinEntry.inverseBindMatrices.array, j * 16);
  32180. }
  32181. boneInverses.push(mat);
  32182. } else {
  32183. console.warn('THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[j]);
  32184. }
  32185. }
  32186. mesh.bind(new _threeModule.Skeleton(bones, boneInverses), mesh.matrixWorld);
  32187. });
  32188. return node;
  32189. });
  32190. }).then(function (node) {
  32191. // build node hierachy
  32192. parentObject.add(node);
  32193. var pending = [];
  32194. if (nodeDef.children) {
  32195. var children = nodeDef.children;
  32196. for (var i = 0, il = children.length; i < il; i++) {
  32197. var child = children[i];
  32198. pending.push(buildNodeHierachy(child, node, json, parser));
  32199. }
  32200. }
  32201. return Promise.all(pending);
  32202. });
  32203. }
  32204. return function loadScene(sceneIndex) {
  32205. var json = this.json;
  32206. var extensions = this.extensions;
  32207. var sceneDef = this.json.scenes[sceneIndex];
  32208. var parser = this;
  32209. var scene = new _threeModule.Scene();
  32210. if (sceneDef.name !== undefined) scene.name = sceneDef.name;
  32211. assignExtrasToUserData(scene, sceneDef);
  32212. if (sceneDef.extensions) addUnknownExtensionsToUserData(extensions, scene, sceneDef);
  32213. var nodeIds = sceneDef.nodes || [];
  32214. var pending = [];
  32215. for (var i = 0, il = nodeIds.length; i < il; i++) {
  32216. pending.push(buildNodeHierachy(nodeIds[i], scene, json, parser));
  32217. }
  32218. return Promise.all(pending).then(function () {
  32219. return scene;
  32220. });
  32221. };
  32222. }();
  32223. return GLTFLoader;
  32224. }();
  32225. exports.GLTFLoader = GLTFLoader;
  32226. },{"../../../build/three.module.js":"../node_modules/three/build/three.module.js"}],"../src/three/ThreeB3DMLoader.js":[function(require,module,exports) {
  32227. "use strict";
  32228. Object.defineProperty(exports, "__esModule", {
  32229. value: true
  32230. });
  32231. exports.ThreeB3DMLoader = void 0;
  32232. var _B3DMLoader = require("../B3DMLoader.js");
  32233. var _GLTFLoader = require("three/examples/jsm/loaders/GLTFLoader.js");
  32234. class ThreeB3DMLoader extends _B3DMLoader.B3DMLoader {
  32235. parse(buffer) {
  32236. const b3dm = super.parse(buffer);
  32237. const gltfBuffer = b3dm.glbBytes.slice().buffer;
  32238. return new Promise((resolve, reject) => {
  32239. new _GLTFLoader.GLTFLoader().parse(gltfBuffer, null, resolve, reject);
  32240. });
  32241. }
  32242. }
  32243. exports.ThreeB3DMLoader = ThreeB3DMLoader;
  32244. },{"../B3DMLoader.js":"../src/B3DMLoader.js","three/examples/jsm/loaders/GLTFLoader.js":"../node_modules/three/examples/jsm/loaders/GLTFLoader.js"}],"../src/three/ThreeTilesRenderer.js":[function(require,module,exports) {
  32245. "use strict";
  32246. Object.defineProperty(exports, "__esModule", {
  32247. value: true
  32248. });
  32249. exports.ThreeTilesRenderer = void 0;
  32250. var _TilesRenderer = require("../TilesRenderer.js");
  32251. var _ThreeB3DMLoader = require("./ThreeB3DMLoader.js");
  32252. var _three = require("three");
  32253. const DEG2RAD = _three.Math.DEG2RAD;
  32254. const tempMat = new _three.Matrix4();
  32255. const tempQuaternion = new _three.Quaternion();
  32256. const tempVector = new _three.Vector3();
  32257. const resVector = new _three.Vector2();
  32258. const vecX = new _three.Vector3();
  32259. const vecY = new _three.Vector3();
  32260. const vecZ = new _three.Vector3();
  32261. const ray = new _three.Ray();
  32262. const _sphere = new _three.Sphere(); // Specialization of "Group" that only updates world matrices of children if
  32263. // the transform has changed since the last update and ignores the "force"
  32264. // parameter under the assumption that the children tiles will not move.
  32265. class TilesGroup extends _three.Group {
  32266. constructor(tilesRenderer) {
  32267. super();
  32268. this.tilesRenderer = tilesRenderer;
  32269. }
  32270. raycast(raycaster, intersects) {
  32271. // TODO: Figure out how to do traversal here -- submit issue to three.js?
  32272. const tilesRenderer = this.tilesRenderer;
  32273. const visibleSet = tilesRenderer.visibleSet;
  32274. const activeSet = tilesRenderer.activeSet;
  32275. activeSet.forEach(scene => {
  32276. if (!visibleSet.has(scene)) {
  32277. raycaster.intersectObject(scene, true, intersects);
  32278. }
  32279. });
  32280. }
  32281. updateMatrixWorld(force) {
  32282. if (this.matrixAutoUpdate) {
  32283. this.updateMatrix();
  32284. }
  32285. if (this.matrixWorldNeedsUpdate || force) {
  32286. if (this.parent === null) {
  32287. tempMat.copy(this.matrix);
  32288. } else {
  32289. tempMat.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  32290. }
  32291. this.matrixWorldNeedsUpdate = false;
  32292. const elA = tempMat.elements;
  32293. const elB = this.matrixWorld.elements;
  32294. let isDifferent = false;
  32295. for (let i = 0; i < 16; i++) {
  32296. const itemA = elA[i];
  32297. const itemB = elB[i];
  32298. const diff = Math.abs(itemA - itemB);
  32299. if (diff > Number.EPSILON) {
  32300. isDifferent = true;
  32301. break;
  32302. }
  32303. }
  32304. if (isDifferent) {
  32305. this.matrixWorld.copy(tempMat); // update children
  32306. // the children will not have to change unless the parent group has updated
  32307. const children = this.children;
  32308. for (let i = 0, l = children.length; i < l; i++) {
  32309. children[i].updateMatrixWorld();
  32310. }
  32311. }
  32312. }
  32313. }
  32314. }
  32315. class ThreeTilesRenderer extends _TilesRenderer.TilesRenderer {
  32316. get displayBounds() {
  32317. return this._displayBounds;
  32318. }
  32319. set displayBounds(val) {
  32320. if (val !== this.displayBounds) {
  32321. this._displayBounds = val;
  32322. this.traverse(t => {
  32323. const scene = t.cached.scene;
  32324. const boxHelper = t.cached.boxHelper;
  32325. if (scene) {
  32326. if (val) {
  32327. scene.add(boxHelper);
  32328. boxHelper.updateMatrixWorld(true);
  32329. } else {
  32330. scene.remove(boxHelper);
  32331. }
  32332. }
  32333. });
  32334. }
  32335. }
  32336. constructor(url, cameras, renderer) {
  32337. super(url);
  32338. this.group = new TilesGroup(this);
  32339. this.cameras = Array.isArray(cameras) ? cameras : [cameras];
  32340. this.frustums = [];
  32341. this.renderer = renderer;
  32342. this.activeSet = new Set();
  32343. this.visibleSet = new Set();
  32344. }
  32345. /* Public API */
  32346. getBounds(box) {
  32347. if (!this.root) {
  32348. return false;
  32349. }
  32350. const cached = this.root.cached;
  32351. const boundingBox = cached.box;
  32352. const obbMat = cached.boxTransform;
  32353. const transformMat = cached.transform;
  32354. box.copy(boundingBox);
  32355. tempMat.multiplyMatrices(transformMat, obbMat);
  32356. box.applyMatrix4(tempMat);
  32357. return true;
  32358. }
  32359. raycast(raycaster, intersects) {
  32360. const activeSet = this.activeSet;
  32361. const group = this.group;
  32362. this.traverse(tile => {
  32363. const cached = tile.cached;
  32364. const groupMatrixWorld = group.matrixWorld;
  32365. const transformMat = cached.transform;
  32366. tempMat.copy(groupMatrixWorld);
  32367. tempMat.multiply(transformMat);
  32368. const sphere = cached.sphere;
  32369. if (sphere) {
  32370. _sphere.copy(sphere);
  32371. _sphere.applyMatrix4(tempMat);
  32372. if (!raycaster.ray.intersectsSphere(_sphere)) {
  32373. return true;
  32374. }
  32375. }
  32376. const boundingBox = cached.box;
  32377. const obbMat = cached.boxTransform;
  32378. if (boundingBox) {
  32379. tempMat.multiply(obbMat);
  32380. tempMat.getInverse(tempMat);
  32381. ray.copy(raycaster.ray).applyMatrix4(tempMat);
  32382. if (!ray.intersectsBox(boundingBox)) {
  32383. return true;
  32384. }
  32385. } // TODO: check region
  32386. // TODO: how do we prevent the child checks from happening?
  32387. const scene = cached.scene;
  32388. if (activeSet.has(scene)) {
  32389. raycaster.intersectObject(scene, true, intersects);
  32390. }
  32391. });
  32392. }
  32393. /* Overriden */
  32394. update() {
  32395. const group = this.group;
  32396. const renderer = this.renderer;
  32397. const cameras = this.cameras;
  32398. const frustums = this.frustums; // automatically scale the array of frustums to match the cameras
  32399. while (frustums.length > cameras.length) {
  32400. frustums.pop();
  32401. }
  32402. while (frustums.length < cameras.length) {
  32403. frustums.push(new _three.Frustum());
  32404. } // store the camera frustums in the 3d tiles root frame
  32405. for (let i = 0, l = frustums.length; i < l; i++) {
  32406. const camera = cameras[i];
  32407. const frustum = frustums[i];
  32408. tempMat.copy(group.matrixWorld);
  32409. tempMat.premultiply(camera.matrixWorldInverse);
  32410. tempMat.premultiply(camera.projectionMatrix);
  32411. frustum.setFromMatrix(tempMat);
  32412. } // store the resolution of the render
  32413. renderer.getSize(resVector);
  32414. resVector.multiplyScalar(renderer.getPixelRatio());
  32415. super.update();
  32416. }
  32417. preprocessNode(tile, parentTile, tileSetDir) {
  32418. super.preprocessNode(tile, parentTile, tileSetDir);
  32419. const transform = new _three.Matrix4();
  32420. if (tile.transform) {
  32421. const transformArr = tile.transform;
  32422. for (let i = 0; i < 16; i++) {
  32423. transform.elements[i] = transformArr[i];
  32424. }
  32425. } else {
  32426. transform.identity();
  32427. }
  32428. if (parentTile) {
  32429. transform.multiply(parentTile.cached.transform);
  32430. }
  32431. let box = null;
  32432. let boxTransform = null;
  32433. if ('box' in tile.boundingVolume) {
  32434. const data = tile.boundingVolume.box;
  32435. box = new _three.Box3();
  32436. boxTransform = new _three.Matrix4(); // get the extents of the bounds in each axis
  32437. vecX.set(data[3], data[4], data[5]);
  32438. vecY.set(data[6], data[7], data[8]);
  32439. vecZ.set(data[9], data[10], data[11]);
  32440. const scaleX = vecX.length();
  32441. const scaleY = vecY.length();
  32442. const scaleZ = vecZ.length();
  32443. vecX.normalize();
  32444. vecY.normalize();
  32445. vecZ.normalize(); // create the oriented frame that the box exists in
  32446. boxTransform.set(vecX.x, vecY.x, vecZ.x, data[0], vecX.y, vecY.y, vecZ.y, data[1], vecX.z, vecY.z, vecZ.z, data[2], 0, 0, 0, 1); // scale the box by the extents
  32447. box.min.set(-scaleX, -scaleY, -scaleZ);
  32448. box.max.set(scaleX, scaleY, scaleZ);
  32449. }
  32450. let sphere = null;
  32451. if ('sphere' in tile.boundingVolume) {
  32452. const data = tile.boundingVolume.sphere;
  32453. sphere = new _three.Sphere();
  32454. sphere.center.set(data[0], data[1], data[2]);
  32455. sphere.radius = data[3];
  32456. } else if ('box' in tile.boundingVolume) {
  32457. sphere = new _three.Sphere();
  32458. box.getBoundingSphere(sphere);
  32459. boxTransform.decompose(sphere.center, tempQuaternion, tempVector);
  32460. }
  32461. let region = null;
  32462. if ('region' in tile.boundingVolume) {
  32463. console.warn('ThreeTilesRenderer: region bounding volume not supported.');
  32464. }
  32465. tile.cached = {
  32466. loadIndex: 0,
  32467. transform,
  32468. active: false,
  32469. box,
  32470. boxTransform,
  32471. sphere,
  32472. region,
  32473. boxHelper: null,
  32474. scene: null
  32475. };
  32476. }
  32477. parseTile(buffer, tile) {
  32478. tile._loadIndex = tile._loadIndex || 0;
  32479. tile._loadIndex++; // TODO: 90 degree rotation must be applied to GLTF file to resolve "up"
  32480. const loadIndex = tile._loadIndex;
  32481. return new _ThreeB3DMLoader.ThreeB3DMLoader().parse(buffer).then(res => {
  32482. if (tile._loadIndex !== loadIndex) {
  32483. return;
  32484. }
  32485. const cached = tile.cached;
  32486. const cachedBox = cached.box;
  32487. const cachedBoxMat = cached.boxTransform; // add a helper group to represent the obb rotation matrix
  32488. const boxHelper = new _three.Box3Helper(cachedBox);
  32489. const boxHelperGroup = new _three.Group();
  32490. cachedBoxMat.decompose(boxHelperGroup.position, boxHelperGroup.quaternion, boxHelperGroup.scale);
  32491. boxHelperGroup.add(boxHelper);
  32492. boxHelperGroup.updateMatrixWorld(true);
  32493. const scene = res.scene;
  32494. cached.transform.decompose(scene.position, scene.quaternion, scene.scale);
  32495. scene.traverse(c => c.frustumCulled = false);
  32496. cached.boxHelper = boxHelperGroup;
  32497. cached.scene = res.scene;
  32498. if (this.displayBounds) {
  32499. cached.scene.add(cached.boxHelper);
  32500. }
  32501. });
  32502. }
  32503. disposeTile(tile) {
  32504. const cached = tile.cached;
  32505. if (cached.scene) {
  32506. const scene = cached.scene;
  32507. if (scene.parent) {
  32508. scene.parent.remove(scene);
  32509. }
  32510. scene.traverse(c => {
  32511. if (c.geometry) {
  32512. c.geometry.dispose();
  32513. }
  32514. if (c.material) {
  32515. c.material.dispose(); // TODO: dispose textures
  32516. }
  32517. });
  32518. cached.scene = null;
  32519. cached.boxHelper = null;
  32520. }
  32521. tile._loadIndex++;
  32522. }
  32523. setTileVisible(tile, visible) {
  32524. const scene = tile.cached.scene;
  32525. const visibleSet = this.visibleSet;
  32526. const group = this.group;
  32527. if (visible) {
  32528. if (scene && !scene.parent) {
  32529. group.add(scene);
  32530. visibleSet.add(scene);
  32531. scene.updateMatrixWorld(true);
  32532. }
  32533. } else {
  32534. group.remove(scene);
  32535. visibleSet.delete(scene);
  32536. }
  32537. }
  32538. setTileActive(tile, active) {
  32539. const cached = tile.cached;
  32540. const activeSet = this.activeSet;
  32541. if (active !== cached.active) {
  32542. cached.active = active;
  32543. if (active) {
  32544. activeSet.add(cached.scene);
  32545. } else {
  32546. activeSet.delete(cached.scene);
  32547. }
  32548. }
  32549. }
  32550. calculateError(tile) {
  32551. const cached = tile.cached;
  32552. const cameras = this.cameras; // TODO: Use the content bounding volume here?
  32553. const boundingVolume = tile.boundingVolume;
  32554. const transformMat = cached.transform;
  32555. if ('box' in boundingVolume) {
  32556. const group = this.group;
  32557. const boundingBox = cached.box;
  32558. const obbMat = cached.boxTransform; // TODO: these can likely be cached? Or the world transform mat can be used
  32559. // transformMat can be rolled into oobMat
  32560. tempMat.copy(transformMat);
  32561. tempMat.multiply(obbMat);
  32562. tempMat.getInverse(tempMat);
  32563. let minError = Infinity;
  32564. for (let i = 0, l = cameras.length; i < l; i++) {
  32565. // transform camera position into local frame of the tile bounding box
  32566. const cam = cameras[i];
  32567. tempVector.copy(cam.position);
  32568. tempVector.applyMatrix4(tempMat);
  32569. let error;
  32570. if (cam.isOrthographic) {
  32571. const w = cam.right - cam.left;
  32572. const h = cam.top - cam.bottom;
  32573. const pixelSize = Math.Max(h, w) / Math.Max(resVector.width, resVector.height);
  32574. error = tile.geometricError / pixelSize;
  32575. } else {
  32576. const distance = boundingBox.distanceToPoint(tempVector); // assume the scales on all axes are uniform.
  32577. let scale; // account for tile scale.
  32578. tempVector.setFromMatrixScale(tempMat);
  32579. scale = tempVector.x; // account for parent group scale. Divide because this matrix has not been inverted like the previous one.
  32580. tempVector.setFromMatrixScale(group.matrixWorld);
  32581. scale /= tempVector.x;
  32582. if (Math.abs(Math.max(scale.x - scale.y, scale.x - scale.z)) > 1e-6) {
  32583. console.warn('ThreeTilesRenderer : Non uniform scale used for tile which may cause issues when claculating screen space error.');
  32584. }
  32585. const scaledDistance = distance * scale;
  32586. const sseDenominator = 2 * Math.tan(0.5 * cam.fov * DEG2RAD);
  32587. error = tile.geometricError * resVector.height / (scaledDistance * sseDenominator);
  32588. }
  32589. minError = Math.min(minError, error);
  32590. }
  32591. return minError;
  32592. } else if ('sphere' in boundingVolume) {
  32593. const sphere = cached.sphere;
  32594. console.warn('ThreeTilesRenderer : Sphere bounds not supported.');
  32595. } else if ('region' in boundingVolume) {
  32596. // unsupported
  32597. console.warn('ThreeTilesRenderer : Region bounds not supported.');
  32598. }
  32599. return Infinity;
  32600. }
  32601. tileInView(tile) {
  32602. // TODO: we should use the more precise bounding volumes here if possible
  32603. // cache the root-space planes
  32604. const sphere = tile.cached.sphere;
  32605. if (sphere) {
  32606. _sphere.copy(sphere);
  32607. _sphere.applyMatrix4(tile.cached.transform);
  32608. const frustums = this.frustums;
  32609. for (let i = 0, l = frustums.length; i < l; i++) {
  32610. const frustum = frustums[i];
  32611. if (frustum.intersectsSphere(_sphere)) {
  32612. return true;
  32613. }
  32614. }
  32615. return false;
  32616. }
  32617. return true;
  32618. }
  32619. }
  32620. exports.ThreeTilesRenderer = ThreeTilesRenderer;
  32621. },{"../TilesRenderer.js":"../src/TilesRenderer.js","./ThreeB3DMLoader.js":"../src/three/ThreeB3DMLoader.js","three":"../node_modules/three/build/three.module.js"}],"../src/index.js":[function(require,module,exports) {
  32622. "use strict";
  32623. Object.defineProperty(exports, "__esModule", {
  32624. value: true
  32625. });
  32626. Object.defineProperty(exports, "ThreeTilesRenderer", {
  32627. enumerable: true,
  32628. get: function () {
  32629. return _ThreeTilesRenderer.ThreeTilesRenderer;
  32630. }
  32631. });
  32632. Object.defineProperty(exports, "ThreeB3DMLoader", {
  32633. enumerable: true,
  32634. get: function () {
  32635. return _ThreeB3DMLoader.ThreeB3DMLoader;
  32636. }
  32637. });
  32638. Object.defineProperty(exports, "TilesRenderer", {
  32639. enumerable: true,
  32640. get: function () {
  32641. return _TilesRenderer.TilesRenderer;
  32642. }
  32643. });
  32644. Object.defineProperty(exports, "B3DMLoader", {
  32645. enumerable: true,
  32646. get: function () {
  32647. return _B3DMLoader.B3DMLoader;
  32648. }
  32649. });
  32650. var _ThreeTilesRenderer = require("./three/ThreeTilesRenderer.js");
  32651. var _ThreeB3DMLoader = require("./three/ThreeB3DMLoader");
  32652. var _TilesRenderer = require("./TilesRenderer.js");
  32653. var _B3DMLoader = require("./B3DMLoader");
  32654. },{"./three/ThreeTilesRenderer.js":"../src/three/ThreeTilesRenderer.js","./three/ThreeB3DMLoader":"../src/three/ThreeB3DMLoader.js","./TilesRenderer.js":"../src/TilesRenderer.js","./B3DMLoader":"../src/B3DMLoader.js"}],"../node_modules/three/examples/jsm/controls/OrbitControls.js":[function(require,module,exports) {
  32655. "use strict";
  32656. Object.defineProperty(exports, "__esModule", {
  32657. value: true
  32658. });
  32659. exports.MapControls = exports.OrbitControls = void 0;
  32660. var _threeModule = require("../../../build/three.module.js");
  32661. /**
  32662. * @author qiao / https://github.com/qiao
  32663. * @author mrdoob / http://mrdoob.com
  32664. * @author alteredq / http://alteredqualia.com/
  32665. * @author WestLangley / http://github.com/WestLangley
  32666. * @author erich666 / http://erichaines.com
  32667. * @author ScieCode / http://github.com/sciecode
  32668. */
  32669. // This set of controls performs orbiting, dollying (zooming), and panning.
  32670. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
  32671. //
  32672. // Orbit - left mouse / touch: one-finger move
  32673. // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
  32674. // Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move
  32675. var OrbitControls = function (object, domElement) {
  32676. this.object = object;
  32677. this.domElement = domElement !== undefined ? domElement : document; // Set to false to disable this control
  32678. this.enabled = true; // "target" sets the location of focus, where the object orbits around
  32679. this.target = new _threeModule.Vector3(); // How far you can dolly in and out ( PerspectiveCamera only )
  32680. this.minDistance = 0;
  32681. this.maxDistance = Infinity; // How far you can zoom in and out ( OrthographicCamera only )
  32682. this.minZoom = 0;
  32683. this.maxZoom = Infinity; // How far you can orbit vertically, upper and lower limits.
  32684. // Range is 0 to Math.PI radians.
  32685. this.minPolarAngle = 0; // radians
  32686. this.maxPolarAngle = Math.PI; // radians
  32687. // How far you can orbit horizontally, upper and lower limits.
  32688. // If set, must be a sub-interval of the interval [ - Math.PI, Math.PI ].
  32689. this.minAzimuthAngle = -Infinity; // radians
  32690. this.maxAzimuthAngle = Infinity; // radians
  32691. // Set to true to enable damping (inertia)
  32692. // If damping is enabled, you must call controls.update() in your animation loop
  32693. this.enableDamping = false;
  32694. this.dampingFactor = 0.05; // This option actually enables dollying in and out; left as "zoom" for backwards compatibility.
  32695. // Set to false to disable zooming
  32696. this.enableZoom = true;
  32697. this.zoomSpeed = 1.0; // Set to false to disable rotating
  32698. this.enableRotate = true;
  32699. this.rotateSpeed = 1.0; // Set to false to disable panning
  32700. this.enablePan = true;
  32701. this.panSpeed = 1.0;
  32702. this.screenSpacePanning = false; // if true, pan in screen-space
  32703. this.keyPanSpeed = 7.0; // pixels moved per arrow key push
  32704. // Set to true to automatically rotate around the target
  32705. // If auto-rotate is enabled, you must call controls.update() in your animation loop
  32706. this.autoRotate = false;
  32707. this.autoRotateSpeed = 2.0; // 30 seconds per round when fps is 60
  32708. // Set to false to disable use of the keys
  32709. this.enableKeys = true; // The four arrow keys
  32710. this.keys = {
  32711. LEFT: 37,
  32712. UP: 38,
  32713. RIGHT: 39,
  32714. BOTTOM: 40
  32715. }; // Mouse buttons
  32716. this.mouseButtons = {
  32717. LEFT: _threeModule.MOUSE.ROTATE,
  32718. MIDDLE: _threeModule.MOUSE.DOLLY,
  32719. RIGHT: _threeModule.MOUSE.PAN
  32720. }; // Touch fingers
  32721. this.touches = {
  32722. ONE: _threeModule.TOUCH.ROTATE,
  32723. TWO: _threeModule.TOUCH.DOLLY_PAN
  32724. }; // for reset
  32725. this.target0 = this.target.clone();
  32726. this.position0 = this.object.position.clone();
  32727. this.zoom0 = this.object.zoom; //
  32728. // public methods
  32729. //
  32730. this.getPolarAngle = function () {
  32731. return spherical.phi;
  32732. };
  32733. this.getAzimuthalAngle = function () {
  32734. return spherical.theta;
  32735. };
  32736. this.saveState = function () {
  32737. scope.target0.copy(scope.target);
  32738. scope.position0.copy(scope.object.position);
  32739. scope.zoom0 = scope.object.zoom;
  32740. };
  32741. this.reset = function () {
  32742. scope.target.copy(scope.target0);
  32743. scope.object.position.copy(scope.position0);
  32744. scope.object.zoom = scope.zoom0;
  32745. scope.object.updateProjectionMatrix();
  32746. scope.dispatchEvent(changeEvent);
  32747. scope.update();
  32748. state = STATE.NONE;
  32749. }; // this method is exposed, but perhaps it would be better if we can make it private...
  32750. this.update = function () {
  32751. var offset = new _threeModule.Vector3(); // so camera.up is the orbit axis
  32752. var quat = new _threeModule.Quaternion().setFromUnitVectors(object.up, new _threeModule.Vector3(0, 1, 0));
  32753. var quatInverse = quat.clone().inverse();
  32754. var lastPosition = new _threeModule.Vector3();
  32755. var lastQuaternion = new _threeModule.Quaternion();
  32756. return function update() {
  32757. var position = scope.object.position;
  32758. offset.copy(position).sub(scope.target); // rotate offset to "y-axis-is-up" space
  32759. offset.applyQuaternion(quat); // angle from z-axis around y-axis
  32760. spherical.setFromVector3(offset);
  32761. if (scope.autoRotate && state === STATE.NONE) {
  32762. rotateLeft(getAutoRotationAngle());
  32763. }
  32764. if (scope.enableDamping) {
  32765. spherical.theta += sphericalDelta.theta * scope.dampingFactor;
  32766. spherical.phi += sphericalDelta.phi * scope.dampingFactor;
  32767. } else {
  32768. spherical.theta += sphericalDelta.theta;
  32769. spherical.phi += sphericalDelta.phi;
  32770. } // restrict theta to be between desired limits
  32771. spherical.theta = Math.max(scope.minAzimuthAngle, Math.min(scope.maxAzimuthAngle, spherical.theta)); // restrict phi to be between desired limits
  32772. spherical.phi = Math.max(scope.minPolarAngle, Math.min(scope.maxPolarAngle, spherical.phi));
  32773. spherical.makeSafe();
  32774. spherical.radius *= scale; // restrict radius to be between desired limits
  32775. spherical.radius = Math.max(scope.minDistance, Math.min(scope.maxDistance, spherical.radius)); // move target to panned location
  32776. if (scope.enableDamping === true) {
  32777. scope.target.addScaledVector(panOffset, scope.dampingFactor);
  32778. } else {
  32779. scope.target.add(panOffset);
  32780. }
  32781. offset.setFromSpherical(spherical); // rotate offset back to "camera-up-vector-is-up" space
  32782. offset.applyQuaternion(quatInverse);
  32783. position.copy(scope.target).add(offset);
  32784. scope.object.lookAt(scope.target);
  32785. if (scope.enableDamping === true) {
  32786. sphericalDelta.theta *= 1 - scope.dampingFactor;
  32787. sphericalDelta.phi *= 1 - scope.dampingFactor;
  32788. panOffset.multiplyScalar(1 - scope.dampingFactor);
  32789. } else {
  32790. sphericalDelta.set(0, 0, 0);
  32791. panOffset.set(0, 0, 0);
  32792. }
  32793. scale = 1; // update condition is:
  32794. // min(camera displacement, camera rotation in radians)^2 > EPS
  32795. // using small-angle approximation cos(x/2) = 1 - x^2 / 8
  32796. if (zoomChanged || lastPosition.distanceToSquared(scope.object.position) > EPS || 8 * (1 - lastQuaternion.dot(scope.object.quaternion)) > EPS) {
  32797. scope.dispatchEvent(changeEvent);
  32798. lastPosition.copy(scope.object.position);
  32799. lastQuaternion.copy(scope.object.quaternion);
  32800. zoomChanged = false;
  32801. return true;
  32802. }
  32803. return false;
  32804. };
  32805. }();
  32806. this.dispose = function () {
  32807. scope.domElement.removeEventListener('contextmenu', onContextMenu, false);
  32808. scope.domElement.removeEventListener('mousedown', onMouseDown, false);
  32809. scope.domElement.removeEventListener('wheel', onMouseWheel, false);
  32810. scope.domElement.removeEventListener('touchstart', onTouchStart, false);
  32811. scope.domElement.removeEventListener('touchend', onTouchEnd, false);
  32812. scope.domElement.removeEventListener('touchmove', onTouchMove, false);
  32813. document.removeEventListener('mousemove', onMouseMove, false);
  32814. document.removeEventListener('mouseup', onMouseUp, false);
  32815. window.removeEventListener('keydown', onKeyDown, false); //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here?
  32816. }; //
  32817. // internals
  32818. //
  32819. var scope = this;
  32820. var changeEvent = {
  32821. type: 'change'
  32822. };
  32823. var startEvent = {
  32824. type: 'start'
  32825. };
  32826. var endEvent = {
  32827. type: 'end'
  32828. };
  32829. var STATE = {
  32830. NONE: -1,
  32831. ROTATE: 0,
  32832. DOLLY: 1,
  32833. PAN: 2,
  32834. TOUCH_ROTATE: 3,
  32835. TOUCH_PAN: 4,
  32836. TOUCH_DOLLY_PAN: 5,
  32837. TOUCH_DOLLY_ROTATE: 6
  32838. };
  32839. var state = STATE.NONE;
  32840. var EPS = 0.000001; // current position in spherical coordinates
  32841. var spherical = new _threeModule.Spherical();
  32842. var sphericalDelta = new _threeModule.Spherical();
  32843. var scale = 1;
  32844. var panOffset = new _threeModule.Vector3();
  32845. var zoomChanged = false;
  32846. var rotateStart = new _threeModule.Vector2();
  32847. var rotateEnd = new _threeModule.Vector2();
  32848. var rotateDelta = new _threeModule.Vector2();
  32849. var panStart = new _threeModule.Vector2();
  32850. var panEnd = new _threeModule.Vector2();
  32851. var panDelta = new _threeModule.Vector2();
  32852. var dollyStart = new _threeModule.Vector2();
  32853. var dollyEnd = new _threeModule.Vector2();
  32854. var dollyDelta = new _threeModule.Vector2();
  32855. function getAutoRotationAngle() {
  32856. return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;
  32857. }
  32858. function getZoomScale() {
  32859. return Math.pow(0.95, scope.zoomSpeed);
  32860. }
  32861. function rotateLeft(angle) {
  32862. sphericalDelta.theta -= angle;
  32863. }
  32864. function rotateUp(angle) {
  32865. sphericalDelta.phi -= angle;
  32866. }
  32867. var panLeft = function () {
  32868. var v = new _threeModule.Vector3();
  32869. return function panLeft(distance, objectMatrix) {
  32870. v.setFromMatrixColumn(objectMatrix, 0); // get X column of objectMatrix
  32871. v.multiplyScalar(-distance);
  32872. panOffset.add(v);
  32873. };
  32874. }();
  32875. var panUp = function () {
  32876. var v = new _threeModule.Vector3();
  32877. return function panUp(distance, objectMatrix) {
  32878. if (scope.screenSpacePanning === true) {
  32879. v.setFromMatrixColumn(objectMatrix, 1);
  32880. } else {
  32881. v.setFromMatrixColumn(objectMatrix, 0);
  32882. v.crossVectors(scope.object.up, v);
  32883. }
  32884. v.multiplyScalar(distance);
  32885. panOffset.add(v);
  32886. };
  32887. }(); // deltaX and deltaY are in pixels; right and down are positive
  32888. var pan = function () {
  32889. var offset = new _threeModule.Vector3();
  32890. return function pan(deltaX, deltaY) {
  32891. var element = scope.domElement === document ? scope.domElement.body : scope.domElement;
  32892. if (scope.object.isPerspectiveCamera) {
  32893. // perspective
  32894. var position = scope.object.position;
  32895. offset.copy(position).sub(scope.target);
  32896. var targetDistance = offset.length(); // half of the fov is center to top of screen
  32897. targetDistance *= Math.tan(scope.object.fov / 2 * Math.PI / 180.0); // we use only clientHeight here so aspect ratio does not distort speed
  32898. panLeft(2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix);
  32899. panUp(2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix);
  32900. } else if (scope.object.isOrthographicCamera) {
  32901. // orthographic
  32902. panLeft(deltaX * (scope.object.right - scope.object.left) / scope.object.zoom / element.clientWidth, scope.object.matrix);
  32903. panUp(deltaY * (scope.object.top - scope.object.bottom) / scope.object.zoom / element.clientHeight, scope.object.matrix);
  32904. } else {
  32905. // camera neither orthographic nor perspective
  32906. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.');
  32907. scope.enablePan = false;
  32908. }
  32909. };
  32910. }();
  32911. function dollyIn(dollyScale) {
  32912. if (scope.object.isPerspectiveCamera) {
  32913. scale /= dollyScale;
  32914. } else if (scope.object.isOrthographicCamera) {
  32915. scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom * dollyScale));
  32916. scope.object.updateProjectionMatrix();
  32917. zoomChanged = true;
  32918. } else {
  32919. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.');
  32920. scope.enableZoom = false;
  32921. }
  32922. }
  32923. function dollyOut(dollyScale) {
  32924. if (scope.object.isPerspectiveCamera) {
  32925. scale *= dollyScale;
  32926. } else if (scope.object.isOrthographicCamera) {
  32927. scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom / dollyScale));
  32928. scope.object.updateProjectionMatrix();
  32929. zoomChanged = true;
  32930. } else {
  32931. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.');
  32932. scope.enableZoom = false;
  32933. }
  32934. } //
  32935. // event callbacks - update the object state
  32936. //
  32937. function handleMouseDownRotate(event) {
  32938. rotateStart.set(event.clientX, event.clientY);
  32939. }
  32940. function handleMouseDownDolly(event) {
  32941. dollyStart.set(event.clientX, event.clientY);
  32942. }
  32943. function handleMouseDownPan(event) {
  32944. panStart.set(event.clientX, event.clientY);
  32945. }
  32946. function handleMouseMoveRotate(event) {
  32947. rotateEnd.set(event.clientX, event.clientY);
  32948. rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed);
  32949. var element = scope.domElement === document ? scope.domElement.body : scope.domElement;
  32950. rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); // yes, height
  32951. rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight);
  32952. rotateStart.copy(rotateEnd);
  32953. scope.update();
  32954. }
  32955. function handleMouseMoveDolly(event) {
  32956. dollyEnd.set(event.clientX, event.clientY);
  32957. dollyDelta.subVectors(dollyEnd, dollyStart);
  32958. if (dollyDelta.y > 0) {
  32959. dollyIn(getZoomScale());
  32960. } else if (dollyDelta.y < 0) {
  32961. dollyOut(getZoomScale());
  32962. }
  32963. dollyStart.copy(dollyEnd);
  32964. scope.update();
  32965. }
  32966. function handleMouseMovePan(event) {
  32967. panEnd.set(event.clientX, event.clientY);
  32968. panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed);
  32969. pan(panDelta.x, panDelta.y);
  32970. panStart.copy(panEnd);
  32971. scope.update();
  32972. }
  32973. function handleMouseUp()
  32974. /*event*/
  32975. {// no-op
  32976. }
  32977. function handleMouseWheel(event) {
  32978. if (event.deltaY < 0) {
  32979. dollyOut(getZoomScale());
  32980. } else if (event.deltaY > 0) {
  32981. dollyIn(getZoomScale());
  32982. }
  32983. scope.update();
  32984. }
  32985. function handleKeyDown(event) {
  32986. var needsUpdate = false;
  32987. switch (event.keyCode) {
  32988. case scope.keys.UP:
  32989. pan(0, scope.keyPanSpeed);
  32990. needsUpdate = true;
  32991. break;
  32992. case scope.keys.BOTTOM:
  32993. pan(0, -scope.keyPanSpeed);
  32994. needsUpdate = true;
  32995. break;
  32996. case scope.keys.LEFT:
  32997. pan(scope.keyPanSpeed, 0);
  32998. needsUpdate = true;
  32999. break;
  33000. case scope.keys.RIGHT:
  33001. pan(-scope.keyPanSpeed, 0);
  33002. needsUpdate = true;
  33003. break;
  33004. }
  33005. if (needsUpdate) {
  33006. // prevent the browser from scrolling on cursor keys
  33007. event.preventDefault();
  33008. scope.update();
  33009. }
  33010. }
  33011. function handleTouchStartRotate(event) {
  33012. if (event.touches.length == 1) {
  33013. rotateStart.set(event.touches[0].pageX, event.touches[0].pageY);
  33014. } else {
  33015. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  33016. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  33017. rotateStart.set(x, y);
  33018. }
  33019. }
  33020. function handleTouchStartPan(event) {
  33021. if (event.touches.length == 1) {
  33022. panStart.set(event.touches[0].pageX, event.touches[0].pageY);
  33023. } else {
  33024. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  33025. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  33026. panStart.set(x, y);
  33027. }
  33028. }
  33029. function handleTouchStartDolly(event) {
  33030. var dx = event.touches[0].pageX - event.touches[1].pageX;
  33031. var dy = event.touches[0].pageY - event.touches[1].pageY;
  33032. var distance = Math.sqrt(dx * dx + dy * dy);
  33033. dollyStart.set(0, distance);
  33034. }
  33035. function handleTouchStartDollyPan(event) {
  33036. if (scope.enableZoom) handleTouchStartDolly(event);
  33037. if (scope.enablePan) handleTouchStartPan(event);
  33038. }
  33039. function handleTouchStartDollyRotate(event) {
  33040. if (scope.enableZoom) handleTouchStartDolly(event);
  33041. if (scope.enableRotate) handleTouchStartRotate(event);
  33042. }
  33043. function handleTouchMoveRotate(event) {
  33044. if (event.touches.length == 1) {
  33045. rotateEnd.set(event.touches[0].pageX, event.touches[0].pageY);
  33046. } else {
  33047. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  33048. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  33049. rotateEnd.set(x, y);
  33050. }
  33051. rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed);
  33052. var element = scope.domElement === document ? scope.domElement.body : scope.domElement;
  33053. rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); // yes, height
  33054. rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight);
  33055. rotateStart.copy(rotateEnd);
  33056. }
  33057. function handleTouchMovePan(event) {
  33058. if (event.touches.length == 1) {
  33059. panEnd.set(event.touches[0].pageX, event.touches[0].pageY);
  33060. } else {
  33061. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  33062. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  33063. panEnd.set(x, y);
  33064. }
  33065. panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed);
  33066. pan(panDelta.x, panDelta.y);
  33067. panStart.copy(panEnd);
  33068. }
  33069. function handleTouchMoveDolly(event) {
  33070. var dx = event.touches[0].pageX - event.touches[1].pageX;
  33071. var dy = event.touches[0].pageY - event.touches[1].pageY;
  33072. var distance = Math.sqrt(dx * dx + dy * dy);
  33073. dollyEnd.set(0, distance);
  33074. dollyDelta.set(0, Math.pow(dollyEnd.y / dollyStart.y, scope.zoomSpeed));
  33075. dollyIn(dollyDelta.y);
  33076. dollyStart.copy(dollyEnd);
  33077. }
  33078. function handleTouchMoveDollyPan(event) {
  33079. if (scope.enableZoom) handleTouchMoveDolly(event);
  33080. if (scope.enablePan) handleTouchMovePan(event);
  33081. }
  33082. function handleTouchMoveDollyRotate(event) {
  33083. if (scope.enableZoom) handleTouchMoveDolly(event);
  33084. if (scope.enableRotate) handleTouchMoveRotate(event);
  33085. }
  33086. function handleTouchEnd()
  33087. /*event*/
  33088. {} // no-op
  33089. //
  33090. // event handlers - FSM: listen for events and reset state
  33091. //
  33092. function onMouseDown(event) {
  33093. if (scope.enabled === false) return; // Prevent the browser from scrolling.
  33094. event.preventDefault(); // Manually set the focus since calling preventDefault above
  33095. // prevents the browser from setting it automatically.
  33096. scope.domElement.focus ? scope.domElement.focus() : window.focus();
  33097. switch (event.button) {
  33098. case 0:
  33099. switch (scope.mouseButtons.LEFT) {
  33100. case _threeModule.MOUSE.ROTATE:
  33101. if (event.ctrlKey || event.metaKey || event.shiftKey) {
  33102. if (scope.enablePan === false) return;
  33103. handleMouseDownPan(event);
  33104. state = STATE.PAN;
  33105. } else {
  33106. if (scope.enableRotate === false) return;
  33107. handleMouseDownRotate(event);
  33108. state = STATE.ROTATE;
  33109. }
  33110. break;
  33111. case _threeModule.MOUSE.PAN:
  33112. if (event.ctrlKey || event.metaKey || event.shiftKey) {
  33113. if (scope.enableRotate === false) return;
  33114. handleMouseDownRotate(event);
  33115. state = STATE.ROTATE;
  33116. } else {
  33117. if (scope.enablePan === false) return;
  33118. handleMouseDownPan(event);
  33119. state = STATE.PAN;
  33120. }
  33121. break;
  33122. default:
  33123. state = STATE.NONE;
  33124. }
  33125. break;
  33126. case 1:
  33127. switch (scope.mouseButtons.MIDDLE) {
  33128. case _threeModule.MOUSE.DOLLY:
  33129. if (scope.enableZoom === false) return;
  33130. handleMouseDownDolly(event);
  33131. state = STATE.DOLLY;
  33132. break;
  33133. default:
  33134. state = STATE.NONE;
  33135. }
  33136. break;
  33137. case 2:
  33138. switch (scope.mouseButtons.RIGHT) {
  33139. case _threeModule.MOUSE.ROTATE:
  33140. if (scope.enableRotate === false) return;
  33141. handleMouseDownRotate(event);
  33142. state = STATE.ROTATE;
  33143. break;
  33144. case _threeModule.MOUSE.PAN:
  33145. if (scope.enablePan === false) return;
  33146. handleMouseDownPan(event);
  33147. state = STATE.PAN;
  33148. break;
  33149. default:
  33150. state = STATE.NONE;
  33151. }
  33152. break;
  33153. }
  33154. if (state !== STATE.NONE) {
  33155. document.addEventListener('mousemove', onMouseMove, false);
  33156. document.addEventListener('mouseup', onMouseUp, false);
  33157. scope.dispatchEvent(startEvent);
  33158. }
  33159. }
  33160. function onMouseMove(event) {
  33161. if (scope.enabled === false) return;
  33162. event.preventDefault();
  33163. switch (state) {
  33164. case STATE.ROTATE:
  33165. if (scope.enableRotate === false) return;
  33166. handleMouseMoveRotate(event);
  33167. break;
  33168. case STATE.DOLLY:
  33169. if (scope.enableZoom === false) return;
  33170. handleMouseMoveDolly(event);
  33171. break;
  33172. case STATE.PAN:
  33173. if (scope.enablePan === false) return;
  33174. handleMouseMovePan(event);
  33175. break;
  33176. }
  33177. }
  33178. function onMouseUp(event) {
  33179. if (scope.enabled === false) return;
  33180. handleMouseUp(event);
  33181. document.removeEventListener('mousemove', onMouseMove, false);
  33182. document.removeEventListener('mouseup', onMouseUp, false);
  33183. scope.dispatchEvent(endEvent);
  33184. state = STATE.NONE;
  33185. }
  33186. function onMouseWheel(event) {
  33187. if (scope.enabled === false || scope.enableZoom === false || state !== STATE.NONE && state !== STATE.ROTATE) return;
  33188. event.preventDefault();
  33189. event.stopPropagation();
  33190. scope.dispatchEvent(startEvent);
  33191. handleMouseWheel(event);
  33192. scope.dispatchEvent(endEvent);
  33193. }
  33194. function onKeyDown(event) {
  33195. if (scope.enabled === false || scope.enableKeys === false || scope.enablePan === false) return;
  33196. handleKeyDown(event);
  33197. }
  33198. function onTouchStart(event) {
  33199. if (scope.enabled === false) return;
  33200. event.preventDefault();
  33201. switch (event.touches.length) {
  33202. case 1:
  33203. switch (scope.touches.ONE) {
  33204. case _threeModule.TOUCH.ROTATE:
  33205. if (scope.enableRotate === false) return;
  33206. handleTouchStartRotate(event);
  33207. state = STATE.TOUCH_ROTATE;
  33208. break;
  33209. case _threeModule.TOUCH.PAN:
  33210. if (scope.enablePan === false) return;
  33211. handleTouchStartPan(event);
  33212. state = STATE.TOUCH_PAN;
  33213. break;
  33214. default:
  33215. state = STATE.NONE;
  33216. }
  33217. break;
  33218. case 2:
  33219. switch (scope.touches.TWO) {
  33220. case _threeModule.TOUCH.DOLLY_PAN:
  33221. if (scope.enableZoom === false && scope.enablePan === false) return;
  33222. handleTouchStartDollyPan(event);
  33223. state = STATE.TOUCH_DOLLY_PAN;
  33224. break;
  33225. case _threeModule.TOUCH.DOLLY_ROTATE:
  33226. if (scope.enableZoom === false && scope.enableRotate === false) return;
  33227. handleTouchStartDollyRotate(event);
  33228. state = STATE.TOUCH_DOLLY_ROTATE;
  33229. break;
  33230. default:
  33231. state = STATE.NONE;
  33232. }
  33233. break;
  33234. default:
  33235. state = STATE.NONE;
  33236. }
  33237. if (state !== STATE.NONE) {
  33238. scope.dispatchEvent(startEvent);
  33239. }
  33240. }
  33241. function onTouchMove(event) {
  33242. if (scope.enabled === false) return;
  33243. event.preventDefault();
  33244. event.stopPropagation();
  33245. switch (state) {
  33246. case STATE.TOUCH_ROTATE:
  33247. if (scope.enableRotate === false) return;
  33248. handleTouchMoveRotate(event);
  33249. scope.update();
  33250. break;
  33251. case STATE.TOUCH_PAN:
  33252. if (scope.enablePan === false) return;
  33253. handleTouchMovePan(event);
  33254. scope.update();
  33255. break;
  33256. case STATE.TOUCH_DOLLY_PAN:
  33257. if (scope.enableZoom === false && scope.enablePan === false) return;
  33258. handleTouchMoveDollyPan(event);
  33259. scope.update();
  33260. break;
  33261. case STATE.TOUCH_DOLLY_ROTATE:
  33262. if (scope.enableZoom === false && scope.enableRotate === false) return;
  33263. handleTouchMoveDollyRotate(event);
  33264. scope.update();
  33265. break;
  33266. default:
  33267. state = STATE.NONE;
  33268. }
  33269. }
  33270. function onTouchEnd(event) {
  33271. if (scope.enabled === false) return;
  33272. handleTouchEnd(event);
  33273. scope.dispatchEvent(endEvent);
  33274. state = STATE.NONE;
  33275. }
  33276. function onContextMenu(event) {
  33277. if (scope.enabled === false) return;
  33278. event.preventDefault();
  33279. } //
  33280. scope.domElement.addEventListener('contextmenu', onContextMenu, false);
  33281. scope.domElement.addEventListener('mousedown', onMouseDown, false);
  33282. scope.domElement.addEventListener('wheel', onMouseWheel, false);
  33283. scope.domElement.addEventListener('touchstart', onTouchStart, false);
  33284. scope.domElement.addEventListener('touchend', onTouchEnd, false);
  33285. scope.domElement.addEventListener('touchmove', onTouchMove, false);
  33286. window.addEventListener('keydown', onKeyDown, false); // force an update at start
  33287. this.update();
  33288. };
  33289. exports.OrbitControls = OrbitControls;
  33290. OrbitControls.prototype = Object.create(_threeModule.EventDispatcher.prototype);
  33291. OrbitControls.prototype.constructor = OrbitControls; // This set of controls performs orbiting, dollying (zooming), and panning.
  33292. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
  33293. // This is very similar to OrbitControls, another set of touch behavior
  33294. //
  33295. // Orbit - right mouse, or left mouse + ctrl/meta/shiftKey / touch: two-finger rotate
  33296. // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
  33297. // Pan - left mouse, or arrow keys / touch: one-finger move
  33298. var MapControls = function (object, domElement) {
  33299. OrbitControls.call(this, object, domElement);
  33300. this.mouseButtons.LEFT = _threeModule.MOUSE.PAN;
  33301. this.mouseButtons.RIGHT = _threeModule.MOUSE.ROTATE;
  33302. this.touches.ONE = _threeModule.TOUCH.PAN;
  33303. this.touches.TWO = _threeModule.TOUCH.DOLLY_ROTATE;
  33304. };
  33305. exports.MapControls = MapControls;
  33306. MapControls.prototype = Object.create(_threeModule.EventDispatcher.prototype);
  33307. MapControls.prototype.constructor = MapControls;
  33308. },{"../../../build/three.module.js":"../node_modules/three/build/three.module.js"}],"../node_modules/three/examples/jsm/libs/dat.gui.module.js":[function(require,module,exports) {
  33309. "use strict";
  33310. Object.defineProperty(exports, "__esModule", {
  33311. value: true
  33312. });
  33313. exports.default = exports.GUI = exports.gui = exports.dom = exports.controllers = exports.color = void 0;
  33314. /**
  33315. * dat-gui JavaScript Controller Library
  33316. * http://code.google.com/p/dat-gui
  33317. *
  33318. * Copyright 2011 Data Arts Team, Google Creative Lab
  33319. *
  33320. * Licensed under the Apache License, Version 2.0 (the "License");
  33321. * you may not use this file except in compliance with the License.
  33322. * You may obtain a copy of the License at
  33323. *
  33324. * http://www.apache.org/licenses/LICENSE-2.0
  33325. */
  33326. function ___$insertStyle(css) {
  33327. if (!css) {
  33328. return;
  33329. }
  33330. if (typeof window === 'undefined') {
  33331. return;
  33332. }
  33333. var style = document.createElement('style');
  33334. style.setAttribute('type', 'text/css');
  33335. style.innerHTML = css;
  33336. document.head.appendChild(style);
  33337. return css;
  33338. }
  33339. function colorToString(color, forceCSSHex) {
  33340. var colorFormat = color.__state.conversionName.toString();
  33341. var r = Math.round(color.r);
  33342. var g = Math.round(color.g);
  33343. var b = Math.round(color.b);
  33344. var a = color.a;
  33345. var h = Math.round(color.h);
  33346. var s = color.s.toFixed(1);
  33347. var v = color.v.toFixed(1);
  33348. if (forceCSSHex || colorFormat === 'THREE_CHAR_HEX' || colorFormat === 'SIX_CHAR_HEX') {
  33349. var str = color.hex.toString(16);
  33350. while (str.length < 6) {
  33351. str = '0' + str;
  33352. }
  33353. return '#' + str;
  33354. } else if (colorFormat === 'CSS_RGB') {
  33355. return 'rgb(' + r + ',' + g + ',' + b + ')';
  33356. } else if (colorFormat === 'CSS_RGBA') {
  33357. return 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
  33358. } else if (colorFormat === 'HEX') {
  33359. return '0x' + color.hex.toString(16);
  33360. } else if (colorFormat === 'RGB_ARRAY') {
  33361. return '[' + r + ',' + g + ',' + b + ']';
  33362. } else if (colorFormat === 'RGBA_ARRAY') {
  33363. return '[' + r + ',' + g + ',' + b + ',' + a + ']';
  33364. } else if (colorFormat === 'RGB_OBJ') {
  33365. return '{r:' + r + ',g:' + g + ',b:' + b + '}';
  33366. } else if (colorFormat === 'RGBA_OBJ') {
  33367. return '{r:' + r + ',g:' + g + ',b:' + b + ',a:' + a + '}';
  33368. } else if (colorFormat === 'HSV_OBJ') {
  33369. return '{h:' + h + ',s:' + s + ',v:' + v + '}';
  33370. } else if (colorFormat === 'HSVA_OBJ') {
  33371. return '{h:' + h + ',s:' + s + ',v:' + v + ',a:' + a + '}';
  33372. }
  33373. return 'unknown format';
  33374. }
  33375. var ARR_EACH = Array.prototype.forEach;
  33376. var ARR_SLICE = Array.prototype.slice;
  33377. var Common = {
  33378. BREAK: {},
  33379. extend: function extend(target) {
  33380. this.each(ARR_SLICE.call(arguments, 1), function (obj) {
  33381. var keys = this.isObject(obj) ? Object.keys(obj) : [];
  33382. keys.forEach(function (key) {
  33383. if (!this.isUndefined(obj[key])) {
  33384. target[key] = obj[key];
  33385. }
  33386. }.bind(this));
  33387. }, this);
  33388. return target;
  33389. },
  33390. defaults: function defaults(target) {
  33391. this.each(ARR_SLICE.call(arguments, 1), function (obj) {
  33392. var keys = this.isObject(obj) ? Object.keys(obj) : [];
  33393. keys.forEach(function (key) {
  33394. if (this.isUndefined(target[key])) {
  33395. target[key] = obj[key];
  33396. }
  33397. }.bind(this));
  33398. }, this);
  33399. return target;
  33400. },
  33401. compose: function compose() {
  33402. var toCall = ARR_SLICE.call(arguments);
  33403. return function () {
  33404. var args = ARR_SLICE.call(arguments);
  33405. for (var i = toCall.length - 1; i >= 0; i--) {
  33406. args = [toCall[i].apply(this, args)];
  33407. }
  33408. return args[0];
  33409. };
  33410. },
  33411. each: function each(obj, itr, scope) {
  33412. if (!obj) {
  33413. return;
  33414. }
  33415. if (ARR_EACH && obj.forEach && obj.forEach === ARR_EACH) {
  33416. obj.forEach(itr, scope);
  33417. } else if (obj.length === obj.length + 0) {
  33418. var key = void 0;
  33419. var l = void 0;
  33420. for (key = 0, l = obj.length; key < l; key++) {
  33421. if (key in obj && itr.call(scope, obj[key], key) === this.BREAK) {
  33422. return;
  33423. }
  33424. }
  33425. } else {
  33426. for (var _key in obj) {
  33427. if (itr.call(scope, obj[_key], _key) === this.BREAK) {
  33428. return;
  33429. }
  33430. }
  33431. }
  33432. },
  33433. defer: function defer(fnc) {
  33434. setTimeout(fnc, 0);
  33435. },
  33436. debounce: function debounce(func, threshold, callImmediately) {
  33437. var timeout = void 0;
  33438. return function () {
  33439. var obj = this;
  33440. var args = arguments;
  33441. function delayed() {
  33442. timeout = null;
  33443. if (!callImmediately) func.apply(obj, args);
  33444. }
  33445. var callNow = callImmediately || !timeout;
  33446. clearTimeout(timeout);
  33447. timeout = setTimeout(delayed, threshold);
  33448. if (callNow) {
  33449. func.apply(obj, args);
  33450. }
  33451. };
  33452. },
  33453. toArray: function toArray(obj) {
  33454. if (obj.toArray) return obj.toArray();
  33455. return ARR_SLICE.call(obj);
  33456. },
  33457. isUndefined: function isUndefined(obj) {
  33458. return obj === undefined;
  33459. },
  33460. isNull: function isNull(obj) {
  33461. return obj === null;
  33462. },
  33463. isNaN: function (_isNaN) {
  33464. function isNaN() {
  33465. return _isNaN.apply(this, arguments);
  33466. }
  33467. isNaN.toString = function () {
  33468. return _isNaN.toString();
  33469. };
  33470. return isNaN;
  33471. }(function (obj) {
  33472. return isNaN(obj);
  33473. }),
  33474. isArray: Array.isArray || function (obj) {
  33475. return obj.constructor === Array;
  33476. },
  33477. isObject: function isObject(obj) {
  33478. return obj === Object(obj);
  33479. },
  33480. isNumber: function isNumber(obj) {
  33481. return obj === obj + 0;
  33482. },
  33483. isString: function isString(obj) {
  33484. return obj === obj + '';
  33485. },
  33486. isBoolean: function isBoolean(obj) {
  33487. return obj === false || obj === true;
  33488. },
  33489. isFunction: function isFunction(obj) {
  33490. return Object.prototype.toString.call(obj) === '[object Function]';
  33491. }
  33492. };
  33493. var INTERPRETATIONS = [{
  33494. litmus: Common.isString,
  33495. conversions: {
  33496. THREE_CHAR_HEX: {
  33497. read: function read(original) {
  33498. var test = original.match(/^#([A-F0-9])([A-F0-9])([A-F0-9])$/i);
  33499. if (test === null) {
  33500. return false;
  33501. }
  33502. return {
  33503. space: 'HEX',
  33504. hex: parseInt('0x' + test[1].toString() + test[1].toString() + test[2].toString() + test[2].toString() + test[3].toString() + test[3].toString(), 0)
  33505. };
  33506. },
  33507. write: colorToString
  33508. },
  33509. SIX_CHAR_HEX: {
  33510. read: function read(original) {
  33511. var test = original.match(/^#([A-F0-9]{6})$/i);
  33512. if (test === null) {
  33513. return false;
  33514. }
  33515. return {
  33516. space: 'HEX',
  33517. hex: parseInt('0x' + test[1].toString(), 0)
  33518. };
  33519. },
  33520. write: colorToString
  33521. },
  33522. CSS_RGB: {
  33523. read: function read(original) {
  33524. var test = original.match(/^rgb\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\)/);
  33525. if (test === null) {
  33526. return false;
  33527. }
  33528. return {
  33529. space: 'RGB',
  33530. r: parseFloat(test[1]),
  33531. g: parseFloat(test[2]),
  33532. b: parseFloat(test[3])
  33533. };
  33534. },
  33535. write: colorToString
  33536. },
  33537. CSS_RGBA: {
  33538. read: function read(original) {
  33539. var test = original.match(/^rgba\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\)/);
  33540. if (test === null) {
  33541. return false;
  33542. }
  33543. return {
  33544. space: 'RGB',
  33545. r: parseFloat(test[1]),
  33546. g: parseFloat(test[2]),
  33547. b: parseFloat(test[3]),
  33548. a: parseFloat(test[4])
  33549. };
  33550. },
  33551. write: colorToString
  33552. }
  33553. }
  33554. }, {
  33555. litmus: Common.isNumber,
  33556. conversions: {
  33557. HEX: {
  33558. read: function read(original) {
  33559. return {
  33560. space: 'HEX',
  33561. hex: original,
  33562. conversionName: 'HEX'
  33563. };
  33564. },
  33565. write: function write(color) {
  33566. return color.hex;
  33567. }
  33568. }
  33569. }
  33570. }, {
  33571. litmus: Common.isArray,
  33572. conversions: {
  33573. RGB_ARRAY: {
  33574. read: function read(original) {
  33575. if (original.length !== 3) {
  33576. return false;
  33577. }
  33578. return {
  33579. space: 'RGB',
  33580. r: original[0],
  33581. g: original[1],
  33582. b: original[2]
  33583. };
  33584. },
  33585. write: function write(color) {
  33586. return [color.r, color.g, color.b];
  33587. }
  33588. },
  33589. RGBA_ARRAY: {
  33590. read: function read(original) {
  33591. if (original.length !== 4) return false;
  33592. return {
  33593. space: 'RGB',
  33594. r: original[0],
  33595. g: original[1],
  33596. b: original[2],
  33597. a: original[3]
  33598. };
  33599. },
  33600. write: function write(color) {
  33601. return [color.r, color.g, color.b, color.a];
  33602. }
  33603. }
  33604. }
  33605. }, {
  33606. litmus: Common.isObject,
  33607. conversions: {
  33608. RGBA_OBJ: {
  33609. read: function read(original) {
  33610. if (Common.isNumber(original.r) && Common.isNumber(original.g) && Common.isNumber(original.b) && Common.isNumber(original.a)) {
  33611. return {
  33612. space: 'RGB',
  33613. r: original.r,
  33614. g: original.g,
  33615. b: original.b,
  33616. a: original.a
  33617. };
  33618. }
  33619. return false;
  33620. },
  33621. write: function write(color) {
  33622. return {
  33623. r: color.r,
  33624. g: color.g,
  33625. b: color.b,
  33626. a: color.a
  33627. };
  33628. }
  33629. },
  33630. RGB_OBJ: {
  33631. read: function read(original) {
  33632. if (Common.isNumber(original.r) && Common.isNumber(original.g) && Common.isNumber(original.b)) {
  33633. return {
  33634. space: 'RGB',
  33635. r: original.r,
  33636. g: original.g,
  33637. b: original.b
  33638. };
  33639. }
  33640. return false;
  33641. },
  33642. write: function write(color) {
  33643. return {
  33644. r: color.r,
  33645. g: color.g,
  33646. b: color.b
  33647. };
  33648. }
  33649. },
  33650. HSVA_OBJ: {
  33651. read: function read(original) {
  33652. if (Common.isNumber(original.h) && Common.isNumber(original.s) && Common.isNumber(original.v) && Common.isNumber(original.a)) {
  33653. return {
  33654. space: 'HSV',
  33655. h: original.h,
  33656. s: original.s,
  33657. v: original.v,
  33658. a: original.a
  33659. };
  33660. }
  33661. return false;
  33662. },
  33663. write: function write(color) {
  33664. return {
  33665. h: color.h,
  33666. s: color.s,
  33667. v: color.v,
  33668. a: color.a
  33669. };
  33670. }
  33671. },
  33672. HSV_OBJ: {
  33673. read: function read(original) {
  33674. if (Common.isNumber(original.h) && Common.isNumber(original.s) && Common.isNumber(original.v)) {
  33675. return {
  33676. space: 'HSV',
  33677. h: original.h,
  33678. s: original.s,
  33679. v: original.v
  33680. };
  33681. }
  33682. return false;
  33683. },
  33684. write: function write(color) {
  33685. return {
  33686. h: color.h,
  33687. s: color.s,
  33688. v: color.v
  33689. };
  33690. }
  33691. }
  33692. }
  33693. }];
  33694. var result = void 0;
  33695. var toReturn = void 0;
  33696. var interpret = function interpret() {
  33697. toReturn = false;
  33698. var original = arguments.length > 1 ? Common.toArray(arguments) : arguments[0];
  33699. Common.each(INTERPRETATIONS, function (family) {
  33700. if (family.litmus(original)) {
  33701. Common.each(family.conversions, function (conversion, conversionName) {
  33702. result = conversion.read(original);
  33703. if (toReturn === false && result !== false) {
  33704. toReturn = result;
  33705. result.conversionName = conversionName;
  33706. result.conversion = conversion;
  33707. return Common.BREAK;
  33708. }
  33709. });
  33710. return Common.BREAK;
  33711. }
  33712. });
  33713. return toReturn;
  33714. };
  33715. var tmpComponent = void 0;
  33716. var ColorMath = {
  33717. hsv_to_rgb: function hsv_to_rgb(h, s, v) {
  33718. var hi = Math.floor(h / 60) % 6;
  33719. var f = h / 60 - Math.floor(h / 60);
  33720. var p = v * (1.0 - s);
  33721. var q = v * (1.0 - f * s);
  33722. var t = v * (1.0 - (1.0 - f) * s);
  33723. var c = [[v, t, p], [q, v, p], [p, v, t], [p, q, v], [t, p, v], [v, p, q]][hi];
  33724. return {
  33725. r: c[0] * 255,
  33726. g: c[1] * 255,
  33727. b: c[2] * 255
  33728. };
  33729. },
  33730. rgb_to_hsv: function rgb_to_hsv(r, g, b) {
  33731. var min = Math.min(r, g, b);
  33732. var max = Math.max(r, g, b);
  33733. var delta = max - min;
  33734. var h = void 0;
  33735. var s = void 0;
  33736. if (max !== 0) {
  33737. s = delta / max;
  33738. } else {
  33739. return {
  33740. h: NaN,
  33741. s: 0,
  33742. v: 0
  33743. };
  33744. }
  33745. if (r === max) {
  33746. h = (g - b) / delta;
  33747. } else if (g === max) {
  33748. h = 2 + (b - r) / delta;
  33749. } else {
  33750. h = 4 + (r - g) / delta;
  33751. }
  33752. h /= 6;
  33753. if (h < 0) {
  33754. h += 1;
  33755. }
  33756. return {
  33757. h: h * 360,
  33758. s: s,
  33759. v: max / 255
  33760. };
  33761. },
  33762. rgb_to_hex: function rgb_to_hex(r, g, b) {
  33763. var hex = this.hex_with_component(0, 2, r);
  33764. hex = this.hex_with_component(hex, 1, g);
  33765. hex = this.hex_with_component(hex, 0, b);
  33766. return hex;
  33767. },
  33768. component_from_hex: function component_from_hex(hex, componentIndex) {
  33769. return hex >> componentIndex * 8 & 0xFF;
  33770. },
  33771. hex_with_component: function hex_with_component(hex, componentIndex, value) {
  33772. return value << (tmpComponent = componentIndex * 8) | hex & ~(0xFF << tmpComponent);
  33773. }
  33774. };
  33775. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  33776. return typeof obj;
  33777. } : function (obj) {
  33778. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  33779. };
  33780. var classCallCheck = function (instance, Constructor) {
  33781. if (!(instance instanceof Constructor)) {
  33782. throw new TypeError("Cannot call a class as a function");
  33783. }
  33784. };
  33785. var createClass = function () {
  33786. function defineProperties(target, props) {
  33787. for (var i = 0; i < props.length; i++) {
  33788. var descriptor = props[i];
  33789. descriptor.enumerable = descriptor.enumerable || false;
  33790. descriptor.configurable = true;
  33791. if ("value" in descriptor) descriptor.writable = true;
  33792. Object.defineProperty(target, descriptor.key, descriptor);
  33793. }
  33794. }
  33795. return function (Constructor, protoProps, staticProps) {
  33796. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  33797. if (staticProps) defineProperties(Constructor, staticProps);
  33798. return Constructor;
  33799. };
  33800. }();
  33801. var get = function get(object, property, receiver) {
  33802. if (object === null) object = Function.prototype;
  33803. var desc = Object.getOwnPropertyDescriptor(object, property);
  33804. if (desc === undefined) {
  33805. var parent = Object.getPrototypeOf(object);
  33806. if (parent === null) {
  33807. return undefined;
  33808. } else {
  33809. return get(parent, property, receiver);
  33810. }
  33811. } else if ("value" in desc) {
  33812. return desc.value;
  33813. } else {
  33814. var getter = desc.get;
  33815. if (getter === undefined) {
  33816. return undefined;
  33817. }
  33818. return getter.call(receiver);
  33819. }
  33820. };
  33821. var inherits = function (subClass, superClass) {
  33822. if (typeof superClass !== "function" && superClass !== null) {
  33823. throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
  33824. }
  33825. subClass.prototype = Object.create(superClass && superClass.prototype, {
  33826. constructor: {
  33827. value: subClass,
  33828. enumerable: false,
  33829. writable: true,
  33830. configurable: true
  33831. }
  33832. });
  33833. if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
  33834. };
  33835. var possibleConstructorReturn = function (self, call) {
  33836. if (!self) {
  33837. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  33838. }
  33839. return call && (typeof call === "object" || typeof call === "function") ? call : self;
  33840. };
  33841. var Color = function () {
  33842. function Color() {
  33843. classCallCheck(this, Color);
  33844. this.__state = interpret.apply(this, arguments);
  33845. if (this.__state === false) {
  33846. throw new Error('Failed to interpret color arguments');
  33847. }
  33848. this.__state.a = this.__state.a || 1;
  33849. }
  33850. createClass(Color, [{
  33851. key: 'toString',
  33852. value: function toString() {
  33853. return colorToString(this);
  33854. }
  33855. }, {
  33856. key: 'toHexString',
  33857. value: function toHexString() {
  33858. return colorToString(this, true);
  33859. }
  33860. }, {
  33861. key: 'toOriginal',
  33862. value: function toOriginal() {
  33863. return this.__state.conversion.write(this);
  33864. }
  33865. }]);
  33866. return Color;
  33867. }();
  33868. function defineRGBComponent(target, component, componentHexIndex) {
  33869. Object.defineProperty(target, component, {
  33870. get: function get$$1() {
  33871. if (this.__state.space === 'RGB') {
  33872. return this.__state[component];
  33873. }
  33874. Color.recalculateRGB(this, component, componentHexIndex);
  33875. return this.__state[component];
  33876. },
  33877. set: function set$$1(v) {
  33878. if (this.__state.space !== 'RGB') {
  33879. Color.recalculateRGB(this, component, componentHexIndex);
  33880. this.__state.space = 'RGB';
  33881. }
  33882. this.__state[component] = v;
  33883. }
  33884. });
  33885. }
  33886. function defineHSVComponent(target, component) {
  33887. Object.defineProperty(target, component, {
  33888. get: function get$$1() {
  33889. if (this.__state.space === 'HSV') {
  33890. return this.__state[component];
  33891. }
  33892. Color.recalculateHSV(this);
  33893. return this.__state[component];
  33894. },
  33895. set: function set$$1(v) {
  33896. if (this.__state.space !== 'HSV') {
  33897. Color.recalculateHSV(this);
  33898. this.__state.space = 'HSV';
  33899. }
  33900. this.__state[component] = v;
  33901. }
  33902. });
  33903. }
  33904. Color.recalculateRGB = function (color, component, componentHexIndex) {
  33905. if (color.__state.space === 'HEX') {
  33906. color.__state[component] = ColorMath.component_from_hex(color.__state.hex, componentHexIndex);
  33907. } else if (color.__state.space === 'HSV') {
  33908. Common.extend(color.__state, ColorMath.hsv_to_rgb(color.__state.h, color.__state.s, color.__state.v));
  33909. } else {
  33910. throw new Error('Corrupted color state');
  33911. }
  33912. };
  33913. Color.recalculateHSV = function (color) {
  33914. var result = ColorMath.rgb_to_hsv(color.r, color.g, color.b);
  33915. Common.extend(color.__state, {
  33916. s: result.s,
  33917. v: result.v
  33918. });
  33919. if (!Common.isNaN(result.h)) {
  33920. color.__state.h = result.h;
  33921. } else if (Common.isUndefined(color.__state.h)) {
  33922. color.__state.h = 0;
  33923. }
  33924. };
  33925. Color.COMPONENTS = ['r', 'g', 'b', 'h', 's', 'v', 'hex', 'a'];
  33926. defineRGBComponent(Color.prototype, 'r', 2);
  33927. defineRGBComponent(Color.prototype, 'g', 1);
  33928. defineRGBComponent(Color.prototype, 'b', 0);
  33929. defineHSVComponent(Color.prototype, 'h');
  33930. defineHSVComponent(Color.prototype, 's');
  33931. defineHSVComponent(Color.prototype, 'v');
  33932. Object.defineProperty(Color.prototype, 'a', {
  33933. get: function get$$1() {
  33934. return this.__state.a;
  33935. },
  33936. set: function set$$1(v) {
  33937. this.__state.a = v;
  33938. }
  33939. });
  33940. Object.defineProperty(Color.prototype, 'hex', {
  33941. get: function get$$1() {
  33942. if (!this.__state.space !== 'HEX') {
  33943. this.__state.hex = ColorMath.rgb_to_hex(this.r, this.g, this.b);
  33944. }
  33945. return this.__state.hex;
  33946. },
  33947. set: function set$$1(v) {
  33948. this.__state.space = 'HEX';
  33949. this.__state.hex = v;
  33950. }
  33951. });
  33952. var Controller = function () {
  33953. function Controller(object, property) {
  33954. classCallCheck(this, Controller);
  33955. this.initialValue = object[property];
  33956. this.domElement = document.createElement('div');
  33957. this.object = object;
  33958. this.property = property;
  33959. this.__onChange = undefined;
  33960. this.__onFinishChange = undefined;
  33961. }
  33962. createClass(Controller, [{
  33963. key: 'onChange',
  33964. value: function onChange(fnc) {
  33965. this.__onChange = fnc;
  33966. return this;
  33967. }
  33968. }, {
  33969. key: 'onFinishChange',
  33970. value: function onFinishChange(fnc) {
  33971. this.__onFinishChange = fnc;
  33972. return this;
  33973. }
  33974. }, {
  33975. key: 'setValue',
  33976. value: function setValue(newValue) {
  33977. this.object[this.property] = newValue;
  33978. if (this.__onChange) {
  33979. this.__onChange.call(this, newValue);
  33980. }
  33981. this.updateDisplay();
  33982. return this;
  33983. }
  33984. }, {
  33985. key: 'getValue',
  33986. value: function getValue() {
  33987. return this.object[this.property];
  33988. }
  33989. }, {
  33990. key: 'updateDisplay',
  33991. value: function updateDisplay() {
  33992. return this;
  33993. }
  33994. }, {
  33995. key: 'isModified',
  33996. value: function isModified() {
  33997. return this.initialValue !== this.getValue();
  33998. }
  33999. }]);
  34000. return Controller;
  34001. }();
  34002. var EVENT_MAP = {
  34003. HTMLEvents: ['change'],
  34004. MouseEvents: ['click', 'mousemove', 'mousedown', 'mouseup', 'mouseover'],
  34005. KeyboardEvents: ['keydown']
  34006. };
  34007. var EVENT_MAP_INV = {};
  34008. Common.each(EVENT_MAP, function (v, k) {
  34009. Common.each(v, function (e) {
  34010. EVENT_MAP_INV[e] = k;
  34011. });
  34012. });
  34013. var CSS_VALUE_PIXELS = /(\d+(\.\d+)?)px/;
  34014. function cssValueToPixels(val) {
  34015. if (val === '0' || Common.isUndefined(val)) {
  34016. return 0;
  34017. }
  34018. var match = val.match(CSS_VALUE_PIXELS);
  34019. if (!Common.isNull(match)) {
  34020. return parseFloat(match[1]);
  34021. }
  34022. return 0;
  34023. }
  34024. var dom = {
  34025. makeSelectable: function makeSelectable(elem, selectable) {
  34026. if (elem === undefined || elem.style === undefined) return;
  34027. elem.onselectstart = selectable ? function () {
  34028. return false;
  34029. } : function () {};
  34030. elem.style.MozUserSelect = selectable ? 'auto' : 'none';
  34031. elem.style.KhtmlUserSelect = selectable ? 'auto' : 'none';
  34032. elem.unselectable = selectable ? 'on' : 'off';
  34033. },
  34034. makeFullscreen: function makeFullscreen(elem, hor, vert) {
  34035. var vertical = vert;
  34036. var horizontal = hor;
  34037. if (Common.isUndefined(horizontal)) {
  34038. horizontal = true;
  34039. }
  34040. if (Common.isUndefined(vertical)) {
  34041. vertical = true;
  34042. }
  34043. elem.style.position = 'absolute';
  34044. if (horizontal) {
  34045. elem.style.left = 0;
  34046. elem.style.right = 0;
  34047. }
  34048. if (vertical) {
  34049. elem.style.top = 0;
  34050. elem.style.bottom = 0;
  34051. }
  34052. },
  34053. fakeEvent: function fakeEvent(elem, eventType, pars, aux) {
  34054. var params = pars || {};
  34055. var className = EVENT_MAP_INV[eventType];
  34056. if (!className) {
  34057. throw new Error('Event type ' + eventType + ' not supported.');
  34058. }
  34059. var evt = document.createEvent(className);
  34060. switch (className) {
  34061. case 'MouseEvents':
  34062. {
  34063. var clientX = params.x || params.clientX || 0;
  34064. var clientY = params.y || params.clientY || 0;
  34065. evt.initMouseEvent(eventType, params.bubbles || false, params.cancelable || true, window, params.clickCount || 1, 0, 0, clientX, clientY, false, false, false, false, 0, null);
  34066. break;
  34067. }
  34068. case 'KeyboardEvents':
  34069. {
  34070. var init = evt.initKeyboardEvent || evt.initKeyEvent;
  34071. Common.defaults(params, {
  34072. cancelable: true,
  34073. ctrlKey: false,
  34074. altKey: false,
  34075. shiftKey: false,
  34076. metaKey: false,
  34077. keyCode: undefined,
  34078. charCode: undefined
  34079. });
  34080. init(eventType, params.bubbles || false, params.cancelable, window, params.ctrlKey, params.altKey, params.shiftKey, params.metaKey, params.keyCode, params.charCode);
  34081. break;
  34082. }
  34083. default:
  34084. {
  34085. evt.initEvent(eventType, params.bubbles || false, params.cancelable || true);
  34086. break;
  34087. }
  34088. }
  34089. Common.defaults(evt, aux);
  34090. elem.dispatchEvent(evt);
  34091. },
  34092. bind: function bind(elem, event, func, newBool) {
  34093. var bool = newBool || false;
  34094. if (elem.addEventListener) {
  34095. elem.addEventListener(event, func, bool);
  34096. } else if (elem.attachEvent) {
  34097. elem.attachEvent('on' + event, func);
  34098. }
  34099. return dom;
  34100. },
  34101. unbind: function unbind(elem, event, func, newBool) {
  34102. var bool = newBool || false;
  34103. if (elem.removeEventListener) {
  34104. elem.removeEventListener(event, func, bool);
  34105. } else if (elem.detachEvent) {
  34106. elem.detachEvent('on' + event, func);
  34107. }
  34108. return dom;
  34109. },
  34110. addClass: function addClass(elem, className) {
  34111. if (elem.className === undefined) {
  34112. elem.className = className;
  34113. } else if (elem.className !== className) {
  34114. var classes = elem.className.split(/ +/);
  34115. if (classes.indexOf(className) === -1) {
  34116. classes.push(className);
  34117. elem.className = classes.join(' ').replace(/^\s+/, '').replace(/\s+$/, '');
  34118. }
  34119. }
  34120. return dom;
  34121. },
  34122. removeClass: function removeClass(elem, className) {
  34123. if (className) {
  34124. if (elem.className === className) {
  34125. elem.removeAttribute('class');
  34126. } else {
  34127. var classes = elem.className.split(/ +/);
  34128. var index = classes.indexOf(className);
  34129. if (index !== -1) {
  34130. classes.splice(index, 1);
  34131. elem.className = classes.join(' ');
  34132. }
  34133. }
  34134. } else {
  34135. elem.className = undefined;
  34136. }
  34137. return dom;
  34138. },
  34139. hasClass: function hasClass(elem, className) {
  34140. return new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)').test(elem.className) || false;
  34141. },
  34142. getWidth: function getWidth(elem) {
  34143. var style = getComputedStyle(elem);
  34144. return cssValueToPixels(style['border-left-width']) + cssValueToPixels(style['border-right-width']) + cssValueToPixels(style['padding-left']) + cssValueToPixels(style['padding-right']) + cssValueToPixels(style.width);
  34145. },
  34146. getHeight: function getHeight(elem) {
  34147. var style = getComputedStyle(elem);
  34148. return cssValueToPixels(style['border-top-width']) + cssValueToPixels(style['border-bottom-width']) + cssValueToPixels(style['padding-top']) + cssValueToPixels(style['padding-bottom']) + cssValueToPixels(style.height);
  34149. },
  34150. getOffset: function getOffset(el) {
  34151. var elem = el;
  34152. var offset = {
  34153. left: 0,
  34154. top: 0
  34155. };
  34156. if (elem.offsetParent) {
  34157. do {
  34158. offset.left += elem.offsetLeft;
  34159. offset.top += elem.offsetTop;
  34160. elem = elem.offsetParent;
  34161. } while (elem);
  34162. }
  34163. return offset;
  34164. },
  34165. isActive: function isActive(elem) {
  34166. return elem === document.activeElement && (elem.type || elem.href);
  34167. }
  34168. };
  34169. var BooleanController = function (_Controller) {
  34170. inherits(BooleanController, _Controller);
  34171. function BooleanController(object, property) {
  34172. classCallCheck(this, BooleanController);
  34173. var _this2 = possibleConstructorReturn(this, (BooleanController.__proto__ || Object.getPrototypeOf(BooleanController)).call(this, object, property));
  34174. var _this = _this2;
  34175. _this2.__prev = _this2.getValue();
  34176. _this2.__checkbox = document.createElement('input');
  34177. _this2.__checkbox.setAttribute('type', 'checkbox');
  34178. function onChange() {
  34179. _this.setValue(!_this.__prev);
  34180. }
  34181. dom.bind(_this2.__checkbox, 'change', onChange, false);
  34182. _this2.domElement.appendChild(_this2.__checkbox);
  34183. _this2.updateDisplay();
  34184. return _this2;
  34185. }
  34186. createClass(BooleanController, [{
  34187. key: 'setValue',
  34188. value: function setValue(v) {
  34189. var toReturn = get(BooleanController.prototype.__proto__ || Object.getPrototypeOf(BooleanController.prototype), 'setValue', this).call(this, v);
  34190. if (this.__onFinishChange) {
  34191. this.__onFinishChange.call(this, this.getValue());
  34192. }
  34193. this.__prev = this.getValue();
  34194. return toReturn;
  34195. }
  34196. }, {
  34197. key: 'updateDisplay',
  34198. value: function updateDisplay() {
  34199. if (this.getValue() === true) {
  34200. this.__checkbox.setAttribute('checked', 'checked');
  34201. this.__checkbox.checked = true;
  34202. this.__prev = true;
  34203. } else {
  34204. this.__checkbox.checked = false;
  34205. this.__prev = false;
  34206. }
  34207. return get(BooleanController.prototype.__proto__ || Object.getPrototypeOf(BooleanController.prototype), 'updateDisplay', this).call(this);
  34208. }
  34209. }]);
  34210. return BooleanController;
  34211. }(Controller);
  34212. var OptionController = function (_Controller) {
  34213. inherits(OptionController, _Controller);
  34214. function OptionController(object, property, opts) {
  34215. classCallCheck(this, OptionController);
  34216. var _this2 = possibleConstructorReturn(this, (OptionController.__proto__ || Object.getPrototypeOf(OptionController)).call(this, object, property));
  34217. var options = opts;
  34218. var _this = _this2;
  34219. _this2.__select = document.createElement('select');
  34220. if (Common.isArray(options)) {
  34221. var map = {};
  34222. Common.each(options, function (element) {
  34223. map[element] = element;
  34224. });
  34225. options = map;
  34226. }
  34227. Common.each(options, function (value, key) {
  34228. var opt = document.createElement('option');
  34229. opt.innerHTML = key;
  34230. opt.setAttribute('value', value);
  34231. _this.__select.appendChild(opt);
  34232. });
  34233. _this2.updateDisplay();
  34234. dom.bind(_this2.__select, 'change', function () {
  34235. var desiredValue = this.options[this.selectedIndex].value;
  34236. _this.setValue(desiredValue);
  34237. });
  34238. _this2.domElement.appendChild(_this2.__select);
  34239. return _this2;
  34240. }
  34241. createClass(OptionController, [{
  34242. key: 'setValue',
  34243. value: function setValue(v) {
  34244. var toReturn = get(OptionController.prototype.__proto__ || Object.getPrototypeOf(OptionController.prototype), 'setValue', this).call(this, v);
  34245. if (this.__onFinishChange) {
  34246. this.__onFinishChange.call(this, this.getValue());
  34247. }
  34248. return toReturn;
  34249. }
  34250. }, {
  34251. key: 'updateDisplay',
  34252. value: function updateDisplay() {
  34253. if (dom.isActive(this.__select)) return this;
  34254. this.__select.value = this.getValue();
  34255. return get(OptionController.prototype.__proto__ || Object.getPrototypeOf(OptionController.prototype), 'updateDisplay', this).call(this);
  34256. }
  34257. }]);
  34258. return OptionController;
  34259. }(Controller);
  34260. var StringController = function (_Controller) {
  34261. inherits(StringController, _Controller);
  34262. function StringController(object, property) {
  34263. classCallCheck(this, StringController);
  34264. var _this2 = possibleConstructorReturn(this, (StringController.__proto__ || Object.getPrototypeOf(StringController)).call(this, object, property));
  34265. var _this = _this2;
  34266. function onChange() {
  34267. _this.setValue(_this.__input.value);
  34268. }
  34269. function onBlur() {
  34270. if (_this.__onFinishChange) {
  34271. _this.__onFinishChange.call(_this, _this.getValue());
  34272. }
  34273. }
  34274. _this2.__input = document.createElement('input');
  34275. _this2.__input.setAttribute('type', 'text');
  34276. dom.bind(_this2.__input, 'keyup', onChange);
  34277. dom.bind(_this2.__input, 'change', onChange);
  34278. dom.bind(_this2.__input, 'blur', onBlur);
  34279. dom.bind(_this2.__input, 'keydown', function (e) {
  34280. if (e.keyCode === 13) {
  34281. this.blur();
  34282. }
  34283. });
  34284. _this2.updateDisplay();
  34285. _this2.domElement.appendChild(_this2.__input);
  34286. return _this2;
  34287. }
  34288. createClass(StringController, [{
  34289. key: 'updateDisplay',
  34290. value: function updateDisplay() {
  34291. if (!dom.isActive(this.__input)) {
  34292. this.__input.value = this.getValue();
  34293. }
  34294. return get(StringController.prototype.__proto__ || Object.getPrototypeOf(StringController.prototype), 'updateDisplay', this).call(this);
  34295. }
  34296. }]);
  34297. return StringController;
  34298. }(Controller);
  34299. function numDecimals(x) {
  34300. var _x = x.toString();
  34301. if (_x.indexOf('.') > -1) {
  34302. return _x.length - _x.indexOf('.') - 1;
  34303. }
  34304. return 0;
  34305. }
  34306. var NumberController = function (_Controller) {
  34307. inherits(NumberController, _Controller);
  34308. function NumberController(object, property, params) {
  34309. classCallCheck(this, NumberController);
  34310. var _this = possibleConstructorReturn(this, (NumberController.__proto__ || Object.getPrototypeOf(NumberController)).call(this, object, property));
  34311. var _params = params || {};
  34312. _this.__min = _params.min;
  34313. _this.__max = _params.max;
  34314. _this.__step = _params.step;
  34315. if (Common.isUndefined(_this.__step)) {
  34316. if (_this.initialValue === 0) {
  34317. _this.__impliedStep = 1;
  34318. } else {
  34319. _this.__impliedStep = Math.pow(10, Math.floor(Math.log(Math.abs(_this.initialValue)) / Math.LN10)) / 10;
  34320. }
  34321. } else {
  34322. _this.__impliedStep = _this.__step;
  34323. }
  34324. _this.__precision = numDecimals(_this.__impliedStep);
  34325. return _this;
  34326. }
  34327. createClass(NumberController, [{
  34328. key: 'setValue',
  34329. value: function setValue(v) {
  34330. var _v = v;
  34331. if (this.__min !== undefined && _v < this.__min) {
  34332. _v = this.__min;
  34333. } else if (this.__max !== undefined && _v > this.__max) {
  34334. _v = this.__max;
  34335. }
  34336. if (this.__step !== undefined && _v % this.__step !== 0) {
  34337. _v = Math.round(_v / this.__step) * this.__step;
  34338. }
  34339. return get(NumberController.prototype.__proto__ || Object.getPrototypeOf(NumberController.prototype), 'setValue', this).call(this, _v);
  34340. }
  34341. }, {
  34342. key: 'min',
  34343. value: function min(minValue) {
  34344. this.__min = minValue;
  34345. return this;
  34346. }
  34347. }, {
  34348. key: 'max',
  34349. value: function max(maxValue) {
  34350. this.__max = maxValue;
  34351. return this;
  34352. }
  34353. }, {
  34354. key: 'step',
  34355. value: function step(stepValue) {
  34356. this.__step = stepValue;
  34357. this.__impliedStep = stepValue;
  34358. this.__precision = numDecimals(stepValue);
  34359. return this;
  34360. }
  34361. }]);
  34362. return NumberController;
  34363. }(Controller);
  34364. function roundToDecimal(value, decimals) {
  34365. var tenTo = Math.pow(10, decimals);
  34366. return Math.round(value * tenTo) / tenTo;
  34367. }
  34368. var NumberControllerBox = function (_NumberController) {
  34369. inherits(NumberControllerBox, _NumberController);
  34370. function NumberControllerBox(object, property, params) {
  34371. classCallCheck(this, NumberControllerBox);
  34372. var _this2 = possibleConstructorReturn(this, (NumberControllerBox.__proto__ || Object.getPrototypeOf(NumberControllerBox)).call(this, object, property, params));
  34373. _this2.__truncationSuspended = false;
  34374. var _this = _this2;
  34375. var prevY = void 0;
  34376. function onChange() {
  34377. var attempted = parseFloat(_this.__input.value);
  34378. if (!Common.isNaN(attempted)) {
  34379. _this.setValue(attempted);
  34380. }
  34381. }
  34382. function onFinish() {
  34383. if (_this.__onFinishChange) {
  34384. _this.__onFinishChange.call(_this, _this.getValue());
  34385. }
  34386. }
  34387. function onBlur() {
  34388. onFinish();
  34389. }
  34390. function onMouseDrag(e) {
  34391. var diff = prevY - e.clientY;
  34392. _this.setValue(_this.getValue() + diff * _this.__impliedStep);
  34393. prevY = e.clientY;
  34394. }
  34395. function onMouseUp() {
  34396. dom.unbind(window, 'mousemove', onMouseDrag);
  34397. dom.unbind(window, 'mouseup', onMouseUp);
  34398. onFinish();
  34399. }
  34400. function onMouseDown(e) {
  34401. dom.bind(window, 'mousemove', onMouseDrag);
  34402. dom.bind(window, 'mouseup', onMouseUp);
  34403. prevY = e.clientY;
  34404. }
  34405. _this2.__input = document.createElement('input');
  34406. _this2.__input.setAttribute('type', 'text');
  34407. dom.bind(_this2.__input, 'change', onChange);
  34408. dom.bind(_this2.__input, 'blur', onBlur);
  34409. dom.bind(_this2.__input, 'mousedown', onMouseDown);
  34410. dom.bind(_this2.__input, 'keydown', function (e) {
  34411. if (e.keyCode === 13) {
  34412. _this.__truncationSuspended = true;
  34413. this.blur();
  34414. _this.__truncationSuspended = false;
  34415. onFinish();
  34416. }
  34417. });
  34418. _this2.updateDisplay();
  34419. _this2.domElement.appendChild(_this2.__input);
  34420. return _this2;
  34421. }
  34422. createClass(NumberControllerBox, [{
  34423. key: 'updateDisplay',
  34424. value: function updateDisplay() {
  34425. this.__input.value = this.__truncationSuspended ? this.getValue() : roundToDecimal(this.getValue(), this.__precision);
  34426. return get(NumberControllerBox.prototype.__proto__ || Object.getPrototypeOf(NumberControllerBox.prototype), 'updateDisplay', this).call(this);
  34427. }
  34428. }]);
  34429. return NumberControllerBox;
  34430. }(NumberController);
  34431. function map(v, i1, i2, o1, o2) {
  34432. return o1 + (o2 - o1) * ((v - i1) / (i2 - i1));
  34433. }
  34434. var NumberControllerSlider = function (_NumberController) {
  34435. inherits(NumberControllerSlider, _NumberController);
  34436. function NumberControllerSlider(object, property, min, max, step) {
  34437. classCallCheck(this, NumberControllerSlider);
  34438. var _this2 = possibleConstructorReturn(this, (NumberControllerSlider.__proto__ || Object.getPrototypeOf(NumberControllerSlider)).call(this, object, property, {
  34439. min: min,
  34440. max: max,
  34441. step: step
  34442. }));
  34443. var _this = _this2;
  34444. _this2.__background = document.createElement('div');
  34445. _this2.__foreground = document.createElement('div');
  34446. dom.bind(_this2.__background, 'mousedown', onMouseDown);
  34447. dom.bind(_this2.__background, 'touchstart', onTouchStart);
  34448. dom.addClass(_this2.__background, 'slider');
  34449. dom.addClass(_this2.__foreground, 'slider-fg');
  34450. function onMouseDown(e) {
  34451. document.activeElement.blur();
  34452. dom.bind(window, 'mousemove', onMouseDrag);
  34453. dom.bind(window, 'mouseup', onMouseUp);
  34454. onMouseDrag(e);
  34455. }
  34456. function onMouseDrag(e) {
  34457. e.preventDefault();
  34458. var bgRect = _this.__background.getBoundingClientRect();
  34459. _this.setValue(map(e.clientX, bgRect.left, bgRect.right, _this.__min, _this.__max));
  34460. return false;
  34461. }
  34462. function onMouseUp() {
  34463. dom.unbind(window, 'mousemove', onMouseDrag);
  34464. dom.unbind(window, 'mouseup', onMouseUp);
  34465. if (_this.__onFinishChange) {
  34466. _this.__onFinishChange.call(_this, _this.getValue());
  34467. }
  34468. }
  34469. function onTouchStart(e) {
  34470. if (e.touches.length !== 1) {
  34471. return;
  34472. }
  34473. dom.bind(window, 'touchmove', onTouchMove);
  34474. dom.bind(window, 'touchend', onTouchEnd);
  34475. onTouchMove(e);
  34476. }
  34477. function onTouchMove(e) {
  34478. var clientX = e.touches[0].clientX;
  34479. var bgRect = _this.__background.getBoundingClientRect();
  34480. _this.setValue(map(clientX, bgRect.left, bgRect.right, _this.__min, _this.__max));
  34481. }
  34482. function onTouchEnd() {
  34483. dom.unbind(window, 'touchmove', onTouchMove);
  34484. dom.unbind(window, 'touchend', onTouchEnd);
  34485. if (_this.__onFinishChange) {
  34486. _this.__onFinishChange.call(_this, _this.getValue());
  34487. }
  34488. }
  34489. _this2.updateDisplay();
  34490. _this2.__background.appendChild(_this2.__foreground);
  34491. _this2.domElement.appendChild(_this2.__background);
  34492. return _this2;
  34493. }
  34494. createClass(NumberControllerSlider, [{
  34495. key: 'updateDisplay',
  34496. value: function updateDisplay() {
  34497. var pct = (this.getValue() - this.__min) / (this.__max - this.__min);
  34498. this.__foreground.style.width = pct * 100 + '%';
  34499. return get(NumberControllerSlider.prototype.__proto__ || Object.getPrototypeOf(NumberControllerSlider.prototype), 'updateDisplay', this).call(this);
  34500. }
  34501. }]);
  34502. return NumberControllerSlider;
  34503. }(NumberController);
  34504. var FunctionController = function (_Controller) {
  34505. inherits(FunctionController, _Controller);
  34506. function FunctionController(object, property, text) {
  34507. classCallCheck(this, FunctionController);
  34508. var _this2 = possibleConstructorReturn(this, (FunctionController.__proto__ || Object.getPrototypeOf(FunctionController)).call(this, object, property));
  34509. var _this = _this2;
  34510. _this2.__button = document.createElement('div');
  34511. _this2.__button.innerHTML = text === undefined ? 'Fire' : text;
  34512. dom.bind(_this2.__button, 'click', function (e) {
  34513. e.preventDefault();
  34514. _this.fire();
  34515. return false;
  34516. });
  34517. dom.addClass(_this2.__button, 'button');
  34518. _this2.domElement.appendChild(_this2.__button);
  34519. return _this2;
  34520. }
  34521. createClass(FunctionController, [{
  34522. key: 'fire',
  34523. value: function fire() {
  34524. if (this.__onChange) {
  34525. this.__onChange.call(this);
  34526. }
  34527. this.getValue().call(this.object);
  34528. if (this.__onFinishChange) {
  34529. this.__onFinishChange.call(this, this.getValue());
  34530. }
  34531. }
  34532. }]);
  34533. return FunctionController;
  34534. }(Controller);
  34535. var ColorController = function (_Controller) {
  34536. inherits(ColorController, _Controller);
  34537. function ColorController(object, property) {
  34538. classCallCheck(this, ColorController);
  34539. var _this2 = possibleConstructorReturn(this, (ColorController.__proto__ || Object.getPrototypeOf(ColorController)).call(this, object, property));
  34540. _this2.__color = new Color(_this2.getValue());
  34541. _this2.__temp = new Color(0);
  34542. var _this = _this2;
  34543. _this2.domElement = document.createElement('div');
  34544. dom.makeSelectable(_this2.domElement, false);
  34545. _this2.__selector = document.createElement('div');
  34546. _this2.__selector.className = 'selector';
  34547. _this2.__saturation_field = document.createElement('div');
  34548. _this2.__saturation_field.className = 'saturation-field';
  34549. _this2.__field_knob = document.createElement('div');
  34550. _this2.__field_knob.className = 'field-knob';
  34551. _this2.__field_knob_border = '2px solid ';
  34552. _this2.__hue_knob = document.createElement('div');
  34553. _this2.__hue_knob.className = 'hue-knob';
  34554. _this2.__hue_field = document.createElement('div');
  34555. _this2.__hue_field.className = 'hue-field';
  34556. _this2.__input = document.createElement('input');
  34557. _this2.__input.type = 'text';
  34558. _this2.__input_textShadow = '0 1px 1px ';
  34559. dom.bind(_this2.__input, 'keydown', function (e) {
  34560. if (e.keyCode === 13) {
  34561. onBlur.call(this);
  34562. }
  34563. });
  34564. dom.bind(_this2.__input, 'blur', onBlur);
  34565. dom.bind(_this2.__selector, 'mousedown', function () {
  34566. dom.addClass(this, 'drag').bind(window, 'mouseup', function () {
  34567. dom.removeClass(_this.__selector, 'drag');
  34568. });
  34569. });
  34570. dom.bind(_this2.__selector, 'touchstart', function () {
  34571. dom.addClass(this, 'drag').bind(window, 'touchend', function () {
  34572. dom.removeClass(_this.__selector, 'drag');
  34573. });
  34574. });
  34575. var valueField = document.createElement('div');
  34576. Common.extend(_this2.__selector.style, {
  34577. width: '122px',
  34578. height: '102px',
  34579. padding: '3px',
  34580. backgroundColor: '#222',
  34581. boxShadow: '0px 1px 3px rgba(0,0,0,0.3)'
  34582. });
  34583. Common.extend(_this2.__field_knob.style, {
  34584. position: 'absolute',
  34585. width: '12px',
  34586. height: '12px',
  34587. border: _this2.__field_knob_border + (_this2.__color.v < 0.5 ? '#fff' : '#000'),
  34588. boxShadow: '0px 1px 3px rgba(0,0,0,0.5)',
  34589. borderRadius: '12px',
  34590. zIndex: 1
  34591. });
  34592. Common.extend(_this2.__hue_knob.style, {
  34593. position: 'absolute',
  34594. width: '15px',
  34595. height: '2px',
  34596. borderRight: '4px solid #fff',
  34597. zIndex: 1
  34598. });
  34599. Common.extend(_this2.__saturation_field.style, {
  34600. width: '100px',
  34601. height: '100px',
  34602. border: '1px solid #555',
  34603. marginRight: '3px',
  34604. display: 'inline-block',
  34605. cursor: 'pointer'
  34606. });
  34607. Common.extend(valueField.style, {
  34608. width: '100%',
  34609. height: '100%',
  34610. background: 'none'
  34611. });
  34612. linearGradient(valueField, 'top', 'rgba(0,0,0,0)', '#000');
  34613. Common.extend(_this2.__hue_field.style, {
  34614. width: '15px',
  34615. height: '100px',
  34616. border: '1px solid #555',
  34617. cursor: 'ns-resize',
  34618. position: 'absolute',
  34619. top: '3px',
  34620. right: '3px'
  34621. });
  34622. hueGradient(_this2.__hue_field);
  34623. Common.extend(_this2.__input.style, {
  34624. outline: 'none',
  34625. textAlign: 'center',
  34626. color: '#fff',
  34627. border: 0,
  34628. fontWeight: 'bold',
  34629. textShadow: _this2.__input_textShadow + 'rgba(0,0,0,0.7)'
  34630. });
  34631. dom.bind(_this2.__saturation_field, 'mousedown', fieldDown);
  34632. dom.bind(_this2.__saturation_field, 'touchstart', fieldDown);
  34633. dom.bind(_this2.__field_knob, 'mousedown', fieldDown);
  34634. dom.bind(_this2.__field_knob, 'touchstart', fieldDown);
  34635. dom.bind(_this2.__hue_field, 'mousedown', fieldDownH);
  34636. dom.bind(_this2.__hue_field, 'touchstart', fieldDownH);
  34637. function fieldDown(e) {
  34638. setSV(e);
  34639. dom.bind(window, 'mousemove', setSV);
  34640. dom.bind(window, 'touchmove', setSV);
  34641. dom.bind(window, 'mouseup', fieldUpSV);
  34642. dom.bind(window, 'touchend', fieldUpSV);
  34643. }
  34644. function fieldDownH(e) {
  34645. setH(e);
  34646. dom.bind(window, 'mousemove', setH);
  34647. dom.bind(window, 'touchmove', setH);
  34648. dom.bind(window, 'mouseup', fieldUpH);
  34649. dom.bind(window, 'touchend', fieldUpH);
  34650. }
  34651. function fieldUpSV() {
  34652. dom.unbind(window, 'mousemove', setSV);
  34653. dom.unbind(window, 'touchmove', setSV);
  34654. dom.unbind(window, 'mouseup', fieldUpSV);
  34655. dom.unbind(window, 'touchend', fieldUpSV);
  34656. onFinish();
  34657. }
  34658. function fieldUpH() {
  34659. dom.unbind(window, 'mousemove', setH);
  34660. dom.unbind(window, 'touchmove', setH);
  34661. dom.unbind(window, 'mouseup', fieldUpH);
  34662. dom.unbind(window, 'touchend', fieldUpH);
  34663. onFinish();
  34664. }
  34665. function onBlur() {
  34666. var i = interpret(this.value);
  34667. if (i !== false) {
  34668. _this.__color.__state = i;
  34669. _this.setValue(_this.__color.toOriginal());
  34670. } else {
  34671. this.value = _this.__color.toString();
  34672. }
  34673. }
  34674. function onFinish() {
  34675. if (_this.__onFinishChange) {
  34676. _this.__onFinishChange.call(_this, _this.__color.toOriginal());
  34677. }
  34678. }
  34679. _this2.__saturation_field.appendChild(valueField);
  34680. _this2.__selector.appendChild(_this2.__field_knob);
  34681. _this2.__selector.appendChild(_this2.__saturation_field);
  34682. _this2.__selector.appendChild(_this2.__hue_field);
  34683. _this2.__hue_field.appendChild(_this2.__hue_knob);
  34684. _this2.domElement.appendChild(_this2.__input);
  34685. _this2.domElement.appendChild(_this2.__selector);
  34686. _this2.updateDisplay();
  34687. function setSV(e) {
  34688. if (e.type.indexOf('touch') === -1) {
  34689. e.preventDefault();
  34690. }
  34691. var fieldRect = _this.__saturation_field.getBoundingClientRect();
  34692. var _ref = e.touches && e.touches[0] || e,
  34693. clientX = _ref.clientX,
  34694. clientY = _ref.clientY;
  34695. var s = (clientX - fieldRect.left) / (fieldRect.right - fieldRect.left);
  34696. var v = 1 - (clientY - fieldRect.top) / (fieldRect.bottom - fieldRect.top);
  34697. if (v > 1) {
  34698. v = 1;
  34699. } else if (v < 0) {
  34700. v = 0;
  34701. }
  34702. if (s > 1) {
  34703. s = 1;
  34704. } else if (s < 0) {
  34705. s = 0;
  34706. }
  34707. _this.__color.v = v;
  34708. _this.__color.s = s;
  34709. _this.setValue(_this.__color.toOriginal());
  34710. return false;
  34711. }
  34712. function setH(e) {
  34713. if (e.type.indexOf('touch') === -1) {
  34714. e.preventDefault();
  34715. }
  34716. var fieldRect = _this.__hue_field.getBoundingClientRect();
  34717. var _ref2 = e.touches && e.touches[0] || e,
  34718. clientY = _ref2.clientY;
  34719. var h = 1 - (clientY - fieldRect.top) / (fieldRect.bottom - fieldRect.top);
  34720. if (h > 1) {
  34721. h = 1;
  34722. } else if (h < 0) {
  34723. h = 0;
  34724. }
  34725. _this.__color.h = h * 360;
  34726. _this.setValue(_this.__color.toOriginal());
  34727. return false;
  34728. }
  34729. return _this2;
  34730. }
  34731. createClass(ColorController, [{
  34732. key: 'updateDisplay',
  34733. value: function updateDisplay() {
  34734. var i = interpret(this.getValue());
  34735. if (i !== false) {
  34736. var mismatch = false;
  34737. Common.each(Color.COMPONENTS, function (component) {
  34738. if (!Common.isUndefined(i[component]) && !Common.isUndefined(this.__color.__state[component]) && i[component] !== this.__color.__state[component]) {
  34739. mismatch = true;
  34740. return {};
  34741. }
  34742. }, this);
  34743. if (mismatch) {
  34744. Common.extend(this.__color.__state, i);
  34745. }
  34746. }
  34747. Common.extend(this.__temp.__state, this.__color.__state);
  34748. this.__temp.a = 1;
  34749. var flip = this.__color.v < 0.5 || this.__color.s > 0.5 ? 255 : 0;
  34750. var _flip = 255 - flip;
  34751. Common.extend(this.__field_knob.style, {
  34752. marginLeft: 100 * this.__color.s - 7 + 'px',
  34753. marginTop: 100 * (1 - this.__color.v) - 7 + 'px',
  34754. backgroundColor: this.__temp.toHexString(),
  34755. border: this.__field_knob_border + 'rgb(' + flip + ',' + flip + ',' + flip + ')'
  34756. });
  34757. this.__hue_knob.style.marginTop = (1 - this.__color.h / 360) * 100 + 'px';
  34758. this.__temp.s = 1;
  34759. this.__temp.v = 1;
  34760. linearGradient(this.__saturation_field, 'left', '#fff', this.__temp.toHexString());
  34761. this.__input.value = this.__color.toString();
  34762. Common.extend(this.__input.style, {
  34763. backgroundColor: this.__color.toHexString(),
  34764. color: 'rgb(' + flip + ',' + flip + ',' + flip + ')',
  34765. textShadow: this.__input_textShadow + 'rgba(' + _flip + ',' + _flip + ',' + _flip + ',.7)'
  34766. });
  34767. }
  34768. }]);
  34769. return ColorController;
  34770. }(Controller);
  34771. var vendors = ['-moz-', '-o-', '-webkit-', '-ms-', ''];
  34772. function linearGradient(elem, x, a, b) {
  34773. elem.style.background = '';
  34774. Common.each(vendors, function (vendor) {
  34775. elem.style.cssText += 'background: ' + vendor + 'linear-gradient(' + x + ', ' + a + ' 0%, ' + b + ' 100%); ';
  34776. });
  34777. }
  34778. function hueGradient(elem) {
  34779. elem.style.background = '';
  34780. elem.style.cssText += 'background: -moz-linear-gradient(top, #ff0000 0%, #ff00ff 17%, #0000ff 34%, #00ffff 50%, #00ff00 67%, #ffff00 84%, #ff0000 100%);';
  34781. elem.style.cssText += 'background: -webkit-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  34782. elem.style.cssText += 'background: -o-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  34783. elem.style.cssText += 'background: -ms-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  34784. elem.style.cssText += 'background: linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  34785. }
  34786. var css = {
  34787. load: function load(url, indoc) {
  34788. var doc = indoc || document;
  34789. var link = doc.createElement('link');
  34790. link.type = 'text/css';
  34791. link.rel = 'stylesheet';
  34792. link.href = url;
  34793. doc.getElementsByTagName('head')[0].appendChild(link);
  34794. },
  34795. inject: function inject(cssContent, indoc) {
  34796. var doc = indoc || document;
  34797. var injected = document.createElement('style');
  34798. injected.type = 'text/css';
  34799. injected.innerHTML = cssContent;
  34800. var head = doc.getElementsByTagName('head')[0];
  34801. try {
  34802. head.appendChild(injected);
  34803. } catch (e) {}
  34804. }
  34805. };
  34806. var saveDialogContents = "<div id=\"dg-save\" class=\"dg dialogue\">\n\n Here's the new load parameter for your <code>GUI</code>'s constructor:\n\n <textarea id=\"dg-new-constructor\"></textarea>\n\n <div id=\"dg-save-locally\">\n\n <input id=\"dg-local-storage\" type=\"checkbox\"/> Automatically save\n values to <code>localStorage</code> on exit.\n\n <div id=\"dg-local-explain\">The values saved to <code>localStorage</code> will\n override those passed to <code>dat.GUI</code>'s constructor. This makes it\n easier to work incrementally, but <code>localStorage</code> is fragile,\n and your friends may not see the same values you do.\n\n </div>\n\n </div>\n\n</div>";
  34807. var ControllerFactory = function ControllerFactory(object, property) {
  34808. var initialValue = object[property];
  34809. if (Common.isArray(arguments[2]) || Common.isObject(arguments[2])) {
  34810. return new OptionController(object, property, arguments[2]);
  34811. }
  34812. if (Common.isNumber(initialValue)) {
  34813. if (Common.isNumber(arguments[2]) && Common.isNumber(arguments[3])) {
  34814. if (Common.isNumber(arguments[4])) {
  34815. return new NumberControllerSlider(object, property, arguments[2], arguments[3], arguments[4]);
  34816. }
  34817. return new NumberControllerSlider(object, property, arguments[2], arguments[3]);
  34818. }
  34819. if (Common.isNumber(arguments[4])) {
  34820. return new NumberControllerBox(object, property, {
  34821. min: arguments[2],
  34822. max: arguments[3],
  34823. step: arguments[4]
  34824. });
  34825. }
  34826. return new NumberControllerBox(object, property, {
  34827. min: arguments[2],
  34828. max: arguments[3]
  34829. });
  34830. }
  34831. if (Common.isString(initialValue)) {
  34832. return new StringController(object, property);
  34833. }
  34834. if (Common.isFunction(initialValue)) {
  34835. return new FunctionController(object, property, '');
  34836. }
  34837. if (Common.isBoolean(initialValue)) {
  34838. return new BooleanController(object, property);
  34839. }
  34840. return null;
  34841. };
  34842. function requestAnimationFrame(callback) {
  34843. setTimeout(callback, 1000 / 60);
  34844. }
  34845. var requestAnimationFrame$1 = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || requestAnimationFrame;
  34846. var CenteredDiv = function () {
  34847. function CenteredDiv() {
  34848. classCallCheck(this, CenteredDiv);
  34849. this.backgroundElement = document.createElement('div');
  34850. Common.extend(this.backgroundElement.style, {
  34851. backgroundColor: 'rgba(0,0,0,0.8)',
  34852. top: 0,
  34853. left: 0,
  34854. display: 'none',
  34855. zIndex: '1000',
  34856. opacity: 0,
  34857. WebkitTransition: 'opacity 0.2s linear',
  34858. transition: 'opacity 0.2s linear'
  34859. });
  34860. dom.makeFullscreen(this.backgroundElement);
  34861. this.backgroundElement.style.position = 'fixed';
  34862. this.domElement = document.createElement('div');
  34863. Common.extend(this.domElement.style, {
  34864. position: 'fixed',
  34865. display: 'none',
  34866. zIndex: '1001',
  34867. opacity: 0,
  34868. WebkitTransition: '-webkit-transform 0.2s ease-out, opacity 0.2s linear',
  34869. transition: 'transform 0.2s ease-out, opacity 0.2s linear'
  34870. });
  34871. document.body.appendChild(this.backgroundElement);
  34872. document.body.appendChild(this.domElement);
  34873. var _this = this;
  34874. dom.bind(this.backgroundElement, 'click', function () {
  34875. _this.hide();
  34876. });
  34877. }
  34878. createClass(CenteredDiv, [{
  34879. key: 'show',
  34880. value: function show() {
  34881. var _this = this;
  34882. this.backgroundElement.style.display = 'block';
  34883. this.domElement.style.display = 'block';
  34884. this.domElement.style.opacity = 0;
  34885. this.domElement.style.webkitTransform = 'scale(1.1)';
  34886. this.layout();
  34887. Common.defer(function () {
  34888. _this.backgroundElement.style.opacity = 1;
  34889. _this.domElement.style.opacity = 1;
  34890. _this.domElement.style.webkitTransform = 'scale(1)';
  34891. });
  34892. }
  34893. }, {
  34894. key: 'hide',
  34895. value: function hide() {
  34896. var _this = this;
  34897. var hide = function hide() {
  34898. _this.domElement.style.display = 'none';
  34899. _this.backgroundElement.style.display = 'none';
  34900. dom.unbind(_this.domElement, 'webkitTransitionEnd', hide);
  34901. dom.unbind(_this.domElement, 'transitionend', hide);
  34902. dom.unbind(_this.domElement, 'oTransitionEnd', hide);
  34903. };
  34904. dom.bind(this.domElement, 'webkitTransitionEnd', hide);
  34905. dom.bind(this.domElement, 'transitionend', hide);
  34906. dom.bind(this.domElement, 'oTransitionEnd', hide);
  34907. this.backgroundElement.style.opacity = 0;
  34908. this.domElement.style.opacity = 0;
  34909. this.domElement.style.webkitTransform = 'scale(1.1)';
  34910. }
  34911. }, {
  34912. key: 'layout',
  34913. value: function layout() {
  34914. this.domElement.style.left = window.innerWidth / 2 - dom.getWidth(this.domElement) / 2 + 'px';
  34915. this.domElement.style.top = window.innerHeight / 2 - dom.getHeight(this.domElement) / 2 + 'px';
  34916. }
  34917. }]);
  34918. return CenteredDiv;
  34919. }();
  34920. var styleSheet = ___$insertStyle(".dg ul{list-style:none;margin:0;padding:0;width:100%;clear:both}.dg.ac{position:fixed;top:0;left:0;right:0;height:0;z-index:0}.dg:not(.ac) .main{overflow:hidden}.dg.main{-webkit-transition:opacity .1s linear;-o-transition:opacity .1s linear;-moz-transition:opacity .1s linear;transition:opacity .1s linear}.dg.main.taller-than-window{overflow-y:auto}.dg.main.taller-than-window .close-button{opacity:1;margin-top:-1px;border-top:1px solid #2c2c2c}.dg.main ul.closed .close-button{opacity:1 !important}.dg.main:hover .close-button,.dg.main .close-button.drag{opacity:1}.dg.main .close-button{-webkit-transition:opacity .1s linear;-o-transition:opacity .1s linear;-moz-transition:opacity .1s linear;transition:opacity .1s linear;border:0;line-height:19px;height:20px;cursor:pointer;text-align:center;background-color:#000}.dg.main .close-button.close-top{position:relative}.dg.main .close-button.close-bottom{position:absolute}.dg.main .close-button:hover{background-color:#111}.dg.a{float:right;margin-right:15px;overflow-y:visible}.dg.a.has-save>ul.close-top{margin-top:0}.dg.a.has-save>ul.close-bottom{margin-top:27px}.dg.a.has-save>ul.closed{margin-top:0}.dg.a .save-row{top:0;z-index:1002}.dg.a .save-row.close-top{position:relative}.dg.a .save-row.close-bottom{position:fixed}.dg li{-webkit-transition:height .1s ease-out;-o-transition:height .1s ease-out;-moz-transition:height .1s ease-out;transition:height .1s ease-out;-webkit-transition:overflow .1s linear;-o-transition:overflow .1s linear;-moz-transition:overflow .1s linear;transition:overflow .1s linear}.dg li:not(.folder){cursor:auto;height:27px;line-height:27px;padding:0 4px 0 5px}.dg li.folder{padding:0;border-left:4px solid rgba(0,0,0,0)}.dg li.title{cursor:pointer;margin-left:-4px}.dg .closed li:not(.title),.dg .closed ul li,.dg .closed ul li>*{height:0;overflow:hidden;border:0}.dg .cr{clear:both;padding-left:3px;height:27px;overflow:hidden}.dg .property-name{cursor:default;float:left;clear:left;width:40%;overflow:hidden;text-overflow:ellipsis}.dg .c{float:left;width:60%;position:relative}.dg .c input[type=text]{border:0;margin-top:4px;padding:3px;width:100%;float:right}.dg .has-slider input[type=text]{width:30%;margin-left:0}.dg .slider{float:left;width:66%;margin-left:-5px;margin-right:0;height:19px;margin-top:4px}.dg .slider-fg{height:100%}.dg .c input[type=checkbox]{margin-top:7px}.dg .c select{margin-top:5px}.dg .cr.function,.dg .cr.function .property-name,.dg .cr.function *,.dg .cr.boolean,.dg .cr.boolean *{cursor:pointer}.dg .cr.color{overflow:visible}.dg .selector{display:none;position:absolute;margin-left:-9px;margin-top:23px;z-index:10}.dg .c:hover .selector,.dg .selector.drag{display:block}.dg li.save-row{padding:0}.dg li.save-row .button{display:inline-block;padding:0px 6px}.dg.dialogue{background-color:#222;width:460px;padding:15px;font-size:13px;line-height:15px}#dg-new-constructor{padding:10px;color:#222;font-family:Monaco, monospace;font-size:10px;border:0;resize:none;box-shadow:inset 1px 1px 1px #888;word-wrap:break-word;margin:12px 0;display:block;width:440px;overflow-y:scroll;height:100px;position:relative}#dg-local-explain{display:none;font-size:11px;line-height:17px;border-radius:3px;background-color:#333;padding:8px;margin-top:10px}#dg-local-explain code{font-size:10px}#dat-gui-save-locally{display:none}.dg{color:#eee;font:11px 'Lucida Grande', sans-serif;text-shadow:0 -1px 0 #111}.dg.main::-webkit-scrollbar{width:5px;background:#1a1a1a}.dg.main::-webkit-scrollbar-corner{height:0;display:none}.dg.main::-webkit-scrollbar-thumb{border-radius:5px;background:#676767}.dg li:not(.folder){background:#1a1a1a;border-bottom:1px solid #2c2c2c}.dg li.save-row{line-height:25px;background:#dad5cb;border:0}.dg li.save-row select{margin-left:5px;width:108px}.dg li.save-row .button{margin-left:5px;margin-top:1px;border-radius:2px;font-size:9px;line-height:7px;padding:4px 4px 5px 4px;background:#c5bdad;color:#fff;text-shadow:0 1px 0 #b0a58f;box-shadow:0 -1px 0 #b0a58f;cursor:pointer}.dg li.save-row .button.gears{background:#c5bdad url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAsAAAANCAYAAAB/9ZQ7AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAQJJREFUeNpiYKAU/P//PwGIC/ApCABiBSAW+I8AClAcgKxQ4T9hoMAEUrxx2QSGN6+egDX+/vWT4e7N82AMYoPAx/evwWoYoSYbACX2s7KxCxzcsezDh3evFoDEBYTEEqycggWAzA9AuUSQQgeYPa9fPv6/YWm/Acx5IPb7ty/fw+QZblw67vDs8R0YHyQhgObx+yAJkBqmG5dPPDh1aPOGR/eugW0G4vlIoTIfyFcA+QekhhHJhPdQxbiAIguMBTQZrPD7108M6roWYDFQiIAAv6Aow/1bFwXgis+f2LUAynwoIaNcz8XNx3Dl7MEJUDGQpx9gtQ8YCueB+D26OECAAQDadt7e46D42QAAAABJRU5ErkJggg==) 2px 1px no-repeat;height:7px;width:8px}.dg li.save-row .button:hover{background-color:#bab19e;box-shadow:0 -1px 0 #b0a58f}.dg li.folder{border-bottom:0}.dg li.title{padding-left:16px;background:#000 url(data:image/gif;base64,R0lGODlhBQAFAJEAAP////Pz8////////yH5BAEAAAIALAAAAAAFAAUAAAIIlI+hKgFxoCgAOw==) 6px 10px no-repeat;cursor:pointer;border-bottom:1px solid rgba(255,255,255,0.2)}.dg .closed li.title{background-image:url(data:image/gif;base64,R0lGODlhBQAFAJEAAP////Pz8////////yH5BAEAAAIALAAAAAAFAAUAAAIIlGIWqMCbWAEAOw==)}.dg .cr.boolean{border-left:3px solid #806787}.dg .cr.color{border-left:3px solid}.dg .cr.function{border-left:3px solid #e61d5f}.dg .cr.number{border-left:3px solid #2FA1D6}.dg .cr.number input[type=text]{color:#2FA1D6}.dg .cr.string{border-left:3px solid #1ed36f}.dg .cr.string input[type=text]{color:#1ed36f}.dg .cr.function:hover,.dg .cr.boolean:hover{background:#111}.dg .c input[type=text]{background:#303030;outline:none}.dg .c input[type=text]:hover{background:#3c3c3c}.dg .c input[type=text]:focus{background:#494949;color:#fff}.dg .c .slider{background:#303030;cursor:ew-resize}.dg .c .slider-fg{background:#2FA1D6;max-width:100%}.dg .c .slider:hover{background:#3c3c3c}.dg .c .slider:hover .slider-fg{background:#44abda}\n");
  34921. css.inject(styleSheet);
  34922. var CSS_NAMESPACE = 'dg';
  34923. var HIDE_KEY_CODE = 72;
  34924. var CLOSE_BUTTON_HEIGHT = 20;
  34925. var DEFAULT_DEFAULT_PRESET_NAME = 'Default';
  34926. var SUPPORTS_LOCAL_STORAGE = function () {
  34927. try {
  34928. return !!window.localStorage;
  34929. } catch (e) {
  34930. return false;
  34931. }
  34932. }();
  34933. var SAVE_DIALOGUE = void 0;
  34934. var autoPlaceVirgin = true;
  34935. var autoPlaceContainer = void 0;
  34936. var hide = false;
  34937. var hideableGuis = [];
  34938. var GUI = function GUI(pars) {
  34939. var _this = this;
  34940. var params = pars || {};
  34941. this.domElement = document.createElement('div');
  34942. this.__ul = document.createElement('ul');
  34943. this.domElement.appendChild(this.__ul);
  34944. dom.addClass(this.domElement, CSS_NAMESPACE);
  34945. this.__folders = {};
  34946. this.__controllers = [];
  34947. this.__rememberedObjects = [];
  34948. this.__rememberedObjectIndecesToControllers = [];
  34949. this.__listening = [];
  34950. params = Common.defaults(params, {
  34951. closeOnTop: false,
  34952. autoPlace: true,
  34953. width: GUI.DEFAULT_WIDTH
  34954. });
  34955. params = Common.defaults(params, {
  34956. resizable: params.autoPlace,
  34957. hideable: params.autoPlace
  34958. });
  34959. if (!Common.isUndefined(params.load)) {
  34960. if (params.preset) {
  34961. params.load.preset = params.preset;
  34962. }
  34963. } else {
  34964. params.load = {
  34965. preset: DEFAULT_DEFAULT_PRESET_NAME
  34966. };
  34967. }
  34968. if (Common.isUndefined(params.parent) && params.hideable) {
  34969. hideableGuis.push(this);
  34970. }
  34971. params.resizable = Common.isUndefined(params.parent) && params.resizable;
  34972. if (params.autoPlace && Common.isUndefined(params.scrollable)) {
  34973. params.scrollable = true;
  34974. }
  34975. var useLocalStorage = SUPPORTS_LOCAL_STORAGE && localStorage.getItem(getLocalStorageHash(this, 'isLocal')) === 'true';
  34976. var saveToLocalStorage = void 0;
  34977. var titleRow = void 0;
  34978. Object.defineProperties(this, {
  34979. parent: {
  34980. get: function get$$1() {
  34981. return params.parent;
  34982. }
  34983. },
  34984. scrollable: {
  34985. get: function get$$1() {
  34986. return params.scrollable;
  34987. }
  34988. },
  34989. autoPlace: {
  34990. get: function get$$1() {
  34991. return params.autoPlace;
  34992. }
  34993. },
  34994. closeOnTop: {
  34995. get: function get$$1() {
  34996. return params.closeOnTop;
  34997. }
  34998. },
  34999. preset: {
  35000. get: function get$$1() {
  35001. if (_this.parent) {
  35002. return _this.getRoot().preset;
  35003. }
  35004. return params.load.preset;
  35005. },
  35006. set: function set$$1(v) {
  35007. if (_this.parent) {
  35008. _this.getRoot().preset = v;
  35009. } else {
  35010. params.load.preset = v;
  35011. }
  35012. setPresetSelectIndex(this);
  35013. _this.revert();
  35014. }
  35015. },
  35016. width: {
  35017. get: function get$$1() {
  35018. return params.width;
  35019. },
  35020. set: function set$$1(v) {
  35021. params.width = v;
  35022. setWidth(_this, v);
  35023. }
  35024. },
  35025. name: {
  35026. get: function get$$1() {
  35027. return params.name;
  35028. },
  35029. set: function set$$1(v) {
  35030. params.name = v;
  35031. if (titleRow) {
  35032. titleRow.innerHTML = params.name;
  35033. }
  35034. }
  35035. },
  35036. closed: {
  35037. get: function get$$1() {
  35038. return params.closed;
  35039. },
  35040. set: function set$$1(v) {
  35041. params.closed = v;
  35042. if (params.closed) {
  35043. dom.addClass(_this.__ul, GUI.CLASS_CLOSED);
  35044. } else {
  35045. dom.removeClass(_this.__ul, GUI.CLASS_CLOSED);
  35046. }
  35047. this.onResize();
  35048. if (_this.__closeButton) {
  35049. _this.__closeButton.innerHTML = v ? GUI.TEXT_OPEN : GUI.TEXT_CLOSED;
  35050. }
  35051. }
  35052. },
  35053. load: {
  35054. get: function get$$1() {
  35055. return params.load;
  35056. }
  35057. },
  35058. useLocalStorage: {
  35059. get: function get$$1() {
  35060. return useLocalStorage;
  35061. },
  35062. set: function set$$1(bool) {
  35063. if (SUPPORTS_LOCAL_STORAGE) {
  35064. useLocalStorage = bool;
  35065. if (bool) {
  35066. dom.bind(window, 'unload', saveToLocalStorage);
  35067. } else {
  35068. dom.unbind(window, 'unload', saveToLocalStorage);
  35069. }
  35070. localStorage.setItem(getLocalStorageHash(_this, 'isLocal'), bool);
  35071. }
  35072. }
  35073. }
  35074. });
  35075. if (Common.isUndefined(params.parent)) {
  35076. this.closed = params.closed || false;
  35077. dom.addClass(this.domElement, GUI.CLASS_MAIN);
  35078. dom.makeSelectable(this.domElement, false);
  35079. if (SUPPORTS_LOCAL_STORAGE) {
  35080. if (useLocalStorage) {
  35081. _this.useLocalStorage = true;
  35082. var savedGui = localStorage.getItem(getLocalStorageHash(this, 'gui'));
  35083. if (savedGui) {
  35084. params.load = JSON.parse(savedGui);
  35085. }
  35086. }
  35087. }
  35088. this.__closeButton = document.createElement('div');
  35089. this.__closeButton.innerHTML = GUI.TEXT_CLOSED;
  35090. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_BUTTON);
  35091. if (params.closeOnTop) {
  35092. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_TOP);
  35093. this.domElement.insertBefore(this.__closeButton, this.domElement.childNodes[0]);
  35094. } else {
  35095. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_BOTTOM);
  35096. this.domElement.appendChild(this.__closeButton);
  35097. }
  35098. dom.bind(this.__closeButton, 'click', function () {
  35099. _this.closed = !_this.closed;
  35100. });
  35101. } else {
  35102. if (params.closed === undefined) {
  35103. params.closed = true;
  35104. }
  35105. var titleRowName = document.createTextNode(params.name);
  35106. dom.addClass(titleRowName, 'controller-name');
  35107. titleRow = addRow(_this, titleRowName);
  35108. var onClickTitle = function onClickTitle(e) {
  35109. e.preventDefault();
  35110. _this.closed = !_this.closed;
  35111. return false;
  35112. };
  35113. dom.addClass(this.__ul, GUI.CLASS_CLOSED);
  35114. dom.addClass(titleRow, 'title');
  35115. dom.bind(titleRow, 'click', onClickTitle);
  35116. if (!params.closed) {
  35117. this.closed = false;
  35118. }
  35119. }
  35120. if (params.autoPlace) {
  35121. if (Common.isUndefined(params.parent)) {
  35122. if (autoPlaceVirgin) {
  35123. autoPlaceContainer = document.createElement('div');
  35124. dom.addClass(autoPlaceContainer, CSS_NAMESPACE);
  35125. dom.addClass(autoPlaceContainer, GUI.CLASS_AUTO_PLACE_CONTAINER);
  35126. document.body.appendChild(autoPlaceContainer);
  35127. autoPlaceVirgin = false;
  35128. }
  35129. autoPlaceContainer.appendChild(this.domElement);
  35130. dom.addClass(this.domElement, GUI.CLASS_AUTO_PLACE);
  35131. }
  35132. if (!this.parent) {
  35133. setWidth(_this, params.width);
  35134. }
  35135. }
  35136. this.__resizeHandler = function () {
  35137. _this.onResizeDebounced();
  35138. };
  35139. dom.bind(window, 'resize', this.__resizeHandler);
  35140. dom.bind(this.__ul, 'webkitTransitionEnd', this.__resizeHandler);
  35141. dom.bind(this.__ul, 'transitionend', this.__resizeHandler);
  35142. dom.bind(this.__ul, 'oTransitionEnd', this.__resizeHandler);
  35143. this.onResize();
  35144. if (params.resizable) {
  35145. addResizeHandle(this);
  35146. }
  35147. saveToLocalStorage = function saveToLocalStorage() {
  35148. if (SUPPORTS_LOCAL_STORAGE && localStorage.getItem(getLocalStorageHash(_this, 'isLocal')) === 'true') {
  35149. localStorage.setItem(getLocalStorageHash(_this, 'gui'), JSON.stringify(_this.getSaveObject()));
  35150. }
  35151. };
  35152. this.saveToLocalStorageIfPossible = saveToLocalStorage;
  35153. function resetWidth() {
  35154. var root = _this.getRoot();
  35155. root.width += 1;
  35156. Common.defer(function () {
  35157. root.width -= 1;
  35158. });
  35159. }
  35160. if (!params.parent) {
  35161. resetWidth();
  35162. }
  35163. };
  35164. GUI.toggleHide = function () {
  35165. hide = !hide;
  35166. Common.each(hideableGuis, function (gui) {
  35167. gui.domElement.style.display = hide ? 'none' : '';
  35168. });
  35169. };
  35170. GUI.CLASS_AUTO_PLACE = 'a';
  35171. GUI.CLASS_AUTO_PLACE_CONTAINER = 'ac';
  35172. GUI.CLASS_MAIN = 'main';
  35173. GUI.CLASS_CONTROLLER_ROW = 'cr';
  35174. GUI.CLASS_TOO_TALL = 'taller-than-window';
  35175. GUI.CLASS_CLOSED = 'closed';
  35176. GUI.CLASS_CLOSE_BUTTON = 'close-button';
  35177. GUI.CLASS_CLOSE_TOP = 'close-top';
  35178. GUI.CLASS_CLOSE_BOTTOM = 'close-bottom';
  35179. GUI.CLASS_DRAG = 'drag';
  35180. GUI.DEFAULT_WIDTH = 245;
  35181. GUI.TEXT_CLOSED = 'Close Controls';
  35182. GUI.TEXT_OPEN = 'Open Controls';
  35183. GUI._keydownHandler = function (e) {
  35184. if (document.activeElement.type !== 'text' && (e.which === HIDE_KEY_CODE || e.keyCode === HIDE_KEY_CODE)) {
  35185. GUI.toggleHide();
  35186. }
  35187. };
  35188. dom.bind(window, 'keydown', GUI._keydownHandler, false);
  35189. Common.extend(GUI.prototype, {
  35190. add: function add(object, property) {
  35191. return _add(this, object, property, {
  35192. factoryArgs: Array.prototype.slice.call(arguments, 2)
  35193. });
  35194. },
  35195. addColor: function addColor(object, property) {
  35196. return _add(this, object, property, {
  35197. color: true
  35198. });
  35199. },
  35200. remove: function remove(controller) {
  35201. this.__ul.removeChild(controller.__li);
  35202. this.__controllers.splice(this.__controllers.indexOf(controller), 1);
  35203. var _this = this;
  35204. Common.defer(function () {
  35205. _this.onResize();
  35206. });
  35207. },
  35208. destroy: function destroy() {
  35209. if (this.parent) {
  35210. throw new Error('Only the root GUI should be removed with .destroy(). ' + 'For subfolders, use gui.removeFolder(folder) instead.');
  35211. }
  35212. if (this.autoPlace) {
  35213. autoPlaceContainer.removeChild(this.domElement);
  35214. }
  35215. var _this = this;
  35216. Common.each(this.__folders, function (subfolder) {
  35217. _this.removeFolder(subfolder);
  35218. });
  35219. dom.unbind(window, 'keydown', GUI._keydownHandler, false);
  35220. removeListeners(this);
  35221. },
  35222. addFolder: function addFolder(name) {
  35223. if (this.__folders[name] !== undefined) {
  35224. throw new Error('You already have a folder in this GUI by the' + ' name "' + name + '"');
  35225. }
  35226. var newGuiParams = {
  35227. name: name,
  35228. parent: this
  35229. };
  35230. newGuiParams.autoPlace = this.autoPlace;
  35231. if (this.load && this.load.folders && this.load.folders[name]) {
  35232. newGuiParams.closed = this.load.folders[name].closed;
  35233. newGuiParams.load = this.load.folders[name];
  35234. }
  35235. var gui = new GUI(newGuiParams);
  35236. this.__folders[name] = gui;
  35237. var li = addRow(this, gui.domElement);
  35238. dom.addClass(li, 'folder');
  35239. return gui;
  35240. },
  35241. removeFolder: function removeFolder(folder) {
  35242. this.__ul.removeChild(folder.domElement.parentElement);
  35243. delete this.__folders[folder.name];
  35244. if (this.load && this.load.folders && this.load.folders[folder.name]) {
  35245. delete this.load.folders[folder.name];
  35246. }
  35247. removeListeners(folder);
  35248. var _this = this;
  35249. Common.each(folder.__folders, function (subfolder) {
  35250. folder.removeFolder(subfolder);
  35251. });
  35252. Common.defer(function () {
  35253. _this.onResize();
  35254. });
  35255. },
  35256. open: function open() {
  35257. this.closed = false;
  35258. },
  35259. close: function close() {
  35260. this.closed = true;
  35261. },
  35262. hide: function hide() {
  35263. this.domElement.style.display = 'none';
  35264. },
  35265. show: function show() {
  35266. this.domElement.style.display = '';
  35267. },
  35268. onResize: function onResize() {
  35269. var root = this.getRoot();
  35270. if (root.scrollable) {
  35271. var top = dom.getOffset(root.__ul).top;
  35272. var h = 0;
  35273. Common.each(root.__ul.childNodes, function (node) {
  35274. if (!(root.autoPlace && node === root.__save_row)) {
  35275. h += dom.getHeight(node);
  35276. }
  35277. });
  35278. if (window.innerHeight - top - CLOSE_BUTTON_HEIGHT < h) {
  35279. dom.addClass(root.domElement, GUI.CLASS_TOO_TALL);
  35280. root.__ul.style.height = window.innerHeight - top - CLOSE_BUTTON_HEIGHT + 'px';
  35281. } else {
  35282. dom.removeClass(root.domElement, GUI.CLASS_TOO_TALL);
  35283. root.__ul.style.height = 'auto';
  35284. }
  35285. }
  35286. if (root.__resize_handle) {
  35287. Common.defer(function () {
  35288. root.__resize_handle.style.height = root.__ul.offsetHeight + 'px';
  35289. });
  35290. }
  35291. if (root.__closeButton) {
  35292. root.__closeButton.style.width = root.width + 'px';
  35293. }
  35294. },
  35295. onResizeDebounced: Common.debounce(function () {
  35296. this.onResize();
  35297. }, 50),
  35298. remember: function remember() {
  35299. if (Common.isUndefined(SAVE_DIALOGUE)) {
  35300. SAVE_DIALOGUE = new CenteredDiv();
  35301. SAVE_DIALOGUE.domElement.innerHTML = saveDialogContents;
  35302. }
  35303. if (this.parent) {
  35304. throw new Error('You can only call remember on a top level GUI.');
  35305. }
  35306. var _this = this;
  35307. Common.each(Array.prototype.slice.call(arguments), function (object) {
  35308. if (_this.__rememberedObjects.length === 0) {
  35309. addSaveMenu(_this);
  35310. }
  35311. if (_this.__rememberedObjects.indexOf(object) === -1) {
  35312. _this.__rememberedObjects.push(object);
  35313. }
  35314. });
  35315. if (this.autoPlace) {
  35316. setWidth(this, this.width);
  35317. }
  35318. },
  35319. getRoot: function getRoot() {
  35320. var gui = this;
  35321. while (gui.parent) {
  35322. gui = gui.parent;
  35323. }
  35324. return gui;
  35325. },
  35326. getSaveObject: function getSaveObject() {
  35327. var toReturn = this.load;
  35328. toReturn.closed = this.closed;
  35329. if (this.__rememberedObjects.length > 0) {
  35330. toReturn.preset = this.preset;
  35331. if (!toReturn.remembered) {
  35332. toReturn.remembered = {};
  35333. }
  35334. toReturn.remembered[this.preset] = getCurrentPreset(this);
  35335. }
  35336. toReturn.folders = {};
  35337. Common.each(this.__folders, function (element, key) {
  35338. toReturn.folders[key] = element.getSaveObject();
  35339. });
  35340. return toReturn;
  35341. },
  35342. save: function save() {
  35343. if (!this.load.remembered) {
  35344. this.load.remembered = {};
  35345. }
  35346. this.load.remembered[this.preset] = getCurrentPreset(this);
  35347. markPresetModified(this, false);
  35348. this.saveToLocalStorageIfPossible();
  35349. },
  35350. saveAs: function saveAs(presetName) {
  35351. if (!this.load.remembered) {
  35352. this.load.remembered = {};
  35353. this.load.remembered[DEFAULT_DEFAULT_PRESET_NAME] = getCurrentPreset(this, true);
  35354. }
  35355. this.load.remembered[presetName] = getCurrentPreset(this);
  35356. this.preset = presetName;
  35357. addPresetOption(this, presetName, true);
  35358. this.saveToLocalStorageIfPossible();
  35359. },
  35360. revert: function revert(gui) {
  35361. Common.each(this.__controllers, function (controller) {
  35362. if (!this.getRoot().load.remembered) {
  35363. controller.setValue(controller.initialValue);
  35364. } else {
  35365. recallSavedValue(gui || this.getRoot(), controller);
  35366. }
  35367. if (controller.__onFinishChange) {
  35368. controller.__onFinishChange.call(controller, controller.getValue());
  35369. }
  35370. }, this);
  35371. Common.each(this.__folders, function (folder) {
  35372. folder.revert(folder);
  35373. });
  35374. if (!gui) {
  35375. markPresetModified(this.getRoot(), false);
  35376. }
  35377. },
  35378. listen: function listen(controller) {
  35379. var init = this.__listening.length === 0;
  35380. this.__listening.push(controller);
  35381. if (init) {
  35382. updateDisplays(this.__listening);
  35383. }
  35384. },
  35385. updateDisplay: function updateDisplay() {
  35386. Common.each(this.__controllers, function (controller) {
  35387. controller.updateDisplay();
  35388. });
  35389. Common.each(this.__folders, function (folder) {
  35390. folder.updateDisplay();
  35391. });
  35392. }
  35393. });
  35394. function addRow(gui, newDom, liBefore) {
  35395. var li = document.createElement('li');
  35396. if (newDom) {
  35397. li.appendChild(newDom);
  35398. }
  35399. if (liBefore) {
  35400. gui.__ul.insertBefore(li, liBefore);
  35401. } else {
  35402. gui.__ul.appendChild(li);
  35403. }
  35404. gui.onResize();
  35405. return li;
  35406. }
  35407. function removeListeners(gui) {
  35408. dom.unbind(window, 'resize', gui.__resizeHandler);
  35409. if (gui.saveToLocalStorageIfPossible) {
  35410. dom.unbind(window, 'unload', gui.saveToLocalStorageIfPossible);
  35411. }
  35412. }
  35413. function markPresetModified(gui, modified) {
  35414. var opt = gui.__preset_select[gui.__preset_select.selectedIndex];
  35415. if (modified) {
  35416. opt.innerHTML = opt.value + '*';
  35417. } else {
  35418. opt.innerHTML = opt.value;
  35419. }
  35420. }
  35421. function augmentController(gui, li, controller) {
  35422. controller.__li = li;
  35423. controller.__gui = gui;
  35424. Common.extend(controller, {
  35425. options: function options(_options) {
  35426. if (arguments.length > 1) {
  35427. var nextSibling = controller.__li.nextElementSibling;
  35428. controller.remove();
  35429. return _add(gui, controller.object, controller.property, {
  35430. before: nextSibling,
  35431. factoryArgs: [Common.toArray(arguments)]
  35432. });
  35433. }
  35434. if (Common.isArray(_options) || Common.isObject(_options)) {
  35435. var _nextSibling = controller.__li.nextElementSibling;
  35436. controller.remove();
  35437. return _add(gui, controller.object, controller.property, {
  35438. before: _nextSibling,
  35439. factoryArgs: [_options]
  35440. });
  35441. }
  35442. },
  35443. name: function name(_name) {
  35444. controller.__li.firstElementChild.firstElementChild.innerHTML = _name;
  35445. return controller;
  35446. },
  35447. listen: function listen() {
  35448. controller.__gui.listen(controller);
  35449. return controller;
  35450. },
  35451. remove: function remove() {
  35452. controller.__gui.remove(controller);
  35453. return controller;
  35454. }
  35455. });
  35456. if (controller instanceof NumberControllerSlider) {
  35457. var box = new NumberControllerBox(controller.object, controller.property, {
  35458. min: controller.__min,
  35459. max: controller.__max,
  35460. step: controller.__step
  35461. });
  35462. Common.each(['updateDisplay', 'onChange', 'onFinishChange', 'step', 'min', 'max'], function (method) {
  35463. var pc = controller[method];
  35464. var pb = box[method];
  35465. controller[method] = box[method] = function () {
  35466. var args = Array.prototype.slice.call(arguments);
  35467. pb.apply(box, args);
  35468. return pc.apply(controller, args);
  35469. };
  35470. });
  35471. dom.addClass(li, 'has-slider');
  35472. controller.domElement.insertBefore(box.domElement, controller.domElement.firstElementChild);
  35473. } else if (controller instanceof NumberControllerBox) {
  35474. var r = function r(returned) {
  35475. if (Common.isNumber(controller.__min) && Common.isNumber(controller.__max)) {
  35476. var oldName = controller.__li.firstElementChild.firstElementChild.innerHTML;
  35477. var wasListening = controller.__gui.__listening.indexOf(controller) > -1;
  35478. controller.remove();
  35479. var newController = _add(gui, controller.object, controller.property, {
  35480. before: controller.__li.nextElementSibling,
  35481. factoryArgs: [controller.__min, controller.__max, controller.__step]
  35482. });
  35483. newController.name(oldName);
  35484. if (wasListening) newController.listen();
  35485. return newController;
  35486. }
  35487. return returned;
  35488. };
  35489. controller.min = Common.compose(r, controller.min);
  35490. controller.max = Common.compose(r, controller.max);
  35491. } else if (controller instanceof BooleanController) {
  35492. dom.bind(li, 'click', function () {
  35493. dom.fakeEvent(controller.__checkbox, 'click');
  35494. });
  35495. dom.bind(controller.__checkbox, 'click', function (e) {
  35496. e.stopPropagation();
  35497. });
  35498. } else if (controller instanceof FunctionController) {
  35499. dom.bind(li, 'click', function () {
  35500. dom.fakeEvent(controller.__button, 'click');
  35501. });
  35502. dom.bind(li, 'mouseover', function () {
  35503. dom.addClass(controller.__button, 'hover');
  35504. });
  35505. dom.bind(li, 'mouseout', function () {
  35506. dom.removeClass(controller.__button, 'hover');
  35507. });
  35508. } else if (controller instanceof ColorController) {
  35509. dom.addClass(li, 'color');
  35510. controller.updateDisplay = Common.compose(function (val) {
  35511. li.style.borderLeftColor = controller.__color.toString();
  35512. return val;
  35513. }, controller.updateDisplay);
  35514. controller.updateDisplay();
  35515. }
  35516. controller.setValue = Common.compose(function (val) {
  35517. if (gui.getRoot().__preset_select && controller.isModified()) {
  35518. markPresetModified(gui.getRoot(), true);
  35519. }
  35520. return val;
  35521. }, controller.setValue);
  35522. }
  35523. function recallSavedValue(gui, controller) {
  35524. var root = gui.getRoot();
  35525. var matchedIndex = root.__rememberedObjects.indexOf(controller.object);
  35526. if (matchedIndex !== -1) {
  35527. var controllerMap = root.__rememberedObjectIndecesToControllers[matchedIndex];
  35528. if (controllerMap === undefined) {
  35529. controllerMap = {};
  35530. root.__rememberedObjectIndecesToControllers[matchedIndex] = controllerMap;
  35531. }
  35532. controllerMap[controller.property] = controller;
  35533. if (root.load && root.load.remembered) {
  35534. var presetMap = root.load.remembered;
  35535. var preset = void 0;
  35536. if (presetMap[gui.preset]) {
  35537. preset = presetMap[gui.preset];
  35538. } else if (presetMap[DEFAULT_DEFAULT_PRESET_NAME]) {
  35539. preset = presetMap[DEFAULT_DEFAULT_PRESET_NAME];
  35540. } else {
  35541. return;
  35542. }
  35543. if (preset[matchedIndex] && preset[matchedIndex][controller.property] !== undefined) {
  35544. var value = preset[matchedIndex][controller.property];
  35545. controller.initialValue = value;
  35546. controller.setValue(value);
  35547. }
  35548. }
  35549. }
  35550. }
  35551. function _add(gui, object, property, params) {
  35552. if (object[property] === undefined) {
  35553. throw new Error('Object "' + object + '" has no property "' + property + '"');
  35554. }
  35555. var controller = void 0;
  35556. if (params.color) {
  35557. controller = new ColorController(object, property);
  35558. } else {
  35559. var factoryArgs = [object, property].concat(params.factoryArgs);
  35560. controller = ControllerFactory.apply(gui, factoryArgs);
  35561. }
  35562. if (params.before instanceof Controller) {
  35563. params.before = params.before.__li;
  35564. }
  35565. recallSavedValue(gui, controller);
  35566. dom.addClass(controller.domElement, 'c');
  35567. var name = document.createElement('span');
  35568. dom.addClass(name, 'property-name');
  35569. name.innerHTML = controller.property;
  35570. var container = document.createElement('div');
  35571. container.appendChild(name);
  35572. container.appendChild(controller.domElement);
  35573. var li = addRow(gui, container, params.before);
  35574. dom.addClass(li, GUI.CLASS_CONTROLLER_ROW);
  35575. if (controller instanceof ColorController) {
  35576. dom.addClass(li, 'color');
  35577. } else {
  35578. dom.addClass(li, _typeof(controller.getValue()));
  35579. }
  35580. augmentController(gui, li, controller);
  35581. gui.__controllers.push(controller);
  35582. return controller;
  35583. }
  35584. function getLocalStorageHash(gui, key) {
  35585. return document.location.href + '.' + key;
  35586. }
  35587. function addPresetOption(gui, name, setSelected) {
  35588. var opt = document.createElement('option');
  35589. opt.innerHTML = name;
  35590. opt.value = name;
  35591. gui.__preset_select.appendChild(opt);
  35592. if (setSelected) {
  35593. gui.__preset_select.selectedIndex = gui.__preset_select.length - 1;
  35594. }
  35595. }
  35596. function showHideExplain(gui, explain) {
  35597. explain.style.display = gui.useLocalStorage ? 'block' : 'none';
  35598. }
  35599. function addSaveMenu(gui) {
  35600. var div = gui.__save_row = document.createElement('li');
  35601. dom.addClass(gui.domElement, 'has-save');
  35602. gui.__ul.insertBefore(div, gui.__ul.firstChild);
  35603. dom.addClass(div, 'save-row');
  35604. var gears = document.createElement('span');
  35605. gears.innerHTML = '&nbsp;';
  35606. dom.addClass(gears, 'button gears');
  35607. var button = document.createElement('span');
  35608. button.innerHTML = 'Save';
  35609. dom.addClass(button, 'button');
  35610. dom.addClass(button, 'save');
  35611. var button2 = document.createElement('span');
  35612. button2.innerHTML = 'New';
  35613. dom.addClass(button2, 'button');
  35614. dom.addClass(button2, 'save-as');
  35615. var button3 = document.createElement('span');
  35616. button3.innerHTML = 'Revert';
  35617. dom.addClass(button3, 'button');
  35618. dom.addClass(button3, 'revert');
  35619. var select = gui.__preset_select = document.createElement('select');
  35620. if (gui.load && gui.load.remembered) {
  35621. Common.each(gui.load.remembered, function (value, key) {
  35622. addPresetOption(gui, key, key === gui.preset);
  35623. });
  35624. } else {
  35625. addPresetOption(gui, DEFAULT_DEFAULT_PRESET_NAME, false);
  35626. }
  35627. dom.bind(select, 'change', function () {
  35628. for (var index = 0; index < gui.__preset_select.length; index++) {
  35629. gui.__preset_select[index].innerHTML = gui.__preset_select[index].value;
  35630. }
  35631. gui.preset = this.value;
  35632. });
  35633. div.appendChild(select);
  35634. div.appendChild(gears);
  35635. div.appendChild(button);
  35636. div.appendChild(button2);
  35637. div.appendChild(button3);
  35638. if (SUPPORTS_LOCAL_STORAGE) {
  35639. var explain = document.getElementById('dg-local-explain');
  35640. var localStorageCheckBox = document.getElementById('dg-local-storage');
  35641. var saveLocally = document.getElementById('dg-save-locally');
  35642. saveLocally.style.display = 'block';
  35643. if (localStorage.getItem(getLocalStorageHash(gui, 'isLocal')) === 'true') {
  35644. localStorageCheckBox.setAttribute('checked', 'checked');
  35645. }
  35646. showHideExplain(gui, explain);
  35647. dom.bind(localStorageCheckBox, 'change', function () {
  35648. gui.useLocalStorage = !gui.useLocalStorage;
  35649. showHideExplain(gui, explain);
  35650. });
  35651. }
  35652. var newConstructorTextArea = document.getElementById('dg-new-constructor');
  35653. dom.bind(newConstructorTextArea, 'keydown', function (e) {
  35654. if (e.metaKey && (e.which === 67 || e.keyCode === 67)) {
  35655. SAVE_DIALOGUE.hide();
  35656. }
  35657. });
  35658. dom.bind(gears, 'click', function () {
  35659. newConstructorTextArea.innerHTML = JSON.stringify(gui.getSaveObject(), undefined, 2);
  35660. SAVE_DIALOGUE.show();
  35661. newConstructorTextArea.focus();
  35662. newConstructorTextArea.select();
  35663. });
  35664. dom.bind(button, 'click', function () {
  35665. gui.save();
  35666. });
  35667. dom.bind(button2, 'click', function () {
  35668. var presetName = prompt('Enter a new preset name.');
  35669. if (presetName) {
  35670. gui.saveAs(presetName);
  35671. }
  35672. });
  35673. dom.bind(button3, 'click', function () {
  35674. gui.revert();
  35675. });
  35676. }
  35677. function addResizeHandle(gui) {
  35678. var pmouseX = void 0;
  35679. gui.__resize_handle = document.createElement('div');
  35680. Common.extend(gui.__resize_handle.style, {
  35681. width: '6px',
  35682. marginLeft: '-3px',
  35683. height: '200px',
  35684. cursor: 'ew-resize',
  35685. position: 'absolute'
  35686. });
  35687. function drag(e) {
  35688. e.preventDefault();
  35689. gui.width += pmouseX - e.clientX;
  35690. gui.onResize();
  35691. pmouseX = e.clientX;
  35692. return false;
  35693. }
  35694. function dragStop() {
  35695. dom.removeClass(gui.__closeButton, GUI.CLASS_DRAG);
  35696. dom.unbind(window, 'mousemove', drag);
  35697. dom.unbind(window, 'mouseup', dragStop);
  35698. }
  35699. function dragStart(e) {
  35700. e.preventDefault();
  35701. pmouseX = e.clientX;
  35702. dom.addClass(gui.__closeButton, GUI.CLASS_DRAG);
  35703. dom.bind(window, 'mousemove', drag);
  35704. dom.bind(window, 'mouseup', dragStop);
  35705. return false;
  35706. }
  35707. dom.bind(gui.__resize_handle, 'mousedown', dragStart);
  35708. dom.bind(gui.__closeButton, 'mousedown', dragStart);
  35709. gui.domElement.insertBefore(gui.__resize_handle, gui.domElement.firstElementChild);
  35710. }
  35711. function setWidth(gui, w) {
  35712. gui.domElement.style.width = w + 'px';
  35713. if (gui.__save_row && gui.autoPlace) {
  35714. gui.__save_row.style.width = w + 'px';
  35715. }
  35716. if (gui.__closeButton) {
  35717. gui.__closeButton.style.width = w + 'px';
  35718. }
  35719. }
  35720. function getCurrentPreset(gui, useInitialValues) {
  35721. var toReturn = {};
  35722. Common.each(gui.__rememberedObjects, function (val, index) {
  35723. var savedValues = {};
  35724. var controllerMap = gui.__rememberedObjectIndecesToControllers[index];
  35725. Common.each(controllerMap, function (controller, property) {
  35726. savedValues[property] = useInitialValues ? controller.initialValue : controller.getValue();
  35727. });
  35728. toReturn[index] = savedValues;
  35729. });
  35730. return toReturn;
  35731. }
  35732. function setPresetSelectIndex(gui) {
  35733. for (var index = 0; index < gui.__preset_select.length; index++) {
  35734. if (gui.__preset_select[index].value === gui.preset) {
  35735. gui.__preset_select.selectedIndex = index;
  35736. }
  35737. }
  35738. }
  35739. function updateDisplays(controllerArray) {
  35740. if (controllerArray.length !== 0) {
  35741. requestAnimationFrame$1.call(window, function () {
  35742. updateDisplays(controllerArray);
  35743. });
  35744. }
  35745. Common.each(controllerArray, function (c) {
  35746. c.updateDisplay();
  35747. });
  35748. }
  35749. var color = {
  35750. Color: Color,
  35751. math: ColorMath,
  35752. interpret: interpret
  35753. };
  35754. exports.color = color;
  35755. var controllers = {
  35756. Controller: Controller,
  35757. BooleanController: BooleanController,
  35758. OptionController: OptionController,
  35759. StringController: StringController,
  35760. NumberController: NumberController,
  35761. NumberControllerBox: NumberControllerBox,
  35762. NumberControllerSlider: NumberControllerSlider,
  35763. FunctionController: FunctionController,
  35764. ColorController: ColorController
  35765. };
  35766. exports.controllers = controllers;
  35767. var dom$1 = {
  35768. dom: dom
  35769. };
  35770. exports.dom = dom$1;
  35771. var gui = {
  35772. GUI: GUI
  35773. };
  35774. exports.gui = gui;
  35775. var GUI$1 = GUI;
  35776. exports.GUI = GUI$1;
  35777. var index = {
  35778. color: color,
  35779. controllers: controllers,
  35780. dom: dom$1,
  35781. gui: gui,
  35782. GUI: GUI$1
  35783. };
  35784. var _default = index;
  35785. exports.default = _default;
  35786. },{}],"../node_modules/three/examples/jsm/libs/stats.module.js":[function(require,module,exports) {
  35787. "use strict";
  35788. Object.defineProperty(exports, "__esModule", {
  35789. value: true
  35790. });
  35791. exports.default = void 0;
  35792. /**
  35793. * @author mrdoob / http://mrdoob.com/
  35794. */
  35795. var Stats = function () {
  35796. var mode = 0;
  35797. var container = document.createElement('div');
  35798. container.style.cssText = 'position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000';
  35799. container.addEventListener('click', function (event) {
  35800. event.preventDefault();
  35801. showPanel(++mode % container.children.length);
  35802. }, false); //
  35803. function addPanel(panel) {
  35804. container.appendChild(panel.dom);
  35805. return panel;
  35806. }
  35807. function showPanel(id) {
  35808. for (var i = 0; i < container.children.length; i++) {
  35809. container.children[i].style.display = i === id ? 'block' : 'none';
  35810. }
  35811. mode = id;
  35812. } //
  35813. var beginTime = (performance || Date).now(),
  35814. prevTime = beginTime,
  35815. frames = 0;
  35816. var fpsPanel = addPanel(new Stats.Panel('FPS', '#0ff', '#002'));
  35817. var msPanel = addPanel(new Stats.Panel('MS', '#0f0', '#020'));
  35818. if (self.performance && self.performance.memory) {
  35819. var memPanel = addPanel(new Stats.Panel('MB', '#f08', '#201'));
  35820. }
  35821. showPanel(0);
  35822. return {
  35823. REVISION: 16,
  35824. dom: container,
  35825. addPanel: addPanel,
  35826. showPanel: showPanel,
  35827. begin: function () {
  35828. beginTime = (performance || Date).now();
  35829. },
  35830. end: function () {
  35831. frames++;
  35832. var time = (performance || Date).now();
  35833. msPanel.update(time - beginTime, 200);
  35834. if (time >= prevTime + 1000) {
  35835. fpsPanel.update(frames * 1000 / (time - prevTime), 100);
  35836. prevTime = time;
  35837. frames = 0;
  35838. if (memPanel) {
  35839. var memory = performance.memory;
  35840. memPanel.update(memory.usedJSHeapSize / 1048576, memory.jsHeapSizeLimit / 1048576);
  35841. }
  35842. }
  35843. return time;
  35844. },
  35845. update: function () {
  35846. beginTime = this.end();
  35847. },
  35848. // Backwards Compatibility
  35849. domElement: container,
  35850. setMode: showPanel
  35851. };
  35852. };
  35853. Stats.Panel = function (name, fg, bg) {
  35854. var min = Infinity,
  35855. max = 0,
  35856. round = Math.round;
  35857. var PR = round(window.devicePixelRatio || 1);
  35858. var WIDTH = 80 * PR,
  35859. HEIGHT = 48 * PR,
  35860. TEXT_X = 3 * PR,
  35861. TEXT_Y = 2 * PR,
  35862. GRAPH_X = 3 * PR,
  35863. GRAPH_Y = 15 * PR,
  35864. GRAPH_WIDTH = 74 * PR,
  35865. GRAPH_HEIGHT = 30 * PR;
  35866. var canvas = document.createElement('canvas');
  35867. canvas.width = WIDTH;
  35868. canvas.height = HEIGHT;
  35869. canvas.style.cssText = 'width:80px;height:48px';
  35870. var context = canvas.getContext('2d');
  35871. context.font = 'bold ' + 9 * PR + 'px Helvetica,Arial,sans-serif';
  35872. context.textBaseline = 'top';
  35873. context.fillStyle = bg;
  35874. context.fillRect(0, 0, WIDTH, HEIGHT);
  35875. context.fillStyle = fg;
  35876. context.fillText(name, TEXT_X, TEXT_Y);
  35877. context.fillRect(GRAPH_X, GRAPH_Y, GRAPH_WIDTH, GRAPH_HEIGHT);
  35878. context.fillStyle = bg;
  35879. context.globalAlpha = 0.9;
  35880. context.fillRect(GRAPH_X, GRAPH_Y, GRAPH_WIDTH, GRAPH_HEIGHT);
  35881. return {
  35882. dom: canvas,
  35883. update: function (value, maxValue) {
  35884. min = Math.min(min, value);
  35885. max = Math.max(max, value);
  35886. context.fillStyle = bg;
  35887. context.globalAlpha = 1;
  35888. context.fillRect(0, 0, WIDTH, GRAPH_Y);
  35889. context.fillStyle = fg;
  35890. context.fillText(round(value) + ' ' + name + ' (' + round(min) + '-' + round(max) + ')', TEXT_X, TEXT_Y);
  35891. context.drawImage(canvas, GRAPH_X + PR, GRAPH_Y, GRAPH_WIDTH - PR, GRAPH_HEIGHT, GRAPH_X, GRAPH_Y, GRAPH_WIDTH - PR, GRAPH_HEIGHT);
  35892. context.fillRect(GRAPH_X + GRAPH_WIDTH - PR, GRAPH_Y, PR, GRAPH_HEIGHT);
  35893. context.fillStyle = bg;
  35894. context.globalAlpha = 0.9;
  35895. context.fillRect(GRAPH_X + GRAPH_WIDTH - PR, GRAPH_Y, PR, round((1 - value / maxValue) * GRAPH_HEIGHT));
  35896. }
  35897. };
  35898. };
  35899. var _default = Stats;
  35900. exports.default = _default;
  35901. },{}],"index.js":[function(require,module,exports) {
  35902. "use strict";
  35903. var _index = require("../src/index.js");
  35904. var _three = require("three");
  35905. var _OrbitControls = require("three/examples/jsm/controls/OrbitControls.js");
  35906. var dat = _interopRequireWildcard(require("three/examples/jsm/libs/dat.gui.module.js"));
  35907. var _statsModule = _interopRequireDefault(require("three/examples/jsm/libs/stats.module.js"));
  35908. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  35909. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
  35910. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  35911. let camera, controls, scene, renderer, tiles, cameraHelper;
  35912. let thirdPersonCamera, thirdPersonRenderer, thirdPersonControls;
  35913. let box;
  35914. let raycaster, mouse, rayIntersect;
  35915. let offsetParent;
  35916. let statsContainer, stats;
  35917. let params = {
  35918. 'errorTarget': 6,
  35919. 'errorThreshold': 60,
  35920. 'maxDepth': 15,
  35921. 'loadSiblings': true,
  35922. 'up': '+Y',
  35923. 'displayBounds': false,
  35924. 'showThirdPerson': true,
  35925. 'reload': reinstantiateTiles
  35926. };
  35927. init();
  35928. animate();
  35929. function reinstantiateTiles() {
  35930. const url = window.location.hash.replace(/^#/, '') || './SampleTileset/tileset.json';
  35931. if (tiles) {
  35932. offsetParent.remove(tiles.group);
  35933. }
  35934. tiles = new _index.ThreeTilesRenderer(url, camera, renderer);
  35935. offsetParent.add(tiles.group);
  35936. }
  35937. function init() {
  35938. // Third person camera view
  35939. thirdPersonCamera = new _three.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 3000);
  35940. thirdPersonCamera.position.set(50, 40, 40);
  35941. thirdPersonCamera.lookAt(0, 0, 0);
  35942. thirdPersonRenderer = new _three.WebGLRenderer({
  35943. antialias: true
  35944. });
  35945. thirdPersonRenderer.setPixelRatio(window.devicePixelRatio);
  35946. thirdPersonRenderer.setSize(window.innerWidth, window.innerHeight);
  35947. thirdPersonRenderer.setClearColor(0x0f1416);
  35948. document.body.appendChild(thirdPersonRenderer.domElement);
  35949. thirdPersonRenderer.domElement.style.position = 'fixed';
  35950. thirdPersonRenderer.domElement.style.left = '5px';
  35951. thirdPersonRenderer.domElement.style.bottom = '5px';
  35952. thirdPersonControls = new _OrbitControls.OrbitControls(thirdPersonCamera, thirdPersonRenderer.domElement);
  35953. thirdPersonControls.screenSpacePanning = false;
  35954. thirdPersonControls.minDistance = 1;
  35955. thirdPersonControls.maxDistance = 2000; // primary camera view
  35956. scene = new _three.Scene();
  35957. renderer = new _three.WebGLRenderer({
  35958. antialias: true
  35959. });
  35960. renderer.setPixelRatio(window.devicePixelRatio);
  35961. renderer.setSize(window.innerWidth, window.innerHeight);
  35962. renderer.setClearColor(0x151c1f);
  35963. renderer.gammaInput = true;
  35964. renderer.gameOutput = true;
  35965. document.body.appendChild(renderer.domElement);
  35966. camera = new _three.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 2000);
  35967. camera.position.set(100, 100, 100);
  35968. cameraHelper = new _three.CameraHelper(camera);
  35969. scene.add(cameraHelper); // controls
  35970. controls = new _OrbitControls.OrbitControls(camera, renderer.domElement);
  35971. controls.screenSpacePanning = false;
  35972. controls.minDistance = 1;
  35973. controls.maxDistance = 2000; // lights
  35974. var dirLight = new _three.DirectionalLight(0xffffff);
  35975. dirLight.position.set(1, 1, 1);
  35976. scene.add(dirLight);
  35977. var ambLight = new _three.AmbientLight(0x222222);
  35978. scene.add(ambLight);
  35979. box = new _three.Box3();
  35980. offsetParent = new _three.Group();
  35981. scene.add(offsetParent); // Raycasting init
  35982. raycaster = new _three.Raycaster();
  35983. mouse = new _three.Vector2();
  35984. rayIntersect = new _three.Group();
  35985. const rayIntersectMat = new _three.MeshBasicMaterial({
  35986. color: 0xe91e63
  35987. });
  35988. const rayMesh = new _three.Mesh(new _three.CylinderBufferGeometry(0.25, 0.25, 10), rayIntersectMat);
  35989. rayMesh.rotation.x = Math.PI / 2;
  35990. rayMesh.position.z += 5;
  35991. rayIntersect.add(rayMesh);
  35992. const rayRing = new _three.Mesh(new _three.TorusBufferGeometry(1.5, 0.2, 16, 100), rayIntersectMat);
  35993. rayIntersect.add(rayRing);
  35994. scene.add(rayIntersect);
  35995. rayIntersect.visible = false;
  35996. reinstantiateTiles();
  35997. onWindowResize();
  35998. window.addEventListener('resize', onWindowResize, false);
  35999. window.addEventListener('mousemove', onMouseMove, false); // GUI
  36000. const gui = new dat.GUI();
  36001. const tiles = gui.addFolder('Tiles Options');
  36002. tiles.add(params, 'loadSiblings');
  36003. tiles.add(params, 'errorTarget').min(0).max(50);
  36004. tiles.add(params, 'errorThreshold').min(0).max(1000);
  36005. tiles.add(params, 'maxDepth').min(1).max(100);
  36006. tiles.add(params, 'up', ['+Y', '-Z']);
  36007. tiles.open();
  36008. gui.add(params, 'displayBounds');
  36009. gui.add(params, 'showThirdPerson');
  36010. gui.add(params, 'reload');
  36011. gui.open();
  36012. statsContainer = document.createElement('div');
  36013. statsContainer.style.position = 'absolute';
  36014. statsContainer.style.top = 0;
  36015. statsContainer.style.left = 0;
  36016. statsContainer.style.color = 'white';
  36017. statsContainer.style.width = '100%';
  36018. statsContainer.style.textAlign = 'center';
  36019. statsContainer.style.padding = '10px';
  36020. document.body.appendChild(statsContainer); // Stats
  36021. stats = new _statsModule.default();
  36022. stats.showPanel(0);
  36023. document.body.appendChild(stats.dom);
  36024. }
  36025. function onWindowResize() {
  36026. thirdPersonCamera.aspect = window.innerWidth / window.innerHeight;
  36027. thirdPersonCamera.updateProjectionMatrix();
  36028. thirdPersonRenderer.setSize(Math.floor(window.innerWidth / 3), Math.floor(window.innerHeight / 3));
  36029. camera.aspect = window.innerWidth / window.innerHeight;
  36030. camera.updateProjectionMatrix();
  36031. renderer.setSize(window.innerWidth, window.innerHeight);
  36032. }
  36033. function onMouseMove(e) {
  36034. mouse.x = e.clientX / window.innerWidth * 2 - 1;
  36035. mouse.y = -(e.clientY / window.innerHeight) * 2 + 1;
  36036. }
  36037. function animate() {
  36038. // update options
  36039. tiles.errorTarget = params.errorTarget;
  36040. tiles.errorThreshold = params.errorThreshold;
  36041. tiles.loadSiblings = params.loadSiblings;
  36042. tiles.maxDepth = params.maxDepth;
  36043. tiles.displayBounds = params.displayBounds; // update tiles
  36044. tiles.update();
  36045. window.tiles = tiles;
  36046. offsetParent.rotation.set(0, 0, 0);
  36047. if (params.up === '-Z') {
  36048. offsetParent.rotation.x = Math.PI / 2;
  36049. } // update tiles center
  36050. if (tiles.getBounds(box)) {
  36051. box.getCenter(tiles.group.position);
  36052. tiles.group.position.multiplyScalar(-1);
  36053. }
  36054. raycaster.setFromCamera(mouse, camera);
  36055. const results = raycaster.intersectObject(tiles.group, true);
  36056. if (results.length) {
  36057. const closestHit = results[0];
  36058. const point = closestHit.point;
  36059. const normal = closestHit.face.normal;
  36060. rayIntersect.position.copy(point);
  36061. rayIntersect.lookAt(point.x + normal.x, point.y + normal.y, point.z + normal.z);
  36062. rayIntersect.visible = true;
  36063. } else {
  36064. rayIntersect.visible = false;
  36065. }
  36066. stats.begin();
  36067. render();
  36068. stats.end();
  36069. requestAnimationFrame(animate);
  36070. }
  36071. function render() {
  36072. // render primary view
  36073. cameraHelper.visible = false;
  36074. renderer.render(scene, camera); // render third person view
  36075. thirdPersonRenderer.domElement.style.visibility = params.showThirdPerson ? 'visible' : 'hidden';
  36076. if (params.showThirdPerson) {
  36077. cameraHelper.visible = true;
  36078. thirdPersonRenderer.render(scene, thirdPersonCamera);
  36079. }
  36080. statsContainer.innerText = `Downloading: ${tiles.stats.downloading} Parsing: ${tiles.stats.parsing} Visible: ${tiles.group.children.length}`;
  36081. }
  36082. },{"../src/index.js":"../src/index.js","three":"../node_modules/three/build/three.module.js","three/examples/jsm/controls/OrbitControls.js":"../node_modules/three/examples/jsm/controls/OrbitControls.js","three/examples/jsm/libs/dat.gui.module.js":"../node_modules/three/examples/jsm/libs/dat.gui.module.js","three/examples/jsm/libs/stats.module.js":"../node_modules/three/examples/jsm/libs/stats.module.js"}],"../node_modules/parcel-bundler/src/builtins/hmr-runtime.js":[function(require,module,exports) {
  36083. var global = arguments[3];
  36084. var OVERLAY_ID = '__parcel__error__overlay__';
  36085. var OldModule = module.bundle.Module;
  36086. function Module(moduleName) {
  36087. OldModule.call(this, moduleName);
  36088. this.hot = {
  36089. data: module.bundle.hotData,
  36090. _acceptCallbacks: [],
  36091. _disposeCallbacks: [],
  36092. accept: function (fn) {
  36093. this._acceptCallbacks.push(fn || function () {});
  36094. },
  36095. dispose: function (fn) {
  36096. this._disposeCallbacks.push(fn);
  36097. }
  36098. };
  36099. module.bundle.hotData = null;
  36100. }
  36101. module.bundle.Module = Module;
  36102. var checkedAssets, assetsToAccept;
  36103. var parent = module.bundle.parent;
  36104. if ((!parent || !parent.isParcelRequire) && typeof WebSocket !== 'undefined') {
  36105. var hostname = "" || location.hostname;
  36106. var protocol = location.protocol === 'https:' ? 'wss' : 'ws';
  36107. var ws = new WebSocket(protocol + '://' + hostname + ':' + "52787" + '/');
  36108. ws.onmessage = function (event) {
  36109. checkedAssets = {};
  36110. assetsToAccept = [];
  36111. var data = JSON.parse(event.data);
  36112. if (data.type === 'update') {
  36113. var handled = false;
  36114. data.assets.forEach(function (asset) {
  36115. if (!asset.isNew) {
  36116. var didAccept = hmrAcceptCheck(global.parcelRequire, asset.id);
  36117. if (didAccept) {
  36118. handled = true;
  36119. }
  36120. }
  36121. }); // Enable HMR for CSS by default.
  36122. handled = handled || data.assets.every(function (asset) {
  36123. return asset.type === 'css' && asset.generated.js;
  36124. });
  36125. if (handled) {
  36126. console.clear();
  36127. data.assets.forEach(function (asset) {
  36128. hmrApply(global.parcelRequire, asset);
  36129. });
  36130. assetsToAccept.forEach(function (v) {
  36131. hmrAcceptRun(v[0], v[1]);
  36132. });
  36133. } else if (location.reload) {
  36134. // `location` global exists in a web worker context but lacks `.reload()` function.
  36135. location.reload();
  36136. }
  36137. }
  36138. if (data.type === 'reload') {
  36139. ws.close();
  36140. ws.onclose = function () {
  36141. location.reload();
  36142. };
  36143. }
  36144. if (data.type === 'error-resolved') {
  36145. console.log('[parcel] ✨ Error resolved');
  36146. removeErrorOverlay();
  36147. }
  36148. if (data.type === 'error') {
  36149. console.error('[parcel] 🚨 ' + data.error.message + '\n' + data.error.stack);
  36150. removeErrorOverlay();
  36151. var overlay = createErrorOverlay(data);
  36152. document.body.appendChild(overlay);
  36153. }
  36154. };
  36155. }
  36156. function removeErrorOverlay() {
  36157. var overlay = document.getElementById(OVERLAY_ID);
  36158. if (overlay) {
  36159. overlay.remove();
  36160. }
  36161. }
  36162. function createErrorOverlay(data) {
  36163. var overlay = document.createElement('div');
  36164. overlay.id = OVERLAY_ID; // html encode message and stack trace
  36165. var message = document.createElement('div');
  36166. var stackTrace = document.createElement('pre');
  36167. message.innerText = data.error.message;
  36168. stackTrace.innerText = data.error.stack;
  36169. overlay.innerHTML = '<div style="background: black; font-size: 16px; color: white; position: fixed; height: 100%; width: 100%; top: 0px; left: 0px; padding: 30px; opacity: 0.85; font-family: Menlo, Consolas, monospace; z-index: 9999;">' + '<span style="background: red; padding: 2px 4px; border-radius: 2px;">ERROR</span>' + '<span style="top: 2px; margin-left: 5px; position: relative;">🚨</span>' + '<div style="font-size: 18px; font-weight: bold; margin-top: 20px;">' + message.innerHTML + '</div>' + '<pre>' + stackTrace.innerHTML + '</pre>' + '</div>';
  36170. return overlay;
  36171. }
  36172. function getParents(bundle, id) {
  36173. var modules = bundle.modules;
  36174. if (!modules) {
  36175. return [];
  36176. }
  36177. var parents = [];
  36178. var k, d, dep;
  36179. for (k in modules) {
  36180. for (d in modules[k][1]) {
  36181. dep = modules[k][1][d];
  36182. if (dep === id || Array.isArray(dep) && dep[dep.length - 1] === id) {
  36183. parents.push(k);
  36184. }
  36185. }
  36186. }
  36187. if (bundle.parent) {
  36188. parents = parents.concat(getParents(bundle.parent, id));
  36189. }
  36190. return parents;
  36191. }
  36192. function hmrApply(bundle, asset) {
  36193. var modules = bundle.modules;
  36194. if (!modules) {
  36195. return;
  36196. }
  36197. if (modules[asset.id] || !bundle.parent) {
  36198. var fn = new Function('require', 'module', 'exports', asset.generated.js);
  36199. asset.isNew = !modules[asset.id];
  36200. modules[asset.id] = [fn, asset.deps];
  36201. } else if (bundle.parent) {
  36202. hmrApply(bundle.parent, asset);
  36203. }
  36204. }
  36205. function hmrAcceptCheck(bundle, id) {
  36206. var modules = bundle.modules;
  36207. if (!modules) {
  36208. return;
  36209. }
  36210. if (!modules[id] && bundle.parent) {
  36211. return hmrAcceptCheck(bundle.parent, id);
  36212. }
  36213. if (checkedAssets[id]) {
  36214. return;
  36215. }
  36216. checkedAssets[id] = true;
  36217. var cached = bundle.cache[id];
  36218. assetsToAccept.push([bundle, id]);
  36219. if (cached && cached.hot && cached.hot._acceptCallbacks.length) {
  36220. return true;
  36221. }
  36222. return getParents(global.parcelRequire, id).some(function (id) {
  36223. return hmrAcceptCheck(global.parcelRequire, id);
  36224. });
  36225. }
  36226. function hmrAcceptRun(bundle, id) {
  36227. var cached = bundle.cache[id];
  36228. bundle.hotData = {};
  36229. if (cached) {
  36230. cached.hot.data = bundle.hotData;
  36231. }
  36232. if (cached && cached.hot && cached.hot._disposeCallbacks.length) {
  36233. cached.hot._disposeCallbacks.forEach(function (cb) {
  36234. cb(bundle.hotData);
  36235. });
  36236. }
  36237. delete bundle.cache[id];
  36238. bundle(id);
  36239. cached = bundle.cache[id];
  36240. if (cached && cached.hot && cached.hot._acceptCallbacks.length) {
  36241. cached.hot._acceptCallbacks.forEach(function (cb) {
  36242. cb();
  36243. });
  36244. return true;
  36245. }
  36246. }
  36247. },{}]},{},["../node_modules/parcel-bundler/src/builtins/hmr-runtime.js","index.js"], null)
  36248. //# sourceMappingURL=example.e31bb0bc.js.map